From 953ddd82e48dd206cef5ac94456549aed13b3ad5 Mon Sep 17 00:00:00 2001 From: RaindropsSys Date: Fri, 17 Nov 2023 23:25:29 +0100 Subject: Updated 30 files and deleted 2976 files (automated) --- .../matrix-js-sdk/dist/browser-matrix.js | 101316 ------------------ .../matrix-js-sdk/dist/browser-matrix.js.map | 801 - .../matrix-js-sdk/dist/browser-matrix.min.js | 18 - .../matrix-js-sdk/dist/browser-matrix.min.js.map | 1 - 4 files changed, 102136 deletions(-) delete mode 100644 includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.js delete mode 100644 includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.js.map delete mode 100644 includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.min.js delete mode 100644 includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.min.js.map (limited to 'includes/external/matrix/node_modules/matrix-js-sdk/dist') diff --git a/includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.js b/includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.js deleted file mode 100644 index 01029d7..0000000 --- a/includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.js +++ /dev/null @@ -1,101316 +0,0 @@ -(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i> 6]; - const primitive = (tag & 0x20) === 0; - - // Multi-octet tag - load - if ((tag & 0x1f) === 0x1f) { - let oct = tag; - tag = 0; - while ((oct & 0x80) === 0x80) { - oct = buf.readUInt8(fail); - if (buf.isError(oct)) - return oct; - - tag <<= 7; - tag |= oct & 0x7f; - } - } else { - tag &= 0x1f; - } - const tagStr = der.tag[tag]; - - return { - cls: cls, - primitive: primitive, - tag: tag, - tagStr: tagStr - }; -} - -function derDecodeLen(buf, primitive, fail) { - let len = buf.readUInt8(fail); - if (buf.isError(len)) - return len; - - // Indefinite form - if (!primitive && len === 0x80) - return null; - - // Definite form - if ((len & 0x80) === 0) { - // Short form - return len; - } - - // Long form - const num = len & 0x7f; - if (num > 4) - return buf.error('length octect is too long'); - - len = 0; - for (let i = 0; i < num; i++) { - len <<= 8; - const j = buf.readUInt8(fail); - if (buf.isError(j)) - return j; - len |= j; - } - - return len; -} - -},{"../base/buffer":4,"../base/node":6,"../constants/der":8,"bn.js":18,"inherits":146}],11:[function(require,module,exports){ -'use strict'; - -const decoders = exports; - -decoders.der = require('./der'); -decoders.pem = require('./pem'); - -},{"./der":10,"./pem":12}],12:[function(require,module,exports){ -'use strict'; - -const inherits = require('inherits'); -const Buffer = require('safer-buffer').Buffer; - -const DERDecoder = require('./der'); - -function PEMDecoder(entity) { - DERDecoder.call(this, entity); - this.enc = 'pem'; -} -inherits(PEMDecoder, DERDecoder); -module.exports = PEMDecoder; - -PEMDecoder.prototype.decode = function decode(data, options) { - const lines = data.toString().split(/[\r\n]+/g); - - const label = options.label.toUpperCase(); - - const re = /^-----(BEGIN|END) ([^-]+)-----$/; - let start = -1; - let end = -1; - for (let i = 0; i < lines.length; i++) { - const match = lines[i].match(re); - if (match === null) - continue; - - if (match[2] !== label) - continue; - - if (start === -1) { - if (match[1] !== 'BEGIN') - break; - start = i; - } else { - if (match[1] !== 'END') - break; - end = i; - break; - } - } - if (start === -1 || end === -1) - throw new Error('PEM section not found for: ' + label); - - const base64 = lines.slice(start + 1, end).join(''); - // Remove excessive symbols - base64.replace(/[^a-z0-9+/=]+/gi, ''); - - const input = Buffer.from(base64, 'base64'); - return DERDecoder.prototype.decode.call(this, input, options); -}; - -},{"./der":10,"inherits":146,"safer-buffer":251}],13:[function(require,module,exports){ -'use strict'; - -const inherits = require('inherits'); -const Buffer = require('safer-buffer').Buffer; -const Node = require('../base/node'); - -// Import DER constants -const der = require('../constants/der'); - -function DEREncoder(entity) { - this.enc = 'der'; - this.name = entity.name; - this.entity = entity; - - // Construct base tree - this.tree = new DERNode(); - this.tree._init(entity.body); -} -module.exports = DEREncoder; - -DEREncoder.prototype.encode = function encode(data, reporter) { - return this.tree._encode(data, reporter).join(); -}; - -// Tree methods - -function DERNode(parent) { - Node.call(this, 'der', parent); -} -inherits(DERNode, Node); - -DERNode.prototype._encodeComposite = function encodeComposite(tag, - primitive, - cls, - content) { - const encodedTag = encodeTag(tag, primitive, cls, this.reporter); - - // Short form - if (content.length < 0x80) { - const header = Buffer.alloc(2); - header[0] = encodedTag; - header[1] = content.length; - return this._createEncoderBuffer([ header, content ]); - } - - // Long form - // Count octets required to store length - let lenOctets = 1; - for (let i = content.length; i >= 0x100; i >>= 8) - lenOctets++; - - const header = Buffer.alloc(1 + 1 + lenOctets); - header[0] = encodedTag; - header[1] = 0x80 | lenOctets; - - for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) - header[i] = j & 0xff; - - return this._createEncoderBuffer([ header, content ]); -}; - -DERNode.prototype._encodeStr = function encodeStr(str, tag) { - if (tag === 'bitstr') { - return this._createEncoderBuffer([ str.unused | 0, str.data ]); - } else if (tag === 'bmpstr') { - const buf = Buffer.alloc(str.length * 2); - for (let i = 0; i < str.length; i++) { - buf.writeUInt16BE(str.charCodeAt(i), i * 2); - } - return this._createEncoderBuffer(buf); - } else if (tag === 'numstr') { - if (!this._isNumstr(str)) { - return this.reporter.error('Encoding of string type: numstr supports ' + - 'only digits and space'); - } - return this._createEncoderBuffer(str); - } else if (tag === 'printstr') { - if (!this._isPrintstr(str)) { - return this.reporter.error('Encoding of string type: printstr supports ' + - 'only latin upper and lower case letters, ' + - 'digits, space, apostrophe, left and rigth ' + - 'parenthesis, plus sign, comma, hyphen, ' + - 'dot, slash, colon, equal sign, ' + - 'question mark'); - } - return this._createEncoderBuffer(str); - } else if (/str$/.test(tag)) { - return this._createEncoderBuffer(str); - } else if (tag === 'objDesc') { - return this._createEncoderBuffer(str); - } else { - return this.reporter.error('Encoding of string type: ' + tag + - ' unsupported'); - } -}; - -DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { - if (typeof id === 'string') { - if (!values) - return this.reporter.error('string objid given, but no values map found'); - if (!values.hasOwnProperty(id)) - return this.reporter.error('objid not found in values map'); - id = values[id].split(/[\s.]+/g); - for (let i = 0; i < id.length; i++) - id[i] |= 0; - } else if (Array.isArray(id)) { - id = id.slice(); - for (let i = 0; i < id.length; i++) - id[i] |= 0; - } - - if (!Array.isArray(id)) { - return this.reporter.error('objid() should be either array or string, ' + - 'got: ' + JSON.stringify(id)); - } - - if (!relative) { - if (id[1] >= 40) - return this.reporter.error('Second objid identifier OOB'); - id.splice(0, 2, id[0] * 40 + id[1]); - } - - // Count number of octets - let size = 0; - for (let i = 0; i < id.length; i++) { - let ident = id[i]; - for (size++; ident >= 0x80; ident >>= 7) - size++; - } - - const objid = Buffer.alloc(size); - let offset = objid.length - 1; - for (let i = id.length - 1; i >= 0; i--) { - let ident = id[i]; - objid[offset--] = ident & 0x7f; - while ((ident >>= 7) > 0) - objid[offset--] = 0x80 | (ident & 0x7f); - } - - return this._createEncoderBuffer(objid); -}; - -function two(num) { - if (num < 10) - return '0' + num; - else - return num; -} - -DERNode.prototype._encodeTime = function encodeTime(time, tag) { - let str; - const date = new Date(time); - - if (tag === 'gentime') { - str = [ - two(date.getUTCFullYear()), - two(date.getUTCMonth() + 1), - two(date.getUTCDate()), - two(date.getUTCHours()), - two(date.getUTCMinutes()), - two(date.getUTCSeconds()), - 'Z' - ].join(''); - } else if (tag === 'utctime') { - str = [ - two(date.getUTCFullYear() % 100), - two(date.getUTCMonth() + 1), - two(date.getUTCDate()), - two(date.getUTCHours()), - two(date.getUTCMinutes()), - two(date.getUTCSeconds()), - 'Z' - ].join(''); - } else { - this.reporter.error('Encoding ' + tag + ' time is not supported yet'); - } - - return this._encodeStr(str, 'octstr'); -}; - -DERNode.prototype._encodeNull = function encodeNull() { - return this._createEncoderBuffer(''); -}; - -DERNode.prototype._encodeInt = function encodeInt(num, values) { - if (typeof num === 'string') { - if (!values) - return this.reporter.error('String int or enum given, but no values map'); - if (!values.hasOwnProperty(num)) { - return this.reporter.error('Values map doesn\'t contain: ' + - JSON.stringify(num)); - } - num = values[num]; - } - - // Bignum, assume big endian - if (typeof num !== 'number' && !Buffer.isBuffer(num)) { - const numArray = num.toArray(); - if (!num.sign && numArray[0] & 0x80) { - numArray.unshift(0); - } - num = Buffer.from(numArray); - } - - if (Buffer.isBuffer(num)) { - let size = num.length; - if (num.length === 0) - size++; - - const out = Buffer.alloc(size); - num.copy(out); - if (num.length === 0) - out[0] = 0; - return this._createEncoderBuffer(out); - } - - if (num < 0x80) - return this._createEncoderBuffer(num); - - if (num < 0x100) - return this._createEncoderBuffer([0, num]); - - let size = 1; - for (let i = num; i >= 0x100; i >>= 8) - size++; - - const out = new Array(size); - for (let i = out.length - 1; i >= 0; i--) { - out[i] = num & 0xff; - num >>= 8; - } - if(out[0] & 0x80) { - out.unshift(0); - } - - return this._createEncoderBuffer(Buffer.from(out)); -}; - -DERNode.prototype._encodeBool = function encodeBool(value) { - return this._createEncoderBuffer(value ? 0xff : 0); -}; - -DERNode.prototype._use = function use(entity, obj) { - if (typeof entity === 'function') - entity = entity(obj); - return entity._getEncoder('der').tree; -}; - -DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { - const state = this._baseState; - let i; - if (state['default'] === null) - return false; - - const data = dataBuffer.join(); - if (state.defaultBuffer === undefined) - state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); - - if (data.length !== state.defaultBuffer.length) - return false; - - for (i=0; i < data.length; i++) - if (data[i] !== state.defaultBuffer[i]) - return false; - - return true; -}; - -// Utility methods - -function encodeTag(tag, primitive, cls, reporter) { - let res; - - if (tag === 'seqof') - tag = 'seq'; - else if (tag === 'setof') - tag = 'set'; - - if (der.tagByName.hasOwnProperty(tag)) - res = der.tagByName[tag]; - else if (typeof tag === 'number' && (tag | 0) === tag) - res = tag; - else - return reporter.error('Unknown tag: ' + tag); - - if (res >= 0x1f) - return reporter.error('Multi-octet tag encoding unsupported'); - - if (!primitive) - res |= 0x20; - - res |= (der.tagClassByName[cls || 'universal'] << 6); - - return res; -} - -},{"../base/node":6,"../constants/der":8,"inherits":146,"safer-buffer":251}],14:[function(require,module,exports){ -'use strict'; - -const encoders = exports; - -encoders.der = require('./der'); -encoders.pem = require('./pem'); - -},{"./der":13,"./pem":15}],15:[function(require,module,exports){ -'use strict'; - -const inherits = require('inherits'); - -const DEREncoder = require('./der'); - -function PEMEncoder(entity) { - DEREncoder.call(this, entity); - this.enc = 'pem'; -} -inherits(PEMEncoder, DEREncoder); -module.exports = PEMEncoder; - -PEMEncoder.prototype.encode = function encode(data, options) { - const buf = DEREncoder.prototype.encode.call(this, data); - - const p = buf.toString('base64'); - const out = [ '-----BEGIN ' + options.label + '-----' ]; - for (let i = 0; i < p.length; i += 64) - out.push(p.slice(i, i + 64)); - out.push('-----END ' + options.label + '-----'); - return out.join('\n'); -}; - -},{"./der":13,"inherits":146}],16:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var possibleNames = [ - 'BigInt64Array', - 'BigUint64Array', - 'Float32Array', - 'Float64Array', - 'Int16Array', - 'Int32Array', - 'Int8Array', - 'Uint16Array', - 'Uint32Array', - 'Uint8Array', - 'Uint8ClampedArray' -]; - -var g = typeof globalThis === 'undefined' ? global : globalThis; - -module.exports = function availableTypedArrays() { - var out = []; - for (var i = 0; i < possibleNames.length; i++) { - if (typeof g[possibleNames[i]] === 'function') { - out[out.length] = possibleNames[i]; - } - } - return out; -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{}],17:[function(require,module,exports){ -'use strict' - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} - -},{}],18:[function(require,module,exports){ -(function (module, exports) { - 'use strict'; - - // Utils - function assert (val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); - } - - // Could use `inherits` module, but don't want to move from single file - // architecture yet. - function inherits (ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - } - - // BN - - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; - } - - this.negative = 0; - this.words = null; - this.length = 0; - - // Reduction context - this.red = null; - - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } - - this._init(number || 0, base || 10, endian || 'be'); - } - } - if (typeof module === 'object') { - module.exports = BN; - } else { - exports.BN = BN; - } - - BN.BN = BN; - BN.wordSize = 26; - - var Buffer; - try { - if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { - Buffer = window.Buffer; - } else { - Buffer = require('buffer').Buffer; - } - } catch (e) { - } - - BN.isBN = function isBN (num) { - if (num instanceof BN) { - return true; - } - - return num !== null && typeof num === 'object' && - num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); - }; - - BN.max = function max (left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; - - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; - - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } - - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } - - if (base === 'hex') { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); - - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - this.negative = 1; - } - - if (start < number.length) { - if (base === 16) { - this._parseHex(number, start, endian); - } else { - this._parseBase(number, base, start); - if (endian === 'le') { - this._initArray(this.toArray(), base, endian); - } - } - } - }; - - BN.prototype._initNumber = function _initNumber (number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; - } - if (number < 0x4000000) { - this.words = [ number & 0x3ffffff ]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff - ]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff, - 1 - ]; - this.length = 3; - } - - if (endian !== 'le') return; - - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; - - BN.prototype._initArray = function _initArray (number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === 'number'); - if (number.length <= 0) { - this.words = [ 0 ]; - this.length = 1; - return this; - } - - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - var j, w; - var off = 0; - if (endian === 'be') { - for (i = number.length - 1, j = 0; i >= 0; i -= 3) { - w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } else if (endian === 'le') { - for (i = 0, j = 0; i < number.length; i += 3) { - w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } - return this.strip(); - }; - - function parseHex4Bits (string, index) { - var c = string.charCodeAt(index); - // 'A' - 'F' - if (c >= 65 && c <= 70) { - return c - 55; - // 'a' - 'f' - } else if (c >= 97 && c <= 102) { - return c - 87; - // '0' - '9' - } else { - return (c - 48) & 0xf; - } - } - - function parseHexByte (string, lowerBound, index) { - var r = parseHex4Bits(string, index); - if (index - 1 >= lowerBound) { - r |= parseHex4Bits(string, index - 1) << 4; - } - return r; - } - - BN.prototype._parseHex = function _parseHex (number, start, endian) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - // 24-bits chunks - var off = 0; - var j = 0; - - var w; - if (endian === 'be') { - for (i = number.length - 1; i >= start; i -= 2) { - w = parseHexByte(number, start, i) << off; - this.words[j] |= w & 0x3ffffff; - if (off >= 18) { - off -= 18; - j += 1; - this.words[j] |= w >>> 26; - } else { - off += 8; - } - } - } else { - var parseLength = number.length - start; - for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { - w = parseHexByte(number, start, i) << off; - this.words[j] |= w & 0x3ffffff; - if (off >= 18) { - off -= 18; - j += 1; - this.words[j] |= w >>> 26; - } else { - off += 8; - } - } - } - - this.strip(); - }; - - function parseBase (str, start, end, mul) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r *= mul; - - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; - - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; - - // '0' - '9' - } else { - r += c; - } - } - return r; - } - - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; - - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; - - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; - - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); - - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); - - for (i = 0; i < mod; i++) { - pow *= base; - } - - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - - this.strip(); - }; - - BN.prototype.copy = function copy (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - dest.words[i] = this.words[i]; - } - dest.length = this.length; - dest.negative = this.negative; - dest.red = this.red; - }; - - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; - - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; - - // Remove leading `0` from `this` - BN.prototype.strip = function strip () { - while (this.length > 1 && this.words[this.length - 1] === 0) { - this.length--; - } - return this._normSign(); - }; - - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } - return this; - }; - - BN.prototype.inspect = function inspect () { - return (this.red ? ''; - }; - - /* - - var zeros = []; - var groupSizes = []; - var groupBases = []; - - var s = ''; - var i = -1; - while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; - } - groupSizes[0] = 0; - groupSizes[1] = 0; - groupBases[0] = 0; - groupBases[1] = 0; - var base = 2 - 1; - while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; - } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; - } - - */ - - var zeros = [ - '', - '0', - '00', - '000', - '0000', - '00000', - '000000', - '0000000', - '00000000', - '000000000', - '0000000000', - '00000000000', - '000000000000', - '0000000000000', - '00000000000000', - '000000000000000', - '0000000000000000', - '00000000000000000', - '000000000000000000', - '0000000000000000000', - '00000000000000000000', - '000000000000000000000', - '0000000000000000000000', - '00000000000000000000000', - '000000000000000000000000', - '0000000000000000000000000' - ]; - - var groupSizes = [ - 0, 0, - 25, 16, 12, 11, 10, 9, 8, - 8, 7, 7, 7, 7, 6, 6, - 6, 6, 6, 6, 6, 5, 5, - 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5 - ]; - - var groupBases = [ - 0, 0, - 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, - 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, - 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, - 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, - 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 - ]; - - BN.prototype.toString = function toString (base, padding) { - base = base || 10; - padding = padding | 0 || 1; - - var out; - if (base === 16 || base === 'hex') { - out = ''; - var off = 0; - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = (((w << off) | carry) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } - off += 2; - if (off >= 26) { - off -= 26; - i--; - } - } - if (carry !== 0) { - out = carry.toString(16) + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } - - if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - out = ''; - var c = this.clone(); - c.negative = 0; - while (!c.isZero()) { - var r = c.modn(groupBase).toString(base); - c = c.idivn(groupBase); - - if (!c.isZero()) { - out = zeros[groupSize - r.length] + r + out; - } else { - out = r + out; - } - } - if (this.isZero()) { - out = '0' + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } - - assert(false, 'Base should be between 2 and 36'); - }; - - BN.prototype.toNumber = function toNumber () { - var ret = this.words[0]; - if (this.length === 2) { - ret += this.words[1] * 0x4000000; - } else if (this.length === 3 && this.words[2] === 0x01) { - // NOTE: at this stage it is known that the top bit is set - ret += 0x10000000000000 + (this.words[1] * 0x4000000); - } else if (this.length > 2) { - assert(false, 'Number can only safely store up to 53 bits'); - } - return (this.negative !== 0) ? -ret : ret; - }; - - BN.prototype.toJSON = function toJSON () { - return this.toString(16); - }; - - BN.prototype.toBuffer = function toBuffer (endian, length) { - assert(typeof Buffer !== 'undefined'); - return this.toArrayLike(Buffer, endian, length); - }; - - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; - - BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { - var byteLength = this.byteLength(); - var reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, 'byte array longer than desired length'); - assert(reqLength > 0, 'Requested array length <= 0'); - - this.strip(); - var littleEndian = endian === 'le'; - var res = new ArrayType(reqLength); - - var b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } - - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); - - res[reqLength - i - 1] = b; - } - } else { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); - - res[i] = b; - } - - for (; i < reqLength; i++) { - res[i] = 0; - } - } - - return res; - }; - - if (Math.clz32) { - BN.prototype._countBits = function _countBits (w) { - return 32 - Math.clz32(w); - }; - } else { - BN.prototype._countBits = function _countBits (w) { - var t = w; - var r = 0; - if (t >= 0x1000) { - r += 13; - t >>>= 13; - } - if (t >= 0x40) { - r += 7; - t >>>= 7; - } - if (t >= 0x8) { - r += 4; - t >>>= 4; - } - if (t >= 0x02) { - r += 2; - t >>>= 2; - } - return r + t; - }; - } - - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; - - var t = w; - var r = 0; - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; - } - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; - } - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; - } - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; - } - if ((t & 0x1) === 0) { - r++; - } - return r; - }; - - // Return number of used bits in a BN - BN.prototype.bitLength = function bitLength () { - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }; - - function toBitArray (num) { - var w = new Array(num.bitLength()); - - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; - - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } - - return w; - } - - // Number of trailing zero bits - BN.prototype.zeroBits = function zeroBits () { - if (this.isZero()) return 0; - - var r = 0; - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - r += b; - if (b !== 26) break; - } - return r; - }; - - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; - - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); - } - return this.clone(); - }; - - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); - } - return this.clone(); - }; - - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; - - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); - }; - - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; - } - - return this; - }; - - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; - } - - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; - } - - return this.strip(); - }; - - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; - - // Or `num` with `this` - BN.prototype.or = function or (num) { - if (this.length > num.length) return this.clone().ior(num); - return num.clone().ior(this); - }; - - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; - - // And `num` with `this` in-place - BN.prototype.iuand = function iuand (num) { - // b = min-length(num, this) - var b; - if (this.length > num.length) { - b = num; - } else { - b = this; - } - - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; - } - - this.length = b.length; - - return this.strip(); - }; - - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; - - // And `num` with `this` - BN.prototype.and = function and (num) { - if (this.length > num.length) return this.clone().iand(num); - return num.clone().iand(this); - }; - - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; - - // Xor `num` with `this` in-place - BN.prototype.iuxor = function iuxor (num) { - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; - } - - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - this.length = a.length; - - return this.strip(); - }; - - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; - - // Xor `num` with `this` - BN.prototype.xor = function xor (num) { - if (this.length > num.length) return this.clone().ixor(num); - return num.clone().ixor(this); - }; - - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; - - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); - - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; - - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); - - if (bitsLeft > 0) { - bytesNeeded--; - } - - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; - } - - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); - } - - // And remove leading zeroes - return this.strip(); - }; - - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; - - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); - - var off = (bit / 26) | 0; - var wbit = bit % 26; - - this._expand(off + 1); - - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); - } - - return this.strip(); - }; - - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; - - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); - - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } - - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) + (b.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - return this; - }; - - // Add `num` to `this` - BN.prototype.add = function add (num) { - var res; - if (num.negative !== 0 && this.negative === 0) { - num.negative = 0; - res = this.sub(num); - num.negative ^= 1; - return res; - } else if (num.negative === 0 && this.negative !== 0) { - this.negative = 0; - res = num.sub(this); - this.negative = 1; - return res; - } - - if (this.length > num.length) return this.clone().iadd(num); - - return num.clone().iadd(this); - }; - - // Subtract `num` from `this` in-place - BN.prototype.isub = function isub (num) { - // this - (-num) = this + num - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - num.negative = 1; - return r._normSign(); - - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } - - // At this point both numbers are positive - var cmp = this.cmp(num); - - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } - - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) - (b.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - this.length = Math.max(this.length, i); - - if (a !== this) { - this.negative = 1; - } - - return this.strip(); - }; - - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; - - function smallMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - var len = (self.length + num.length) | 0; - out.length = len; - len = (len - 1) | 0; - - // Peel one iteration (compiler can't do it, because of code complexity) - var a = self.words[0] | 0; - var b = num.words[0] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; - - for (var k = 1; k < len; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = (k - j) | 0; - a = self.words[i] | 0; - b = num.words[j] | 0; - r = a * b + rword; - ncarry += (r / 0x4000000) | 0; - rword = r & 0x3ffffff; - } - out.words[k] = rword | 0; - carry = ncarry | 0; - } - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; - } - - return out.strip(); - } - - // TODO(indutny): it may be reasonable to omit it for users who don't need - // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit - // multiplication (like elliptic secp256k1). - var comb10MulTo = function comb10MulTo (self, num, out) { - var a = self.words; - var b = num.words; - var o = out.words; - var c = 0; - var lo; - var mid; - var hi; - var a0 = a[0] | 0; - var al0 = a0 & 0x1fff; - var ah0 = a0 >>> 13; - var a1 = a[1] | 0; - var al1 = a1 & 0x1fff; - var ah1 = a1 >>> 13; - var a2 = a[2] | 0; - var al2 = a2 & 0x1fff; - var ah2 = a2 >>> 13; - var a3 = a[3] | 0; - var al3 = a3 & 0x1fff; - var ah3 = a3 >>> 13; - var a4 = a[4] | 0; - var al4 = a4 & 0x1fff; - var ah4 = a4 >>> 13; - var a5 = a[5] | 0; - var al5 = a5 & 0x1fff; - var ah5 = a5 >>> 13; - var a6 = a[6] | 0; - var al6 = a6 & 0x1fff; - var ah6 = a6 >>> 13; - var a7 = a[7] | 0; - var al7 = a7 & 0x1fff; - var ah7 = a7 >>> 13; - var a8 = a[8] | 0; - var al8 = a8 & 0x1fff; - var ah8 = a8 >>> 13; - var a9 = a[9] | 0; - var al9 = a9 & 0x1fff; - var ah9 = a9 >>> 13; - var b0 = b[0] | 0; - var bl0 = b0 & 0x1fff; - var bh0 = b0 >>> 13; - var b1 = b[1] | 0; - var bl1 = b1 & 0x1fff; - var bh1 = b1 >>> 13; - var b2 = b[2] | 0; - var bl2 = b2 & 0x1fff; - var bh2 = b2 >>> 13; - var b3 = b[3] | 0; - var bl3 = b3 & 0x1fff; - var bh3 = b3 >>> 13; - var b4 = b[4] | 0; - var bl4 = b4 & 0x1fff; - var bh4 = b4 >>> 13; - var b5 = b[5] | 0; - var bl5 = b5 & 0x1fff; - var bh5 = b5 >>> 13; - var b6 = b[6] | 0; - var bl6 = b6 & 0x1fff; - var bh6 = b6 >>> 13; - var b7 = b[7] | 0; - var bl7 = b7 & 0x1fff; - var bh7 = b7 >>> 13; - var b8 = b[8] | 0; - var bl8 = b8 & 0x1fff; - var bh8 = b8 >>> 13; - var b9 = b[9] | 0; - var bl9 = b9 & 0x1fff; - var bh9 = b9 >>> 13; - - out.negative = self.negative ^ num.negative; - out.length = 19; - /* k = 0 */ - lo = Math.imul(al0, bl0); - mid = Math.imul(al0, bh0); - mid = (mid + Math.imul(ah0, bl0)) | 0; - hi = Math.imul(ah0, bh0); - var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; - w0 &= 0x3ffffff; - /* k = 1 */ - lo = Math.imul(al1, bl0); - mid = Math.imul(al1, bh0); - mid = (mid + Math.imul(ah1, bl0)) | 0; - hi = Math.imul(ah1, bh0); - lo = (lo + Math.imul(al0, bl1)) | 0; - mid = (mid + Math.imul(al0, bh1)) | 0; - mid = (mid + Math.imul(ah0, bl1)) | 0; - hi = (hi + Math.imul(ah0, bh1)) | 0; - var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; - w1 &= 0x3ffffff; - /* k = 2 */ - lo = Math.imul(al2, bl0); - mid = Math.imul(al2, bh0); - mid = (mid + Math.imul(ah2, bl0)) | 0; - hi = Math.imul(ah2, bh0); - lo = (lo + Math.imul(al1, bl1)) | 0; - mid = (mid + Math.imul(al1, bh1)) | 0; - mid = (mid + Math.imul(ah1, bl1)) | 0; - hi = (hi + Math.imul(ah1, bh1)) | 0; - lo = (lo + Math.imul(al0, bl2)) | 0; - mid = (mid + Math.imul(al0, bh2)) | 0; - mid = (mid + Math.imul(ah0, bl2)) | 0; - hi = (hi + Math.imul(ah0, bh2)) | 0; - var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; - w2 &= 0x3ffffff; - /* k = 3 */ - lo = Math.imul(al3, bl0); - mid = Math.imul(al3, bh0); - mid = (mid + Math.imul(ah3, bl0)) | 0; - hi = Math.imul(ah3, bh0); - lo = (lo + Math.imul(al2, bl1)) | 0; - mid = (mid + Math.imul(al2, bh1)) | 0; - mid = (mid + Math.imul(ah2, bl1)) | 0; - hi = (hi + Math.imul(ah2, bh1)) | 0; - lo = (lo + Math.imul(al1, bl2)) | 0; - mid = (mid + Math.imul(al1, bh2)) | 0; - mid = (mid + Math.imul(ah1, bl2)) | 0; - hi = (hi + Math.imul(ah1, bh2)) | 0; - lo = (lo + Math.imul(al0, bl3)) | 0; - mid = (mid + Math.imul(al0, bh3)) | 0; - mid = (mid + Math.imul(ah0, bl3)) | 0; - hi = (hi + Math.imul(ah0, bh3)) | 0; - var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; - w3 &= 0x3ffffff; - /* k = 4 */ - lo = Math.imul(al4, bl0); - mid = Math.imul(al4, bh0); - mid = (mid + Math.imul(ah4, bl0)) | 0; - hi = Math.imul(ah4, bh0); - lo = (lo + Math.imul(al3, bl1)) | 0; - mid = (mid + Math.imul(al3, bh1)) | 0; - mid = (mid + Math.imul(ah3, bl1)) | 0; - hi = (hi + Math.imul(ah3, bh1)) | 0; - lo = (lo + Math.imul(al2, bl2)) | 0; - mid = (mid + Math.imul(al2, bh2)) | 0; - mid = (mid + Math.imul(ah2, bl2)) | 0; - hi = (hi + Math.imul(ah2, bh2)) | 0; - lo = (lo + Math.imul(al1, bl3)) | 0; - mid = (mid + Math.imul(al1, bh3)) | 0; - mid = (mid + Math.imul(ah1, bl3)) | 0; - hi = (hi + Math.imul(ah1, bh3)) | 0; - lo = (lo + Math.imul(al0, bl4)) | 0; - mid = (mid + Math.imul(al0, bh4)) | 0; - mid = (mid + Math.imul(ah0, bl4)) | 0; - hi = (hi + Math.imul(ah0, bh4)) | 0; - var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; - w4 &= 0x3ffffff; - /* k = 5 */ - lo = Math.imul(al5, bl0); - mid = Math.imul(al5, bh0); - mid = (mid + Math.imul(ah5, bl0)) | 0; - hi = Math.imul(ah5, bh0); - lo = (lo + Math.imul(al4, bl1)) | 0; - mid = (mid + Math.imul(al4, bh1)) | 0; - mid = (mid + Math.imul(ah4, bl1)) | 0; - hi = (hi + Math.imul(ah4, bh1)) | 0; - lo = (lo + Math.imul(al3, bl2)) | 0; - mid = (mid + Math.imul(al3, bh2)) | 0; - mid = (mid + Math.imul(ah3, bl2)) | 0; - hi = (hi + Math.imul(ah3, bh2)) | 0; - lo = (lo + Math.imul(al2, bl3)) | 0; - mid = (mid + Math.imul(al2, bh3)) | 0; - mid = (mid + Math.imul(ah2, bl3)) | 0; - hi = (hi + Math.imul(ah2, bh3)) | 0; - lo = (lo + Math.imul(al1, bl4)) | 0; - mid = (mid + Math.imul(al1, bh4)) | 0; - mid = (mid + Math.imul(ah1, bl4)) | 0; - hi = (hi + Math.imul(ah1, bh4)) | 0; - lo = (lo + Math.imul(al0, bl5)) | 0; - mid = (mid + Math.imul(al0, bh5)) | 0; - mid = (mid + Math.imul(ah0, bl5)) | 0; - hi = (hi + Math.imul(ah0, bh5)) | 0; - var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; - w5 &= 0x3ffffff; - /* k = 6 */ - lo = Math.imul(al6, bl0); - mid = Math.imul(al6, bh0); - mid = (mid + Math.imul(ah6, bl0)) | 0; - hi = Math.imul(ah6, bh0); - lo = (lo + Math.imul(al5, bl1)) | 0; - mid = (mid + Math.imul(al5, bh1)) | 0; - mid = (mid + Math.imul(ah5, bl1)) | 0; - hi = (hi + Math.imul(ah5, bh1)) | 0; - lo = (lo + Math.imul(al4, bl2)) | 0; - mid = (mid + Math.imul(al4, bh2)) | 0; - mid = (mid + Math.imul(ah4, bl2)) | 0; - hi = (hi + Math.imul(ah4, bh2)) | 0; - lo = (lo + Math.imul(al3, bl3)) | 0; - mid = (mid + Math.imul(al3, bh3)) | 0; - mid = (mid + Math.imul(ah3, bl3)) | 0; - hi = (hi + Math.imul(ah3, bh3)) | 0; - lo = (lo + Math.imul(al2, bl4)) | 0; - mid = (mid + Math.imul(al2, bh4)) | 0; - mid = (mid + Math.imul(ah2, bl4)) | 0; - hi = (hi + Math.imul(ah2, bh4)) | 0; - lo = (lo + Math.imul(al1, bl5)) | 0; - mid = (mid + Math.imul(al1, bh5)) | 0; - mid = (mid + Math.imul(ah1, bl5)) | 0; - hi = (hi + Math.imul(ah1, bh5)) | 0; - lo = (lo + Math.imul(al0, bl6)) | 0; - mid = (mid + Math.imul(al0, bh6)) | 0; - mid = (mid + Math.imul(ah0, bl6)) | 0; - hi = (hi + Math.imul(ah0, bh6)) | 0; - var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; - w6 &= 0x3ffffff; - /* k = 7 */ - lo = Math.imul(al7, bl0); - mid = Math.imul(al7, bh0); - mid = (mid + Math.imul(ah7, bl0)) | 0; - hi = Math.imul(ah7, bh0); - lo = (lo + Math.imul(al6, bl1)) | 0; - mid = (mid + Math.imul(al6, bh1)) | 0; - mid = (mid + Math.imul(ah6, bl1)) | 0; - hi = (hi + Math.imul(ah6, bh1)) | 0; - lo = (lo + Math.imul(al5, bl2)) | 0; - mid = (mid + Math.imul(al5, bh2)) | 0; - mid = (mid + Math.imul(ah5, bl2)) | 0; - hi = (hi + Math.imul(ah5, bh2)) | 0; - lo = (lo + Math.imul(al4, bl3)) | 0; - mid = (mid + Math.imul(al4, bh3)) | 0; - mid = (mid + Math.imul(ah4, bl3)) | 0; - hi = (hi + Math.imul(ah4, bh3)) | 0; - lo = (lo + Math.imul(al3, bl4)) | 0; - mid = (mid + Math.imul(al3, bh4)) | 0; - mid = (mid + Math.imul(ah3, bl4)) | 0; - hi = (hi + Math.imul(ah3, bh4)) | 0; - lo = (lo + Math.imul(al2, bl5)) | 0; - mid = (mid + Math.imul(al2, bh5)) | 0; - mid = (mid + Math.imul(ah2, bl5)) | 0; - hi = (hi + Math.imul(ah2, bh5)) | 0; - lo = (lo + Math.imul(al1, bl6)) | 0; - mid = (mid + Math.imul(al1, bh6)) | 0; - mid = (mid + Math.imul(ah1, bl6)) | 0; - hi = (hi + Math.imul(ah1, bh6)) | 0; - lo = (lo + Math.imul(al0, bl7)) | 0; - mid = (mid + Math.imul(al0, bh7)) | 0; - mid = (mid + Math.imul(ah0, bl7)) | 0; - hi = (hi + Math.imul(ah0, bh7)) | 0; - var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; - w7 &= 0x3ffffff; - /* k = 8 */ - lo = Math.imul(al8, bl0); - mid = Math.imul(al8, bh0); - mid = (mid + Math.imul(ah8, bl0)) | 0; - hi = Math.imul(ah8, bh0); - lo = (lo + Math.imul(al7, bl1)) | 0; - mid = (mid + Math.imul(al7, bh1)) | 0; - mid = (mid + Math.imul(ah7, bl1)) | 0; - hi = (hi + Math.imul(ah7, bh1)) | 0; - lo = (lo + Math.imul(al6, bl2)) | 0; - mid = (mid + Math.imul(al6, bh2)) | 0; - mid = (mid + Math.imul(ah6, bl2)) | 0; - hi = (hi + Math.imul(ah6, bh2)) | 0; - lo = (lo + Math.imul(al5, bl3)) | 0; - mid = (mid + Math.imul(al5, bh3)) | 0; - mid = (mid + Math.imul(ah5, bl3)) | 0; - hi = (hi + Math.imul(ah5, bh3)) | 0; - lo = (lo + Math.imul(al4, bl4)) | 0; - mid = (mid + Math.imul(al4, bh4)) | 0; - mid = (mid + Math.imul(ah4, bl4)) | 0; - hi = (hi + Math.imul(ah4, bh4)) | 0; - lo = (lo + Math.imul(al3, bl5)) | 0; - mid = (mid + Math.imul(al3, bh5)) | 0; - mid = (mid + Math.imul(ah3, bl5)) | 0; - hi = (hi + Math.imul(ah3, bh5)) | 0; - lo = (lo + Math.imul(al2, bl6)) | 0; - mid = (mid + Math.imul(al2, bh6)) | 0; - mid = (mid + Math.imul(ah2, bl6)) | 0; - hi = (hi + Math.imul(ah2, bh6)) | 0; - lo = (lo + Math.imul(al1, bl7)) | 0; - mid = (mid + Math.imul(al1, bh7)) | 0; - mid = (mid + Math.imul(ah1, bl7)) | 0; - hi = (hi + Math.imul(ah1, bh7)) | 0; - lo = (lo + Math.imul(al0, bl8)) | 0; - mid = (mid + Math.imul(al0, bh8)) | 0; - mid = (mid + Math.imul(ah0, bl8)) | 0; - hi = (hi + Math.imul(ah0, bh8)) | 0; - var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; - w8 &= 0x3ffffff; - /* k = 9 */ - lo = Math.imul(al9, bl0); - mid = Math.imul(al9, bh0); - mid = (mid + Math.imul(ah9, bl0)) | 0; - hi = Math.imul(ah9, bh0); - lo = (lo + Math.imul(al8, bl1)) | 0; - mid = (mid + Math.imul(al8, bh1)) | 0; - mid = (mid + Math.imul(ah8, bl1)) | 0; - hi = (hi + Math.imul(ah8, bh1)) | 0; - lo = (lo + Math.imul(al7, bl2)) | 0; - mid = (mid + Math.imul(al7, bh2)) | 0; - mid = (mid + Math.imul(ah7, bl2)) | 0; - hi = (hi + Math.imul(ah7, bh2)) | 0; - lo = (lo + Math.imul(al6, bl3)) | 0; - mid = (mid + Math.imul(al6, bh3)) | 0; - mid = (mid + Math.imul(ah6, bl3)) | 0; - hi = (hi + Math.imul(ah6, bh3)) | 0; - lo = (lo + Math.imul(al5, bl4)) | 0; - mid = (mid + Math.imul(al5, bh4)) | 0; - mid = (mid + Math.imul(ah5, bl4)) | 0; - hi = (hi + Math.imul(ah5, bh4)) | 0; - lo = (lo + Math.imul(al4, bl5)) | 0; - mid = (mid + Math.imul(al4, bh5)) | 0; - mid = (mid + Math.imul(ah4, bl5)) | 0; - hi = (hi + Math.imul(ah4, bh5)) | 0; - lo = (lo + Math.imul(al3, bl6)) | 0; - mid = (mid + Math.imul(al3, bh6)) | 0; - mid = (mid + Math.imul(ah3, bl6)) | 0; - hi = (hi + Math.imul(ah3, bh6)) | 0; - lo = (lo + Math.imul(al2, bl7)) | 0; - mid = (mid + Math.imul(al2, bh7)) | 0; - mid = (mid + Math.imul(ah2, bl7)) | 0; - hi = (hi + Math.imul(ah2, bh7)) | 0; - lo = (lo + Math.imul(al1, bl8)) | 0; - mid = (mid + Math.imul(al1, bh8)) | 0; - mid = (mid + Math.imul(ah1, bl8)) | 0; - hi = (hi + Math.imul(ah1, bh8)) | 0; - lo = (lo + Math.imul(al0, bl9)) | 0; - mid = (mid + Math.imul(al0, bh9)) | 0; - mid = (mid + Math.imul(ah0, bl9)) | 0; - hi = (hi + Math.imul(ah0, bh9)) | 0; - var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; - w9 &= 0x3ffffff; - /* k = 10 */ - lo = Math.imul(al9, bl1); - mid = Math.imul(al9, bh1); - mid = (mid + Math.imul(ah9, bl1)) | 0; - hi = Math.imul(ah9, bh1); - lo = (lo + Math.imul(al8, bl2)) | 0; - mid = (mid + Math.imul(al8, bh2)) | 0; - mid = (mid + Math.imul(ah8, bl2)) | 0; - hi = (hi + Math.imul(ah8, bh2)) | 0; - lo = (lo + Math.imul(al7, bl3)) | 0; - mid = (mid + Math.imul(al7, bh3)) | 0; - mid = (mid + Math.imul(ah7, bl3)) | 0; - hi = (hi + Math.imul(ah7, bh3)) | 0; - lo = (lo + Math.imul(al6, bl4)) | 0; - mid = (mid + Math.imul(al6, bh4)) | 0; - mid = (mid + Math.imul(ah6, bl4)) | 0; - hi = (hi + Math.imul(ah6, bh4)) | 0; - lo = (lo + Math.imul(al5, bl5)) | 0; - mid = (mid + Math.imul(al5, bh5)) | 0; - mid = (mid + Math.imul(ah5, bl5)) | 0; - hi = (hi + Math.imul(ah5, bh5)) | 0; - lo = (lo + Math.imul(al4, bl6)) | 0; - mid = (mid + Math.imul(al4, bh6)) | 0; - mid = (mid + Math.imul(ah4, bl6)) | 0; - hi = (hi + Math.imul(ah4, bh6)) | 0; - lo = (lo + Math.imul(al3, bl7)) | 0; - mid = (mid + Math.imul(al3, bh7)) | 0; - mid = (mid + Math.imul(ah3, bl7)) | 0; - hi = (hi + Math.imul(ah3, bh7)) | 0; - lo = (lo + Math.imul(al2, bl8)) | 0; - mid = (mid + Math.imul(al2, bh8)) | 0; - mid = (mid + Math.imul(ah2, bl8)) | 0; - hi = (hi + Math.imul(ah2, bh8)) | 0; - lo = (lo + Math.imul(al1, bl9)) | 0; - mid = (mid + Math.imul(al1, bh9)) | 0; - mid = (mid + Math.imul(ah1, bl9)) | 0; - hi = (hi + Math.imul(ah1, bh9)) | 0; - var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; - w10 &= 0x3ffffff; - /* k = 11 */ - lo = Math.imul(al9, bl2); - mid = Math.imul(al9, bh2); - mid = (mid + Math.imul(ah9, bl2)) | 0; - hi = Math.imul(ah9, bh2); - lo = (lo + Math.imul(al8, bl3)) | 0; - mid = (mid + Math.imul(al8, bh3)) | 0; - mid = (mid + Math.imul(ah8, bl3)) | 0; - hi = (hi + Math.imul(ah8, bh3)) | 0; - lo = (lo + Math.imul(al7, bl4)) | 0; - mid = (mid + Math.imul(al7, bh4)) | 0; - mid = (mid + Math.imul(ah7, bl4)) | 0; - hi = (hi + Math.imul(ah7, bh4)) | 0; - lo = (lo + Math.imul(al6, bl5)) | 0; - mid = (mid + Math.imul(al6, bh5)) | 0; - mid = (mid + Math.imul(ah6, bl5)) | 0; - hi = (hi + Math.imul(ah6, bh5)) | 0; - lo = (lo + Math.imul(al5, bl6)) | 0; - mid = (mid + Math.imul(al5, bh6)) | 0; - mid = (mid + Math.imul(ah5, bl6)) | 0; - hi = (hi + Math.imul(ah5, bh6)) | 0; - lo = (lo + Math.imul(al4, bl7)) | 0; - mid = (mid + Math.imul(al4, bh7)) | 0; - mid = (mid + Math.imul(ah4, bl7)) | 0; - hi = (hi + Math.imul(ah4, bh7)) | 0; - lo = (lo + Math.imul(al3, bl8)) | 0; - mid = (mid + Math.imul(al3, bh8)) | 0; - mid = (mid + Math.imul(ah3, bl8)) | 0; - hi = (hi + Math.imul(ah3, bh8)) | 0; - lo = (lo + Math.imul(al2, bl9)) | 0; - mid = (mid + Math.imul(al2, bh9)) | 0; - mid = (mid + Math.imul(ah2, bl9)) | 0; - hi = (hi + Math.imul(ah2, bh9)) | 0; - var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; - w11 &= 0x3ffffff; - /* k = 12 */ - lo = Math.imul(al9, bl3); - mid = Math.imul(al9, bh3); - mid = (mid + Math.imul(ah9, bl3)) | 0; - hi = Math.imul(ah9, bh3); - lo = (lo + Math.imul(al8, bl4)) | 0; - mid = (mid + Math.imul(al8, bh4)) | 0; - mid = (mid + Math.imul(ah8, bl4)) | 0; - hi = (hi + Math.imul(ah8, bh4)) | 0; - lo = (lo + Math.imul(al7, bl5)) | 0; - mid = (mid + Math.imul(al7, bh5)) | 0; - mid = (mid + Math.imul(ah7, bl5)) | 0; - hi = (hi + Math.imul(ah7, bh5)) | 0; - lo = (lo + Math.imul(al6, bl6)) | 0; - mid = (mid + Math.imul(al6, bh6)) | 0; - mid = (mid + Math.imul(ah6, bl6)) | 0; - hi = (hi + Math.imul(ah6, bh6)) | 0; - lo = (lo + Math.imul(al5, bl7)) | 0; - mid = (mid + Math.imul(al5, bh7)) | 0; - mid = (mid + Math.imul(ah5, bl7)) | 0; - hi = (hi + Math.imul(ah5, bh7)) | 0; - lo = (lo + Math.imul(al4, bl8)) | 0; - mid = (mid + Math.imul(al4, bh8)) | 0; - mid = (mid + Math.imul(ah4, bl8)) | 0; - hi = (hi + Math.imul(ah4, bh8)) | 0; - lo = (lo + Math.imul(al3, bl9)) | 0; - mid = (mid + Math.imul(al3, bh9)) | 0; - mid = (mid + Math.imul(ah3, bl9)) | 0; - hi = (hi + Math.imul(ah3, bh9)) | 0; - var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; - w12 &= 0x3ffffff; - /* k = 13 */ - lo = Math.imul(al9, bl4); - mid = Math.imul(al9, bh4); - mid = (mid + Math.imul(ah9, bl4)) | 0; - hi = Math.imul(ah9, bh4); - lo = (lo + Math.imul(al8, bl5)) | 0; - mid = (mid + Math.imul(al8, bh5)) | 0; - mid = (mid + Math.imul(ah8, bl5)) | 0; - hi = (hi + Math.imul(ah8, bh5)) | 0; - lo = (lo + Math.imul(al7, bl6)) | 0; - mid = (mid + Math.imul(al7, bh6)) | 0; - mid = (mid + Math.imul(ah7, bl6)) | 0; - hi = (hi + Math.imul(ah7, bh6)) | 0; - lo = (lo + Math.imul(al6, bl7)) | 0; - mid = (mid + Math.imul(al6, bh7)) | 0; - mid = (mid + Math.imul(ah6, bl7)) | 0; - hi = (hi + Math.imul(ah6, bh7)) | 0; - lo = (lo + Math.imul(al5, bl8)) | 0; - mid = (mid + Math.imul(al5, bh8)) | 0; - mid = (mid + Math.imul(ah5, bl8)) | 0; - hi = (hi + Math.imul(ah5, bh8)) | 0; - lo = (lo + Math.imul(al4, bl9)) | 0; - mid = (mid + Math.imul(al4, bh9)) | 0; - mid = (mid + Math.imul(ah4, bl9)) | 0; - hi = (hi + Math.imul(ah4, bh9)) | 0; - var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; - w13 &= 0x3ffffff; - /* k = 14 */ - lo = Math.imul(al9, bl5); - mid = Math.imul(al9, bh5); - mid = (mid + Math.imul(ah9, bl5)) | 0; - hi = Math.imul(ah9, bh5); - lo = (lo + Math.imul(al8, bl6)) | 0; - mid = (mid + Math.imul(al8, bh6)) | 0; - mid = (mid + Math.imul(ah8, bl6)) | 0; - hi = (hi + Math.imul(ah8, bh6)) | 0; - lo = (lo + Math.imul(al7, bl7)) | 0; - mid = (mid + Math.imul(al7, bh7)) | 0; - mid = (mid + Math.imul(ah7, bl7)) | 0; - hi = (hi + Math.imul(ah7, bh7)) | 0; - lo = (lo + Math.imul(al6, bl8)) | 0; - mid = (mid + Math.imul(al6, bh8)) | 0; - mid = (mid + Math.imul(ah6, bl8)) | 0; - hi = (hi + Math.imul(ah6, bh8)) | 0; - lo = (lo + Math.imul(al5, bl9)) | 0; - mid = (mid + Math.imul(al5, bh9)) | 0; - mid = (mid + Math.imul(ah5, bl9)) | 0; - hi = (hi + Math.imul(ah5, bh9)) | 0; - var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; - w14 &= 0x3ffffff; - /* k = 15 */ - lo = Math.imul(al9, bl6); - mid = Math.imul(al9, bh6); - mid = (mid + Math.imul(ah9, bl6)) | 0; - hi = Math.imul(ah9, bh6); - lo = (lo + Math.imul(al8, bl7)) | 0; - mid = (mid + Math.imul(al8, bh7)) | 0; - mid = (mid + Math.imul(ah8, bl7)) | 0; - hi = (hi + Math.imul(ah8, bh7)) | 0; - lo = (lo + Math.imul(al7, bl8)) | 0; - mid = (mid + Math.imul(al7, bh8)) | 0; - mid = (mid + Math.imul(ah7, bl8)) | 0; - hi = (hi + Math.imul(ah7, bh8)) | 0; - lo = (lo + Math.imul(al6, bl9)) | 0; - mid = (mid + Math.imul(al6, bh9)) | 0; - mid = (mid + Math.imul(ah6, bl9)) | 0; - hi = (hi + Math.imul(ah6, bh9)) | 0; - var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; - w15 &= 0x3ffffff; - /* k = 16 */ - lo = Math.imul(al9, bl7); - mid = Math.imul(al9, bh7); - mid = (mid + Math.imul(ah9, bl7)) | 0; - hi = Math.imul(ah9, bh7); - lo = (lo + Math.imul(al8, bl8)) | 0; - mid = (mid + Math.imul(al8, bh8)) | 0; - mid = (mid + Math.imul(ah8, bl8)) | 0; - hi = (hi + Math.imul(ah8, bh8)) | 0; - lo = (lo + Math.imul(al7, bl9)) | 0; - mid = (mid + Math.imul(al7, bh9)) | 0; - mid = (mid + Math.imul(ah7, bl9)) | 0; - hi = (hi + Math.imul(ah7, bh9)) | 0; - var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; - w16 &= 0x3ffffff; - /* k = 17 */ - lo = Math.imul(al9, bl8); - mid = Math.imul(al9, bh8); - mid = (mid + Math.imul(ah9, bl8)) | 0; - hi = Math.imul(ah9, bh8); - lo = (lo + Math.imul(al8, bl9)) | 0; - mid = (mid + Math.imul(al8, bh9)) | 0; - mid = (mid + Math.imul(ah8, bl9)) | 0; - hi = (hi + Math.imul(ah8, bh9)) | 0; - var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; - w17 &= 0x3ffffff; - /* k = 18 */ - lo = Math.imul(al9, bl9); - mid = Math.imul(al9, bh9); - mid = (mid + Math.imul(ah9, bl9)) | 0; - hi = Math.imul(ah9, bh9); - var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; - w18 &= 0x3ffffff; - o[0] = w0; - o[1] = w1; - o[2] = w2; - o[3] = w3; - o[4] = w4; - o[5] = w5; - o[6] = w6; - o[7] = w7; - o[8] = w8; - o[9] = w9; - o[10] = w10; - o[11] = w11; - o[12] = w12; - o[13] = w13; - o[14] = w14; - o[15] = w15; - o[16] = w16; - o[17] = w17; - o[18] = w18; - if (c !== 0) { - o[19] = c; - out.length++; - } - return out; - }; - - // Polyfill comb - if (!Math.imul) { - comb10MulTo = smallMulTo; - } - - function bigMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - out.length = self.length + num.length; - - var carry = 0; - var hncarry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = self.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; - - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; - } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } - - return out.strip(); - } - - function jumboMulTo (self, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self, num, out); - } - - BN.prototype.mulTo = function mulTo (num, out) { - var res; - var len = this.length + num.length; - if (this.length === 10 && num.length === 10) { - res = comb10MulTo(this, num, out); - } else if (len < 63) { - res = smallMulTo(this, num, out); - } else if (len < 1024) { - res = bigMulTo(this, num, out); - } else { - res = jumboMulTo(this, num, out); - } - - return res; - }; - - // Cooley-Tukey algorithm for FFT - // slightly revisited to rely on looping instead of recursion - - function FFTM (x, y) { - this.x = x; - this.y = y; - } - - FFTM.prototype.makeRBT = function makeRBT (N) { - var t = new Array(N); - var l = BN.prototype._countBits(N) - 1; - for (var i = 0; i < N; i++) { - t[i] = this.revBin(i, l, N); - } - - return t; - }; - - // Returns binary-reversed representation of `x` - FFTM.prototype.revBin = function revBin (x, l, N) { - if (x === 0 || x === N - 1) return x; - - var rb = 0; - for (var i = 0; i < l; i++) { - rb |= (x & 1) << (l - i - 1); - x >>= 1; - } - - return rb; - }; - - // Performs "tweedling" phase, therefore 'emulating' - // behaviour of the recursive algorithm - FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) { - rtws[i] = rws[rbt[i]]; - itws[i] = iws[rbt[i]]; - } - }; - - FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); - - for (var s = 1; s < N; s <<= 1) { - var l = s << 1; - - var rtwdf = Math.cos(2 * Math.PI / l); - var itwdf = Math.sin(2 * Math.PI / l); - - for (var p = 0; p < N; p += l) { - var rtwdf_ = rtwdf; - var itwdf_ = itwdf; - - for (var j = 0; j < s; j++) { - var re = rtws[p + j]; - var ie = itws[p + j]; - - var ro = rtws[p + j + s]; - var io = itws[p + j + s]; - - var rx = rtwdf_ * ro - itwdf_ * io; - - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; - - rtws[p + j] = re + ro; - itws[p + j] = ie + io; - - rtws[p + j + s] = re - ro; - itws[p + j + s] = ie - io; - - /* jshint maxdepth : false */ - if (j !== l) { - rx = rtwdf * rtwdf_ - itwdf * itwdf_; - - itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; - rtwdf_ = rx; - } - } - } - } - }; - - FFTM.prototype.guessLen13b = function guessLen13b (n, m) { - var N = Math.max(m, n) | 1; - var odd = N & 1; - var i = 0; - for (N = N / 2 | 0; N; N = N >>> 1) { - i++; - } - - return 1 << i + 1 + odd; - }; - - FFTM.prototype.conjugate = function conjugate (rws, iws, N) { - if (N <= 1) return; - - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; - - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; - - t = iws[i]; - - iws[i] = -iws[N - i - 1]; - iws[N - i - 1] = -t; - } - }; - - FFTM.prototype.normalize13b = function normalize13b (ws, N) { - var carry = 0; - for (var i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + - Math.round(ws[2 * i] / N) + - carry; - - ws[i] = w & 0x3ffffff; - - if (w < 0x4000000) { - carry = 0; - } else { - carry = w / 0x4000000 | 0; - } - } - - return ws; - }; - - FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { - var carry = 0; - for (var i = 0; i < len; i++) { - carry = carry + (ws[i] | 0); - - rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; - rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; - } - - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 0; - } - - assert(carry === 0); - assert((carry & ~0x1fff) === 0); - }; - - FFTM.prototype.stub = function stub (N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; - } - - return ph; - }; - - FFTM.prototype.mulp = function mulp (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); - - var rbt = this.makeRBT(N); - - var _ = this.stub(N); - - var rws = new Array(N); - var rwst = new Array(N); - var iwst = new Array(N); - - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); - - var rmws = out.words; - rmws.length = N; - - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); - - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); - - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; - rwst[i] = rx; - } - - this.conjugate(rwst, iwst, N); - this.transform(rwst, iwst, rmws, _, N, rbt); - this.conjugate(rmws, _, N); - this.normalize13b(rmws, N); - - out.negative = x.negative ^ y.negative; - out.length = x.length + y.length; - return out.strip(); - }; - - // Multiply `this` by `num` - BN.prototype.mul = function mul (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); - }; - - // Multiply employing FFT - BN.prototype.mulf = function mulf (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return jumboMulTo(this, num, out); - }; - - // In-place Multiplication - BN.prototype.imul = function imul (num) { - return this.clone().mulTo(num, this); - }; - - BN.prototype.imuln = function imuln (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - - // Carry - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += (w / 0x4000000) | 0; - // NOTE: lo is 27bit maximum - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } - - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - - return this; - }; - - BN.prototype.muln = function muln (num) { - return this.clone().imuln(num); - }; - - // `this` * `this` - BN.prototype.sqr = function sqr () { - return this.mul(this); - }; - - // `this` * `this` in-place - BN.prototype.isqr = function isqr () { - return this.imul(this.clone()); - }; - - // Math.pow(`this`, `num`) - BN.prototype.pow = function pow (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); - - // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; - } - - if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { - if (w[i] === 0) continue; - - res = res.mul(q); - } - } - - return res; - }; - - // Shift-left in-place - BN.prototype.iushln = function iushln (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); - var i; - - if (r !== 0) { - var carry = 0; - - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = ((this.words[i] | 0) - newCarry) << r; - this.words[i] = c | carry; - carry = newCarry >>> (26 - r); - } - - if (carry) { - this.words[i] = carry; - this.length++; - } - } - - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } - - for (i = 0; i < s; i++) { - this.words[i] = 0; - } - - this.length += s; - } - - return this.strip(); - }; - - BN.prototype.ishln = function ishln (bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; - - // Shift-right in-place - // NOTE: `hint` is a lowest bit before trailing zeroes - // NOTE: if `extended` is present - it will be filled with destroyed bits - BN.prototype.iushrn = function iushrn (bits, hint, extended) { - assert(typeof bits === 'number' && bits >= 0); - var h; - if (hint) { - h = (hint - (hint % 26)) / 26; - } else { - h = 0; - } - - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; - - h -= s; - h = Math.max(0, h); - - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; - } - - if (s === 0) { - // No-op, we should not move anything at all - } else if (this.length > s) { - this.length -= s; - for (i = 0; i < this.length; i++) { - this.words[i] = this.words[i + s]; - } - } else { - this.words[0] = 0; - this.length = 1; - } - - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - this.words[i] = (carry << (26 - r)) | (word >>> r); - carry = word & mask; - } - - // Push carried bits as a mask - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } - - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } - - return this.strip(); - }; - - BN.prototype.ishrn = function ishrn (bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; - - // Shift-left - BN.prototype.shln = function shln (bits) { - return this.clone().ishln(bits); - }; - - BN.prototype.ushln = function ushln (bits) { - return this.clone().iushln(bits); - }; - - // Shift-right - BN.prototype.shrn = function shrn (bits) { - return this.clone().ishrn(bits); - }; - - BN.prototype.ushrn = function ushrn (bits) { - return this.clone().iushrn(bits); - }; - - // Test if n bit is set - BN.prototype.testn = function testn (bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) return false; - - // Check bit and return - var w = this.words[s]; - - return !!(w & q); - }; - - // Return only lowers bits of number (in-place) - BN.prototype.imaskn = function imaskn (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - - assert(this.negative === 0, 'imaskn works only with positive numbers'); - - if (this.length <= s) { - return this; - } - - if (r !== 0) { - s++; - } - this.length = Math.min(s, this.length); - - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; - } - - return this.strip(); - }; - - // Return only lowers bits of number - BN.prototype.maskn = function maskn (bits) { - return this.clone().imaskn(bits); - }; - - // Add plain number `num` to `this` - BN.prototype.iaddn = function iaddn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.isubn(-num); - - // Possible sign change - if (this.negative !== 0) { - if (this.length === 1 && (this.words[0] | 0) < num) { - this.words[0] = num - (this.words[0] | 0); - this.negative = 0; - return this; - } - - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; - } - - // Add without checks - return this._iaddn(num); - }; - - BN.prototype._iaddn = function _iaddn (num) { - this.words[0] += num; - - // Carry - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; - if (i === this.length - 1) { - this.words[i + 1] = 1; - } else { - this.words[i + 1]++; - } - } - this.length = Math.max(this.length, i + 1); - - return this; - }; - - // Subtract plain number `num` from `this` - BN.prototype.isubn = function isubn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.iaddn(-num); - - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); - this.negative = 1; - return this; - } - - this.words[0] -= num; - - if (this.length === 1 && this.words[0] < 0) { - this.words[0] = -this.words[0]; - this.negative = 1; - } else { - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } - } - - return this.strip(); - }; - - BN.prototype.addn = function addn (num) { - return this.clone().iaddn(num); - }; - - BN.prototype.subn = function subn (num) { - return this.clone().isubn(num); - }; - - BN.prototype.iabs = function iabs () { - this.negative = 0; - - return this; - }; - - BN.prototype.abs = function abs () { - return this.clone().iabs(); - }; - - BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { - var len = num.length + shift; - var i; - - this._expand(len); - - var w; - var carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - w -= right & 0x3ffffff; - carry = (w >> 26) - ((right / 0x4000000) | 0); - this.words[i + shift] = w & 0x3ffffff; - } - for (; i < this.length - shift; i++) { - w = (this.words[i + shift] | 0) + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; - } - - if (carry === 0) return this.strip(); - - // Subtraction overflow - assert(carry === -1); - carry = 0; - for (i = 0; i < this.length; i++) { - w = -(this.words[i] | 0) + carry; - carry = w >> 26; - this.words[i] = w & 0x3ffffff; - } - this.negative = 1; - - return this.strip(); - }; - - BN.prototype._wordDiv = function _wordDiv (num, mode) { - var shift = this.length - num.length; - - var a = this.clone(); - var b = num; - - // Normalize - var bhi = b.words[b.length - 1] | 0; - var bhiBits = this._countBits(bhi); - shift = 26 - bhiBits; - if (shift !== 0) { - b = b.ushln(shift); - a.iushln(shift); - bhi = b.words[b.length - 1] | 0; - } - - // Initialize quotient - var m = a.length - b.length; - var q; - - if (mode !== 'mod') { - q = new BN(null); - q.length = m + 1; - q.words = new Array(q.length); - for (var i = 0; i < q.length; i++) { - q.words[i] = 0; - } - } - - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (diff.negative === 0) { - a = diff; - if (q) { - q.words[m] = 1; - } - } - - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 0x4000000 + - (a.words[b.length + j - 1] | 0); - - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); - - a._ishlnsubmul(b, qj, j); - while (a.negative !== 0) { - qj--; - a.negative = 0; - a._ishlnsubmul(b, 1, j); - if (!a.isZero()) { - a.negative ^= 1; - } - } - if (q) { - q.words[j] = qj; - } - } - if (q) { - q.strip(); - } - a.strip(); - - // Denormalize - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); - } - - return { - div: q || null, - mod: a - }; - }; - - // NOTE: 1) `mode` can be set to `mod` to request mod only, - // to `div` to request div only, or be absent to - // request both div & mod - // 2) `positive` is true if unsigned mod is requested - BN.prototype.divmod = function divmod (num, mode, positive) { - assert(!num.isZero()); - - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(0) - }; - } - - var div, mod, res; - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } - - return { - div: div, - mod: mod - }; - } - - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } - - return { - div: div, - mod: res.mod - }; - } - - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } - } - - return { - div: res.div, - mod: mod - }; - } - - // Both numbers are positive at this point - - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; - } - - // Very short reduction - if (num.length === 1) { - if (mode === 'div') { - return { - div: this.divn(num.words[0]), - mod: null - }; - } - - if (mode === 'mod') { - return { - div: null, - mod: new BN(this.modn(num.words[0])) - }; - } - - return { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])) - }; - } - - return this._wordDiv(num, mode); - }; - - // Find `this` / `num` - BN.prototype.div = function div (num) { - return this.divmod(num, 'div', false).div; - }; - - // Find `this` % `num` - BN.prototype.mod = function mod (num) { - return this.divmod(num, 'mod', false).mod; - }; - - BN.prototype.umod = function umod (num) { - return this.divmod(num, 'mod', true).mod; - }; - - // Find Round(`this` / `num`) - BN.prototype.divRound = function divRound (num) { - var dm = this.divmod(num); - - // Fast case - exact division - if (dm.mod.isZero()) return dm.div; - - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; - - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); - - // Round down - if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; - - // Round up - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); - }; - - BN.prototype.modn = function modn (num) { - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; - - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) { - acc = (p * acc + (this.words[i] | 0)) % num; - } - - return acc; - }; - - // In-place division by number - BN.prototype.idivn = function idivn (num) { - assert(num <= 0x3ffffff); - - var carry = 0; - for (var i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 0x4000000; - this.words[i] = (w / num) | 0; - carry = w % num; - } - - return this.strip(); - }; - - BN.prototype.divn = function divn (num) { - return this.clone().idivn(num); - }; - - BN.prototype.egcd = function egcd (p) { - assert(p.negative === 0); - assert(!p.isZero()); - - var x = this; - var y = p.clone(); - - if (x.negative !== 0) { - x = x.umod(p); - } else { - x = x.clone(); - } - - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); - - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); - - var g = 0; - - while (x.isEven() && y.isEven()) { - x.iushrn(1); - y.iushrn(1); - ++g; - } - - var yp = y.clone(); - var xp = x.clone(); - - while (!x.isZero()) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - x.iushrn(i); - while (i-- > 0) { - if (A.isOdd() || B.isOdd()) { - A.iadd(yp); - B.isub(xp); - } - - A.iushrn(1); - B.iushrn(1); - } - } - - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - y.iushrn(j); - while (j-- > 0) { - if (C.isOdd() || D.isOdd()) { - C.iadd(yp); - D.isub(xp); - } - - C.iushrn(1); - D.iushrn(1); - } - } - - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); - } else { - y.isub(x); - C.isub(A); - D.isub(B); - } - } - - return { - a: C, - b: D, - gcd: y.iushln(g) - }; - }; - - // This is reduced incarnation of the binary EEA - // above, designated to invert members of the - // _prime_ fields F(p) at a maximal speed - BN.prototype._invmp = function _invmp (p) { - assert(p.negative === 0); - assert(!p.isZero()); - - var a = this; - var b = p.clone(); - - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); - } - - var x1 = new BN(1); - var x2 = new BN(0); - - var delta = b.clone(); - - while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - a.iushrn(i); - while (i-- > 0) { - if (x1.isOdd()) { - x1.iadd(delta); - } - - x1.iushrn(1); - } - } - - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - b.iushrn(j); - while (j-- > 0) { - if (x2.isOdd()) { - x2.iadd(delta); - } - - x2.iushrn(1); - } - } - - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } - } - - var res; - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; - } - - if (res.cmpn(0) < 0) { - res.iadd(p); - } - - return res; - }; - - BN.prototype.gcd = function gcd (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; - - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); - } - - do { - while (a.isEven()) { - a.iushrn(1); - } - while (b.isEven()) { - b.iushrn(1); - } - - var r = a.cmp(b); - if (r < 0) { - // Swap `a` and `b` to make `a` always bigger than `b` - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; - } - - a.isub(b); - } while (true); - - return b.iushln(shift); - }; - - // Invert number in the field F(num) - BN.prototype.invm = function invm (num) { - return this.egcd(num).a.umod(num); - }; - - BN.prototype.isEven = function isEven () { - return (this.words[0] & 1) === 0; - }; - - BN.prototype.isOdd = function isOdd () { - return (this.words[0] & 1) === 1; - }; - - // And first word and num - BN.prototype.andln = function andln (num) { - return this.words[0] & num; - }; - - // Increment at the bit position in-line - BN.prototype.bincn = function bincn (bit) { - assert(typeof bit === 'number'); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - this._expand(s + 1); - this.words[s] |= q; - return this; - } - - // Add bit and propagate, if needed - var carry = q; - for (var i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - w += carry; - carry = w >>> 26; - w &= 0x3ffffff; - this.words[i] = w; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - return this; - }; - - BN.prototype.isZero = function isZero () { - return this.length === 1 && this.words[0] === 0; - }; - - BN.prototype.cmpn = function cmpn (num) { - var negative = num < 0; - - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; - - this.strip(); - - var res; - if (this.length > 1) { - res = 1; - } else { - if (negative) { - num = -num; - } - - assert(num <= 0x3ffffff, 'Number is too big'); - - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - if (this.negative !== 0) return -res | 0; - return res; - }; - - // Compare two numbers and return: - // 1 - if `this` > `num` - // 0 - if `this` == `num` - // -1 - if `this` < `num` - BN.prototype.cmp = function cmp (num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; - - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; - }; - - // Unsigned comparison - BN.prototype.ucmp = function ucmp (num) { - // At this point both numbers have the same sign - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0; - var b = num.words[i] | 0; - - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } - break; - } - return res; - }; - - BN.prototype.gtn = function gtn (num) { - return this.cmpn(num) === 1; - }; - - BN.prototype.gt = function gt (num) { - return this.cmp(num) === 1; - }; - - BN.prototype.gten = function gten (num) { - return this.cmpn(num) >= 0; - }; - - BN.prototype.gte = function gte (num) { - return this.cmp(num) >= 0; - }; - - BN.prototype.ltn = function ltn (num) { - return this.cmpn(num) === -1; - }; - - BN.prototype.lt = function lt (num) { - return this.cmp(num) === -1; - }; - - BN.prototype.lten = function lten (num) { - return this.cmpn(num) <= 0; - }; - - BN.prototype.lte = function lte (num) { - return this.cmp(num) <= 0; - }; - - BN.prototype.eqn = function eqn (num) { - return this.cmpn(num) === 0; - }; - - BN.prototype.eq = function eq (num) { - return this.cmp(num) === 0; - }; - - // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // - BN.red = function red (num) { - return new Red(num); - }; - - BN.prototype.toRed = function toRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - assert(this.negative === 0, 'red works only with positives'); - return ctx.convertTo(this)._forceRed(ctx); - }; - - BN.prototype.fromRed = function fromRed () { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); - }; - - BN.prototype._forceRed = function _forceRed (ctx) { - this.red = ctx; - return this; - }; - - BN.prototype.forceRed = function forceRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); - }; - - BN.prototype.redAdd = function redAdd (num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); - }; - - BN.prototype.redIAdd = function redIAdd (num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); - }; - - BN.prototype.redSub = function redSub (num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; - - BN.prototype.redISub = function redISub (num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; - - BN.prototype.redShl = function redShl (num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; - - BN.prototype.redMul = function redMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.mul(this, num); - }; - - BN.prototype.redIMul = function redIMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.imul(this, num); - }; - - BN.prototype.redSqr = function redSqr () { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); - }; - - BN.prototype.redISqr = function redISqr () { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); - }; - - // Square root over p - BN.prototype.redSqrt = function redSqrt () { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); - return this.red.sqrt(this); - }; - - BN.prototype.redInvm = function redInvm () { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); - }; - - // Return negative clone of `this` % `red modulo` - BN.prototype.redNeg = function redNeg () { - assert(this.red, 'redNeg works only with red numbers'); - this.red._verify1(this); - return this.red.neg(this); - }; - - BN.prototype.redPow = function redPow (num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); - }; - - // Prime numbers with efficient reduction - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; - - // Pseudo-Mersenne prime - function MPrime (name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).iushln(this.n).isub(this.p); - - this.tmp = this._tmp(); - } - - MPrime.prototype._tmp = function _tmp () { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; - }; - - MPrime.prototype.ireduce = function ireduce (num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; - - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); - - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); - } else { - if (r.strip !== undefined) { - // r is BN v4 instance - r.strip(); - } else { - // r is BN v5 instance - r._strip(); - } - } - - return r; - }; - - MPrime.prototype.split = function split (input, out) { - input.iushrn(this.n, 0, out); - }; - - MPrime.prototype.imulK = function imulK (num) { - return num.imul(this.k); - }; - - function K256 () { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); - } - inherits(K256, MPrime); - - K256.prototype.split = function split (input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; - - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; - } - output.length = outLen; - - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; - } - - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; - - for (i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); - prev = next; - } - prev >>>= 22; - input.words[i - 10] = prev; - if (prev === 0 && input.length > 10) { - input.length -= 10; - } else { - input.length -= 9; - } - }; - - K256.prototype.imulK = function imulK (num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; - - // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 - var lo = 0; - for (var i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - lo += w * 0x3d1; - num.words[i] = lo & 0x3ffffff; - lo = w * 0x40 + ((lo / 0x4000000) | 0); - } - - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) { - num.length--; - } - } - return num; - }; - - function P224 () { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); - } - inherits(P224, MPrime); - - function P192 () { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); - } - inherits(P192, MPrime); - - function P25519 () { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); - } - inherits(P25519, MPrime); - - P25519.prototype.imulK = function imulK (num) { - // K = 0x13 - var carry = 0; - for (var i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; - - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; - } - return num; - }; - - // Exported mostly for testing purposes, use plain name instead - BN._prime = function prime (name) { - // Cached version of prime - if (primes[name]) return primes[name]; - - var prime; - if (name === 'k256') { - prime = new K256(); - } else if (name === 'p224') { - prime = new P224(); - } else if (name === 'p192') { - prime = new P192(); - } else if (name === 'p25519') { - prime = new P25519(); - } else { - throw new Error('Unknown prime ' + name); - } - primes[name] = prime; - - return prime; - }; - - // - // Base reduction engine - // - function Red (m) { - if (typeof m === 'string') { - var prime = BN._prime(m); - this.m = prime.p; - this.prime = prime; - } else { - assert(m.gtn(1), 'modulus must be greater than 1'); - this.m = m; - this.prime = null; - } - } - - Red.prototype._verify1 = function _verify1 (a) { - assert(a.negative === 0, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); - }; - - Red.prototype._verify2 = function _verify2 (a, b) { - assert((a.negative | b.negative) === 0, 'red works only with positives'); - assert(a.red && a.red === b.red, - 'red works only with red numbers'); - }; - - Red.prototype.imod = function imod (a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - return a.umod(this.m)._forceRed(this); - }; - - Red.prototype.neg = function neg (a) { - if (a.isZero()) { - return a.clone(); - } - - return this.m.sub(a)._forceRed(this); - }; - - Red.prototype.add = function add (a, b) { - this._verify2(a, b); - - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res._forceRed(this); - }; - - Red.prototype.iadd = function iadd (a, b) { - this._verify2(a, b); - - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res; - }; - - Red.prototype.sub = function sub (a, b) { - this._verify2(a, b); - - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res._forceRed(this); - }; - - Red.prototype.isub = function isub (a, b) { - this._verify2(a, b); - - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res; - }; - - Red.prototype.shl = function shl (a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; - - Red.prototype.imul = function imul (a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); - }; - - Red.prototype.mul = function mul (a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); - }; - - Red.prototype.isqr = function isqr (a) { - return this.imul(a, a.clone()); - }; - - Red.prototype.sqr = function sqr (a) { - return this.mul(a, a); - }; - - Red.prototype.sqrt = function sqrt (a) { - if (a.isZero()) return a.clone(); - - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); - - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } - - // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) - var q = this.m.subn(1); - var s = 0; - while (!q.isZero() && q.andln(1) === 0) { - s++; - q.iushrn(1); - } - assert(!q.isZero()); - - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); - - // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. - var lpow = this.m.subn(1).iushrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); - - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); - } - - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).iushrn(1)); - var t = this.pow(a, q); - var m = s; - while (t.cmp(one) !== 0) { - var tmp = t; - for (var i = 0; tmp.cmp(one) !== 0; i++) { - tmp = tmp.redSqr(); - } - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; - } - - return r; - }; - - Red.prototype.invm = function invm (a) { - var inv = a._invmp(this.m); - if (inv.negative !== 0) { - inv.negative = 0; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); - } - }; - - Red.prototype.pow = function pow (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); - - var windowSize = 4; - var wnd = new Array(1 << windowSize); - wnd[0] = new BN(1).toRed(this); - wnd[1] = a; - for (var i = 2; i < wnd.length; i++) { - wnd[i] = this.mul(wnd[i - 1], a); - } - - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; - } - - for (i = num.length - 1; i >= 0; i--) { - var word = num.words[i]; - for (var j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if (res !== wnd[0]) { - res = this.sqr(res); - } - - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } - - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; - - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } - start = 26; - } - - return res; - }; - - Red.prototype.convertTo = function convertTo (num) { - var r = num.umod(this.m); - - return r === num ? r.clone() : r; - }; - - Red.prototype.convertFrom = function convertFrom (num) { - var res = num.clone(); - res.red = null; - return res; - }; - - // - // Montgomery method engine - // - - BN.mont = function mont (num) { - return new Mont(num); - }; - - function Mont (m) { - Red.call(this, m); - - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - (this.shift % 26); - } - - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); - - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv = this.minv.umod(this.r); - this.minv = this.r.sub(this.minv); - } - inherits(Mont, Red); - - Mont.prototype.convertTo = function convertTo (num) { - return this.imod(num.ushln(this.shift)); - }; - - Mont.prototype.convertFrom = function convertFrom (num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; - }; - - Mont.prototype.imul = function imul (a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; - } - - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - - return res._forceRed(this); - }; - - Mont.prototype.mul = function mul (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - - return res._forceRed(this); - }; - - Mont.prototype.invm = function invm (a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }; -})(typeof module === 'undefined' || module, this); - -},{"buffer":20}],19:[function(require,module,exports){ -var r; - -module.exports = function rand(len) { - if (!r) - r = new Rand(null); - - return r.generate(len); -}; - -function Rand(rand) { - this.rand = rand; -} -module.exports.Rand = Rand; - -Rand.prototype.generate = function generate(len) { - return this._rand(len); -}; - -// Emulate crypto API using randy -Rand.prototype._rand = function _rand(n) { - if (this.rand.getBytes) - return this.rand.getBytes(n); - - var res = new Uint8Array(n); - for (var i = 0; i < res.length; i++) - res[i] = this.rand.getByte(); - return res; -}; - -if (typeof self === 'object') { - if (self.crypto && self.crypto.getRandomValues) { - // Modern browsers - Rand.prototype._rand = function _rand(n) { - var arr = new Uint8Array(n); - self.crypto.getRandomValues(arr); - return arr; - }; - } else if (self.msCrypto && self.msCrypto.getRandomValues) { - // IE - Rand.prototype._rand = function _rand(n) { - var arr = new Uint8Array(n); - self.msCrypto.getRandomValues(arr); - return arr; - }; - - // Safari's WebWorkers do not have `crypto` - } else if (typeof window === 'object') { - // Old junk - Rand.prototype._rand = function() { - throw new Error('Not implemented yet'); - }; - } -} else { - // Node.js or Web worker with no crypto support - try { - var crypto = require('crypto'); - if (typeof crypto.randomBytes !== 'function') - throw new Error('Not supported'); - - Rand.prototype._rand = function _rand(n) { - return crypto.randomBytes(n); - }; - } catch (e) { - } -} - -},{"crypto":20}],20:[function(require,module,exports){ - -},{}],21:[function(require,module,exports){ -// based on the aes implimentation in triple sec -// https://github.com/keybase/triplesec -// which is in turn based on the one from crypto-js -// https://code.google.com/p/crypto-js/ - -var Buffer = require('safe-buffer').Buffer - -function asUInt32Array (buf) { - if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) - - var len = (buf.length / 4) | 0 - var out = new Array(len) - - for (var i = 0; i < len; i++) { - out[i] = buf.readUInt32BE(i * 4) - } - - return out -} - -function scrubVec (v) { - for (var i = 0; i < v.length; v++) { - v[i] = 0 - } -} - -function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) { - var SUB_MIX0 = SUB_MIX[0] - var SUB_MIX1 = SUB_MIX[1] - var SUB_MIX2 = SUB_MIX[2] - var SUB_MIX3 = SUB_MIX[3] - - var s0 = M[0] ^ keySchedule[0] - var s1 = M[1] ^ keySchedule[1] - var s2 = M[2] ^ keySchedule[2] - var s3 = M[3] ^ keySchedule[3] - var t0, t1, t2, t3 - var ksRow = 4 - - for (var round = 1; round < nRounds; round++) { - t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++] - t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++] - t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++] - t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++] - s0 = t0 - s1 = t1 - s2 = t2 - s3 = t3 - } - - t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++] - t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++] - t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++] - t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++] - t0 = t0 >>> 0 - t1 = t1 >>> 0 - t2 = t2 >>> 0 - t3 = t3 >>> 0 - - return [t0, t1, t2, t3] -} - -// AES constants -var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36] -var G = (function () { - // Compute double table - var d = new Array(256) - for (var j = 0; j < 256; j++) { - if (j < 128) { - d[j] = j << 1 - } else { - d[j] = (j << 1) ^ 0x11b - } - } - - var SBOX = [] - var INV_SBOX = [] - var SUB_MIX = [[], [], [], []] - var INV_SUB_MIX = [[], [], [], []] - - // Walk GF(2^8) - var x = 0 - var xi = 0 - for (var i = 0; i < 256; ++i) { - // Compute sbox - var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4) - sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63 - SBOX[x] = sx - INV_SBOX[sx] = x - - // Compute multiplication - var x2 = d[x] - var x4 = d[x2] - var x8 = d[x4] - - // Compute sub bytes, mix columns tables - var t = (d[sx] * 0x101) ^ (sx * 0x1010100) - SUB_MIX[0][x] = (t << 24) | (t >>> 8) - SUB_MIX[1][x] = (t << 16) | (t >>> 16) - SUB_MIX[2][x] = (t << 8) | (t >>> 24) - SUB_MIX[3][x] = t - - // Compute inv sub bytes, inv mix columns tables - t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100) - INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8) - INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16) - INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24) - INV_SUB_MIX[3][sx] = t - - if (x === 0) { - x = xi = 1 - } else { - x = x2 ^ d[d[d[x8 ^ x2]]] - xi ^= d[d[xi]] - } - } - - return { - SBOX: SBOX, - INV_SBOX: INV_SBOX, - SUB_MIX: SUB_MIX, - INV_SUB_MIX: INV_SUB_MIX - } -})() - -function AES (key) { - this._key = asUInt32Array(key) - this._reset() -} - -AES.blockSize = 4 * 4 -AES.keySize = 256 / 8 -AES.prototype.blockSize = AES.blockSize -AES.prototype.keySize = AES.keySize -AES.prototype._reset = function () { - var keyWords = this._key - var keySize = keyWords.length - var nRounds = keySize + 6 - var ksRows = (nRounds + 1) * 4 - - var keySchedule = [] - for (var k = 0; k < keySize; k++) { - keySchedule[k] = keyWords[k] - } - - for (k = keySize; k < ksRows; k++) { - var t = keySchedule[k - 1] - - if (k % keySize === 0) { - t = (t << 8) | (t >>> 24) - t = - (G.SBOX[t >>> 24] << 24) | - (G.SBOX[(t >>> 16) & 0xff] << 16) | - (G.SBOX[(t >>> 8) & 0xff] << 8) | - (G.SBOX[t & 0xff]) - - t ^= RCON[(k / keySize) | 0] << 24 - } else if (keySize > 6 && k % keySize === 4) { - t = - (G.SBOX[t >>> 24] << 24) | - (G.SBOX[(t >>> 16) & 0xff] << 16) | - (G.SBOX[(t >>> 8) & 0xff] << 8) | - (G.SBOX[t & 0xff]) - } - - keySchedule[k] = keySchedule[k - keySize] ^ t - } - - var invKeySchedule = [] - for (var ik = 0; ik < ksRows; ik++) { - var ksR = ksRows - ik - var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)] - - if (ik < 4 || ksR <= 4) { - invKeySchedule[ik] = tt - } else { - invKeySchedule[ik] = - G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^ - G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^ - G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^ - G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]] - } - } - - this._nRounds = nRounds - this._keySchedule = keySchedule - this._invKeySchedule = invKeySchedule -} - -AES.prototype.encryptBlockRaw = function (M) { - M = asUInt32Array(M) - return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds) -} - -AES.prototype.encryptBlock = function (M) { - var out = this.encryptBlockRaw(M) - var buf = Buffer.allocUnsafe(16) - buf.writeUInt32BE(out[0], 0) - buf.writeUInt32BE(out[1], 4) - buf.writeUInt32BE(out[2], 8) - buf.writeUInt32BE(out[3], 12) - return buf -} - -AES.prototype.decryptBlock = function (M) { - M = asUInt32Array(M) - - // swap - var m1 = M[1] - M[1] = M[3] - M[3] = m1 - - var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds) - var buf = Buffer.allocUnsafe(16) - buf.writeUInt32BE(out[0], 0) - buf.writeUInt32BE(out[3], 4) - buf.writeUInt32BE(out[2], 8) - buf.writeUInt32BE(out[1], 12) - return buf -} - -AES.prototype.scrub = function () { - scrubVec(this._keySchedule) - scrubVec(this._invKeySchedule) - scrubVec(this._key) -} - -module.exports.AES = AES - -},{"safe-buffer":250}],22:[function(require,module,exports){ -var aes = require('./aes') -var Buffer = require('safe-buffer').Buffer -var Transform = require('cipher-base') -var inherits = require('inherits') -var GHASH = require('./ghash') -var xor = require('buffer-xor') -var incr32 = require('./incr32') - -function xorTest (a, b) { - var out = 0 - if (a.length !== b.length) out++ - - var len = Math.min(a.length, b.length) - for (var i = 0; i < len; ++i) { - out += (a[i] ^ b[i]) - } - - return out -} - -function calcIv (self, iv, ck) { - if (iv.length === 12) { - self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])]) - return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])]) - } - var ghash = new GHASH(ck) - var len = iv.length - var toPad = len % 16 - ghash.update(iv) - if (toPad) { - toPad = 16 - toPad - ghash.update(Buffer.alloc(toPad, 0)) - } - ghash.update(Buffer.alloc(8, 0)) - var ivBits = len * 8 - var tail = Buffer.alloc(8) - tail.writeUIntBE(ivBits, 0, 8) - ghash.update(tail) - self._finID = ghash.state - var out = Buffer.from(self._finID) - incr32(out) - return out -} -function StreamCipher (mode, key, iv, decrypt) { - Transform.call(this) - - var h = Buffer.alloc(4, 0) - - this._cipher = new aes.AES(key) - var ck = this._cipher.encryptBlock(h) - this._ghash = new GHASH(ck) - iv = calcIv(this, iv, ck) - - this._prev = Buffer.from(iv) - this._cache = Buffer.allocUnsafe(0) - this._secCache = Buffer.allocUnsafe(0) - this._decrypt = decrypt - this._alen = 0 - this._len = 0 - this._mode = mode - - this._authTag = null - this._called = false -} - -inherits(StreamCipher, Transform) - -StreamCipher.prototype._update = function (chunk) { - if (!this._called && this._alen) { - var rump = 16 - (this._alen % 16) - if (rump < 16) { - rump = Buffer.alloc(rump, 0) - this._ghash.update(rump) - } - } - - this._called = true - var out = this._mode.encrypt(this, chunk) - if (this._decrypt) { - this._ghash.update(chunk) - } else { - this._ghash.update(out) - } - this._len += chunk.length - return out -} - -StreamCipher.prototype._final = function () { - if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data') - - var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)) - if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data') - - this._authTag = tag - this._cipher.scrub() -} - -StreamCipher.prototype.getAuthTag = function getAuthTag () { - if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state') - - return this._authTag -} - -StreamCipher.prototype.setAuthTag = function setAuthTag (tag) { - if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state') - - this._authTag = tag -} - -StreamCipher.prototype.setAAD = function setAAD (buf) { - if (this._called) throw new Error('Attempting to set AAD in unsupported state') - - this._ghash.update(buf) - this._alen += buf.length -} - -module.exports = StreamCipher - -},{"./aes":21,"./ghash":26,"./incr32":27,"buffer-xor":67,"cipher-base":71,"inherits":146,"safe-buffer":250}],23:[function(require,module,exports){ -var ciphers = require('./encrypter') -var deciphers = require('./decrypter') -var modes = require('./modes/list.json') - -function getCiphers () { - return Object.keys(modes) -} - -exports.createCipher = exports.Cipher = ciphers.createCipher -exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv -exports.createDecipher = exports.Decipher = deciphers.createDecipher -exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv -exports.listCiphers = exports.getCiphers = getCiphers - -},{"./decrypter":24,"./encrypter":25,"./modes/list.json":35}],24:[function(require,module,exports){ -var AuthCipher = require('./authCipher') -var Buffer = require('safe-buffer').Buffer -var MODES = require('./modes') -var StreamCipher = require('./streamCipher') -var Transform = require('cipher-base') -var aes = require('./aes') -var ebtk = require('evp_bytestokey') -var inherits = require('inherits') - -function Decipher (mode, key, iv) { - Transform.call(this) - - this._cache = new Splitter() - this._last = void 0 - this._cipher = new aes.AES(key) - this._prev = Buffer.from(iv) - this._mode = mode - this._autopadding = true -} - -inherits(Decipher, Transform) - -Decipher.prototype._update = function (data) { - this._cache.add(data) - var chunk - var thing - var out = [] - while ((chunk = this._cache.get(this._autopadding))) { - thing = this._mode.decrypt(this, chunk) - out.push(thing) - } - return Buffer.concat(out) -} - -Decipher.prototype._final = function () { - var chunk = this._cache.flush() - if (this._autopadding) { - return unpad(this._mode.decrypt(this, chunk)) - } else if (chunk) { - throw new Error('data not multiple of block length') - } -} - -Decipher.prototype.setAutoPadding = function (setTo) { - this._autopadding = !!setTo - return this -} - -function Splitter () { - this.cache = Buffer.allocUnsafe(0) -} - -Splitter.prototype.add = function (data) { - this.cache = Buffer.concat([this.cache, data]) -} - -Splitter.prototype.get = function (autoPadding) { - var out - if (autoPadding) { - if (this.cache.length > 16) { - out = this.cache.slice(0, 16) - this.cache = this.cache.slice(16) - return out - } - } else { - if (this.cache.length >= 16) { - out = this.cache.slice(0, 16) - this.cache = this.cache.slice(16) - return out - } - } - - return null -} - -Splitter.prototype.flush = function () { - if (this.cache.length) return this.cache -} - -function unpad (last) { - var padded = last[15] - if (padded < 1 || padded > 16) { - throw new Error('unable to decrypt data') - } - var i = -1 - while (++i < padded) { - if (last[(i + (16 - padded))] !== padded) { - throw new Error('unable to decrypt data') - } - } - if (padded === 16) return - - return last.slice(0, 16 - padded) -} - -function createDecipheriv (suite, password, iv) { - var config = MODES[suite.toLowerCase()] - if (!config) throw new TypeError('invalid suite type') - - if (typeof iv === 'string') iv = Buffer.from(iv) - if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length) - - if (typeof password === 'string') password = Buffer.from(password) - if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length) - - if (config.type === 'stream') { - return new StreamCipher(config.module, password, iv, true) - } else if (config.type === 'auth') { - return new AuthCipher(config.module, password, iv, true) - } - - return new Decipher(config.module, password, iv) -} - -function createDecipher (suite, password) { - var config = MODES[suite.toLowerCase()] - if (!config) throw new TypeError('invalid suite type') - - var keys = ebtk(password, false, config.key, config.iv) - return createDecipheriv(suite, keys.key, keys.iv) -} - -exports.createDecipher = createDecipher -exports.createDecipheriv = createDecipheriv - -},{"./aes":21,"./authCipher":22,"./modes":34,"./streamCipher":37,"cipher-base":71,"evp_bytestokey":106,"inherits":146,"safe-buffer":250}],25:[function(require,module,exports){ -var MODES = require('./modes') -var AuthCipher = require('./authCipher') -var Buffer = require('safe-buffer').Buffer -var StreamCipher = require('./streamCipher') -var Transform = require('cipher-base') -var aes = require('./aes') -var ebtk = require('evp_bytestokey') -var inherits = require('inherits') - -function Cipher (mode, key, iv) { - Transform.call(this) - - this._cache = new Splitter() - this._cipher = new aes.AES(key) - this._prev = Buffer.from(iv) - this._mode = mode - this._autopadding = true -} - -inherits(Cipher, Transform) - -Cipher.prototype._update = function (data) { - this._cache.add(data) - var chunk - var thing - var out = [] - - while ((chunk = this._cache.get())) { - thing = this._mode.encrypt(this, chunk) - out.push(thing) - } - - return Buffer.concat(out) -} - -var PADDING = Buffer.alloc(16, 0x10) - -Cipher.prototype._final = function () { - var chunk = this._cache.flush() - if (this._autopadding) { - chunk = this._mode.encrypt(this, chunk) - this._cipher.scrub() - return chunk - } - - if (!chunk.equals(PADDING)) { - this._cipher.scrub() - throw new Error('data not multiple of block length') - } -} - -Cipher.prototype.setAutoPadding = function (setTo) { - this._autopadding = !!setTo - return this -} - -function Splitter () { - this.cache = Buffer.allocUnsafe(0) -} - -Splitter.prototype.add = function (data) { - this.cache = Buffer.concat([this.cache, data]) -} - -Splitter.prototype.get = function () { - if (this.cache.length > 15) { - var out = this.cache.slice(0, 16) - this.cache = this.cache.slice(16) - return out - } - return null -} - -Splitter.prototype.flush = function () { - var len = 16 - this.cache.length - var padBuff = Buffer.allocUnsafe(len) - - var i = -1 - while (++i < len) { - padBuff.writeUInt8(len, i) - } - - return Buffer.concat([this.cache, padBuff]) -} - -function createCipheriv (suite, password, iv) { - var config = MODES[suite.toLowerCase()] - if (!config) throw new TypeError('invalid suite type') - - if (typeof password === 'string') password = Buffer.from(password) - if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length) - - if (typeof iv === 'string') iv = Buffer.from(iv) - if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length) - - if (config.type === 'stream') { - return new StreamCipher(config.module, password, iv) - } else if (config.type === 'auth') { - return new AuthCipher(config.module, password, iv) - } - - return new Cipher(config.module, password, iv) -} - -function createCipher (suite, password) { - var config = MODES[suite.toLowerCase()] - if (!config) throw new TypeError('invalid suite type') - - var keys = ebtk(password, false, config.key, config.iv) - return createCipheriv(suite, keys.key, keys.iv) -} - -exports.createCipheriv = createCipheriv -exports.createCipher = createCipher - -},{"./aes":21,"./authCipher":22,"./modes":34,"./streamCipher":37,"cipher-base":71,"evp_bytestokey":106,"inherits":146,"safe-buffer":250}],26:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var ZEROES = Buffer.alloc(16, 0) - -function toArray (buf) { - return [ - buf.readUInt32BE(0), - buf.readUInt32BE(4), - buf.readUInt32BE(8), - buf.readUInt32BE(12) - ] -} - -function fromArray (out) { - var buf = Buffer.allocUnsafe(16) - buf.writeUInt32BE(out[0] >>> 0, 0) - buf.writeUInt32BE(out[1] >>> 0, 4) - buf.writeUInt32BE(out[2] >>> 0, 8) - buf.writeUInt32BE(out[3] >>> 0, 12) - return buf -} - -function GHASH (key) { - this.h = key - this.state = Buffer.alloc(16, 0) - this.cache = Buffer.allocUnsafe(0) -} - -// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html -// by Juho Vähä-Herttua -GHASH.prototype.ghash = function (block) { - var i = -1 - while (++i < block.length) { - this.state[i] ^= block[i] - } - this._multiply() -} - -GHASH.prototype._multiply = function () { - var Vi = toArray(this.h) - var Zi = [0, 0, 0, 0] - var j, xi, lsbVi - var i = -1 - while (++i < 128) { - xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0 - if (xi) { - // Z_i+1 = Z_i ^ V_i - Zi[0] ^= Vi[0] - Zi[1] ^= Vi[1] - Zi[2] ^= Vi[2] - Zi[3] ^= Vi[3] - } - - // Store the value of LSB(V_i) - lsbVi = (Vi[3] & 1) !== 0 - - // V_i+1 = V_i >> 1 - for (j = 3; j > 0; j--) { - Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31) - } - Vi[0] = Vi[0] >>> 1 - - // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R - if (lsbVi) { - Vi[0] = Vi[0] ^ (0xe1 << 24) - } - } - this.state = fromArray(Zi) -} - -GHASH.prototype.update = function (buf) { - this.cache = Buffer.concat([this.cache, buf]) - var chunk - while (this.cache.length >= 16) { - chunk = this.cache.slice(0, 16) - this.cache = this.cache.slice(16) - this.ghash(chunk) - } -} - -GHASH.prototype.final = function (abl, bl) { - if (this.cache.length) { - this.ghash(Buffer.concat([this.cache, ZEROES], 16)) - } - - this.ghash(fromArray([0, abl, 0, bl])) - return this.state -} - -module.exports = GHASH - -},{"safe-buffer":250}],27:[function(require,module,exports){ -function incr32 (iv) { - var len = iv.length - var item - while (len--) { - item = iv.readUInt8(len) - if (item === 255) { - iv.writeUInt8(0, len) - } else { - item++ - iv.writeUInt8(item, len) - break - } - } -} -module.exports = incr32 - -},{}],28:[function(require,module,exports){ -var xor = require('buffer-xor') - -exports.encrypt = function (self, block) { - var data = xor(block, self._prev) - - self._prev = self._cipher.encryptBlock(data) - return self._prev -} - -exports.decrypt = function (self, block) { - var pad = self._prev - - self._prev = block - var out = self._cipher.decryptBlock(block) - - return xor(out, pad) -} - -},{"buffer-xor":67}],29:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var xor = require('buffer-xor') - -function encryptStart (self, data, decrypt) { - var len = data.length - var out = xor(data, self._cache) - self._cache = self._cache.slice(len) - self._prev = Buffer.concat([self._prev, decrypt ? data : out]) - return out -} - -exports.encrypt = function (self, data, decrypt) { - var out = Buffer.allocUnsafe(0) - var len - - while (data.length) { - if (self._cache.length === 0) { - self._cache = self._cipher.encryptBlock(self._prev) - self._prev = Buffer.allocUnsafe(0) - } - - if (self._cache.length <= data.length) { - len = self._cache.length - out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)]) - data = data.slice(len) - } else { - out = Buffer.concat([out, encryptStart(self, data, decrypt)]) - break - } - } - - return out -} - -},{"buffer-xor":67,"safe-buffer":250}],30:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer - -function encryptByte (self, byteParam, decrypt) { - var pad - var i = -1 - var len = 8 - var out = 0 - var bit, value - while (++i < len) { - pad = self._cipher.encryptBlock(self._prev) - bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0 - value = pad[0] ^ bit - out += ((value & 0x80) >> (i % 8)) - self._prev = shiftIn(self._prev, decrypt ? bit : value) - } - return out -} - -function shiftIn (buffer, value) { - var len = buffer.length - var i = -1 - var out = Buffer.allocUnsafe(buffer.length) - buffer = Buffer.concat([buffer, Buffer.from([value])]) - - while (++i < len) { - out[i] = buffer[i] << 1 | buffer[i + 1] >> (7) - } - - return out -} - -exports.encrypt = function (self, chunk, decrypt) { - var len = chunk.length - var out = Buffer.allocUnsafe(len) - var i = -1 - - while (++i < len) { - out[i] = encryptByte(self, chunk[i], decrypt) - } - - return out -} - -},{"safe-buffer":250}],31:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer - -function encryptByte (self, byteParam, decrypt) { - var pad = self._cipher.encryptBlock(self._prev) - var out = pad[0] ^ byteParam - - self._prev = Buffer.concat([ - self._prev.slice(1), - Buffer.from([decrypt ? byteParam : out]) - ]) - - return out -} - -exports.encrypt = function (self, chunk, decrypt) { - var len = chunk.length - var out = Buffer.allocUnsafe(len) - var i = -1 - - while (++i < len) { - out[i] = encryptByte(self, chunk[i], decrypt) - } - - return out -} - -},{"safe-buffer":250}],32:[function(require,module,exports){ -var xor = require('buffer-xor') -var Buffer = require('safe-buffer').Buffer -var incr32 = require('../incr32') - -function getBlock (self) { - var out = self._cipher.encryptBlockRaw(self._prev) - incr32(self._prev) - return out -} - -var blockSize = 16 -exports.encrypt = function (self, chunk) { - var chunkNum = Math.ceil(chunk.length / blockSize) - var start = self._cache.length - self._cache = Buffer.concat([ - self._cache, - Buffer.allocUnsafe(chunkNum * blockSize) - ]) - for (var i = 0; i < chunkNum; i++) { - var out = getBlock(self) - var offset = start + i * blockSize - self._cache.writeUInt32BE(out[0], offset + 0) - self._cache.writeUInt32BE(out[1], offset + 4) - self._cache.writeUInt32BE(out[2], offset + 8) - self._cache.writeUInt32BE(out[3], offset + 12) - } - var pad = self._cache.slice(0, chunk.length) - self._cache = self._cache.slice(chunk.length) - return xor(chunk, pad) -} - -},{"../incr32":27,"buffer-xor":67,"safe-buffer":250}],33:[function(require,module,exports){ -exports.encrypt = function (self, block) { - return self._cipher.encryptBlock(block) -} - -exports.decrypt = function (self, block) { - return self._cipher.decryptBlock(block) -} - -},{}],34:[function(require,module,exports){ -var modeModules = { - ECB: require('./ecb'), - CBC: require('./cbc'), - CFB: require('./cfb'), - CFB8: require('./cfb8'), - CFB1: require('./cfb1'), - OFB: require('./ofb'), - CTR: require('./ctr'), - GCM: require('./ctr') -} - -var modes = require('./list.json') - -for (var key in modes) { - modes[key].module = modeModules[modes[key].mode] -} - -module.exports = modes - -},{"./cbc":28,"./cfb":29,"./cfb1":30,"./cfb8":31,"./ctr":32,"./ecb":33,"./list.json":35,"./ofb":36}],35:[function(require,module,exports){ -module.exports={ - "aes-128-ecb": { - "cipher": "AES", - "key": 128, - "iv": 0, - "mode": "ECB", - "type": "block" - }, - "aes-192-ecb": { - "cipher": "AES", - "key": 192, - "iv": 0, - "mode": "ECB", - "type": "block" - }, - "aes-256-ecb": { - "cipher": "AES", - "key": 256, - "iv": 0, - "mode": "ECB", - "type": "block" - }, - "aes-128-cbc": { - "cipher": "AES", - "key": 128, - "iv": 16, - "mode": "CBC", - "type": "block" - }, - "aes-192-cbc": { - "cipher": "AES", - "key": 192, - "iv": 16, - "mode": "CBC", - "type": "block" - }, - "aes-256-cbc": { - "cipher": "AES", - "key": 256, - "iv": 16, - "mode": "CBC", - "type": "block" - }, - "aes128": { - "cipher": "AES", - "key": 128, - "iv": 16, - "mode": "CBC", - "type": "block" - }, - "aes192": { - "cipher": "AES", - "key": 192, - "iv": 16, - "mode": "CBC", - "type": "block" - }, - "aes256": { - "cipher": "AES", - "key": 256, - "iv": 16, - "mode": "CBC", - "type": "block" - }, - "aes-128-cfb": { - "cipher": "AES", - "key": 128, - "iv": 16, - "mode": "CFB", - "type": "stream" - }, - "aes-192-cfb": { - "cipher": "AES", - "key": 192, - "iv": 16, - "mode": "CFB", - "type": "stream" - }, - "aes-256-cfb": { - "cipher": "AES", - "key": 256, - "iv": 16, - "mode": "CFB", - "type": "stream" - }, - "aes-128-cfb8": { - "cipher": "AES", - "key": 128, - "iv": 16, - "mode": "CFB8", - "type": "stream" - }, - "aes-192-cfb8": { - "cipher": "AES", - "key": 192, - "iv": 16, - "mode": "CFB8", - "type": "stream" - }, - "aes-256-cfb8": { - "cipher": "AES", - "key": 256, - "iv": 16, - "mode": "CFB8", - "type": "stream" - }, - "aes-128-cfb1": { - "cipher": "AES", - "key": 128, - "iv": 16, - "mode": "CFB1", - "type": "stream" - }, - "aes-192-cfb1": { - "cipher": "AES", - "key": 192, - "iv": 16, - "mode": "CFB1", - "type": "stream" - }, - "aes-256-cfb1": { - "cipher": "AES", - "key": 256, - "iv": 16, - "mode": "CFB1", - "type": "stream" - }, - "aes-128-ofb": { - "cipher": "AES", - "key": 128, - "iv": 16, - "mode": "OFB", - "type": "stream" - }, - "aes-192-ofb": { - "cipher": "AES", - "key": 192, - "iv": 16, - "mode": "OFB", - "type": "stream" - }, - "aes-256-ofb": { - "cipher": "AES", - "key": 256, - "iv": 16, - "mode": "OFB", - "type": "stream" - }, - "aes-128-ctr": { - "cipher": "AES", - "key": 128, - "iv": 16, - "mode": "CTR", - "type": "stream" - }, - "aes-192-ctr": { - "cipher": "AES", - "key": 192, - "iv": 16, - "mode": "CTR", - "type": "stream" - }, - "aes-256-ctr": { - "cipher": "AES", - "key": 256, - "iv": 16, - "mode": "CTR", - "type": "stream" - }, - "aes-128-gcm": { - "cipher": "AES", - "key": 128, - "iv": 12, - "mode": "GCM", - "type": "auth" - }, - "aes-192-gcm": { - "cipher": "AES", - "key": 192, - "iv": 12, - "mode": "GCM", - "type": "auth" - }, - "aes-256-gcm": { - "cipher": "AES", - "key": 256, - "iv": 12, - "mode": "GCM", - "type": "auth" - } -} - -},{}],36:[function(require,module,exports){ -(function (Buffer){(function (){ -var xor = require('buffer-xor') - -function getBlock (self) { - self._prev = self._cipher.encryptBlock(self._prev) - return self._prev -} - -exports.encrypt = function (self, chunk) { - while (self._cache.length < chunk.length) { - self._cache = Buffer.concat([self._cache, getBlock(self)]) - } - - var pad = self._cache.slice(0, chunk.length) - self._cache = self._cache.slice(chunk.length) - return xor(chunk, pad) -} - -}).call(this)}).call(this,require("buffer").Buffer) - -},{"buffer":68,"buffer-xor":67}],37:[function(require,module,exports){ -var aes = require('./aes') -var Buffer = require('safe-buffer').Buffer -var Transform = require('cipher-base') -var inherits = require('inherits') - -function StreamCipher (mode, key, iv, decrypt) { - Transform.call(this) - - this._cipher = new aes.AES(key) - this._prev = Buffer.from(iv) - this._cache = Buffer.allocUnsafe(0) - this._secCache = Buffer.allocUnsafe(0) - this._decrypt = decrypt - this._mode = mode -} - -inherits(StreamCipher, Transform) - -StreamCipher.prototype._update = function (chunk) { - return this._mode.encrypt(this, chunk, this._decrypt) -} - -StreamCipher.prototype._final = function () { - this._cipher.scrub() -} - -module.exports = StreamCipher - -},{"./aes":21,"cipher-base":71,"inherits":146,"safe-buffer":250}],38:[function(require,module,exports){ -var DES = require('browserify-des') -var aes = require('browserify-aes/browser') -var aesModes = require('browserify-aes/modes') -var desModes = require('browserify-des/modes') -var ebtk = require('evp_bytestokey') - -function createCipher (suite, password) { - suite = suite.toLowerCase() - - var keyLen, ivLen - if (aesModes[suite]) { - keyLen = aesModes[suite].key - ivLen = aesModes[suite].iv - } else if (desModes[suite]) { - keyLen = desModes[suite].key * 8 - ivLen = desModes[suite].iv - } else { - throw new TypeError('invalid suite type') - } - - var keys = ebtk(password, false, keyLen, ivLen) - return createCipheriv(suite, keys.key, keys.iv) -} - -function createDecipher (suite, password) { - suite = suite.toLowerCase() - - var keyLen, ivLen - if (aesModes[suite]) { - keyLen = aesModes[suite].key - ivLen = aesModes[suite].iv - } else if (desModes[suite]) { - keyLen = desModes[suite].key * 8 - ivLen = desModes[suite].iv - } else { - throw new TypeError('invalid suite type') - } - - var keys = ebtk(password, false, keyLen, ivLen) - return createDecipheriv(suite, keys.key, keys.iv) -} - -function createCipheriv (suite, key, iv) { - suite = suite.toLowerCase() - if (aesModes[suite]) return aes.createCipheriv(suite, key, iv) - if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite }) - - throw new TypeError('invalid suite type') -} - -function createDecipheriv (suite, key, iv) { - suite = suite.toLowerCase() - if (aesModes[suite]) return aes.createDecipheriv(suite, key, iv) - if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite, decrypt: true }) - - throw new TypeError('invalid suite type') -} - -function getCiphers () { - return Object.keys(desModes).concat(aes.getCiphers()) -} - -exports.createCipher = exports.Cipher = createCipher -exports.createCipheriv = exports.Cipheriv = createCipheriv -exports.createDecipher = exports.Decipher = createDecipher -exports.createDecipheriv = exports.Decipheriv = createDecipheriv -exports.listCiphers = exports.getCiphers = getCiphers - -},{"browserify-aes/browser":23,"browserify-aes/modes":34,"browserify-des":39,"browserify-des/modes":40,"evp_bytestokey":106}],39:[function(require,module,exports){ -var CipherBase = require('cipher-base') -var des = require('des.js') -var inherits = require('inherits') -var Buffer = require('safe-buffer').Buffer - -var modes = { - 'des-ede3-cbc': des.CBC.instantiate(des.EDE), - 'des-ede3': des.EDE, - 'des-ede-cbc': des.CBC.instantiate(des.EDE), - 'des-ede': des.EDE, - 'des-cbc': des.CBC.instantiate(des.DES), - 'des-ecb': des.DES -} -modes.des = modes['des-cbc'] -modes.des3 = modes['des-ede3-cbc'] -module.exports = DES -inherits(DES, CipherBase) -function DES (opts) { - CipherBase.call(this) - var modeName = opts.mode.toLowerCase() - var mode = modes[modeName] - var type - if (opts.decrypt) { - type = 'decrypt' - } else { - type = 'encrypt' - } - var key = opts.key - if (!Buffer.isBuffer(key)) { - key = Buffer.from(key) - } - if (modeName === 'des-ede' || modeName === 'des-ede-cbc') { - key = Buffer.concat([key, key.slice(0, 8)]) - } - var iv = opts.iv - if (!Buffer.isBuffer(iv)) { - iv = Buffer.from(iv) - } - this._des = mode.create({ - key: key, - iv: iv, - type: type - }) -} -DES.prototype._update = function (data) { - return Buffer.from(this._des.update(data)) -} -DES.prototype._final = function () { - return Buffer.from(this._des.final()) -} - -},{"cipher-base":71,"des.js":79,"inherits":146,"safe-buffer":250}],40:[function(require,module,exports){ -exports['des-ecb'] = { - key: 8, - iv: 0 -} -exports['des-cbc'] = exports.des = { - key: 8, - iv: 8 -} -exports['des-ede3-cbc'] = exports.des3 = { - key: 24, - iv: 8 -} -exports['des-ede3'] = { - key: 24, - iv: 0 -} -exports['des-ede-cbc'] = { - key: 16, - iv: 8 -} -exports['des-ede'] = { - key: 16, - iv: 0 -} - -},{}],41:[function(require,module,exports){ -(function (Buffer){(function (){ -var BN = require('bn.js') -var randomBytes = require('randombytes') - -function blind (priv) { - var r = getr(priv) - var blinder = r.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed() - return { blinder: blinder, unblinder: r.invm(priv.modulus) } -} - -function getr (priv) { - var len = priv.modulus.byteLength() - var r - do { - r = new BN(randomBytes(len)) - } while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) - return r -} - -function crt (msg, priv) { - var blinds = blind(priv) - var len = priv.modulus.byteLength() - var blinded = new BN(msg).mul(blinds.blinder).umod(priv.modulus) - var c1 = blinded.toRed(BN.mont(priv.prime1)) - var c2 = blinded.toRed(BN.mont(priv.prime2)) - var qinv = priv.coefficient - var p = priv.prime1 - var q = priv.prime2 - var m1 = c1.redPow(priv.exponent1).fromRed() - var m2 = c2.redPow(priv.exponent2).fromRed() - var h = m1.isub(m2).imul(qinv).umod(p).imul(q) - return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer, 'be', len) -} -crt.getr = getr - -module.exports = crt - -}).call(this)}).call(this,require("buffer").Buffer) - -},{"bn.js":42,"buffer":68,"randombytes":244}],42:[function(require,module,exports){ -(function (module, exports) { - 'use strict'; - - // Utils - function assert (val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); - } - - // Could use `inherits` module, but don't want to move from single file - // architecture yet. - function inherits (ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - } - - // BN - - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; - } - - this.negative = 0; - this.words = null; - this.length = 0; - - // Reduction context - this.red = null; - - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } - - this._init(number || 0, base || 10, endian || 'be'); - } - } - if (typeof module === 'object') { - module.exports = BN; - } else { - exports.BN = BN; - } - - BN.BN = BN; - BN.wordSize = 26; - - var Buffer; - try { - if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') { - Buffer = window.Buffer; - } else { - Buffer = require('buffer').Buffer; - } - } catch (e) { - } - - BN.isBN = function isBN (num) { - if (num instanceof BN) { - return true; - } - - return num !== null && typeof num === 'object' && - num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); - }; - - BN.max = function max (left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; - - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; - - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } - - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } - - if (base === 'hex') { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); - - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - this.negative = 1; - } - - if (start < number.length) { - if (base === 16) { - this._parseHex(number, start, endian); - } else { - this._parseBase(number, base, start); - if (endian === 'le') { - this._initArray(this.toArray(), base, endian); - } - } - } - }; - - BN.prototype._initNumber = function _initNumber (number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; - } - if (number < 0x4000000) { - this.words = [number & 0x3ffffff]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff - ]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff, - 1 - ]; - this.length = 3; - } - - if (endian !== 'le') return; - - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; - - BN.prototype._initArray = function _initArray (number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === 'number'); - if (number.length <= 0) { - this.words = [0]; - this.length = 1; - return this; - } - - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - var j, w; - var off = 0; - if (endian === 'be') { - for (i = number.length - 1, j = 0; i >= 0; i -= 3) { - w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } else if (endian === 'le') { - for (i = 0, j = 0; i < number.length; i += 3) { - w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } - return this._strip(); - }; - - function parseHex4Bits (string, index) { - var c = string.charCodeAt(index); - // '0' - '9' - if (c >= 48 && c <= 57) { - return c - 48; - // 'A' - 'F' - } else if (c >= 65 && c <= 70) { - return c - 55; - // 'a' - 'f' - } else if (c >= 97 && c <= 102) { - return c - 87; - } else { - assert(false, 'Invalid character in ' + string); - } - } - - function parseHexByte (string, lowerBound, index) { - var r = parseHex4Bits(string, index); - if (index - 1 >= lowerBound) { - r |= parseHex4Bits(string, index - 1) << 4; - } - return r; - } - - BN.prototype._parseHex = function _parseHex (number, start, endian) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - // 24-bits chunks - var off = 0; - var j = 0; - - var w; - if (endian === 'be') { - for (i = number.length - 1; i >= start; i -= 2) { - w = parseHexByte(number, start, i) << off; - this.words[j] |= w & 0x3ffffff; - if (off >= 18) { - off -= 18; - j += 1; - this.words[j] |= w >>> 26; - } else { - off += 8; - } - } - } else { - var parseLength = number.length - start; - for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) { - w = parseHexByte(number, start, i) << off; - this.words[j] |= w & 0x3ffffff; - if (off >= 18) { - off -= 18; - j += 1; - this.words[j] |= w >>> 26; - } else { - off += 8; - } - } - } - - this._strip(); - }; - - function parseBase (str, start, end, mul) { - var r = 0; - var b = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r *= mul; - - // 'a' - if (c >= 49) { - b = c - 49 + 0xa; - - // 'A' - } else if (c >= 17) { - b = c - 17 + 0xa; - - // '0' - '9' - } else { - b = c; - } - assert(c >= 0 && b < mul, 'Invalid character'); - r += b; - } - return r; - } - - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [0]; - this.length = 1; - - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; - - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; - - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); - - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); - - for (i = 0; i < mod; i++) { - pow *= base; - } - - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - - this._strip(); - }; - - BN.prototype.copy = function copy (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - dest.words[i] = this.words[i]; - } - dest.length = this.length; - dest.negative = this.negative; - dest.red = this.red; - }; - - function move (dest, src) { - dest.words = src.words; - dest.length = src.length; - dest.negative = src.negative; - dest.red = src.red; - } - - BN.prototype._move = function _move (dest) { - move(dest, this); - }; - - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; - - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; - - // Remove leading `0` from `this` - BN.prototype._strip = function strip () { - while (this.length > 1 && this.words[this.length - 1] === 0) { - this.length--; - } - return this._normSign(); - }; - - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } - return this; - }; - - // Check Symbol.for because not everywhere where Symbol defined - // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility - if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') { - try { - BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect; - } catch (e) { - BN.prototype.inspect = inspect; - } - } else { - BN.prototype.inspect = inspect; - } - - function inspect () { - return (this.red ? ''; - } - - /* - - var zeros = []; - var groupSizes = []; - var groupBases = []; - - var s = ''; - var i = -1; - while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; - } - groupSizes[0] = 0; - groupSizes[1] = 0; - groupBases[0] = 0; - groupBases[1] = 0; - var base = 2 - 1; - while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; - } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; - } - - */ - - var zeros = [ - '', - '0', - '00', - '000', - '0000', - '00000', - '000000', - '0000000', - '00000000', - '000000000', - '0000000000', - '00000000000', - '000000000000', - '0000000000000', - '00000000000000', - '000000000000000', - '0000000000000000', - '00000000000000000', - '000000000000000000', - '0000000000000000000', - '00000000000000000000', - '000000000000000000000', - '0000000000000000000000', - '00000000000000000000000', - '000000000000000000000000', - '0000000000000000000000000' - ]; - - var groupSizes = [ - 0, 0, - 25, 16, 12, 11, 10, 9, 8, - 8, 7, 7, 7, 7, 6, 6, - 6, 6, 6, 6, 6, 5, 5, - 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5 - ]; - - var groupBases = [ - 0, 0, - 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, - 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, - 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, - 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, - 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 - ]; - - BN.prototype.toString = function toString (base, padding) { - base = base || 10; - padding = padding | 0 || 1; - - var out; - if (base === 16 || base === 'hex') { - out = ''; - var off = 0; - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = (((w << off) | carry) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - off += 2; - if (off >= 26) { - off -= 26; - i--; - } - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } - } - if (carry !== 0) { - out = carry.toString(16) + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } - - if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - out = ''; - var c = this.clone(); - c.negative = 0; - while (!c.isZero()) { - var r = c.modrn(groupBase).toString(base); - c = c.idivn(groupBase); - - if (!c.isZero()) { - out = zeros[groupSize - r.length] + r + out; - } else { - out = r + out; - } - } - if (this.isZero()) { - out = '0' + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } - - assert(false, 'Base should be between 2 and 36'); - }; - - BN.prototype.toNumber = function toNumber () { - var ret = this.words[0]; - if (this.length === 2) { - ret += this.words[1] * 0x4000000; - } else if (this.length === 3 && this.words[2] === 0x01) { - // NOTE: at this stage it is known that the top bit is set - ret += 0x10000000000000 + (this.words[1] * 0x4000000); - } else if (this.length > 2) { - assert(false, 'Number can only safely store up to 53 bits'); - } - return (this.negative !== 0) ? -ret : ret; - }; - - BN.prototype.toJSON = function toJSON () { - return this.toString(16, 2); - }; - - if (Buffer) { - BN.prototype.toBuffer = function toBuffer (endian, length) { - return this.toArrayLike(Buffer, endian, length); - }; - } - - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; - - var allocate = function allocate (ArrayType, size) { - if (ArrayType.allocUnsafe) { - return ArrayType.allocUnsafe(size); - } - return new ArrayType(size); - }; - - BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { - this._strip(); - - var byteLength = this.byteLength(); - var reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, 'byte array longer than desired length'); - assert(reqLength > 0, 'Requested array length <= 0'); - - var res = allocate(ArrayType, reqLength); - var postfix = endian === 'le' ? 'LE' : 'BE'; - this['_toArrayLike' + postfix](res, byteLength); - return res; - }; - - BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) { - var position = 0; - var carry = 0; - - for (var i = 0, shift = 0; i < this.length; i++) { - var word = (this.words[i] << shift) | carry; - - res[position++] = word & 0xff; - if (position < res.length) { - res[position++] = (word >> 8) & 0xff; - } - if (position < res.length) { - res[position++] = (word >> 16) & 0xff; - } - - if (shift === 6) { - if (position < res.length) { - res[position++] = (word >> 24) & 0xff; - } - carry = 0; - shift = 0; - } else { - carry = word >>> 24; - shift += 2; - } - } - - if (position < res.length) { - res[position++] = carry; - - while (position < res.length) { - res[position++] = 0; - } - } - }; - - BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) { - var position = res.length - 1; - var carry = 0; - - for (var i = 0, shift = 0; i < this.length; i++) { - var word = (this.words[i] << shift) | carry; - - res[position--] = word & 0xff; - if (position >= 0) { - res[position--] = (word >> 8) & 0xff; - } - if (position >= 0) { - res[position--] = (word >> 16) & 0xff; - } - - if (shift === 6) { - if (position >= 0) { - res[position--] = (word >> 24) & 0xff; - } - carry = 0; - shift = 0; - } else { - carry = word >>> 24; - shift += 2; - } - } - - if (position >= 0) { - res[position--] = carry; - - while (position >= 0) { - res[position--] = 0; - } - } - }; - - if (Math.clz32) { - BN.prototype._countBits = function _countBits (w) { - return 32 - Math.clz32(w); - }; - } else { - BN.prototype._countBits = function _countBits (w) { - var t = w; - var r = 0; - if (t >= 0x1000) { - r += 13; - t >>>= 13; - } - if (t >= 0x40) { - r += 7; - t >>>= 7; - } - if (t >= 0x8) { - r += 4; - t >>>= 4; - } - if (t >= 0x02) { - r += 2; - t >>>= 2; - } - return r + t; - }; - } - - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; - - var t = w; - var r = 0; - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; - } - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; - } - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; - } - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; - } - if ((t & 0x1) === 0) { - r++; - } - return r; - }; - - // Return number of used bits in a BN - BN.prototype.bitLength = function bitLength () { - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }; - - function toBitArray (num) { - var w = new Array(num.bitLength()); - - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; - - w[bit] = (num.words[off] >>> wbit) & 0x01; - } - - return w; - } - - // Number of trailing zero bits - BN.prototype.zeroBits = function zeroBits () { - if (this.isZero()) return 0; - - var r = 0; - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - r += b; - if (b !== 26) break; - } - return r; - }; - - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; - - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); - } - return this.clone(); - }; - - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); - } - return this.clone(); - }; - - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; - - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); - }; - - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; - } - - return this; - }; - - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; - } - - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; - } - - return this._strip(); - }; - - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; - - // Or `num` with `this` - BN.prototype.or = function or (num) { - if (this.length > num.length) return this.clone().ior(num); - return num.clone().ior(this); - }; - - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; - - // And `num` with `this` in-place - BN.prototype.iuand = function iuand (num) { - // b = min-length(num, this) - var b; - if (this.length > num.length) { - b = num; - } else { - b = this; - } - - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; - } - - this.length = b.length; - - return this._strip(); - }; - - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; - - // And `num` with `this` - BN.prototype.and = function and (num) { - if (this.length > num.length) return this.clone().iand(num); - return num.clone().iand(this); - }; - - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; - - // Xor `num` with `this` in-place - BN.prototype.iuxor = function iuxor (num) { - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; - } - - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - this.length = a.length; - - return this._strip(); - }; - - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; - - // Xor `num` with `this` - BN.prototype.xor = function xor (num) { - if (this.length > num.length) return this.clone().ixor(num); - return num.clone().ixor(this); - }; - - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; - - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); - - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; - - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); - - if (bitsLeft > 0) { - bytesNeeded--; - } - - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; - } - - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); - } - - // And remove leading zeroes - return this._strip(); - }; - - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; - - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); - - var off = (bit / 26) | 0; - var wbit = bit % 26; - - this._expand(off + 1); - - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); - } - - return this._strip(); - }; - - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; - - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); - - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } - - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) + (b.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - return this; - }; - - // Add `num` to `this` - BN.prototype.add = function add (num) { - var res; - if (num.negative !== 0 && this.negative === 0) { - num.negative = 0; - res = this.sub(num); - num.negative ^= 1; - return res; - } else if (num.negative === 0 && this.negative !== 0) { - this.negative = 0; - res = num.sub(this); - this.negative = 1; - return res; - } - - if (this.length > num.length) return this.clone().iadd(num); - - return num.clone().iadd(this); - }; - - // Subtract `num` from `this` in-place - BN.prototype.isub = function isub (num) { - // this - (-num) = this + num - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - num.negative = 1; - return r._normSign(); - - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } - - // At this point both numbers are positive - var cmp = this.cmp(num); - - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } - - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) - (b.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - this.length = Math.max(this.length, i); - - if (a !== this) { - this.negative = 1; - } - - return this._strip(); - }; - - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; - - function smallMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - var len = (self.length + num.length) | 0; - out.length = len; - len = (len - 1) | 0; - - // Peel one iteration (compiler can't do it, because of code complexity) - var a = self.words[0] | 0; - var b = num.words[0] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; - - for (var k = 1; k < len; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = (k - j) | 0; - a = self.words[i] | 0; - b = num.words[j] | 0; - r = a * b + rword; - ncarry += (r / 0x4000000) | 0; - rword = r & 0x3ffffff; - } - out.words[k] = rword | 0; - carry = ncarry | 0; - } - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; - } - - return out._strip(); - } - - // TODO(indutny): it may be reasonable to omit it for users who don't need - // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit - // multiplication (like elliptic secp256k1). - var comb10MulTo = function comb10MulTo (self, num, out) { - var a = self.words; - var b = num.words; - var o = out.words; - var c = 0; - var lo; - var mid; - var hi; - var a0 = a[0] | 0; - var al0 = a0 & 0x1fff; - var ah0 = a0 >>> 13; - var a1 = a[1] | 0; - var al1 = a1 & 0x1fff; - var ah1 = a1 >>> 13; - var a2 = a[2] | 0; - var al2 = a2 & 0x1fff; - var ah2 = a2 >>> 13; - var a3 = a[3] | 0; - var al3 = a3 & 0x1fff; - var ah3 = a3 >>> 13; - var a4 = a[4] | 0; - var al4 = a4 & 0x1fff; - var ah4 = a4 >>> 13; - var a5 = a[5] | 0; - var al5 = a5 & 0x1fff; - var ah5 = a5 >>> 13; - var a6 = a[6] | 0; - var al6 = a6 & 0x1fff; - var ah6 = a6 >>> 13; - var a7 = a[7] | 0; - var al7 = a7 & 0x1fff; - var ah7 = a7 >>> 13; - var a8 = a[8] | 0; - var al8 = a8 & 0x1fff; - var ah8 = a8 >>> 13; - var a9 = a[9] | 0; - var al9 = a9 & 0x1fff; - var ah9 = a9 >>> 13; - var b0 = b[0] | 0; - var bl0 = b0 & 0x1fff; - var bh0 = b0 >>> 13; - var b1 = b[1] | 0; - var bl1 = b1 & 0x1fff; - var bh1 = b1 >>> 13; - var b2 = b[2] | 0; - var bl2 = b2 & 0x1fff; - var bh2 = b2 >>> 13; - var b3 = b[3] | 0; - var bl3 = b3 & 0x1fff; - var bh3 = b3 >>> 13; - var b4 = b[4] | 0; - var bl4 = b4 & 0x1fff; - var bh4 = b4 >>> 13; - var b5 = b[5] | 0; - var bl5 = b5 & 0x1fff; - var bh5 = b5 >>> 13; - var b6 = b[6] | 0; - var bl6 = b6 & 0x1fff; - var bh6 = b6 >>> 13; - var b7 = b[7] | 0; - var bl7 = b7 & 0x1fff; - var bh7 = b7 >>> 13; - var b8 = b[8] | 0; - var bl8 = b8 & 0x1fff; - var bh8 = b8 >>> 13; - var b9 = b[9] | 0; - var bl9 = b9 & 0x1fff; - var bh9 = b9 >>> 13; - - out.negative = self.negative ^ num.negative; - out.length = 19; - /* k = 0 */ - lo = Math.imul(al0, bl0); - mid = Math.imul(al0, bh0); - mid = (mid + Math.imul(ah0, bl0)) | 0; - hi = Math.imul(ah0, bh0); - var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; - w0 &= 0x3ffffff; - /* k = 1 */ - lo = Math.imul(al1, bl0); - mid = Math.imul(al1, bh0); - mid = (mid + Math.imul(ah1, bl0)) | 0; - hi = Math.imul(ah1, bh0); - lo = (lo + Math.imul(al0, bl1)) | 0; - mid = (mid + Math.imul(al0, bh1)) | 0; - mid = (mid + Math.imul(ah0, bl1)) | 0; - hi = (hi + Math.imul(ah0, bh1)) | 0; - var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; - w1 &= 0x3ffffff; - /* k = 2 */ - lo = Math.imul(al2, bl0); - mid = Math.imul(al2, bh0); - mid = (mid + Math.imul(ah2, bl0)) | 0; - hi = Math.imul(ah2, bh0); - lo = (lo + Math.imul(al1, bl1)) | 0; - mid = (mid + Math.imul(al1, bh1)) | 0; - mid = (mid + Math.imul(ah1, bl1)) | 0; - hi = (hi + Math.imul(ah1, bh1)) | 0; - lo = (lo + Math.imul(al0, bl2)) | 0; - mid = (mid + Math.imul(al0, bh2)) | 0; - mid = (mid + Math.imul(ah0, bl2)) | 0; - hi = (hi + Math.imul(ah0, bh2)) | 0; - var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; - w2 &= 0x3ffffff; - /* k = 3 */ - lo = Math.imul(al3, bl0); - mid = Math.imul(al3, bh0); - mid = (mid + Math.imul(ah3, bl0)) | 0; - hi = Math.imul(ah3, bh0); - lo = (lo + Math.imul(al2, bl1)) | 0; - mid = (mid + Math.imul(al2, bh1)) | 0; - mid = (mid + Math.imul(ah2, bl1)) | 0; - hi = (hi + Math.imul(ah2, bh1)) | 0; - lo = (lo + Math.imul(al1, bl2)) | 0; - mid = (mid + Math.imul(al1, bh2)) | 0; - mid = (mid + Math.imul(ah1, bl2)) | 0; - hi = (hi + Math.imul(ah1, bh2)) | 0; - lo = (lo + Math.imul(al0, bl3)) | 0; - mid = (mid + Math.imul(al0, bh3)) | 0; - mid = (mid + Math.imul(ah0, bl3)) | 0; - hi = (hi + Math.imul(ah0, bh3)) | 0; - var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; - w3 &= 0x3ffffff; - /* k = 4 */ - lo = Math.imul(al4, bl0); - mid = Math.imul(al4, bh0); - mid = (mid + Math.imul(ah4, bl0)) | 0; - hi = Math.imul(ah4, bh0); - lo = (lo + Math.imul(al3, bl1)) | 0; - mid = (mid + Math.imul(al3, bh1)) | 0; - mid = (mid + Math.imul(ah3, bl1)) | 0; - hi = (hi + Math.imul(ah3, bh1)) | 0; - lo = (lo + Math.imul(al2, bl2)) | 0; - mid = (mid + Math.imul(al2, bh2)) | 0; - mid = (mid + Math.imul(ah2, bl2)) | 0; - hi = (hi + Math.imul(ah2, bh2)) | 0; - lo = (lo + Math.imul(al1, bl3)) | 0; - mid = (mid + Math.imul(al1, bh3)) | 0; - mid = (mid + Math.imul(ah1, bl3)) | 0; - hi = (hi + Math.imul(ah1, bh3)) | 0; - lo = (lo + Math.imul(al0, bl4)) | 0; - mid = (mid + Math.imul(al0, bh4)) | 0; - mid = (mid + Math.imul(ah0, bl4)) | 0; - hi = (hi + Math.imul(ah0, bh4)) | 0; - var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; - w4 &= 0x3ffffff; - /* k = 5 */ - lo = Math.imul(al5, bl0); - mid = Math.imul(al5, bh0); - mid = (mid + Math.imul(ah5, bl0)) | 0; - hi = Math.imul(ah5, bh0); - lo = (lo + Math.imul(al4, bl1)) | 0; - mid = (mid + Math.imul(al4, bh1)) | 0; - mid = (mid + Math.imul(ah4, bl1)) | 0; - hi = (hi + Math.imul(ah4, bh1)) | 0; - lo = (lo + Math.imul(al3, bl2)) | 0; - mid = (mid + Math.imul(al3, bh2)) | 0; - mid = (mid + Math.imul(ah3, bl2)) | 0; - hi = (hi + Math.imul(ah3, bh2)) | 0; - lo = (lo + Math.imul(al2, bl3)) | 0; - mid = (mid + Math.imul(al2, bh3)) | 0; - mid = (mid + Math.imul(ah2, bl3)) | 0; - hi = (hi + Math.imul(ah2, bh3)) | 0; - lo = (lo + Math.imul(al1, bl4)) | 0; - mid = (mid + Math.imul(al1, bh4)) | 0; - mid = (mid + Math.imul(ah1, bl4)) | 0; - hi = (hi + Math.imul(ah1, bh4)) | 0; - lo = (lo + Math.imul(al0, bl5)) | 0; - mid = (mid + Math.imul(al0, bh5)) | 0; - mid = (mid + Math.imul(ah0, bl5)) | 0; - hi = (hi + Math.imul(ah0, bh5)) | 0; - var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; - w5 &= 0x3ffffff; - /* k = 6 */ - lo = Math.imul(al6, bl0); - mid = Math.imul(al6, bh0); - mid = (mid + Math.imul(ah6, bl0)) | 0; - hi = Math.imul(ah6, bh0); - lo = (lo + Math.imul(al5, bl1)) | 0; - mid = (mid + Math.imul(al5, bh1)) | 0; - mid = (mid + Math.imul(ah5, bl1)) | 0; - hi = (hi + Math.imul(ah5, bh1)) | 0; - lo = (lo + Math.imul(al4, bl2)) | 0; - mid = (mid + Math.imul(al4, bh2)) | 0; - mid = (mid + Math.imul(ah4, bl2)) | 0; - hi = (hi + Math.imul(ah4, bh2)) | 0; - lo = (lo + Math.imul(al3, bl3)) | 0; - mid = (mid + Math.imul(al3, bh3)) | 0; - mid = (mid + Math.imul(ah3, bl3)) | 0; - hi = (hi + Math.imul(ah3, bh3)) | 0; - lo = (lo + Math.imul(al2, bl4)) | 0; - mid = (mid + Math.imul(al2, bh4)) | 0; - mid = (mid + Math.imul(ah2, bl4)) | 0; - hi = (hi + Math.imul(ah2, bh4)) | 0; - lo = (lo + Math.imul(al1, bl5)) | 0; - mid = (mid + Math.imul(al1, bh5)) | 0; - mid = (mid + Math.imul(ah1, bl5)) | 0; - hi = (hi + Math.imul(ah1, bh5)) | 0; - lo = (lo + Math.imul(al0, bl6)) | 0; - mid = (mid + Math.imul(al0, bh6)) | 0; - mid = (mid + Math.imul(ah0, bl6)) | 0; - hi = (hi + Math.imul(ah0, bh6)) | 0; - var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; - w6 &= 0x3ffffff; - /* k = 7 */ - lo = Math.imul(al7, bl0); - mid = Math.imul(al7, bh0); - mid = (mid + Math.imul(ah7, bl0)) | 0; - hi = Math.imul(ah7, bh0); - lo = (lo + Math.imul(al6, bl1)) | 0; - mid = (mid + Math.imul(al6, bh1)) | 0; - mid = (mid + Math.imul(ah6, bl1)) | 0; - hi = (hi + Math.imul(ah6, bh1)) | 0; - lo = (lo + Math.imul(al5, bl2)) | 0; - mid = (mid + Math.imul(al5, bh2)) | 0; - mid = (mid + Math.imul(ah5, bl2)) | 0; - hi = (hi + Math.imul(ah5, bh2)) | 0; - lo = (lo + Math.imul(al4, bl3)) | 0; - mid = (mid + Math.imul(al4, bh3)) | 0; - mid = (mid + Math.imul(ah4, bl3)) | 0; - hi = (hi + Math.imul(ah4, bh3)) | 0; - lo = (lo + Math.imul(al3, bl4)) | 0; - mid = (mid + Math.imul(al3, bh4)) | 0; - mid = (mid + Math.imul(ah3, bl4)) | 0; - hi = (hi + Math.imul(ah3, bh4)) | 0; - lo = (lo + Math.imul(al2, bl5)) | 0; - mid = (mid + Math.imul(al2, bh5)) | 0; - mid = (mid + Math.imul(ah2, bl5)) | 0; - hi = (hi + Math.imul(ah2, bh5)) | 0; - lo = (lo + Math.imul(al1, bl6)) | 0; - mid = (mid + Math.imul(al1, bh6)) | 0; - mid = (mid + Math.imul(ah1, bl6)) | 0; - hi = (hi + Math.imul(ah1, bh6)) | 0; - lo = (lo + Math.imul(al0, bl7)) | 0; - mid = (mid + Math.imul(al0, bh7)) | 0; - mid = (mid + Math.imul(ah0, bl7)) | 0; - hi = (hi + Math.imul(ah0, bh7)) | 0; - var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; - w7 &= 0x3ffffff; - /* k = 8 */ - lo = Math.imul(al8, bl0); - mid = Math.imul(al8, bh0); - mid = (mid + Math.imul(ah8, bl0)) | 0; - hi = Math.imul(ah8, bh0); - lo = (lo + Math.imul(al7, bl1)) | 0; - mid = (mid + Math.imul(al7, bh1)) | 0; - mid = (mid + Math.imul(ah7, bl1)) | 0; - hi = (hi + Math.imul(ah7, bh1)) | 0; - lo = (lo + Math.imul(al6, bl2)) | 0; - mid = (mid + Math.imul(al6, bh2)) | 0; - mid = (mid + Math.imul(ah6, bl2)) | 0; - hi = (hi + Math.imul(ah6, bh2)) | 0; - lo = (lo + Math.imul(al5, bl3)) | 0; - mid = (mid + Math.imul(al5, bh3)) | 0; - mid = (mid + Math.imul(ah5, bl3)) | 0; - hi = (hi + Math.imul(ah5, bh3)) | 0; - lo = (lo + Math.imul(al4, bl4)) | 0; - mid = (mid + Math.imul(al4, bh4)) | 0; - mid = (mid + Math.imul(ah4, bl4)) | 0; - hi = (hi + Math.imul(ah4, bh4)) | 0; - lo = (lo + Math.imul(al3, bl5)) | 0; - mid = (mid + Math.imul(al3, bh5)) | 0; - mid = (mid + Math.imul(ah3, bl5)) | 0; - hi = (hi + Math.imul(ah3, bh5)) | 0; - lo = (lo + Math.imul(al2, bl6)) | 0; - mid = (mid + Math.imul(al2, bh6)) | 0; - mid = (mid + Math.imul(ah2, bl6)) | 0; - hi = (hi + Math.imul(ah2, bh6)) | 0; - lo = (lo + Math.imul(al1, bl7)) | 0; - mid = (mid + Math.imul(al1, bh7)) | 0; - mid = (mid + Math.imul(ah1, bl7)) | 0; - hi = (hi + Math.imul(ah1, bh7)) | 0; - lo = (lo + Math.imul(al0, bl8)) | 0; - mid = (mid + Math.imul(al0, bh8)) | 0; - mid = (mid + Math.imul(ah0, bl8)) | 0; - hi = (hi + Math.imul(ah0, bh8)) | 0; - var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; - w8 &= 0x3ffffff; - /* k = 9 */ - lo = Math.imul(al9, bl0); - mid = Math.imul(al9, bh0); - mid = (mid + Math.imul(ah9, bl0)) | 0; - hi = Math.imul(ah9, bh0); - lo = (lo + Math.imul(al8, bl1)) | 0; - mid = (mid + Math.imul(al8, bh1)) | 0; - mid = (mid + Math.imul(ah8, bl1)) | 0; - hi = (hi + Math.imul(ah8, bh1)) | 0; - lo = (lo + Math.imul(al7, bl2)) | 0; - mid = (mid + Math.imul(al7, bh2)) | 0; - mid = (mid + Math.imul(ah7, bl2)) | 0; - hi = (hi + Math.imul(ah7, bh2)) | 0; - lo = (lo + Math.imul(al6, bl3)) | 0; - mid = (mid + Math.imul(al6, bh3)) | 0; - mid = (mid + Math.imul(ah6, bl3)) | 0; - hi = (hi + Math.imul(ah6, bh3)) | 0; - lo = (lo + Math.imul(al5, bl4)) | 0; - mid = (mid + Math.imul(al5, bh4)) | 0; - mid = (mid + Math.imul(ah5, bl4)) | 0; - hi = (hi + Math.imul(ah5, bh4)) | 0; - lo = (lo + Math.imul(al4, bl5)) | 0; - mid = (mid + Math.imul(al4, bh5)) | 0; - mid = (mid + Math.imul(ah4, bl5)) | 0; - hi = (hi + Math.imul(ah4, bh5)) | 0; - lo = (lo + Math.imul(al3, bl6)) | 0; - mid = (mid + Math.imul(al3, bh6)) | 0; - mid = (mid + Math.imul(ah3, bl6)) | 0; - hi = (hi + Math.imul(ah3, bh6)) | 0; - lo = (lo + Math.imul(al2, bl7)) | 0; - mid = (mid + Math.imul(al2, bh7)) | 0; - mid = (mid + Math.imul(ah2, bl7)) | 0; - hi = (hi + Math.imul(ah2, bh7)) | 0; - lo = (lo + Math.imul(al1, bl8)) | 0; - mid = (mid + Math.imul(al1, bh8)) | 0; - mid = (mid + Math.imul(ah1, bl8)) | 0; - hi = (hi + Math.imul(ah1, bh8)) | 0; - lo = (lo + Math.imul(al0, bl9)) | 0; - mid = (mid + Math.imul(al0, bh9)) | 0; - mid = (mid + Math.imul(ah0, bl9)) | 0; - hi = (hi + Math.imul(ah0, bh9)) | 0; - var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; - w9 &= 0x3ffffff; - /* k = 10 */ - lo = Math.imul(al9, bl1); - mid = Math.imul(al9, bh1); - mid = (mid + Math.imul(ah9, bl1)) | 0; - hi = Math.imul(ah9, bh1); - lo = (lo + Math.imul(al8, bl2)) | 0; - mid = (mid + Math.imul(al8, bh2)) | 0; - mid = (mid + Math.imul(ah8, bl2)) | 0; - hi = (hi + Math.imul(ah8, bh2)) | 0; - lo = (lo + Math.imul(al7, bl3)) | 0; - mid = (mid + Math.imul(al7, bh3)) | 0; - mid = (mid + Math.imul(ah7, bl3)) | 0; - hi = (hi + Math.imul(ah7, bh3)) | 0; - lo = (lo + Math.imul(al6, bl4)) | 0; - mid = (mid + Math.imul(al6, bh4)) | 0; - mid = (mid + Math.imul(ah6, bl4)) | 0; - hi = (hi + Math.imul(ah6, bh4)) | 0; - lo = (lo + Math.imul(al5, bl5)) | 0; - mid = (mid + Math.imul(al5, bh5)) | 0; - mid = (mid + Math.imul(ah5, bl5)) | 0; - hi = (hi + Math.imul(ah5, bh5)) | 0; - lo = (lo + Math.imul(al4, bl6)) | 0; - mid = (mid + Math.imul(al4, bh6)) | 0; - mid = (mid + Math.imul(ah4, bl6)) | 0; - hi = (hi + Math.imul(ah4, bh6)) | 0; - lo = (lo + Math.imul(al3, bl7)) | 0; - mid = (mid + Math.imul(al3, bh7)) | 0; - mid = (mid + Math.imul(ah3, bl7)) | 0; - hi = (hi + Math.imul(ah3, bh7)) | 0; - lo = (lo + Math.imul(al2, bl8)) | 0; - mid = (mid + Math.imul(al2, bh8)) | 0; - mid = (mid + Math.imul(ah2, bl8)) | 0; - hi = (hi + Math.imul(ah2, bh8)) | 0; - lo = (lo + Math.imul(al1, bl9)) | 0; - mid = (mid + Math.imul(al1, bh9)) | 0; - mid = (mid + Math.imul(ah1, bl9)) | 0; - hi = (hi + Math.imul(ah1, bh9)) | 0; - var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; - w10 &= 0x3ffffff; - /* k = 11 */ - lo = Math.imul(al9, bl2); - mid = Math.imul(al9, bh2); - mid = (mid + Math.imul(ah9, bl2)) | 0; - hi = Math.imul(ah9, bh2); - lo = (lo + Math.imul(al8, bl3)) | 0; - mid = (mid + Math.imul(al8, bh3)) | 0; - mid = (mid + Math.imul(ah8, bl3)) | 0; - hi = (hi + Math.imul(ah8, bh3)) | 0; - lo = (lo + Math.imul(al7, bl4)) | 0; - mid = (mid + Math.imul(al7, bh4)) | 0; - mid = (mid + Math.imul(ah7, bl4)) | 0; - hi = (hi + Math.imul(ah7, bh4)) | 0; - lo = (lo + Math.imul(al6, bl5)) | 0; - mid = (mid + Math.imul(al6, bh5)) | 0; - mid = (mid + Math.imul(ah6, bl5)) | 0; - hi = (hi + Math.imul(ah6, bh5)) | 0; - lo = (lo + Math.imul(al5, bl6)) | 0; - mid = (mid + Math.imul(al5, bh6)) | 0; - mid = (mid + Math.imul(ah5, bl6)) | 0; - hi = (hi + Math.imul(ah5, bh6)) | 0; - lo = (lo + Math.imul(al4, bl7)) | 0; - mid = (mid + Math.imul(al4, bh7)) | 0; - mid = (mid + Math.imul(ah4, bl7)) | 0; - hi = (hi + Math.imul(ah4, bh7)) | 0; - lo = (lo + Math.imul(al3, bl8)) | 0; - mid = (mid + Math.imul(al3, bh8)) | 0; - mid = (mid + Math.imul(ah3, bl8)) | 0; - hi = (hi + Math.imul(ah3, bh8)) | 0; - lo = (lo + Math.imul(al2, bl9)) | 0; - mid = (mid + Math.imul(al2, bh9)) | 0; - mid = (mid + Math.imul(ah2, bl9)) | 0; - hi = (hi + Math.imul(ah2, bh9)) | 0; - var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; - w11 &= 0x3ffffff; - /* k = 12 */ - lo = Math.imul(al9, bl3); - mid = Math.imul(al9, bh3); - mid = (mid + Math.imul(ah9, bl3)) | 0; - hi = Math.imul(ah9, bh3); - lo = (lo + Math.imul(al8, bl4)) | 0; - mid = (mid + Math.imul(al8, bh4)) | 0; - mid = (mid + Math.imul(ah8, bl4)) | 0; - hi = (hi + Math.imul(ah8, bh4)) | 0; - lo = (lo + Math.imul(al7, bl5)) | 0; - mid = (mid + Math.imul(al7, bh5)) | 0; - mid = (mid + Math.imul(ah7, bl5)) | 0; - hi = (hi + Math.imul(ah7, bh5)) | 0; - lo = (lo + Math.imul(al6, bl6)) | 0; - mid = (mid + Math.imul(al6, bh6)) | 0; - mid = (mid + Math.imul(ah6, bl6)) | 0; - hi = (hi + Math.imul(ah6, bh6)) | 0; - lo = (lo + Math.imul(al5, bl7)) | 0; - mid = (mid + Math.imul(al5, bh7)) | 0; - mid = (mid + Math.imul(ah5, bl7)) | 0; - hi = (hi + Math.imul(ah5, bh7)) | 0; - lo = (lo + Math.imul(al4, bl8)) | 0; - mid = (mid + Math.imul(al4, bh8)) | 0; - mid = (mid + Math.imul(ah4, bl8)) | 0; - hi = (hi + Math.imul(ah4, bh8)) | 0; - lo = (lo + Math.imul(al3, bl9)) | 0; - mid = (mid + Math.imul(al3, bh9)) | 0; - mid = (mid + Math.imul(ah3, bl9)) | 0; - hi = (hi + Math.imul(ah3, bh9)) | 0; - var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; - w12 &= 0x3ffffff; - /* k = 13 */ - lo = Math.imul(al9, bl4); - mid = Math.imul(al9, bh4); - mid = (mid + Math.imul(ah9, bl4)) | 0; - hi = Math.imul(ah9, bh4); - lo = (lo + Math.imul(al8, bl5)) | 0; - mid = (mid + Math.imul(al8, bh5)) | 0; - mid = (mid + Math.imul(ah8, bl5)) | 0; - hi = (hi + Math.imul(ah8, bh5)) | 0; - lo = (lo + Math.imul(al7, bl6)) | 0; - mid = (mid + Math.imul(al7, bh6)) | 0; - mid = (mid + Math.imul(ah7, bl6)) | 0; - hi = (hi + Math.imul(ah7, bh6)) | 0; - lo = (lo + Math.imul(al6, bl7)) | 0; - mid = (mid + Math.imul(al6, bh7)) | 0; - mid = (mid + Math.imul(ah6, bl7)) | 0; - hi = (hi + Math.imul(ah6, bh7)) | 0; - lo = (lo + Math.imul(al5, bl8)) | 0; - mid = (mid + Math.imul(al5, bh8)) | 0; - mid = (mid + Math.imul(ah5, bl8)) | 0; - hi = (hi + Math.imul(ah5, bh8)) | 0; - lo = (lo + Math.imul(al4, bl9)) | 0; - mid = (mid + Math.imul(al4, bh9)) | 0; - mid = (mid + Math.imul(ah4, bl9)) | 0; - hi = (hi + Math.imul(ah4, bh9)) | 0; - var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; - w13 &= 0x3ffffff; - /* k = 14 */ - lo = Math.imul(al9, bl5); - mid = Math.imul(al9, bh5); - mid = (mid + Math.imul(ah9, bl5)) | 0; - hi = Math.imul(ah9, bh5); - lo = (lo + Math.imul(al8, bl6)) | 0; - mid = (mid + Math.imul(al8, bh6)) | 0; - mid = (mid + Math.imul(ah8, bl6)) | 0; - hi = (hi + Math.imul(ah8, bh6)) | 0; - lo = (lo + Math.imul(al7, bl7)) | 0; - mid = (mid + Math.imul(al7, bh7)) | 0; - mid = (mid + Math.imul(ah7, bl7)) | 0; - hi = (hi + Math.imul(ah7, bh7)) | 0; - lo = (lo + Math.imul(al6, bl8)) | 0; - mid = (mid + Math.imul(al6, bh8)) | 0; - mid = (mid + Math.imul(ah6, bl8)) | 0; - hi = (hi + Math.imul(ah6, bh8)) | 0; - lo = (lo + Math.imul(al5, bl9)) | 0; - mid = (mid + Math.imul(al5, bh9)) | 0; - mid = (mid + Math.imul(ah5, bl9)) | 0; - hi = (hi + Math.imul(ah5, bh9)) | 0; - var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; - w14 &= 0x3ffffff; - /* k = 15 */ - lo = Math.imul(al9, bl6); - mid = Math.imul(al9, bh6); - mid = (mid + Math.imul(ah9, bl6)) | 0; - hi = Math.imul(ah9, bh6); - lo = (lo + Math.imul(al8, bl7)) | 0; - mid = (mid + Math.imul(al8, bh7)) | 0; - mid = (mid + Math.imul(ah8, bl7)) | 0; - hi = (hi + Math.imul(ah8, bh7)) | 0; - lo = (lo + Math.imul(al7, bl8)) | 0; - mid = (mid + Math.imul(al7, bh8)) | 0; - mid = (mid + Math.imul(ah7, bl8)) | 0; - hi = (hi + Math.imul(ah7, bh8)) | 0; - lo = (lo + Math.imul(al6, bl9)) | 0; - mid = (mid + Math.imul(al6, bh9)) | 0; - mid = (mid + Math.imul(ah6, bl9)) | 0; - hi = (hi + Math.imul(ah6, bh9)) | 0; - var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; - w15 &= 0x3ffffff; - /* k = 16 */ - lo = Math.imul(al9, bl7); - mid = Math.imul(al9, bh7); - mid = (mid + Math.imul(ah9, bl7)) | 0; - hi = Math.imul(ah9, bh7); - lo = (lo + Math.imul(al8, bl8)) | 0; - mid = (mid + Math.imul(al8, bh8)) | 0; - mid = (mid + Math.imul(ah8, bl8)) | 0; - hi = (hi + Math.imul(ah8, bh8)) | 0; - lo = (lo + Math.imul(al7, bl9)) | 0; - mid = (mid + Math.imul(al7, bh9)) | 0; - mid = (mid + Math.imul(ah7, bl9)) | 0; - hi = (hi + Math.imul(ah7, bh9)) | 0; - var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; - w16 &= 0x3ffffff; - /* k = 17 */ - lo = Math.imul(al9, bl8); - mid = Math.imul(al9, bh8); - mid = (mid + Math.imul(ah9, bl8)) | 0; - hi = Math.imul(ah9, bh8); - lo = (lo + Math.imul(al8, bl9)) | 0; - mid = (mid + Math.imul(al8, bh9)) | 0; - mid = (mid + Math.imul(ah8, bl9)) | 0; - hi = (hi + Math.imul(ah8, bh9)) | 0; - var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; - w17 &= 0x3ffffff; - /* k = 18 */ - lo = Math.imul(al9, bl9); - mid = Math.imul(al9, bh9); - mid = (mid + Math.imul(ah9, bl9)) | 0; - hi = Math.imul(ah9, bh9); - var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; - w18 &= 0x3ffffff; - o[0] = w0; - o[1] = w1; - o[2] = w2; - o[3] = w3; - o[4] = w4; - o[5] = w5; - o[6] = w6; - o[7] = w7; - o[8] = w8; - o[9] = w9; - o[10] = w10; - o[11] = w11; - o[12] = w12; - o[13] = w13; - o[14] = w14; - o[15] = w15; - o[16] = w16; - o[17] = w17; - o[18] = w18; - if (c !== 0) { - o[19] = c; - out.length++; - } - return out; - }; - - // Polyfill comb - if (!Math.imul) { - comb10MulTo = smallMulTo; - } - - function bigMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - out.length = self.length + num.length; - - var carry = 0; - var hncarry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = self.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; - - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; - } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } - - return out._strip(); - } - - function jumboMulTo (self, num, out) { - // Temporary disable, see https://github.com/indutny/bn.js/issues/211 - // var fftm = new FFTM(); - // return fftm.mulp(self, num, out); - return bigMulTo(self, num, out); - } - - BN.prototype.mulTo = function mulTo (num, out) { - var res; - var len = this.length + num.length; - if (this.length === 10 && num.length === 10) { - res = comb10MulTo(this, num, out); - } else if (len < 63) { - res = smallMulTo(this, num, out); - } else if (len < 1024) { - res = bigMulTo(this, num, out); - } else { - res = jumboMulTo(this, num, out); - } - - return res; - }; - - // Cooley-Tukey algorithm for FFT - // slightly revisited to rely on looping instead of recursion - - function FFTM (x, y) { - this.x = x; - this.y = y; - } - - FFTM.prototype.makeRBT = function makeRBT (N) { - var t = new Array(N); - var l = BN.prototype._countBits(N) - 1; - for (var i = 0; i < N; i++) { - t[i] = this.revBin(i, l, N); - } - - return t; - }; - - // Returns binary-reversed representation of `x` - FFTM.prototype.revBin = function revBin (x, l, N) { - if (x === 0 || x === N - 1) return x; - - var rb = 0; - for (var i = 0; i < l; i++) { - rb |= (x & 1) << (l - i - 1); - x >>= 1; - } - - return rb; - }; - - // Performs "tweedling" phase, therefore 'emulating' - // behaviour of the recursive algorithm - FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) { - rtws[i] = rws[rbt[i]]; - itws[i] = iws[rbt[i]]; - } - }; - - FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); - - for (var s = 1; s < N; s <<= 1) { - var l = s << 1; - - var rtwdf = Math.cos(2 * Math.PI / l); - var itwdf = Math.sin(2 * Math.PI / l); - - for (var p = 0; p < N; p += l) { - var rtwdf_ = rtwdf; - var itwdf_ = itwdf; - - for (var j = 0; j < s; j++) { - var re = rtws[p + j]; - var ie = itws[p + j]; - - var ro = rtws[p + j + s]; - var io = itws[p + j + s]; - - var rx = rtwdf_ * ro - itwdf_ * io; - - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; - - rtws[p + j] = re + ro; - itws[p + j] = ie + io; - - rtws[p + j + s] = re - ro; - itws[p + j + s] = ie - io; - - /* jshint maxdepth : false */ - if (j !== l) { - rx = rtwdf * rtwdf_ - itwdf * itwdf_; - - itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; - rtwdf_ = rx; - } - } - } - } - }; - - FFTM.prototype.guessLen13b = function guessLen13b (n, m) { - var N = Math.max(m, n) | 1; - var odd = N & 1; - var i = 0; - for (N = N / 2 | 0; N; N = N >>> 1) { - i++; - } - - return 1 << i + 1 + odd; - }; - - FFTM.prototype.conjugate = function conjugate (rws, iws, N) { - if (N <= 1) return; - - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; - - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; - - t = iws[i]; - - iws[i] = -iws[N - i - 1]; - iws[N - i - 1] = -t; - } - }; - - FFTM.prototype.normalize13b = function normalize13b (ws, N) { - var carry = 0; - for (var i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + - Math.round(ws[2 * i] / N) + - carry; - - ws[i] = w & 0x3ffffff; - - if (w < 0x4000000) { - carry = 0; - } else { - carry = w / 0x4000000 | 0; - } - } - - return ws; - }; - - FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { - var carry = 0; - for (var i = 0; i < len; i++) { - carry = carry + (ws[i] | 0); - - rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; - rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; - } - - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 0; - } - - assert(carry === 0); - assert((carry & ~0x1fff) === 0); - }; - - FFTM.prototype.stub = function stub (N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; - } - - return ph; - }; - - FFTM.prototype.mulp = function mulp (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); - - var rbt = this.makeRBT(N); - - var _ = this.stub(N); - - var rws = new Array(N); - var rwst = new Array(N); - var iwst = new Array(N); - - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); - - var rmws = out.words; - rmws.length = N; - - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); - - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); - - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; - rwst[i] = rx; - } - - this.conjugate(rwst, iwst, N); - this.transform(rwst, iwst, rmws, _, N, rbt); - this.conjugate(rmws, _, N); - this.normalize13b(rmws, N); - - out.negative = x.negative ^ y.negative; - out.length = x.length + y.length; - return out._strip(); - }; - - // Multiply `this` by `num` - BN.prototype.mul = function mul (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); - }; - - // Multiply employing FFT - BN.prototype.mulf = function mulf (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return jumboMulTo(this, num, out); - }; - - // In-place Multiplication - BN.prototype.imul = function imul (num) { - return this.clone().mulTo(num, this); - }; - - BN.prototype.imuln = function imuln (num) { - var isNegNum = num < 0; - if (isNegNum) num = -num; - - assert(typeof num === 'number'); - assert(num < 0x4000000); - - // Carry - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += (w / 0x4000000) | 0; - // NOTE: lo is 27bit maximum - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } - - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - - return isNegNum ? this.ineg() : this; - }; - - BN.prototype.muln = function muln (num) { - return this.clone().imuln(num); - }; - - // `this` * `this` - BN.prototype.sqr = function sqr () { - return this.mul(this); - }; - - // `this` * `this` in-place - BN.prototype.isqr = function isqr () { - return this.imul(this.clone()); - }; - - // Math.pow(`this`, `num`) - BN.prototype.pow = function pow (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); - - // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; - } - - if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { - if (w[i] === 0) continue; - - res = res.mul(q); - } - } - - return res; - }; - - // Shift-left in-place - BN.prototype.iushln = function iushln (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); - var i; - - if (r !== 0) { - var carry = 0; - - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = ((this.words[i] | 0) - newCarry) << r; - this.words[i] = c | carry; - carry = newCarry >>> (26 - r); - } - - if (carry) { - this.words[i] = carry; - this.length++; - } - } - - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } - - for (i = 0; i < s; i++) { - this.words[i] = 0; - } - - this.length += s; - } - - return this._strip(); - }; - - BN.prototype.ishln = function ishln (bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; - - // Shift-right in-place - // NOTE: `hint` is a lowest bit before trailing zeroes - // NOTE: if `extended` is present - it will be filled with destroyed bits - BN.prototype.iushrn = function iushrn (bits, hint, extended) { - assert(typeof bits === 'number' && bits >= 0); - var h; - if (hint) { - h = (hint - (hint % 26)) / 26; - } else { - h = 0; - } - - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; - - h -= s; - h = Math.max(0, h); - - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; - } - - if (s === 0) { - // No-op, we should not move anything at all - } else if (this.length > s) { - this.length -= s; - for (i = 0; i < this.length; i++) { - this.words[i] = this.words[i + s]; - } - } else { - this.words[0] = 0; - this.length = 1; - } - - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - this.words[i] = (carry << (26 - r)) | (word >>> r); - carry = word & mask; - } - - // Push carried bits as a mask - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } - - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } - - return this._strip(); - }; - - BN.prototype.ishrn = function ishrn (bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; - - // Shift-left - BN.prototype.shln = function shln (bits) { - return this.clone().ishln(bits); - }; - - BN.prototype.ushln = function ushln (bits) { - return this.clone().iushln(bits); - }; - - // Shift-right - BN.prototype.shrn = function shrn (bits) { - return this.clone().ishrn(bits); - }; - - BN.prototype.ushrn = function ushrn (bits) { - return this.clone().iushrn(bits); - }; - - // Test if n bit is set - BN.prototype.testn = function testn (bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) return false; - - // Check bit and return - var w = this.words[s]; - - return !!(w & q); - }; - - // Return only lowers bits of number (in-place) - BN.prototype.imaskn = function imaskn (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - - assert(this.negative === 0, 'imaskn works only with positive numbers'); - - if (this.length <= s) { - return this; - } - - if (r !== 0) { - s++; - } - this.length = Math.min(s, this.length); - - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; - } - - return this._strip(); - }; - - // Return only lowers bits of number - BN.prototype.maskn = function maskn (bits) { - return this.clone().imaskn(bits); - }; - - // Add plain number `num` to `this` - BN.prototype.iaddn = function iaddn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.isubn(-num); - - // Possible sign change - if (this.negative !== 0) { - if (this.length === 1 && (this.words[0] | 0) <= num) { - this.words[0] = num - (this.words[0] | 0); - this.negative = 0; - return this; - } - - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; - } - - // Add without checks - return this._iaddn(num); - }; - - BN.prototype._iaddn = function _iaddn (num) { - this.words[0] += num; - - // Carry - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; - if (i === this.length - 1) { - this.words[i + 1] = 1; - } else { - this.words[i + 1]++; - } - } - this.length = Math.max(this.length, i + 1); - - return this; - }; - - // Subtract plain number `num` from `this` - BN.prototype.isubn = function isubn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.iaddn(-num); - - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); - this.negative = 1; - return this; - } - - this.words[0] -= num; - - if (this.length === 1 && this.words[0] < 0) { - this.words[0] = -this.words[0]; - this.negative = 1; - } else { - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } - } - - return this._strip(); - }; - - BN.prototype.addn = function addn (num) { - return this.clone().iaddn(num); - }; - - BN.prototype.subn = function subn (num) { - return this.clone().isubn(num); - }; - - BN.prototype.iabs = function iabs () { - this.negative = 0; - - return this; - }; - - BN.prototype.abs = function abs () { - return this.clone().iabs(); - }; - - BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { - var len = num.length + shift; - var i; - - this._expand(len); - - var w; - var carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - w -= right & 0x3ffffff; - carry = (w >> 26) - ((right / 0x4000000) | 0); - this.words[i + shift] = w & 0x3ffffff; - } - for (; i < this.length - shift; i++) { - w = (this.words[i + shift] | 0) + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; - } - - if (carry === 0) return this._strip(); - - // Subtraction overflow - assert(carry === -1); - carry = 0; - for (i = 0; i < this.length; i++) { - w = -(this.words[i] | 0) + carry; - carry = w >> 26; - this.words[i] = w & 0x3ffffff; - } - this.negative = 1; - - return this._strip(); - }; - - BN.prototype._wordDiv = function _wordDiv (num, mode) { - var shift = this.length - num.length; - - var a = this.clone(); - var b = num; - - // Normalize - var bhi = b.words[b.length - 1] | 0; - var bhiBits = this._countBits(bhi); - shift = 26 - bhiBits; - if (shift !== 0) { - b = b.ushln(shift); - a.iushln(shift); - bhi = b.words[b.length - 1] | 0; - } - - // Initialize quotient - var m = a.length - b.length; - var q; - - if (mode !== 'mod') { - q = new BN(null); - q.length = m + 1; - q.words = new Array(q.length); - for (var i = 0; i < q.length; i++) { - q.words[i] = 0; - } - } - - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (diff.negative === 0) { - a = diff; - if (q) { - q.words[m] = 1; - } - } - - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 0x4000000 + - (a.words[b.length + j - 1] | 0); - - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); - - a._ishlnsubmul(b, qj, j); - while (a.negative !== 0) { - qj--; - a.negative = 0; - a._ishlnsubmul(b, 1, j); - if (!a.isZero()) { - a.negative ^= 1; - } - } - if (q) { - q.words[j] = qj; - } - } - if (q) { - q._strip(); - } - a._strip(); - - // Denormalize - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); - } - - return { - div: q || null, - mod: a - }; - }; - - // NOTE: 1) `mode` can be set to `mod` to request mod only, - // to `div` to request div only, or be absent to - // request both div & mod - // 2) `positive` is true if unsigned mod is requested - BN.prototype.divmod = function divmod (num, mode, positive) { - assert(!num.isZero()); - - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(0) - }; - } - - var div, mod, res; - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } - - return { - div: div, - mod: mod - }; - } - - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } - - return { - div: div, - mod: res.mod - }; - } - - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } - } - - return { - div: res.div, - mod: mod - }; - } - - // Both numbers are positive at this point - - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; - } - - // Very short reduction - if (num.length === 1) { - if (mode === 'div') { - return { - div: this.divn(num.words[0]), - mod: null - }; - } - - if (mode === 'mod') { - return { - div: null, - mod: new BN(this.modrn(num.words[0])) - }; - } - - return { - div: this.divn(num.words[0]), - mod: new BN(this.modrn(num.words[0])) - }; - } - - return this._wordDiv(num, mode); - }; - - // Find `this` / `num` - BN.prototype.div = function div (num) { - return this.divmod(num, 'div', false).div; - }; - - // Find `this` % `num` - BN.prototype.mod = function mod (num) { - return this.divmod(num, 'mod', false).mod; - }; - - BN.prototype.umod = function umod (num) { - return this.divmod(num, 'mod', true).mod; - }; - - // Find Round(`this` / `num`) - BN.prototype.divRound = function divRound (num) { - var dm = this.divmod(num); - - // Fast case - exact division - if (dm.mod.isZero()) return dm.div; - - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; - - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); - - // Round down - if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div; - - // Round up - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); - }; - - BN.prototype.modrn = function modrn (num) { - var isNegNum = num < 0; - if (isNegNum) num = -num; - - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; - - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) { - acc = (p * acc + (this.words[i] | 0)) % num; - } - - return isNegNum ? -acc : acc; - }; - - // WARNING: DEPRECATED - BN.prototype.modn = function modn (num) { - return this.modrn(num); - }; - - // In-place division by number - BN.prototype.idivn = function idivn (num) { - var isNegNum = num < 0; - if (isNegNum) num = -num; - - assert(num <= 0x3ffffff); - - var carry = 0; - for (var i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 0x4000000; - this.words[i] = (w / num) | 0; - carry = w % num; - } - - this._strip(); - return isNegNum ? this.ineg() : this; - }; - - BN.prototype.divn = function divn (num) { - return this.clone().idivn(num); - }; - - BN.prototype.egcd = function egcd (p) { - assert(p.negative === 0); - assert(!p.isZero()); - - var x = this; - var y = p.clone(); - - if (x.negative !== 0) { - x = x.umod(p); - } else { - x = x.clone(); - } - - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); - - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); - - var g = 0; - - while (x.isEven() && y.isEven()) { - x.iushrn(1); - y.iushrn(1); - ++g; - } - - var yp = y.clone(); - var xp = x.clone(); - - while (!x.isZero()) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - x.iushrn(i); - while (i-- > 0) { - if (A.isOdd() || B.isOdd()) { - A.iadd(yp); - B.isub(xp); - } - - A.iushrn(1); - B.iushrn(1); - } - } - - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - y.iushrn(j); - while (j-- > 0) { - if (C.isOdd() || D.isOdd()) { - C.iadd(yp); - D.isub(xp); - } - - C.iushrn(1); - D.iushrn(1); - } - } - - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); - } else { - y.isub(x); - C.isub(A); - D.isub(B); - } - } - - return { - a: C, - b: D, - gcd: y.iushln(g) - }; - }; - - // This is reduced incarnation of the binary EEA - // above, designated to invert members of the - // _prime_ fields F(p) at a maximal speed - BN.prototype._invmp = function _invmp (p) { - assert(p.negative === 0); - assert(!p.isZero()); - - var a = this; - var b = p.clone(); - - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); - } - - var x1 = new BN(1); - var x2 = new BN(0); - - var delta = b.clone(); - - while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - a.iushrn(i); - while (i-- > 0) { - if (x1.isOdd()) { - x1.iadd(delta); - } - - x1.iushrn(1); - } - } - - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - b.iushrn(j); - while (j-- > 0) { - if (x2.isOdd()) { - x2.iadd(delta); - } - - x2.iushrn(1); - } - } - - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } - } - - var res; - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; - } - - if (res.cmpn(0) < 0) { - res.iadd(p); - } - - return res; - }; - - BN.prototype.gcd = function gcd (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; - - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); - } - - do { - while (a.isEven()) { - a.iushrn(1); - } - while (b.isEven()) { - b.iushrn(1); - } - - var r = a.cmp(b); - if (r < 0) { - // Swap `a` and `b` to make `a` always bigger than `b` - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; - } - - a.isub(b); - } while (true); - - return b.iushln(shift); - }; - - // Invert number in the field F(num) - BN.prototype.invm = function invm (num) { - return this.egcd(num).a.umod(num); - }; - - BN.prototype.isEven = function isEven () { - return (this.words[0] & 1) === 0; - }; - - BN.prototype.isOdd = function isOdd () { - return (this.words[0] & 1) === 1; - }; - - // And first word and num - BN.prototype.andln = function andln (num) { - return this.words[0] & num; - }; - - // Increment at the bit position in-line - BN.prototype.bincn = function bincn (bit) { - assert(typeof bit === 'number'); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - this._expand(s + 1); - this.words[s] |= q; - return this; - } - - // Add bit and propagate, if needed - var carry = q; - for (var i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - w += carry; - carry = w >>> 26; - w &= 0x3ffffff; - this.words[i] = w; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - return this; - }; - - BN.prototype.isZero = function isZero () { - return this.length === 1 && this.words[0] === 0; - }; - - BN.prototype.cmpn = function cmpn (num) { - var negative = num < 0; - - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; - - this._strip(); - - var res; - if (this.length > 1) { - res = 1; - } else { - if (negative) { - num = -num; - } - - assert(num <= 0x3ffffff, 'Number is too big'); - - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - if (this.negative !== 0) return -res | 0; - return res; - }; - - // Compare two numbers and return: - // 1 - if `this` > `num` - // 0 - if `this` == `num` - // -1 - if `this` < `num` - BN.prototype.cmp = function cmp (num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; - - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; - }; - - // Unsigned comparison - BN.prototype.ucmp = function ucmp (num) { - // At this point both numbers have the same sign - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0; - var b = num.words[i] | 0; - - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } - break; - } - return res; - }; - - BN.prototype.gtn = function gtn (num) { - return this.cmpn(num) === 1; - }; - - BN.prototype.gt = function gt (num) { - return this.cmp(num) === 1; - }; - - BN.prototype.gten = function gten (num) { - return this.cmpn(num) >= 0; - }; - - BN.prototype.gte = function gte (num) { - return this.cmp(num) >= 0; - }; - - BN.prototype.ltn = function ltn (num) { - return this.cmpn(num) === -1; - }; - - BN.prototype.lt = function lt (num) { - return this.cmp(num) === -1; - }; - - BN.prototype.lten = function lten (num) { - return this.cmpn(num) <= 0; - }; - - BN.prototype.lte = function lte (num) { - return this.cmp(num) <= 0; - }; - - BN.prototype.eqn = function eqn (num) { - return this.cmpn(num) === 0; - }; - - BN.prototype.eq = function eq (num) { - return this.cmp(num) === 0; - }; - - // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // - BN.red = function red (num) { - return new Red(num); - }; - - BN.prototype.toRed = function toRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - assert(this.negative === 0, 'red works only with positives'); - return ctx.convertTo(this)._forceRed(ctx); - }; - - BN.prototype.fromRed = function fromRed () { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); - }; - - BN.prototype._forceRed = function _forceRed (ctx) { - this.red = ctx; - return this; - }; - - BN.prototype.forceRed = function forceRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); - }; - - BN.prototype.redAdd = function redAdd (num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); - }; - - BN.prototype.redIAdd = function redIAdd (num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); - }; - - BN.prototype.redSub = function redSub (num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; - - BN.prototype.redISub = function redISub (num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; - - BN.prototype.redShl = function redShl (num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; - - BN.prototype.redMul = function redMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.mul(this, num); - }; - - BN.prototype.redIMul = function redIMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.imul(this, num); - }; - - BN.prototype.redSqr = function redSqr () { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); - }; - - BN.prototype.redISqr = function redISqr () { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); - }; - - // Square root over p - BN.prototype.redSqrt = function redSqrt () { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); - return this.red.sqrt(this); - }; - - BN.prototype.redInvm = function redInvm () { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); - }; - - // Return negative clone of `this` % `red modulo` - BN.prototype.redNeg = function redNeg () { - assert(this.red, 'redNeg works only with red numbers'); - this.red._verify1(this); - return this.red.neg(this); - }; - - BN.prototype.redPow = function redPow (num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); - }; - - // Prime numbers with efficient reduction - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; - - // Pseudo-Mersenne prime - function MPrime (name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).iushln(this.n).isub(this.p); - - this.tmp = this._tmp(); - } - - MPrime.prototype._tmp = function _tmp () { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; - }; - - MPrime.prototype.ireduce = function ireduce (num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; - - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); - - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); - } else { - if (r.strip !== undefined) { - // r is a BN v4 instance - r.strip(); - } else { - // r is a BN v5 instance - r._strip(); - } - } - - return r; - }; - - MPrime.prototype.split = function split (input, out) { - input.iushrn(this.n, 0, out); - }; - - MPrime.prototype.imulK = function imulK (num) { - return num.imul(this.k); - }; - - function K256 () { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); - } - inherits(K256, MPrime); - - K256.prototype.split = function split (input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; - - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; - } - output.length = outLen; - - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; - } - - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; - - for (i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); - prev = next; - } - prev >>>= 22; - input.words[i - 10] = prev; - if (prev === 0 && input.length > 10) { - input.length -= 10; - } else { - input.length -= 9; - } - }; - - K256.prototype.imulK = function imulK (num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; - - // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 - var lo = 0; - for (var i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - lo += w * 0x3d1; - num.words[i] = lo & 0x3ffffff; - lo = w * 0x40 + ((lo / 0x4000000) | 0); - } - - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) { - num.length--; - } - } - return num; - }; - - function P224 () { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); - } - inherits(P224, MPrime); - - function P192 () { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); - } - inherits(P192, MPrime); - - function P25519 () { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); - } - inherits(P25519, MPrime); - - P25519.prototype.imulK = function imulK (num) { - // K = 0x13 - var carry = 0; - for (var i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; - - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; - } - return num; - }; - - // Exported mostly for testing purposes, use plain name instead - BN._prime = function prime (name) { - // Cached version of prime - if (primes[name]) return primes[name]; - - var prime; - if (name === 'k256') { - prime = new K256(); - } else if (name === 'p224') { - prime = new P224(); - } else if (name === 'p192') { - prime = new P192(); - } else if (name === 'p25519') { - prime = new P25519(); - } else { - throw new Error('Unknown prime ' + name); - } - primes[name] = prime; - - return prime; - }; - - // - // Base reduction engine - // - function Red (m) { - if (typeof m === 'string') { - var prime = BN._prime(m); - this.m = prime.p; - this.prime = prime; - } else { - assert(m.gtn(1), 'modulus must be greater than 1'); - this.m = m; - this.prime = null; - } - } - - Red.prototype._verify1 = function _verify1 (a) { - assert(a.negative === 0, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); - }; - - Red.prototype._verify2 = function _verify2 (a, b) { - assert((a.negative | b.negative) === 0, 'red works only with positives'); - assert(a.red && a.red === b.red, - 'red works only with red numbers'); - }; - - Red.prototype.imod = function imod (a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - - move(a, a.umod(this.m)._forceRed(this)); - return a; - }; - - Red.prototype.neg = function neg (a) { - if (a.isZero()) { - return a.clone(); - } - - return this.m.sub(a)._forceRed(this); - }; - - Red.prototype.add = function add (a, b) { - this._verify2(a, b); - - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res._forceRed(this); - }; - - Red.prototype.iadd = function iadd (a, b) { - this._verify2(a, b); - - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res; - }; - - Red.prototype.sub = function sub (a, b) { - this._verify2(a, b); - - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res._forceRed(this); - }; - - Red.prototype.isub = function isub (a, b) { - this._verify2(a, b); - - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res; - }; - - Red.prototype.shl = function shl (a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; - - Red.prototype.imul = function imul (a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); - }; - - Red.prototype.mul = function mul (a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); - }; - - Red.prototype.isqr = function isqr (a) { - return this.imul(a, a.clone()); - }; - - Red.prototype.sqr = function sqr (a) { - return this.mul(a, a); - }; - - Red.prototype.sqrt = function sqrt (a) { - if (a.isZero()) return a.clone(); - - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); - - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } - - // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) - var q = this.m.subn(1); - var s = 0; - while (!q.isZero() && q.andln(1) === 0) { - s++; - q.iushrn(1); - } - assert(!q.isZero()); - - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); - - // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. - var lpow = this.m.subn(1).iushrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); - - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); - } - - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).iushrn(1)); - var t = this.pow(a, q); - var m = s; - while (t.cmp(one) !== 0) { - var tmp = t; - for (var i = 0; tmp.cmp(one) !== 0; i++) { - tmp = tmp.redSqr(); - } - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; - } - - return r; - }; - - Red.prototype.invm = function invm (a) { - var inv = a._invmp(this.m); - if (inv.negative !== 0) { - inv.negative = 0; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); - } - }; - - Red.prototype.pow = function pow (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); - - var windowSize = 4; - var wnd = new Array(1 << windowSize); - wnd[0] = new BN(1).toRed(this); - wnd[1] = a; - for (var i = 2; i < wnd.length; i++) { - wnd[i] = this.mul(wnd[i - 1], a); - } - - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; - } - - for (i = num.length - 1; i >= 0; i--) { - var word = num.words[i]; - for (var j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if (res !== wnd[0]) { - res = this.sqr(res); - } - - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } - - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; - - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } - start = 26; - } - - return res; - }; - - Red.prototype.convertTo = function convertTo (num) { - var r = num.umod(this.m); - - return r === num ? r.clone() : r; - }; - - Red.prototype.convertFrom = function convertFrom (num) { - var res = num.clone(); - res.red = null; - return res; - }; - - // - // Montgomery method engine - // - - BN.mont = function mont (num) { - return new Mont(num); - }; - - function Mont (m) { - Red.call(this, m); - - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - (this.shift % 26); - } - - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); - - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv = this.minv.umod(this.r); - this.minv = this.r.sub(this.minv); - } - inherits(Mont, Red); - - Mont.prototype.convertTo = function convertTo (num) { - return this.imod(num.ushln(this.shift)); - }; - - Mont.prototype.convertFrom = function convertFrom (num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; - }; - - Mont.prototype.imul = function imul (a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; - } - - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - - return res._forceRed(this); - }; - - Mont.prototype.mul = function mul (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - - return res._forceRed(this); - }; - - Mont.prototype.invm = function invm (a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }; -})(typeof module === 'undefined' || module, this); - -},{"buffer":20}],43:[function(require,module,exports){ -module.exports = require('./browser/algorithms.json') - -},{"./browser/algorithms.json":44}],44:[function(require,module,exports){ -module.exports={ - "sha224WithRSAEncryption": { - "sign": "rsa", - "hash": "sha224", - "id": "302d300d06096086480165030402040500041c" - }, - "RSA-SHA224": { - "sign": "ecdsa/rsa", - "hash": "sha224", - "id": "302d300d06096086480165030402040500041c" - }, - "sha256WithRSAEncryption": { - "sign": "rsa", - "hash": "sha256", - "id": "3031300d060960864801650304020105000420" - }, - "RSA-SHA256": { - "sign": "ecdsa/rsa", - "hash": "sha256", - "id": "3031300d060960864801650304020105000420" - }, - "sha384WithRSAEncryption": { - "sign": "rsa", - "hash": "sha384", - "id": "3041300d060960864801650304020205000430" - }, - "RSA-SHA384": { - "sign": "ecdsa/rsa", - "hash": "sha384", - "id": "3041300d060960864801650304020205000430" - }, - "sha512WithRSAEncryption": { - "sign": "rsa", - "hash": "sha512", - "id": "3051300d060960864801650304020305000440" - }, - "RSA-SHA512": { - "sign": "ecdsa/rsa", - "hash": "sha512", - "id": "3051300d060960864801650304020305000440" - }, - "RSA-SHA1": { - "sign": "rsa", - "hash": "sha1", - "id": "3021300906052b0e03021a05000414" - }, - "ecdsa-with-SHA1": { - "sign": "ecdsa", - "hash": "sha1", - "id": "" - }, - "sha256": { - "sign": "ecdsa", - "hash": "sha256", - "id": "" - }, - "sha224": { - "sign": "ecdsa", - "hash": "sha224", - "id": "" - }, - "sha384": { - "sign": "ecdsa", - "hash": "sha384", - "id": "" - }, - "sha512": { - "sign": "ecdsa", - "hash": "sha512", - "id": "" - }, - "DSA-SHA": { - "sign": "dsa", - "hash": "sha1", - "id": "" - }, - "DSA-SHA1": { - "sign": "dsa", - "hash": "sha1", - "id": "" - }, - "DSA": { - "sign": "dsa", - "hash": "sha1", - "id": "" - }, - "DSA-WITH-SHA224": { - "sign": "dsa", - "hash": "sha224", - "id": "" - }, - "DSA-SHA224": { - "sign": "dsa", - "hash": "sha224", - "id": "" - }, - "DSA-WITH-SHA256": { - "sign": "dsa", - "hash": "sha256", - "id": "" - }, - "DSA-SHA256": { - "sign": "dsa", - "hash": "sha256", - "id": "" - }, - "DSA-WITH-SHA384": { - "sign": "dsa", - "hash": "sha384", - "id": "" - }, - "DSA-SHA384": { - "sign": "dsa", - "hash": "sha384", - "id": "" - }, - "DSA-WITH-SHA512": { - "sign": "dsa", - "hash": "sha512", - "id": "" - }, - "DSA-SHA512": { - "sign": "dsa", - "hash": "sha512", - "id": "" - }, - "DSA-RIPEMD160": { - "sign": "dsa", - "hash": "rmd160", - "id": "" - }, - "ripemd160WithRSA": { - "sign": "rsa", - "hash": "rmd160", - "id": "3021300906052b2403020105000414" - }, - "RSA-RIPEMD160": { - "sign": "rsa", - "hash": "rmd160", - "id": "3021300906052b2403020105000414" - }, - "md5WithRSAEncryption": { - "sign": "rsa", - "hash": "md5", - "id": "3020300c06082a864886f70d020505000410" - }, - "RSA-MD5": { - "sign": "rsa", - "hash": "md5", - "id": "3020300c06082a864886f70d020505000410" - } -} - -},{}],45:[function(require,module,exports){ -module.exports={ - "1.3.132.0.10": "secp256k1", - "1.3.132.0.33": "p224", - "1.2.840.10045.3.1.1": "p192", - "1.2.840.10045.3.1.7": "p256", - "1.3.132.0.34": "p384", - "1.3.132.0.35": "p521" -} - -},{}],46:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var createHash = require('create-hash') -var stream = require('readable-stream') -var inherits = require('inherits') -var sign = require('./sign') -var verify = require('./verify') - -var algorithms = require('./algorithms.json') -Object.keys(algorithms).forEach(function (key) { - algorithms[key].id = Buffer.from(algorithms[key].id, 'hex') - algorithms[key.toLowerCase()] = algorithms[key] -}) - -function Sign (algorithm) { - stream.Writable.call(this) - - var data = algorithms[algorithm] - if (!data) throw new Error('Unknown message digest') - - this._hashType = data.hash - this._hash = createHash(data.hash) - this._tag = data.id - this._signType = data.sign -} -inherits(Sign, stream.Writable) - -Sign.prototype._write = function _write (data, _, done) { - this._hash.update(data) - done() -} - -Sign.prototype.update = function update (data, enc) { - if (typeof data === 'string') data = Buffer.from(data, enc) - - this._hash.update(data) - return this -} - -Sign.prototype.sign = function signMethod (key, enc) { - this.end() - var hash = this._hash.digest() - var sig = sign(hash, key, this._hashType, this._signType, this._tag) - - return enc ? sig.toString(enc) : sig -} - -function Verify (algorithm) { - stream.Writable.call(this) - - var data = algorithms[algorithm] - if (!data) throw new Error('Unknown message digest') - - this._hash = createHash(data.hash) - this._tag = data.id - this._signType = data.sign -} -inherits(Verify, stream.Writable) - -Verify.prototype._write = function _write (data, _, done) { - this._hash.update(data) - done() -} - -Verify.prototype.update = function update (data, enc) { - if (typeof data === 'string') data = Buffer.from(data, enc) - - this._hash.update(data) - return this -} - -Verify.prototype.verify = function verifyMethod (key, sig, enc) { - if (typeof sig === 'string') sig = Buffer.from(sig, enc) - - this.end() - var hash = this._hash.digest() - return verify(sig, hash, key, this._signType, this._tag) -} - -function createSign (algorithm) { - return new Sign(algorithm) -} - -function createVerify (algorithm) { - return new Verify(algorithm) -} - -module.exports = { - Sign: createSign, - Verify: createVerify, - createSign: createSign, - createVerify: createVerify -} - -},{"./algorithms.json":44,"./sign":47,"./verify":48,"create-hash":74,"inherits":146,"readable-stream":64,"safe-buffer":250}],47:[function(require,module,exports){ -// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js -var Buffer = require('safe-buffer').Buffer -var createHmac = require('create-hmac') -var crt = require('browserify-rsa') -var EC = require('elliptic').ec -var BN = require('bn.js') -var parseKeys = require('parse-asn1') -var curves = require('./curves.json') - -function sign (hash, key, hashType, signType, tag) { - var priv = parseKeys(key) - if (priv.curve) { - // rsa keys can be interpreted as ecdsa ones in openssl - if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type') - return ecSign(hash, priv) - } else if (priv.type === 'dsa') { - if (signType !== 'dsa') throw new Error('wrong private key type') - return dsaSign(hash, priv, hashType) - } else { - if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type') - } - hash = Buffer.concat([tag, hash]) - var len = priv.modulus.byteLength() - var pad = [0, 1] - while (hash.length + pad.length + 1 < len) pad.push(0xff) - pad.push(0x00) - var i = -1 - while (++i < hash.length) pad.push(hash[i]) - - var out = crt(pad, priv) - return out -} - -function ecSign (hash, priv) { - var curveId = curves[priv.curve.join('.')] - if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.')) - - var curve = new EC(curveId) - var key = curve.keyFromPrivate(priv.privateKey) - var out = key.sign(hash) - - return Buffer.from(out.toDER()) -} - -function dsaSign (hash, priv, algo) { - var x = priv.params.priv_key - var p = priv.params.p - var q = priv.params.q - var g = priv.params.g - var r = new BN(0) - var k - var H = bits2int(hash, q).mod(q) - var s = false - var kv = getKey(x, q, hash, algo) - while (s === false) { - k = makeKey(q, kv, algo) - r = makeR(g, k, p, q) - s = k.invm(q).imul(H.add(x.mul(r))).mod(q) - if (s.cmpn(0) === 0) { - s = false - r = new BN(0) - } - } - return toDER(r, s) -} - -function toDER (r, s) { - r = r.toArray() - s = s.toArray() - - // Pad values - if (r[0] & 0x80) r = [0].concat(r) - if (s[0] & 0x80) s = [0].concat(s) - - var total = r.length + s.length + 4 - var res = [0x30, total, 0x02, r.length] - res = res.concat(r, [0x02, s.length], s) - return Buffer.from(res) -} - -function getKey (x, q, hash, algo) { - x = Buffer.from(x.toArray()) - if (x.length < q.byteLength()) { - var zeros = Buffer.alloc(q.byteLength() - x.length) - x = Buffer.concat([zeros, x]) - } - var hlen = hash.length - var hbits = bits2octets(hash, q) - var v = Buffer.alloc(hlen) - v.fill(1) - var k = Buffer.alloc(hlen) - k = createHmac(algo, k).update(v).update(Buffer.from([0])).update(x).update(hbits).digest() - v = createHmac(algo, k).update(v).digest() - k = createHmac(algo, k).update(v).update(Buffer.from([1])).update(x).update(hbits).digest() - v = createHmac(algo, k).update(v).digest() - return { k: k, v: v } -} - -function bits2int (obits, q) { - var bits = new BN(obits) - var shift = (obits.length << 3) - q.bitLength() - if (shift > 0) bits.ishrn(shift) - return bits -} - -function bits2octets (bits, q) { - bits = bits2int(bits, q) - bits = bits.mod(q) - var out = Buffer.from(bits.toArray()) - if (out.length < q.byteLength()) { - var zeros = Buffer.alloc(q.byteLength() - out.length) - out = Buffer.concat([zeros, out]) - } - return out -} - -function makeKey (q, kv, algo) { - var t - var k - - do { - t = Buffer.alloc(0) - - while (t.length * 8 < q.bitLength()) { - kv.v = createHmac(algo, kv.k).update(kv.v).digest() - t = Buffer.concat([t, kv.v]) - } - - k = bits2int(t, q) - kv.k = createHmac(algo, kv.k).update(kv.v).update(Buffer.from([0])).digest() - kv.v = createHmac(algo, kv.k).update(kv.v).digest() - } while (k.cmp(q) !== -1) - - return k -} - -function makeR (g, k, p, q) { - return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q) -} - -module.exports = sign -module.exports.getKey = getKey -module.exports.makeKey = makeKey - -},{"./curves.json":45,"bn.js":49,"browserify-rsa":41,"create-hmac":76,"elliptic":89,"parse-asn1":230,"safe-buffer":250}],48:[function(require,module,exports){ -// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js -var Buffer = require('safe-buffer').Buffer -var BN = require('bn.js') -var EC = require('elliptic').ec -var parseKeys = require('parse-asn1') -var curves = require('./curves.json') - -function verify (sig, hash, key, signType, tag) { - var pub = parseKeys(key) - if (pub.type === 'ec') { - // rsa keys can be interpreted as ecdsa ones in openssl - if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type') - return ecVerify(sig, hash, pub) - } else if (pub.type === 'dsa') { - if (signType !== 'dsa') throw new Error('wrong public key type') - return dsaVerify(sig, hash, pub) - } else { - if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type') - } - hash = Buffer.concat([tag, hash]) - var len = pub.modulus.byteLength() - var pad = [1] - var padNum = 0 - while (hash.length + pad.length + 2 < len) { - pad.push(0xff) - padNum++ - } - pad.push(0x00) - var i = -1 - while (++i < hash.length) { - pad.push(hash[i]) - } - pad = Buffer.from(pad) - var red = BN.mont(pub.modulus) - sig = new BN(sig).toRed(red) - - sig = sig.redPow(new BN(pub.publicExponent)) - sig = Buffer.from(sig.fromRed().toArray()) - var out = padNum < 8 ? 1 : 0 - len = Math.min(sig.length, pad.length) - if (sig.length !== pad.length) out = 1 - - i = -1 - while (++i < len) out |= sig[i] ^ pad[i] - return out === 0 -} - -function ecVerify (sig, hash, pub) { - var curveId = curves[pub.data.algorithm.curve.join('.')] - if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.')) - - var curve = new EC(curveId) - var pubkey = pub.data.subjectPrivateKey.data - - return curve.verify(hash, sig, pubkey) -} - -function dsaVerify (sig, hash, pub) { - var p = pub.data.p - var q = pub.data.q - var g = pub.data.g - var y = pub.data.pub_key - var unpacked = parseKeys.signature.decode(sig, 'der') - var s = unpacked.s - var r = unpacked.r - checkValue(s, q) - checkValue(r, q) - var montp = BN.mont(p) - var w = s.invm(q) - var v = g.toRed(montp) - .redPow(new BN(hash).mul(w).mod(q)) - .fromRed() - .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()) - .mod(p) - .mod(q) - return v.cmp(r) === 0 -} - -function checkValue (b, q) { - if (b.cmpn(0) <= 0) throw new Error('invalid sig') - if (b.cmp(q) >= q) throw new Error('invalid sig') -} - -module.exports = verify - -},{"./curves.json":45,"bn.js":49,"elliptic":89,"parse-asn1":230,"safe-buffer":250}],49:[function(require,module,exports){ -arguments[4][42][0].apply(exports,arguments) -},{"buffer":20,"dup":42}],50:[function(require,module,exports){ -'use strict'; - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var codes = {}; - -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - - function getMessage(arg1, arg2, arg3) { - if (typeof message === 'string') { - return message; - } else { - return message(arg1, arg2, arg3); - } - } - - var NodeError = - /*#__PURE__*/ - function (_Base) { - _inheritsLoose(NodeError, _Base); - - function NodeError(arg1, arg2, arg3) { - return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; - } - - return NodeError; - }(Base); - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - codes[code] = NodeError; -} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - - -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function (i) { - return String(i); - }); - - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); - } - } else { - return "of ".concat(thing, " ").concat(String(expected)); - } -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - - -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - - -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - - return str.substring(this_len - search.length, this_len) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - - -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} - -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"'; -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - var determiner; - - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - var msg; - - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } else { - var type = includes(name, '.') ? 'property' : 'argument'; - msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } - - msg += ". Received type ".concat(typeof actual); - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented'; -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg; -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); -module.exports.codes = codes; - -},{}],51:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. -'use strict'; -/**/ - -var objectKeys = Object.keys || function (obj) { - var keys = []; - - for (var key in obj) { - keys.push(key); - } - - return keys; -}; -/**/ - - -module.exports = Duplex; - -var Readable = require('./_stream_readable'); - -var Writable = require('./_stream_writable'); - -require('inherits')(Duplex, Readable); - -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } -} - -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); // the no-half-open enforcer - -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. - - process.nextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); -}).call(this)}).call(this,require('_process')) - -},{"./_stream_readable":53,"./_stream_writable":55,"_process":237,"inherits":146}],52:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. -'use strict'; - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -require('inherits')(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} - -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; -},{"./_stream_transform":54,"inherits":146}],53:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -'use strict'; - -module.exports = Readable; -/**/ - -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; -/**/ - -var EE = require('events').EventEmitter; - -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ - - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ - - -var debugUtil = require('util'); - -var debug; - -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ - - -var BufferList = require('./internal/streams/buffer_list'); - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - - -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; - -require('inherits')(Readable, Stream); - -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} - -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - - this.autoDestroy = !!options.autoDestroy; // has it been destroyed - - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; - - if (options.encoding) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); // legacy - - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; - -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; // Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. - - -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; // Unshift should *always* be something directly out of read() - - -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } - - return er; -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; // backwards compatibility. - - -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; - - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - - this._readableState.buffer.clear(); - - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; // Don't raise the hwm > 1GB - - -var MAX_HWM = 0x40000000; - -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. - - -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - - - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - - if (!state.ended) { - state.needReadable = true; - return 0; - } - - return state.length; -} // you can override either this method, or the async _read(n) below. - - -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - - - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - - - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - - if (state.length === 0) state.needReadable = true; // call internal read method - - this._read(state.highWaterMark); - - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - return ret; -}; - -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; - - if (state.decoder) { - var chunk = state.decoder.end(); - - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - - state.ended = true; - - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } -} // Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. - - -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } -} - -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} // at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. - - -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } - - state.readingMore = false; -} // abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. - - -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - - case 1: - state.pipes = [state.pipes, dest]; - break; - - default: - state.pipes.push(dest); - break; - } - - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); - - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } - - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - - - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. - - - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - - dest.once('close', onclose); - - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - - - dest.emit('pipe', src); // start the flow if it hasn't been started already. - - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. - - if (state.pipesCount === 0) return this; // just one destination. most common case. - - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. - - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. - - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } - - return this; - } // try to find the right one. - - - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; // set up data events if they are asked for -// Ensure readable listeners eventually get something - - -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } - } - } - - return res; -}; - -Readable.prototype.addListener = Readable.prototype.on; - -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } -} - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} // pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. - - -Readable.prototype.resume = function () { - var state = this._readableState; - - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() - - state.flowing = !state.readableListening; - resume(this, state); - } - - state.paused = false; - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - debug('resume', state.reading); - - if (!state.reading) { - stream.read(0); - } - - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - - this._readableState.paused = true; - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - - while (state.flowing && stream.read() !== null) { - ; - } -} // wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. - - -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. - - - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. - - - this._read = function (n) { - debug('wrapped _read', n); - - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; -}; - -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); - } - - return createReadableStreamAsyncIterator(this); - }; -} - -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } -}); // exposed for testing purposes only. - -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } -}); // Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. - -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); - - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } -} - -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = require('./internal/streams/from'); - } - - return from(Readable, iterable, opts); - }; -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - - return -1; -} -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"../errors":50,"./_stream_duplex":51,"./internal/streams/async_iterator":56,"./internal/streams/buffer_list":57,"./internal/streams/destroy":58,"./internal/streams/from":60,"./internal/streams/state":62,"./internal/streams/stream":63,"_process":237,"buffer":68,"events":105,"inherits":146,"string_decoder/":279,"util":20}],54:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. -'use strict'; - -module.exports = Transform; - -var _require$codes = require('../errors').codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - -var Duplex = require('./_stream_duplex'); - -require('inherits')(Transform, Duplex); - -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } - - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} - -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. - - - this.on('prefinish', prefinish); -} - -function prefinish() { - var _this = this; - - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } -} - -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; // This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. - - -Transform.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; // Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. - - -Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - -Transform.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); -}; - -function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); -} -},{"../errors":50,"./_stream_duplex":51,"inherits":146}],55:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. -'use strict'; - -module.exports = Writable; -/* */ - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} // It seems a linked list but it is not -// there will be only 2 of these for each stream - - -function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ - - -var Duplex; -/**/ - -Writable.WritableState = WritableState; -/**/ - -var internalUtil = { - deprecate: require('util-deprecate') -}; -/**/ - -/**/ - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - -var errorOrDestroy = destroyImpl.errorOrDestroy; - -require('inherits')(Writable, Stream); - -function nop() {} - -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream - // contains buffers or objects. - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. - - this.needDrain = false; // at the start of calling end() - - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted - - this.finished = false; // has it been destroyed - - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - - this.length = 0; // a flag to see when we're in the middle of a write. - - this.writing = false; // when true all writes will be buffered until .uncork() call - - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - - - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again - - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - - this.autoDestroy = !!options.autoDestroy; // count buffered requests - - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - - while (current) { - out.push(current); - current = current.next; - } - - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); // Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. - - -var realHasInstance; - -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. - - -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; - -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} // Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. - - -function validChunk(stream, state, chunk, cb) { - var er; - - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } - - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; - } - - return true; -} - -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; -}; - -Writable.prototype.cork = function () { - this._writableState.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - - return chunk; -} - -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); // if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. - -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen - // after error - - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); // this can emit finish, but finish must - // always follow error - - finishMaybe(stream, state); - } -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} // Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. - - -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} // if there's something in the buffer waiting, then process it - - -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - - state.pendingcb++; - state.lastBufferedRequest = null; - - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending) endWritable(this, state, cb); - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} - -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy(stream, err); - } - - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} - -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - - if (need) { - prefinish(stream, state); - - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } - - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; - -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"../errors":50,"./_stream_duplex":51,"./internal/streams/destroy":58,"./internal/streams/state":62,"./internal/streams/stream":63,"_process":237,"buffer":68,"inherits":146,"util-deprecate":283}],56:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; - -var _Object$setPrototypeO; - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var finished = require('./end-of-stream'); - -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); - -function createIterResult(value, done) { - return { - value: value, - done: done - }; -} - -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' - - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } -} - -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} - -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - - iter[kHandlePromise](resolve, reject); - }, reject); - }; -} - -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); - } - - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } - - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; - - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - - promise = new Promise(this[kHandlePromise]); - } - - this[kLastPromise] = promise; - return promise; - } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); - -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - - iterator[kError] = err; - return; - } - - var resolve = iterator[kLastResolve]; - - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } - - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; - -module.exports = createReadableStreamAsyncIterator; -}).call(this)}).call(this,require('_process')) - -},{"./end-of-stream":59,"_process":237}],57:[function(require,module,exports){ -'use strict'; - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { 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: 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); return Constructor; } - -var _require = require('buffer'), - Buffer = _require.Buffer; - -var _require2 = require('util'), - inspect = _require2.inspect; - -var custom = inspect && inspect.custom || 'inspect'; - -function copyBuffer(src, target, offset) { - Buffer.prototype.copy.call(src, target, offset); -} - -module.exports = -/*#__PURE__*/ -function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. - - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. - - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. - - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - - return BufferList; -}(); -},{"buffer":68,"util":20}],58:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; // undocumented cb() API, needed for core, not for public API - -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } - - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); - } - }); - - return this; -} - -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); -} - -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; -}).call(this)}).call(this,require('_process')) - -},{"_process":237}],59:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/end-of-stream with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - callback.apply(this, args); - }; -} - -function noop() {} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function eos(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; - - var writableEnded = stream._writableState && stream._writableState.finished; - - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - - var readableEnded = stream._readableState && stream._readableState.endEmitted; - - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; - - var onerror = function onerror(err) { - callback.call(stream, err); - }; - - var onclose = function onclose() { - var err; - - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; - - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -} - -module.exports = eos; -},{"../../../errors":50}],60:[function(require,module,exports){ -module.exports = function () { - throw new Error('Readable.from is not available in the browser') -}; - -},{}],61:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var eos; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; -} - -var _require$codes = require('../../../errors').codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - -function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; -} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = require('./end-of-stream'); - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want - - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; -} - -function call(fn) { - fn(); -} - -function pipe(from, to) { - return from.pipe(to); -} - -function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); -} - -function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; - - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } - - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); -} - -module.exports = pipeline; -},{"../../../errors":50,"./end-of-stream":59}],62:[function(require,module,exports){ -'use strict'; - -var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; - -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; -} - -function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - - return Math.floor(hwm); - } // Default value - - - return state.objectMode ? 16 : 16 * 1024; -} - -module.exports = { - getHighWaterMark: getHighWaterMark -}; -},{"../../../errors":50}],63:[function(require,module,exports){ -module.exports = require('events').EventEmitter; - -},{"events":105}],64:[function(require,module,exports){ -exports = module.exports = require('./lib/_stream_readable.js'); -exports.Stream = exports; -exports.Readable = exports; -exports.Writable = require('./lib/_stream_writable.js'); -exports.Duplex = require('./lib/_stream_duplex.js'); -exports.Transform = require('./lib/_stream_transform.js'); -exports.PassThrough = require('./lib/_stream_passthrough.js'); -exports.finished = require('./lib/internal/streams/end-of-stream.js'); -exports.pipeline = require('./lib/internal/streams/pipeline.js'); - -},{"./lib/_stream_duplex.js":51,"./lib/_stream_passthrough.js":52,"./lib/_stream_readable.js":53,"./lib/_stream_transform.js":54,"./lib/_stream_writable.js":55,"./lib/internal/streams/end-of-stream.js":59,"./lib/internal/streams/pipeline.js":61}],65:[function(require,module,exports){ -const basex = require('base-x') -const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' - -module.exports = basex(ALPHABET) - -},{"base-x":66}],66:[function(require,module,exports){ -'use strict' -// base-x encoding / decoding -// Copyright (c) 2018 base-x contributors -// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp) -// Distributed under the MIT software license, see the accompanying -// file LICENSE or http://www.opensource.org/licenses/mit-license.php. -function base (ALPHABET) { - if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') } - var BASE_MAP = new Uint8Array(256) - for (var j = 0; j < BASE_MAP.length; j++) { - BASE_MAP[j] = 255 - } - for (var i = 0; i < ALPHABET.length; i++) { - var x = ALPHABET.charAt(i) - var xc = x.charCodeAt(0) - if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') } - BASE_MAP[xc] = i - } - var BASE = ALPHABET.length - var LEADER = ALPHABET.charAt(0) - var FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up - var iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up - 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 '' } - // Skip & count leading zeroes. - var zeroes = 0 - var length = 0 - var pbegin = 0 - var pend = source.length - while (pbegin !== pend && source[pbegin] === 0) { - pbegin++ - zeroes++ - } - // Allocate enough space in big-endian base58 representation. - var size = ((pend - pbegin) * iFACTOR + 1) >>> 0 - var b58 = new Uint8Array(size) - // Process the bytes. - while (pbegin !== pend) { - var carry = source[pbegin] - // Apply "b58 = b58 * 256 + ch". - var i = 0 - for (var 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++ - } - // Skip leading zeroes in base58 result. - var it2 = size - length - while (it2 !== size && b58[it2] === 0) { - it2++ - } - // Translate the result into a string. - var 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() } - var psz = 0 - // Skip and count leading '1's. - var zeroes = 0 - var length = 0 - while (source[psz] === LEADER) { - zeroes++ - psz++ - } - // Allocate enough space in big-endian base256 representation. - var size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up. - var b256 = new Uint8Array(size) - // Process the characters. - while (source[psz]) { - // Decode character - var carry = BASE_MAP[source.charCodeAt(psz)] - // Invalid character - if (carry === 255) { return } - var i = 0 - for (var 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++ - } - // Skip leading zeroes in b256. - var it4 = size - length - while (it4 !== size && b256[it4] === 0) { - it4++ - } - var vch = new Uint8Array(zeroes + (size - it4)) - var j = zeroes - while (it4 !== size) { - vch[j++] = b256[it4++] - } - return vch - } - function decode (string) { - var buffer = decodeUnsafe(string) - if (buffer) { return buffer } - throw new Error('Non-base' + BASE + ' character') - } - return { - encode: encode, - decodeUnsafe: decodeUnsafe, - decode: decode - } -} -module.exports = base - -},{}],67:[function(require,module,exports){ -(function (Buffer){(function (){ -module.exports = function xor (a, b) { - var length = Math.min(a.length, b.length) - var buffer = new Buffer(length) - - for (var i = 0; i < length; ++i) { - buffer[i] = a[i] ^ b[i] - } - - return buffer -} - -}).call(this)}).call(this,require("buffer").Buffer) - -},{"buffer":68}],68:[function(require,module,exports){ -(function (Buffer){(function (){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - -'use strict' - -var base64 = require('base64-js') -var ieee754 = require('ieee754') - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -var K_MAX_LENGTH = 0x7fffffff -exports.kMaxLength = K_MAX_LENGTH - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() - -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && - typeof console.error === 'function') { - console.error( - 'This browser lacks typed array (Uint8Array) support which is required by ' + - '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' - ) -} - -function typedArraySupport () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1) - arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } - return arr.foo() === 42 - } catch (e) { - return false - } -} - -Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.buffer - } -}) - -Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.byteOffset - } -}) - -function createBuffer (length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"') - } - // Return an augmented `Uint8Array` instance - var buf = new Uint8Array(length) - buf.__proto__ = Buffer.prototype - return buf -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ) - } - return allocUnsafe(arg) - } - return from(arg, encodingOrOffset, length) -} - -// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 -if (typeof Symbol !== 'undefined' && Symbol.species != null && - Buffer[Symbol.species] === Buffer) { - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true, - enumerable: false, - writable: false - }) -} - -Buffer.poolSize = 8192 // not used by this implementation - -function from (value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) - } - - if (ArrayBuffer.isView(value)) { - return fromArrayLike(value) - } - - if (value == null) { - throw TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) - } - - if (isInstance(value, ArrayBuffer) || - (value && isInstance(value.buffer, ArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } - - if (typeof value === 'number') { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ) - } - - var valueOf = value.valueOf && value.valueOf() - if (valueOf != null && valueOf !== value) { - return Buffer.from(valueOf, encodingOrOffset, length) - } - - var b = fromObject(value) - if (b) return b - - if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && - typeof value[Symbol.toPrimitive] === 'function') { - return Buffer.from( - value[Symbol.toPrimitive]('string'), encodingOrOffset, length - ) - } - - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length) -} - -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Buffer.prototype.__proto__ = Uint8Array.prototype -Buffer.__proto__ = Uint8Array - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be of type number') - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } -} - -function alloc (size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) - } - return createBuffer(size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) -} - -function allocUnsafe (size) { - assertSize(size) - return createBuffer(size < 0 ? 0 : checked(size) | 0) -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(size) -} - -function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - - var length = byteLength(string, encoding) | 0 - var buf = createBuffer(length) - - var actual = buf.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual) - } - - return buf -} - -function fromArrayLike (array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - var buf = createBuffer(length) - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255 - } - return buf -} - -function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') - } - - var buf - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) - } else { - buf = new Uint8Array(array, byteOffset, length) - } - - // Return an augmented `Uint8Array` instance - buf.__proto__ = Buffer.prototype - return buf -} - -function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - var buf = createBuffer(len) - - if (buf.length === 0) { - return buf - } - - obj.copy(buf, 0, 0, len) - return buf - } - - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) - } -} - -function checked (length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= K_MAX_LENGTH) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true && - b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false -} - -Buffer.compare = function compare (a, b) { - if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) - if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ) - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (isInstance(buf, Uint8Array)) { - buf = Buffer.from(buf) - } - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + - 'Received type ' + typeof string - ) - } - - var len = string.length - var mustMatch = (arguments.length > 2 && arguments[2] === true) - if (!mustMatch && len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 - } - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.toLocaleString = Buffer.prototype.toString - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() - if (this.length > max) str += ' ... ' - return '' -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer.from(target, target.offset, target.byteLength) - } - if (!Buffer.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. ' + - 'Received type ' + (typeof target) - ) - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - var strLen = string.length - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 0 - if (isFinite(length)) { - length = length >>> 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf = this.subarray(start, end) - // Return an augmented `Uint8Array` instance - newBuf.__proto__ = Buffer.prototype - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('Index out of range') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end) - } else if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (var i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if ((encoding === 'utf8' && code < 128) || - encoding === 'latin1') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code - } - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : Buffer.from(val, encoding) - var len = bytes.length - if (len === 0) { - throw new TypeError('The value "' + val + - '" is invalid for argument "value"') - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0] - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass -// the `instanceof` check but they should be treated as of that type. -// See: https://github.com/feross/buffer/issues/166 -function isInstance (obj, type) { - return obj instanceof type || - (obj != null && obj.constructor != null && obj.constructor.name != null && - obj.constructor.name === type.name) -} -function numberIsNaN (obj) { - // For IE11 support - return obj !== obj // eslint-disable-line no-self-compare -} - -}).call(this)}).call(this,require("buffer").Buffer) - -},{"base64-js":17,"buffer":68,"ieee754":145}],69:[function(require,module,exports){ -'use strict'; - -var GetIntrinsic = require('get-intrinsic'); - -var callBind = require('./'); - -var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); - -module.exports = function callBoundIntrinsic(name, allowMissing) { - var intrinsic = GetIntrinsic(name, !!allowMissing); - if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { - return callBind(intrinsic); - } - return intrinsic; -}; - -},{"./":70,"get-intrinsic":110}],70:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); -var GetIntrinsic = require('get-intrinsic'); - -var $apply = GetIntrinsic('%Function.prototype.apply%'); -var $call = GetIntrinsic('%Function.prototype.call%'); -var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); - -var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); -var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); -var $max = GetIntrinsic('%Math.max%'); - -if ($defineProperty) { - try { - $defineProperty({}, 'a', { value: 1 }); - } catch (e) { - // IE 8 has a broken defineProperty - $defineProperty = null; - } -} - -module.exports = function callBind(originalFunction) { - var func = $reflectApply(bind, $call, arguments); - if ($gOPD && $defineProperty) { - var desc = $gOPD(func, 'length'); - if (desc.configurable) { - // original length, plus the receiver, minus any additional arguments (after the receiver) - $defineProperty( - func, - 'length', - { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } - ); - } - } - return func; -}; - -var applyBind = function applyBind() { - return $reflectApply(bind, $apply, arguments); -}; - -if ($defineProperty) { - $defineProperty(module.exports, 'apply', { value: applyBind }); -} else { - module.exports.apply = applyBind; -} - -},{"function-bind":109,"get-intrinsic":110}],71:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var Transform = require('stream').Transform -var StringDecoder = require('string_decoder').StringDecoder -var inherits = require('inherits') - -function CipherBase (hashMode) { - Transform.call(this) - this.hashMode = typeof hashMode === 'string' - if (this.hashMode) { - this[hashMode] = this._finalOrDigest - } else { - this.final = this._finalOrDigest - } - if (this._final) { - this.__final = this._final - this._final = null - } - this._decoder = null - this._encoding = null -} -inherits(CipherBase, Transform) - -CipherBase.prototype.update = function (data, inputEnc, outputEnc) { - if (typeof data === 'string') { - data = Buffer.from(data, inputEnc) - } - - var outData = this._update(data) - if (this.hashMode) return this - - if (outputEnc) { - outData = this._toString(outData, outputEnc) - } - - return outData -} - -CipherBase.prototype.setAutoPadding = function () {} -CipherBase.prototype.getAuthTag = function () { - throw new Error('trying to get auth tag in unsupported state') -} - -CipherBase.prototype.setAuthTag = function () { - throw new Error('trying to set auth tag in unsupported state') -} - -CipherBase.prototype.setAAD = function () { - throw new Error('trying to set aad in unsupported state') -} - -CipherBase.prototype._transform = function (data, _, next) { - var err - try { - if (this.hashMode) { - this._update(data) - } else { - this.push(this._update(data)) - } - } catch (e) { - err = e - } finally { - next(err) - } -} -CipherBase.prototype._flush = function (done) { - var err - try { - this.push(this.__final()) - } catch (e) { - err = e - } - - done(err) -} -CipherBase.prototype._finalOrDigest = function (outputEnc) { - var outData = this.__final() || Buffer.alloc(0) - if (outputEnc) { - outData = this._toString(outData, outputEnc, true) - } - return outData -} - -CipherBase.prototype._toString = function (value, enc, fin) { - if (!this._decoder) { - this._decoder = new StringDecoder(enc) - this._encoding = enc - } - - if (this._encoding !== enc) throw new Error('can\'t switch encodings') - - var out = this._decoder.write(value) - if (fin) { - out += this._decoder.end() - } - - return out -} - -module.exports = CipherBase - -},{"inherits":146,"safe-buffer":250,"stream":264,"string_decoder":279}],72:[function(require,module,exports){ -/*! - * content-type - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 - * - * parameter = token "=" ( token / quoted-string ) - * token = 1*tchar - * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" - * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" - * / DIGIT / ALPHA - * ; any VCHAR, except delimiters - * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE - * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text - * obs-text = %x80-FF - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - */ -var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g // eslint-disable-line no-control-regex -var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ // eslint-disable-line no-control-regex -var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ - -/** - * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 - * - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - * obs-text = %x80-FF - */ -var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g // eslint-disable-line no-control-regex - -/** - * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 - */ -var QUOTE_REGEXP = /([\\"])/g - -/** - * RegExp to match type in RFC 7231 sec 3.1.1.1 - * - * media-type = type "/" subtype - * type = token - * subtype = token - */ -var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ - -/** - * Module exports. - * @public - */ - -exports.format = format -exports.parse = parse - -/** - * Format object to media type. - * - * @param {object} obj - * @return {string} - * @public - */ - -function format (obj) { - if (!obj || typeof obj !== 'object') { - throw new TypeError('argument obj is required') - } - - var parameters = obj.parameters - var type = obj.type - - if (!type || !TYPE_REGEXP.test(type)) { - throw new TypeError('invalid type') - } - - var string = type - - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() - - for (var i = 0; i < params.length; i++) { - param = params[i] - - if (!TOKEN_REGEXP.test(param)) { - throw new TypeError('invalid parameter name') - } - - string += '; ' + param + '=' + qstring(parameters[param]) - } - } - - return string -} - -/** - * Parse media type to object. - * - * @param {string|object} string - * @return {Object} - * @public - */ - -function parse (string) { - if (!string) { - throw new TypeError('argument string is required') - } - - // support req/res-like objects as argument - var header = typeof string === 'object' - ? getcontenttype(string) - : string - - if (typeof header !== 'string') { - throw new TypeError('argument string is required to be a string') - } - - var index = header.indexOf(';') - var type = index !== -1 - ? header.slice(0, index).trim() - : header.trim() - - if (!TYPE_REGEXP.test(type)) { - throw new TypeError('invalid media type') - } - - var obj = new ContentType(type.toLowerCase()) - - // parse parameters - if (index !== -1) { - var key - var match - var value - - PARAM_REGEXP.lastIndex = index - - while ((match = PARAM_REGEXP.exec(header))) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') - } - - index += match[0].length - key = match[1].toLowerCase() - value = match[2] - - if (value.charCodeAt(0) === 0x22 /* " */) { - // remove quotes - value = value.slice(1, -1) - - // remove escapes - if (value.indexOf('\\') !== -1) { - value = value.replace(QESC_REGEXP, '$1') - } - } - - obj.parameters[key] = value - } - - if (index !== header.length) { - throw new TypeError('invalid parameter format') - } - } - - return obj -} - -/** - * Get content-type from req/res objects. - * - * @param {object} - * @return {Object} - * @private - */ - -function getcontenttype (obj) { - var header - - if (typeof obj.getHeader === 'function') { - // res-like - header = obj.getHeader('content-type') - } else if (typeof obj.headers === 'object') { - // req-like - header = obj.headers && obj.headers['content-type'] - } - - if (typeof header !== 'string') { - throw new TypeError('content-type header is missing from object') - } - - return header -} - -/** - * Quote a string if necessary. - * - * @param {string} val - * @return {string} - * @private - */ - -function qstring (val) { - var str = String(val) - - // no need to quote tokens - if (TOKEN_REGEXP.test(str)) { - return str - } - - if (str.length > 0 && !TEXT_REGEXP.test(str)) { - throw new TypeError('invalid parameter value') - } - - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' -} - -/** - * Class to represent a content type. - * @private - */ -function ContentType (type) { - this.parameters = Object.create(null) - this.type = type -} - -},{}],73:[function(require,module,exports){ -(function (Buffer){(function (){ -var elliptic = require('elliptic') -var BN = require('bn.js') - -module.exports = function createECDH (curve) { - return new ECDH(curve) -} - -var aliases = { - secp256k1: { - name: 'secp256k1', - byteLength: 32 - }, - secp224r1: { - name: 'p224', - byteLength: 28 - }, - prime256v1: { - name: 'p256', - byteLength: 32 - }, - prime192v1: { - name: 'p192', - byteLength: 24 - }, - ed25519: { - name: 'ed25519', - byteLength: 32 - }, - secp384r1: { - name: 'p384', - byteLength: 48 - }, - secp521r1: { - name: 'p521', - byteLength: 66 - } -} - -aliases.p224 = aliases.secp224r1 -aliases.p256 = aliases.secp256r1 = aliases.prime256v1 -aliases.p192 = aliases.secp192r1 = aliases.prime192v1 -aliases.p384 = aliases.secp384r1 -aliases.p521 = aliases.secp521r1 - -function ECDH (curve) { - this.curveType = aliases[curve] - if (!this.curveType) { - this.curveType = { - name: curve - } - } - this.curve = new elliptic.ec(this.curveType.name) // eslint-disable-line new-cap - this.keys = void 0 -} - -ECDH.prototype.generateKeys = function (enc, format) { - this.keys = this.curve.genKeyPair() - return this.getPublicKey(enc, format) -} - -ECDH.prototype.computeSecret = function (other, inenc, enc) { - inenc = inenc || 'utf8' - if (!Buffer.isBuffer(other)) { - other = new Buffer(other, inenc) - } - var otherPub = this.curve.keyFromPublic(other).getPublic() - var out = otherPub.mul(this.keys.getPrivate()).getX() - return formatReturnValue(out, enc, this.curveType.byteLength) -} - -ECDH.prototype.getPublicKey = function (enc, format) { - var key = this.keys.getPublic(format === 'compressed', true) - if (format === 'hybrid') { - if (key[key.length - 1] % 2) { - key[0] = 7 - } else { - key[0] = 6 - } - } - return formatReturnValue(key, enc) -} - -ECDH.prototype.getPrivateKey = function (enc) { - return formatReturnValue(this.keys.getPrivate(), enc) -} - -ECDH.prototype.setPublicKey = function (pub, enc) { - enc = enc || 'utf8' - if (!Buffer.isBuffer(pub)) { - pub = new Buffer(pub, enc) - } - this.keys._importPublic(pub) - return this -} - -ECDH.prototype.setPrivateKey = function (priv, enc) { - enc = enc || 'utf8' - if (!Buffer.isBuffer(priv)) { - priv = new Buffer(priv, enc) - } - - var _priv = new BN(priv) - _priv = _priv.toString(16) - this.keys = this.curve.genKeyPair() - this.keys._importPrivate(_priv) - return this -} - -function formatReturnValue (bn, enc, len) { - if (!Array.isArray(bn)) { - bn = bn.toArray() - } - var buf = new Buffer(bn) - if (len && buf.length < len) { - var zeros = new Buffer(len - buf.length) - zeros.fill(0) - buf = Buffer.concat([zeros, buf]) - } - if (!enc) { - return buf - } else { - return buf.toString(enc) - } -} - -}).call(this)}).call(this,require("buffer").Buffer) - -},{"bn.js":18,"buffer":68,"elliptic":89}],74:[function(require,module,exports){ -'use strict' -var inherits = require('inherits') -var MD5 = require('md5.js') -var RIPEMD160 = require('ripemd160') -var sha = require('sha.js') -var Base = require('cipher-base') - -function Hash (hash) { - Base.call(this, 'digest') - - this._hash = hash -} - -inherits(Hash, Base) - -Hash.prototype._update = function (data) { - this._hash.update(data) -} - -Hash.prototype._final = function () { - return this._hash.digest() -} - -module.exports = function createHash (alg) { - alg = alg.toLowerCase() - if (alg === 'md5') return new MD5() - if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160() - - return new Hash(sha(alg)) -} - -},{"cipher-base":71,"inherits":146,"md5.js":221,"ripemd160":249,"sha.js":257}],75:[function(require,module,exports){ -var MD5 = require('md5.js') - -module.exports = function (buffer) { - return new MD5().update(buffer).digest() -} - -},{"md5.js":221}],76:[function(require,module,exports){ -'use strict' -var inherits = require('inherits') -var Legacy = require('./legacy') -var Base = require('cipher-base') -var Buffer = require('safe-buffer').Buffer -var md5 = require('create-hash/md5') -var RIPEMD160 = require('ripemd160') - -var sha = require('sha.js') - -var ZEROS = Buffer.alloc(128) - -function Hmac (alg, key) { - Base.call(this, 'digest') - if (typeof key === 'string') { - key = Buffer.from(key) - } - - var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 - - this._alg = alg - this._key = key - if (key.length > blocksize) { - var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) - key = hash.update(key).digest() - } else if (key.length < blocksize) { - key = Buffer.concat([key, ZEROS], blocksize) - } - - var ipad = this._ipad = Buffer.allocUnsafe(blocksize) - var opad = this._opad = Buffer.allocUnsafe(blocksize) - - for (var i = 0; i < blocksize; i++) { - ipad[i] = key[i] ^ 0x36 - opad[i] = key[i] ^ 0x5C - } - this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) - this._hash.update(ipad) -} - -inherits(Hmac, Base) - -Hmac.prototype._update = function (data) { - this._hash.update(data) -} - -Hmac.prototype._final = function () { - var h = this._hash.digest() - var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg) - return hash.update(this._opad).update(h).digest() -} - -module.exports = function createHmac (alg, key) { - alg = alg.toLowerCase() - if (alg === 'rmd160' || alg === 'ripemd160') { - return new Hmac('rmd160', key) - } - if (alg === 'md5') { - return new Legacy(md5, key) - } - return new Hmac(alg, key) -} - -},{"./legacy":77,"cipher-base":71,"create-hash/md5":75,"inherits":146,"ripemd160":249,"safe-buffer":250,"sha.js":257}],77:[function(require,module,exports){ -'use strict' -var inherits = require('inherits') -var Buffer = require('safe-buffer').Buffer - -var Base = require('cipher-base') - -var ZEROS = Buffer.alloc(128) -var blocksize = 64 - -function Hmac (alg, key) { - Base.call(this, 'digest') - if (typeof key === 'string') { - key = Buffer.from(key) - } - - this._alg = alg - this._key = key - - if (key.length > blocksize) { - key = alg(key) - } else if (key.length < blocksize) { - key = Buffer.concat([key, ZEROS], blocksize) - } - - var ipad = this._ipad = Buffer.allocUnsafe(blocksize) - var opad = this._opad = Buffer.allocUnsafe(blocksize) - - for (var i = 0; i < blocksize; i++) { - ipad[i] = key[i] ^ 0x36 - opad[i] = key[i] ^ 0x5C - } - - this._hash = [ipad] -} - -inherits(Hmac, Base) - -Hmac.prototype._update = function (data) { - this._hash.push(data) -} - -Hmac.prototype._final = function () { - var h = this._alg(Buffer.concat(this._hash)) - return this._alg(Buffer.concat([this._opad, h])) -} -module.exports = Hmac - -},{"cipher-base":71,"inherits":146,"safe-buffer":250}],78:[function(require,module,exports){ -'use strict' - -exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes') -exports.createHash = exports.Hash = require('create-hash') -exports.createHmac = exports.Hmac = require('create-hmac') - -var algos = require('browserify-sign/algos') -var algoKeys = Object.keys(algos) -var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys) -exports.getHashes = function () { - return hashes -} - -var p = require('pbkdf2') -exports.pbkdf2 = p.pbkdf2 -exports.pbkdf2Sync = p.pbkdf2Sync - -var aes = require('browserify-cipher') - -exports.Cipher = aes.Cipher -exports.createCipher = aes.createCipher -exports.Cipheriv = aes.Cipheriv -exports.createCipheriv = aes.createCipheriv -exports.Decipher = aes.Decipher -exports.createDecipher = aes.createDecipher -exports.Decipheriv = aes.Decipheriv -exports.createDecipheriv = aes.createDecipheriv -exports.getCiphers = aes.getCiphers -exports.listCiphers = aes.listCiphers - -var dh = require('diffie-hellman') - -exports.DiffieHellmanGroup = dh.DiffieHellmanGroup -exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup -exports.getDiffieHellman = dh.getDiffieHellman -exports.createDiffieHellman = dh.createDiffieHellman -exports.DiffieHellman = dh.DiffieHellman - -var sign = require('browserify-sign') - -exports.createSign = sign.createSign -exports.Sign = sign.Sign -exports.createVerify = sign.createVerify -exports.Verify = sign.Verify - -exports.createECDH = require('create-ecdh') - -var publicEncrypt = require('public-encrypt') - -exports.publicEncrypt = publicEncrypt.publicEncrypt -exports.privateEncrypt = publicEncrypt.privateEncrypt -exports.publicDecrypt = publicEncrypt.publicDecrypt -exports.privateDecrypt = publicEncrypt.privateDecrypt - -// the least I can do is make error messages for the rest of the node.js/crypto api. -// ;[ -// 'createCredentials' -// ].forEach(function (name) { -// exports[name] = function () { -// throw new Error([ -// 'sorry, ' + name + ' is not implemented yet', -// 'we accept pull requests', -// 'https://github.com/crypto-browserify/crypto-browserify' -// ].join('\n')) -// } -// }) - -var rf = require('randomfill') - -exports.randomFill = rf.randomFill -exports.randomFillSync = rf.randomFillSync - -exports.createCredentials = function () { - throw new Error([ - 'sorry, createCredentials is not implemented yet', - 'we accept pull requests', - 'https://github.com/crypto-browserify/crypto-browserify' - ].join('\n')) -} - -exports.constants = { - 'DH_CHECK_P_NOT_SAFE_PRIME': 2, - 'DH_CHECK_P_NOT_PRIME': 1, - 'DH_UNABLE_TO_CHECK_GENERATOR': 4, - 'DH_NOT_SUITABLE_GENERATOR': 8, - 'NPN_ENABLED': 1, - 'ALPN_ENABLED': 1, - 'RSA_PKCS1_PADDING': 1, - 'RSA_SSLV23_PADDING': 2, - 'RSA_NO_PADDING': 3, - 'RSA_PKCS1_OAEP_PADDING': 4, - 'RSA_X931_PADDING': 5, - 'RSA_PKCS1_PSS_PADDING': 6, - 'POINT_CONVERSION_COMPRESSED': 2, - 'POINT_CONVERSION_UNCOMPRESSED': 4, - 'POINT_CONVERSION_HYBRID': 6 -} - -},{"browserify-cipher":38,"browserify-sign":46,"browserify-sign/algos":43,"create-ecdh":73,"create-hash":74,"create-hmac":76,"diffie-hellman":85,"pbkdf2":231,"public-encrypt":238,"randombytes":244,"randomfill":245}],79:[function(require,module,exports){ -'use strict'; - -exports.utils = require('./des/utils'); -exports.Cipher = require('./des/cipher'); -exports.DES = require('./des/des'); -exports.CBC = require('./des/cbc'); -exports.EDE = require('./des/ede'); - -},{"./des/cbc":80,"./des/cipher":81,"./des/des":82,"./des/ede":83,"./des/utils":84}],80:[function(require,module,exports){ -'use strict'; - -var assert = require('minimalistic-assert'); -var inherits = require('inherits'); - -var proto = {}; - -function CBCState(iv) { - assert.equal(iv.length, 8, 'Invalid IV length'); - - this.iv = new Array(8); - for (var i = 0; i < this.iv.length; i++) - this.iv[i] = iv[i]; -} - -function instantiate(Base) { - function CBC(options) { - Base.call(this, options); - this._cbcInit(); - } - inherits(CBC, Base); - - var keys = Object.keys(proto); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - CBC.prototype[key] = proto[key]; - } - - CBC.create = function create(options) { - return new CBC(options); - }; - - return CBC; -} - -exports.instantiate = instantiate; - -proto._cbcInit = function _cbcInit() { - var state = new CBCState(this.options.iv); - this._cbcState = state; -}; - -proto._update = function _update(inp, inOff, out, outOff) { - var state = this._cbcState; - var superProto = this.constructor.super_.prototype; - - var iv = state.iv; - if (this.type === 'encrypt') { - for (var i = 0; i < this.blockSize; i++) - iv[i] ^= inp[inOff + i]; - - superProto._update.call(this, iv, 0, out, outOff); - - for (var i = 0; i < this.blockSize; i++) - iv[i] = out[outOff + i]; - } else { - superProto._update.call(this, inp, inOff, out, outOff); - - for (var i = 0; i < this.blockSize; i++) - out[outOff + i] ^= iv[i]; - - for (var i = 0; i < this.blockSize; i++) - iv[i] = inp[inOff + i]; - } -}; - -},{"inherits":146,"minimalistic-assert":223}],81:[function(require,module,exports){ -'use strict'; - -var assert = require('minimalistic-assert'); - -function Cipher(options) { - this.options = options; - - this.type = this.options.type; - this.blockSize = 8; - this._init(); - - this.buffer = new Array(this.blockSize); - this.bufferOff = 0; -} -module.exports = Cipher; - -Cipher.prototype._init = function _init() { - // Might be overrided -}; - -Cipher.prototype.update = function update(data) { - if (data.length === 0) - return []; - - if (this.type === 'decrypt') - return this._updateDecrypt(data); - else - return this._updateEncrypt(data); -}; - -Cipher.prototype._buffer = function _buffer(data, off) { - // Append data to buffer - var min = Math.min(this.buffer.length - this.bufferOff, data.length - off); - for (var i = 0; i < min; i++) - this.buffer[this.bufferOff + i] = data[off + i]; - this.bufferOff += min; - - // Shift next - return min; -}; - -Cipher.prototype._flushBuffer = function _flushBuffer(out, off) { - this._update(this.buffer, 0, out, off); - this.bufferOff = 0; - return this.blockSize; -}; - -Cipher.prototype._updateEncrypt = function _updateEncrypt(data) { - var inputOff = 0; - var outputOff = 0; - - var count = ((this.bufferOff + data.length) / this.blockSize) | 0; - var out = new Array(count * this.blockSize); - - if (this.bufferOff !== 0) { - inputOff += this._buffer(data, inputOff); - - if (this.bufferOff === this.buffer.length) - outputOff += this._flushBuffer(out, outputOff); - } - - // Write blocks - var max = data.length - ((data.length - inputOff) % this.blockSize); - for (; inputOff < max; inputOff += this.blockSize) { - this._update(data, inputOff, out, outputOff); - outputOff += this.blockSize; - } - - // Queue rest - for (; inputOff < data.length; inputOff++, this.bufferOff++) - this.buffer[this.bufferOff] = data[inputOff]; - - return out; -}; - -Cipher.prototype._updateDecrypt = function _updateDecrypt(data) { - var inputOff = 0; - var outputOff = 0; - - var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1; - var out = new Array(count * this.blockSize); - - // TODO(indutny): optimize it, this is far from optimal - for (; count > 0; count--) { - inputOff += this._buffer(data, inputOff); - outputOff += this._flushBuffer(out, outputOff); - } - - // Buffer rest of the input - inputOff += this._buffer(data, inputOff); - - return out; -}; - -Cipher.prototype.final = function final(buffer) { - var first; - if (buffer) - first = this.update(buffer); - - var last; - if (this.type === 'encrypt') - last = this._finalEncrypt(); - else - last = this._finalDecrypt(); - - if (first) - return first.concat(last); - else - return last; -}; - -Cipher.prototype._pad = function _pad(buffer, off) { - if (off === 0) - return false; - - while (off < buffer.length) - buffer[off++] = 0; - - return true; -}; - -Cipher.prototype._finalEncrypt = function _finalEncrypt() { - if (!this._pad(this.buffer, this.bufferOff)) - return []; - - var out = new Array(this.blockSize); - this._update(this.buffer, 0, out, 0); - return out; -}; - -Cipher.prototype._unpad = function _unpad(buffer) { - return buffer; -}; - -Cipher.prototype._finalDecrypt = function _finalDecrypt() { - assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt'); - var out = new Array(this.blockSize); - this._flushBuffer(out, 0); - - return this._unpad(out); -}; - -},{"minimalistic-assert":223}],82:[function(require,module,exports){ -'use strict'; - -var assert = require('minimalistic-assert'); -var inherits = require('inherits'); - -var utils = require('./utils'); -var Cipher = require('./cipher'); - -function DESState() { - this.tmp = new Array(2); - this.keys = null; -} - -function DES(options) { - Cipher.call(this, options); - - var state = new DESState(); - this._desState = state; - - this.deriveKeys(state, options.key); -} -inherits(DES, Cipher); -module.exports = DES; - -DES.create = function create(options) { - return new DES(options); -}; - -var shiftTable = [ - 1, 1, 2, 2, 2, 2, 2, 2, - 1, 2, 2, 2, 2, 2, 2, 1 -]; - -DES.prototype.deriveKeys = function deriveKeys(state, key) { - state.keys = new Array(16 * 2); - - assert.equal(key.length, this.blockSize, 'Invalid key length'); - - var kL = utils.readUInt32BE(key, 0); - var kR = utils.readUInt32BE(key, 4); - - utils.pc1(kL, kR, state.tmp, 0); - kL = state.tmp[0]; - kR = state.tmp[1]; - for (var i = 0; i < state.keys.length; i += 2) { - var shift = shiftTable[i >>> 1]; - kL = utils.r28shl(kL, shift); - kR = utils.r28shl(kR, shift); - utils.pc2(kL, kR, state.keys, i); - } -}; - -DES.prototype._update = function _update(inp, inOff, out, outOff) { - var state = this._desState; - - var l = utils.readUInt32BE(inp, inOff); - var r = utils.readUInt32BE(inp, inOff + 4); - - // Initial Permutation - utils.ip(l, r, state.tmp, 0); - l = state.tmp[0]; - r = state.tmp[1]; - - if (this.type === 'encrypt') - this._encrypt(state, l, r, state.tmp, 0); - else - this._decrypt(state, l, r, state.tmp, 0); - - l = state.tmp[0]; - r = state.tmp[1]; - - utils.writeUInt32BE(out, l, outOff); - utils.writeUInt32BE(out, r, outOff + 4); -}; - -DES.prototype._pad = function _pad(buffer, off) { - var value = buffer.length - off; - for (var i = off; i < buffer.length; i++) - buffer[i] = value; - - return true; -}; - -DES.prototype._unpad = function _unpad(buffer) { - var pad = buffer[buffer.length - 1]; - for (var i = buffer.length - pad; i < buffer.length; i++) - assert.equal(buffer[i], pad); - - return buffer.slice(0, buffer.length - pad); -}; - -DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) { - var l = lStart; - var r = rStart; - - // Apply f() x16 times - for (var i = 0; i < state.keys.length; i += 2) { - var keyL = state.keys[i]; - var keyR = state.keys[i + 1]; - - // f(r, k) - utils.expand(r, state.tmp, 0); - - keyL ^= state.tmp[0]; - keyR ^= state.tmp[1]; - var s = utils.substitute(keyL, keyR); - var f = utils.permute(s); - - var t = r; - r = (l ^ f) >>> 0; - l = t; - } - - // Reverse Initial Permutation - utils.rip(r, l, out, off); -}; - -DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) { - var l = rStart; - var r = lStart; - - // Apply f() x16 times - for (var i = state.keys.length - 2; i >= 0; i -= 2) { - var keyL = state.keys[i]; - var keyR = state.keys[i + 1]; - - // f(r, k) - utils.expand(l, state.tmp, 0); - - keyL ^= state.tmp[0]; - keyR ^= state.tmp[1]; - var s = utils.substitute(keyL, keyR); - var f = utils.permute(s); - - var t = l; - l = (r ^ f) >>> 0; - r = t; - } - - // Reverse Initial Permutation - utils.rip(l, r, out, off); -}; - -},{"./cipher":81,"./utils":84,"inherits":146,"minimalistic-assert":223}],83:[function(require,module,exports){ -'use strict'; - -var assert = require('minimalistic-assert'); -var inherits = require('inherits'); - -var Cipher = require('./cipher'); -var DES = require('./des'); - -function EDEState(type, key) { - assert.equal(key.length, 24, 'Invalid key length'); - - var k1 = key.slice(0, 8); - var k2 = key.slice(8, 16); - var k3 = key.slice(16, 24); - - if (type === 'encrypt') { - this.ciphers = [ - DES.create({ type: 'encrypt', key: k1 }), - DES.create({ type: 'decrypt', key: k2 }), - DES.create({ type: 'encrypt', key: k3 }) - ]; - } else { - this.ciphers = [ - DES.create({ type: 'decrypt', key: k3 }), - DES.create({ type: 'encrypt', key: k2 }), - DES.create({ type: 'decrypt', key: k1 }) - ]; - } -} - -function EDE(options) { - Cipher.call(this, options); - - var state = new EDEState(this.type, this.options.key); - this._edeState = state; -} -inherits(EDE, Cipher); - -module.exports = EDE; - -EDE.create = function create(options) { - return new EDE(options); -}; - -EDE.prototype._update = function _update(inp, inOff, out, outOff) { - var state = this._edeState; - - state.ciphers[0]._update(inp, inOff, out, outOff); - state.ciphers[1]._update(out, outOff, out, outOff); - state.ciphers[2]._update(out, outOff, out, outOff); -}; - -EDE.prototype._pad = DES.prototype._pad; -EDE.prototype._unpad = DES.prototype._unpad; - -},{"./cipher":81,"./des":82,"inherits":146,"minimalistic-assert":223}],84:[function(require,module,exports){ -'use strict'; - -exports.readUInt32BE = function readUInt32BE(bytes, off) { - var res = (bytes[0 + off] << 24) | - (bytes[1 + off] << 16) | - (bytes[2 + off] << 8) | - bytes[3 + off]; - return res >>> 0; -}; - -exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) { - bytes[0 + off] = value >>> 24; - bytes[1 + off] = (value >>> 16) & 0xff; - bytes[2 + off] = (value >>> 8) & 0xff; - bytes[3 + off] = value & 0xff; -}; - -exports.ip = function ip(inL, inR, out, off) { - var outL = 0; - var outR = 0; - - for (var i = 6; i >= 0; i -= 2) { - for (var j = 0; j <= 24; j += 8) { - outL <<= 1; - outL |= (inR >>> (j + i)) & 1; - } - for (var j = 0; j <= 24; j += 8) { - outL <<= 1; - outL |= (inL >>> (j + i)) & 1; - } - } - - for (var i = 6; i >= 0; i -= 2) { - for (var j = 1; j <= 25; j += 8) { - outR <<= 1; - outR |= (inR >>> (j + i)) & 1; - } - for (var j = 1; j <= 25; j += 8) { - outR <<= 1; - outR |= (inL >>> (j + i)) & 1; - } - } - - out[off + 0] = outL >>> 0; - out[off + 1] = outR >>> 0; -}; - -exports.rip = function rip(inL, inR, out, off) { - var outL = 0; - var outR = 0; - - for (var i = 0; i < 4; i++) { - for (var j = 24; j >= 0; j -= 8) { - outL <<= 1; - outL |= (inR >>> (j + i)) & 1; - outL <<= 1; - outL |= (inL >>> (j + i)) & 1; - } - } - for (var i = 4; i < 8; i++) { - for (var j = 24; j >= 0; j -= 8) { - outR <<= 1; - outR |= (inR >>> (j + i)) & 1; - outR <<= 1; - outR |= (inL >>> (j + i)) & 1; - } - } - - out[off + 0] = outL >>> 0; - out[off + 1] = outR >>> 0; -}; - -exports.pc1 = function pc1(inL, inR, out, off) { - var outL = 0; - var outR = 0; - - // 7, 15, 23, 31, 39, 47, 55, 63 - // 6, 14, 22, 30, 39, 47, 55, 63 - // 5, 13, 21, 29, 39, 47, 55, 63 - // 4, 12, 20, 28 - for (var i = 7; i >= 5; i--) { - for (var j = 0; j <= 24; j += 8) { - outL <<= 1; - outL |= (inR >> (j + i)) & 1; - } - for (var j = 0; j <= 24; j += 8) { - outL <<= 1; - outL |= (inL >> (j + i)) & 1; - } - } - for (var j = 0; j <= 24; j += 8) { - outL <<= 1; - outL |= (inR >> (j + i)) & 1; - } - - // 1, 9, 17, 25, 33, 41, 49, 57 - // 2, 10, 18, 26, 34, 42, 50, 58 - // 3, 11, 19, 27, 35, 43, 51, 59 - // 36, 44, 52, 60 - for (var i = 1; i <= 3; i++) { - for (var j = 0; j <= 24; j += 8) { - outR <<= 1; - outR |= (inR >> (j + i)) & 1; - } - for (var j = 0; j <= 24; j += 8) { - outR <<= 1; - outR |= (inL >> (j + i)) & 1; - } - } - for (var j = 0; j <= 24; j += 8) { - outR <<= 1; - outR |= (inL >> (j + i)) & 1; - } - - out[off + 0] = outL >>> 0; - out[off + 1] = outR >>> 0; -}; - -exports.r28shl = function r28shl(num, shift) { - return ((num << shift) & 0xfffffff) | (num >>> (28 - shift)); -}; - -var pc2table = [ - // inL => outL - 14, 11, 17, 4, 27, 23, 25, 0, - 13, 22, 7, 18, 5, 9, 16, 24, - 2, 20, 12, 21, 1, 8, 15, 26, - - // inR => outR - 15, 4, 25, 19, 9, 1, 26, 16, - 5, 11, 23, 8, 12, 7, 17, 0, - 22, 3, 10, 14, 6, 20, 27, 24 -]; - -exports.pc2 = function pc2(inL, inR, out, off) { - var outL = 0; - var outR = 0; - - var len = pc2table.length >>> 1; - for (var i = 0; i < len; i++) { - outL <<= 1; - outL |= (inL >>> pc2table[i]) & 0x1; - } - for (var i = len; i < pc2table.length; i++) { - outR <<= 1; - outR |= (inR >>> pc2table[i]) & 0x1; - } - - out[off + 0] = outL >>> 0; - out[off + 1] = outR >>> 0; -}; - -exports.expand = function expand(r, out, off) { - var outL = 0; - var outR = 0; - - outL = ((r & 1) << 5) | (r >>> 27); - for (var i = 23; i >= 15; i -= 4) { - outL <<= 6; - outL |= (r >>> i) & 0x3f; - } - for (var i = 11; i >= 3; i -= 4) { - outR |= (r >>> i) & 0x3f; - outR <<= 6; - } - outR |= ((r & 0x1f) << 1) | (r >>> 31); - - out[off + 0] = outL >>> 0; - out[off + 1] = outR >>> 0; -}; - -var sTable = [ - 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1, - 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8, - 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7, - 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13, - - 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14, - 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5, - 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2, - 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9, - - 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10, - 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1, - 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7, - 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12, - - 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3, - 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9, - 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8, - 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14, - - 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1, - 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6, - 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13, - 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3, - - 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5, - 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8, - 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10, - 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13, - - 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10, - 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6, - 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7, - 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12, - - 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4, - 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2, - 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13, - 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11 -]; - -exports.substitute = function substitute(inL, inR) { - var out = 0; - for (var i = 0; i < 4; i++) { - var b = (inL >>> (18 - i * 6)) & 0x3f; - var sb = sTable[i * 0x40 + b]; - - out <<= 4; - out |= sb; - } - for (var i = 0; i < 4; i++) { - var b = (inR >>> (18 - i * 6)) & 0x3f; - var sb = sTable[4 * 0x40 + i * 0x40 + b]; - - out <<= 4; - out |= sb; - } - return out >>> 0; -}; - -var permuteTable = [ - 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22, - 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7 -]; - -exports.permute = function permute(num) { - var out = 0; - for (var i = 0; i < permuteTable.length; i++) { - out <<= 1; - out |= (num >>> permuteTable[i]) & 0x1; - } - return out >>> 0; -}; - -exports.padSplit = function padSplit(num, size, group) { - var str = num.toString(2); - while (str.length < size) - str = '0' + str; - - var out = []; - for (var i = 0; i < size; i += group) - out.push(str.slice(i, i + group)); - return out.join(' '); -}; - -},{}],85:[function(require,module,exports){ -(function (Buffer){(function (){ -var generatePrime = require('./lib/generatePrime') -var primes = require('./lib/primes.json') - -var DH = require('./lib/dh') - -function getDiffieHellman (mod) { - var prime = new Buffer(primes[mod].prime, 'hex') - var gen = new Buffer(primes[mod].gen, 'hex') - - return new DH(prime, gen) -} - -var ENCODINGS = { - 'binary': true, 'hex': true, 'base64': true -} - -function createDiffieHellman (prime, enc, generator, genc) { - if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) { - return createDiffieHellman(prime, 'binary', enc, generator) - } - - enc = enc || 'binary' - genc = genc || 'binary' - generator = generator || new Buffer([2]) - - if (!Buffer.isBuffer(generator)) { - generator = new Buffer(generator, genc) - } - - if (typeof prime === 'number') { - return new DH(generatePrime(prime, generator), generator, true) - } - - if (!Buffer.isBuffer(prime)) { - prime = new Buffer(prime, enc) - } - - return new DH(prime, generator, true) -} - -exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman -exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman - -}).call(this)}).call(this,require("buffer").Buffer) - -},{"./lib/dh":86,"./lib/generatePrime":87,"./lib/primes.json":88,"buffer":68}],86:[function(require,module,exports){ -(function (Buffer){(function (){ -var BN = require('bn.js'); -var MillerRabin = require('miller-rabin'); -var millerRabin = new MillerRabin(); -var TWENTYFOUR = new BN(24); -var ELEVEN = new BN(11); -var TEN = new BN(10); -var THREE = new BN(3); -var SEVEN = new BN(7); -var primes = require('./generatePrime'); -var randomBytes = require('randombytes'); -module.exports = DH; - -function setPublicKey(pub, enc) { - enc = enc || 'utf8'; - if (!Buffer.isBuffer(pub)) { - pub = new Buffer(pub, enc); - } - this._pub = new BN(pub); - return this; -} - -function setPrivateKey(priv, enc) { - enc = enc || 'utf8'; - if (!Buffer.isBuffer(priv)) { - priv = new Buffer(priv, enc); - } - this._priv = new BN(priv); - return this; -} - -var primeCache = {}; -function checkPrime(prime, generator) { - var gen = generator.toString('hex'); - var hex = [gen, prime.toString(16)].join('_'); - if (hex in primeCache) { - return primeCache[hex]; - } - var error = 0; - - if (prime.isEven() || - !primes.simpleSieve || - !primes.fermatTest(prime) || - !millerRabin.test(prime)) { - //not a prime so +1 - error += 1; - - if (gen === '02' || gen === '05') { - // we'd be able to check the generator - // it would fail so +8 - error += 8; - } else { - //we wouldn't be able to test the generator - // so +4 - error += 4; - } - primeCache[hex] = error; - return error; - } - if (!millerRabin.test(prime.shrn(1))) { - //not a safe prime - error += 2; - } - var rem; - switch (gen) { - case '02': - if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) { - // unsuidable generator - error += 8; - } - break; - case '05': - rem = prime.mod(TEN); - if (rem.cmp(THREE) && rem.cmp(SEVEN)) { - // prime mod 10 needs to equal 3 or 7 - error += 8; - } - break; - default: - error += 4; - } - primeCache[hex] = error; - return error; -} - -function DH(prime, generator, malleable) { - this.setGenerator(generator); - this.__prime = new BN(prime); - this._prime = BN.mont(this.__prime); - this._primeLen = prime.length; - this._pub = undefined; - this._priv = undefined; - this._primeCode = undefined; - if (malleable) { - this.setPublicKey = setPublicKey; - this.setPrivateKey = setPrivateKey; - } else { - this._primeCode = 8; - } -} -Object.defineProperty(DH.prototype, 'verifyError', { - enumerable: true, - get: function () { - if (typeof this._primeCode !== 'number') { - this._primeCode = checkPrime(this.__prime, this.__gen); - } - return this._primeCode; - } -}); -DH.prototype.generateKeys = function () { - if (!this._priv) { - this._priv = new BN(randomBytes(this._primeLen)); - } - this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed(); - return this.getPublicKey(); -}; - -DH.prototype.computeSecret = function (other) { - other = new BN(other); - other = other.toRed(this._prime); - var secret = other.redPow(this._priv).fromRed(); - var out = new Buffer(secret.toArray()); - var prime = this.getPrime(); - if (out.length < prime.length) { - var front = new Buffer(prime.length - out.length); - front.fill(0); - out = Buffer.concat([front, out]); - } - return out; -}; - -DH.prototype.getPublicKey = function getPublicKey(enc) { - return formatReturnValue(this._pub, enc); -}; - -DH.prototype.getPrivateKey = function getPrivateKey(enc) { - return formatReturnValue(this._priv, enc); -}; - -DH.prototype.getPrime = function (enc) { - return formatReturnValue(this.__prime, enc); -}; - -DH.prototype.getGenerator = function (enc) { - return formatReturnValue(this._gen, enc); -}; - -DH.prototype.setGenerator = function (gen, enc) { - enc = enc || 'utf8'; - if (!Buffer.isBuffer(gen)) { - gen = new Buffer(gen, enc); - } - this.__gen = gen; - this._gen = new BN(gen); - return this; -}; - -function formatReturnValue(bn, enc) { - var buf = new Buffer(bn.toArray()); - if (!enc) { - return buf; - } else { - return buf.toString(enc); - } -} - -}).call(this)}).call(this,require("buffer").Buffer) - -},{"./generatePrime":87,"bn.js":18,"buffer":68,"miller-rabin":222,"randombytes":244}],87:[function(require,module,exports){ -var randomBytes = require('randombytes'); -module.exports = findPrime; -findPrime.simpleSieve = simpleSieve; -findPrime.fermatTest = fermatTest; -var BN = require('bn.js'); -var TWENTYFOUR = new BN(24); -var MillerRabin = require('miller-rabin'); -var millerRabin = new MillerRabin(); -var ONE = new BN(1); -var TWO = new BN(2); -var FIVE = new BN(5); -var SIXTEEN = new BN(16); -var EIGHT = new BN(8); -var TEN = new BN(10); -var THREE = new BN(3); -var SEVEN = new BN(7); -var ELEVEN = new BN(11); -var FOUR = new BN(4); -var TWELVE = new BN(12); -var primes = null; - -function _getPrimes() { - if (primes !== null) - return primes; - - var limit = 0x100000; - var res = []; - res[0] = 2; - for (var i = 1, k = 3; k < limit; k += 2) { - var sqrt = Math.ceil(Math.sqrt(k)); - for (var j = 0; j < i && res[j] <= sqrt; j++) - if (k % res[j] === 0) - break; - - if (i !== j && res[j] <= sqrt) - continue; - - res[i++] = k; - } - primes = res; - return res; -} - -function simpleSieve(p) { - var primes = _getPrimes(); - - for (var i = 0; i < primes.length; i++) - if (p.modn(primes[i]) === 0) { - if (p.cmpn(primes[i]) === 0) { - return true; - } else { - return false; - } - } - - return true; -} - -function fermatTest(p) { - var red = BN.mont(p); - return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0; -} - -function findPrime(bits, gen) { - if (bits < 16) { - // this is what openssl does - if (gen === 2 || gen === 5) { - return new BN([0x8c, 0x7b]); - } else { - return new BN([0x8c, 0x27]); - } - } - gen = new BN(gen); - - var num, n2; - - while (true) { - num = new BN(randomBytes(Math.ceil(bits / 8))); - while (num.bitLength() > bits) { - num.ishrn(1); - } - if (num.isEven()) { - num.iadd(ONE); - } - if (!num.testn(1)) { - num.iadd(TWO); - } - if (!gen.cmp(TWO)) { - while (num.mod(TWENTYFOUR).cmp(ELEVEN)) { - num.iadd(FOUR); - } - } else if (!gen.cmp(FIVE)) { - while (num.mod(TEN).cmp(THREE)) { - num.iadd(FOUR); - } - } - n2 = num.shrn(1); - if (simpleSieve(n2) && simpleSieve(num) && - fermatTest(n2) && fermatTest(num) && - millerRabin.test(n2) && millerRabin.test(num)) { - return num; - } - } - -} - -},{"bn.js":18,"miller-rabin":222,"randombytes":244}],88:[function(require,module,exports){ -module.exports={ - "modp1": { - "gen": "02", - "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff" - }, - "modp2": { - "gen": "02", - "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff" - }, - "modp5": { - "gen": "02", - "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff" - }, - "modp14": { - "gen": "02", - "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff" - }, - "modp15": { - "gen": "02", - "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff" - }, - "modp16": { - "gen": "02", - "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff" - }, - "modp17": { - "gen": "02", - "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff" - }, - "modp18": { - "gen": "02", - "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff" - } -} -},{}],89:[function(require,module,exports){ -'use strict'; - -var elliptic = exports; - -elliptic.version = require('../package.json').version; -elliptic.utils = require('./elliptic/utils'); -elliptic.rand = require('brorand'); -elliptic.curve = require('./elliptic/curve'); -elliptic.curves = require('./elliptic/curves'); - -// Protocols -elliptic.ec = require('./elliptic/ec'); -elliptic.eddsa = require('./elliptic/eddsa'); - -},{"../package.json":104,"./elliptic/curve":92,"./elliptic/curves":95,"./elliptic/ec":96,"./elliptic/eddsa":99,"./elliptic/utils":103,"brorand":19}],90:[function(require,module,exports){ -'use strict'; - -var BN = require('bn.js'); -var utils = require('../utils'); -var getNAF = utils.getNAF; -var getJSF = utils.getJSF; -var assert = utils.assert; - -function BaseCurve(type, conf) { - this.type = type; - this.p = new BN(conf.p, 16); - - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p); - - // Useful for many curves - this.zero = new BN(0).toRed(this.red); - this.one = new BN(1).toRed(this.red); - this.two = new BN(2).toRed(this.red); - - // Curve configuration, optional - this.n = conf.n && new BN(conf.n, 16); - this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); - - // Temporary arrays - this._wnafT1 = new Array(4); - this._wnafT2 = new Array(4); - this._wnafT3 = new Array(4); - this._wnafT4 = new Array(4); - - this._bitLength = this.n ? this.n.bitLength() : 0; - - // Generalized Greg Maxwell's trick - var adjustCount = this.n && this.p.div(this.n); - if (!adjustCount || adjustCount.cmpn(100) > 0) { - this.redN = null; - } else { - this._maxwellTrick = true; - this.redN = this.n.toRed(this.red); - } -} -module.exports = BaseCurve; - -BaseCurve.prototype.point = function point() { - throw new Error('Not implemented'); -}; - -BaseCurve.prototype.validate = function validate() { - throw new Error('Not implemented'); -}; - -BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { - assert(p.precomputed); - var doubles = p._getDoubles(); - - var naf = getNAF(k, 1, this._bitLength); - var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); - I /= 3; - - // Translate into more windowed form - var repr = []; - var j; - var nafW; - for (j = 0; j < naf.length; j += doubles.step) { - nafW = 0; - for (var l = j + doubles.step - 1; l >= j; l--) - nafW = (nafW << 1) + naf[l]; - repr.push(nafW); - } - - var a = this.jpoint(null, null, null); - var b = this.jpoint(null, null, null); - for (var i = I; i > 0; i--) { - for (j = 0; j < repr.length; j++) { - nafW = repr[j]; - if (nafW === i) - b = b.mixedAdd(doubles.points[j]); - else if (nafW === -i) - b = b.mixedAdd(doubles.points[j].neg()); - } - a = a.add(b); - } - return a.toP(); -}; - -BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { - var w = 4; - - // Precompute window - var nafPoints = p._getNAFPoints(w); - w = nafPoints.wnd; - var wnd = nafPoints.points; - - // Get NAF form - var naf = getNAF(k, w, this._bitLength); - - // Add `this`*(N+1) for every w-NAF index - var acc = this.jpoint(null, null, null); - for (var i = naf.length - 1; i >= 0; i--) { - // Count zeroes - for (var l = 0; i >= 0 && naf[i] === 0; i--) - l++; - if (i >= 0) - l++; - acc = acc.dblp(l); - - if (i < 0) - break; - var z = naf[i]; - assert(z !== 0); - if (p.type === 'affine') { - // J +- P - if (z > 0) - acc = acc.mixedAdd(wnd[(z - 1) >> 1]); - else - acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); - } else { - // J +- J - if (z > 0) - acc = acc.add(wnd[(z - 1) >> 1]); - else - acc = acc.add(wnd[(-z - 1) >> 1].neg()); - } - } - return p.type === 'affine' ? acc.toP() : acc; -}; - -BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, - points, - coeffs, - len, - jacobianResult) { - var wndWidth = this._wnafT1; - var wnd = this._wnafT2; - var naf = this._wnafT3; - - // Fill all arrays - var max = 0; - var i; - var j; - var p; - for (i = 0; i < len; i++) { - p = points[i]; - var nafPoints = p._getNAFPoints(defW); - wndWidth[i] = nafPoints.wnd; - wnd[i] = nafPoints.points; - } - - // Comb small window NAFs - for (i = len - 1; i >= 1; i -= 2) { - var a = i - 1; - var b = i; - if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { - naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength); - naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength); - max = Math.max(naf[a].length, max); - max = Math.max(naf[b].length, max); - continue; - } - - var comb = [ - points[a], /* 1 */ - null, /* 3 */ - null, /* 5 */ - points[b], /* 7 */ - ]; - - // Try to avoid Projective points, if possible - if (points[a].y.cmp(points[b].y) === 0) { - comb[1] = points[a].add(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].add(points[b].neg()); - } else { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } - - var index = [ - -3, /* -1 -1 */ - -1, /* -1 0 */ - -5, /* -1 1 */ - -7, /* 0 -1 */ - 0, /* 0 0 */ - 7, /* 0 1 */ - 5, /* 1 -1 */ - 1, /* 1 0 */ - 3, /* 1 1 */ - ]; - - var jsf = getJSF(coeffs[a], coeffs[b]); - max = Math.max(jsf[0].length, max); - naf[a] = new Array(max); - naf[b] = new Array(max); - for (j = 0; j < max; j++) { - var ja = jsf[0][j] | 0; - var jb = jsf[1][j] | 0; - - naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; - naf[b][j] = 0; - wnd[a] = comb; - } - } - - var acc = this.jpoint(null, null, null); - var tmp = this._wnafT4; - for (i = max; i >= 0; i--) { - var k = 0; - - while (i >= 0) { - var zero = true; - for (j = 0; j < len; j++) { - tmp[j] = naf[j][i] | 0; - if (tmp[j] !== 0) - zero = false; - } - if (!zero) - break; - k++; - i--; - } - if (i >= 0) - k++; - acc = acc.dblp(k); - if (i < 0) - break; - - for (j = 0; j < len; j++) { - var z = tmp[j]; - p; - if (z === 0) - continue; - else if (z > 0) - p = wnd[j][(z - 1) >> 1]; - else if (z < 0) - p = wnd[j][(-z - 1) >> 1].neg(); - - if (p.type === 'affine') - acc = acc.mixedAdd(p); - else - acc = acc.add(p); - } - } - // Zeroify references - for (i = 0; i < len; i++) - wnd[i] = null; - - if (jacobianResult) - return acc; - else - return acc.toP(); -}; - -function BasePoint(curve, type) { - this.curve = curve; - this.type = type; - this.precomputed = null; -} -BaseCurve.BasePoint = BasePoint; - -BasePoint.prototype.eq = function eq(/*other*/) { - throw new Error('Not implemented'); -}; - -BasePoint.prototype.validate = function validate() { - return this.curve.validate(this); -}; - -BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - bytes = utils.toArray(bytes, enc); - - var len = this.p.byteLength(); - - // uncompressed, hybrid-odd, hybrid-even - if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && - bytes.length - 1 === 2 * len) { - if (bytes[0] === 0x06) - assert(bytes[bytes.length - 1] % 2 === 0); - else if (bytes[0] === 0x07) - assert(bytes[bytes.length - 1] % 2 === 1); - - var res = this.point(bytes.slice(1, 1 + len), - bytes.slice(1 + len, 1 + 2 * len)); - - return res; - } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && - bytes.length - 1 === len) { - return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); - } - throw new Error('Unknown point format'); -}; - -BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { - return this.encode(enc, true); -}; - -BasePoint.prototype._encode = function _encode(compact) { - var len = this.curve.p.byteLength(); - var x = this.getX().toArray('be', len); - - if (compact) - return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); - - return [ 0x04 ].concat(x, this.getY().toArray('be', len)); -}; - -BasePoint.prototype.encode = function encode(enc, compact) { - return utils.encode(this._encode(compact), enc); -}; - -BasePoint.prototype.precompute = function precompute(power) { - if (this.precomputed) - return this; - - var precomputed = { - doubles: null, - naf: null, - beta: null, - }; - precomputed.naf = this._getNAFPoints(8); - precomputed.doubles = this._getDoubles(4, power); - precomputed.beta = this._getBeta(); - this.precomputed = precomputed; - - return this; -}; - -BasePoint.prototype._hasDoubles = function _hasDoubles(k) { - if (!this.precomputed) - return false; - - var doubles = this.precomputed.doubles; - if (!doubles) - return false; - - return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); -}; - -BasePoint.prototype._getDoubles = function _getDoubles(step, power) { - if (this.precomputed && this.precomputed.doubles) - return this.precomputed.doubles; - - var doubles = [ this ]; - var acc = this; - for (var i = 0; i < power; i += step) { - for (var j = 0; j < step; j++) - acc = acc.dbl(); - doubles.push(acc); - } - return { - step: step, - points: doubles, - }; -}; - -BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { - if (this.precomputed && this.precomputed.naf) - return this.precomputed.naf; - - var res = [ this ]; - var max = (1 << wnd) - 1; - var dbl = max === 1 ? null : this.dbl(); - for (var i = 1; i < max; i++) - res[i] = res[i - 1].add(dbl); - return { - wnd: wnd, - points: res, - }; -}; - -BasePoint.prototype._getBeta = function _getBeta() { - return null; -}; - -BasePoint.prototype.dblp = function dblp(k) { - var r = this; - for (var i = 0; i < k; i++) - r = r.dbl(); - return r; -}; - -},{"../utils":103,"bn.js":18}],91:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); -var BN = require('bn.js'); -var inherits = require('inherits'); -var Base = require('./base'); - -var assert = utils.assert; - -function EdwardsCurve(conf) { - // NOTE: Important as we are creating point in Base.call() - this.twisted = (conf.a | 0) !== 1; - this.mOneA = this.twisted && (conf.a | 0) === -1; - this.extended = this.mOneA; - - Base.call(this, 'edwards', conf); - - this.a = new BN(conf.a, 16).umod(this.red.m); - this.a = this.a.toRed(this.red); - this.c = new BN(conf.c, 16).toRed(this.red); - this.c2 = this.c.redSqr(); - this.d = new BN(conf.d, 16).toRed(this.red); - this.dd = this.d.redAdd(this.d); - - assert(!this.twisted || this.c.fromRed().cmpn(1) === 0); - this.oneC = (conf.c | 0) === 1; -} -inherits(EdwardsCurve, Base); -module.exports = EdwardsCurve; - -EdwardsCurve.prototype._mulA = function _mulA(num) { - if (this.mOneA) - return num.redNeg(); - else - return this.a.redMul(num); -}; - -EdwardsCurve.prototype._mulC = function _mulC(num) { - if (this.oneC) - return num; - else - return this.c.redMul(num); -}; - -// Just for compatibility with Short curve -EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { - return this.point(x, y, z, t); -}; - -EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new BN(x, 16); - if (!x.red) - x = x.toRed(this.red); - - var x2 = x.redSqr(); - var rhs = this.c2.redSub(this.a.redMul(x2)); - var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); - - var y2 = rhs.redMul(lhs.redInvm()); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); - - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); - - return this.point(x, y); -}; - -EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { - y = new BN(y, 16); - if (!y.red) - y = y.toRed(this.red); - - // x^2 = (y^2 - c^2) / (c^2 d y^2 - a) - var y2 = y.redSqr(); - var lhs = y2.redSub(this.c2); - var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a); - var x2 = lhs.redMul(rhs.redInvm()); - - if (x2.cmp(this.zero) === 0) { - if (odd) - throw new Error('invalid point'); - else - return this.point(this.zero, y); - } - - var x = x2.redSqrt(); - if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) - throw new Error('invalid point'); - - if (x.fromRed().isOdd() !== odd) - x = x.redNeg(); - - return this.point(x, y); -}; - -EdwardsCurve.prototype.validate = function validate(point) { - if (point.isInfinity()) - return true; - - // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) - point.normalize(); - - var x2 = point.x.redSqr(); - var y2 = point.y.redSqr(); - var lhs = x2.redMul(this.a).redAdd(y2); - var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); - - return lhs.cmp(rhs) === 0; -}; - -function Point(curve, x, y, z, t) { - Base.BasePoint.call(this, curve, 'projective'); - if (x === null && y === null && z === null) { - this.x = this.curve.zero; - this.y = this.curve.one; - this.z = this.curve.one; - this.t = this.curve.zero; - this.zOne = true; - } else { - this.x = new BN(x, 16); - this.y = new BN(y, 16); - this.z = z ? new BN(z, 16) : this.curve.one; - this.t = t && new BN(t, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - if (this.t && !this.t.red) - this.t = this.t.toRed(this.curve.red); - this.zOne = this.z === this.curve.one; - - // Use extended coordinates - if (this.curve.extended && !this.t) { - this.t = this.x.redMul(this.y); - if (!this.zOne) - this.t = this.t.redMul(this.z.redInvm()); - } - } -} -inherits(Point, Base.BasePoint); - -EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point.fromJSON(this, obj); -}; - -EdwardsCurve.prototype.point = function point(x, y, z, t) { - return new Point(this, x, y, z, t); -}; - -Point.fromJSON = function fromJSON(curve, obj) { - return new Point(curve, obj[0], obj[1], obj[2]); -}; - -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -Point.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.x.cmpn(0) === 0 && - (this.y.cmp(this.z) === 0 || - (this.zOne && this.y.cmp(this.curve.c) === 0)); -}; - -Point.prototype._extDbl = function _extDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #doubling-dbl-2008-hwcd - // 4M + 4S - - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = 2 * Z1^2 - var c = this.z.redSqr(); - c = c.redIAdd(c); - // D = a * A - var d = this.curve._mulA(a); - // E = (X1 + Y1)^2 - A - B - var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); - // G = D + B - var g = d.redAdd(b); - // F = G - C - var f = g.redSub(c); - // H = D - B - var h = d.redSub(b); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); -}; - -Point.prototype._projDbl = function _projDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #doubling-dbl-2008-bbjlp - // #doubling-dbl-2007-bl - // and others - // Generally 3M + 4S or 2M + 4S - - // B = (X1 + Y1)^2 - var b = this.x.redAdd(this.y).redSqr(); - // C = X1^2 - var c = this.x.redSqr(); - // D = Y1^2 - var d = this.y.redSqr(); - - var nx; - var ny; - var nz; - var e; - var h; - var j; - if (this.curve.twisted) { - // E = a * C - e = this.curve._mulA(c); - // F = E + D - var f = e.redAdd(d); - if (this.zOne) { - // X3 = (B - C - D) * (F - 2) - nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); - // Y3 = F * (E - D) - ny = f.redMul(e.redSub(d)); - // Z3 = F^2 - 2 * F - nz = f.redSqr().redSub(f).redSub(f); - } else { - // H = Z1^2 - h = this.z.redSqr(); - // J = F - 2 * H - j = f.redSub(h).redISub(h); - // X3 = (B-C-D)*J - nx = b.redSub(c).redISub(d).redMul(j); - // Y3 = F * (E - D) - ny = f.redMul(e.redSub(d)); - // Z3 = F * J - nz = f.redMul(j); - } - } else { - // E = C + D - e = c.redAdd(d); - // H = (c * Z1)^2 - h = this.curve._mulC(this.z).redSqr(); - // J = E - 2 * H - j = e.redSub(h).redSub(h); - // X3 = c * (B - E) * J - nx = this.curve._mulC(b.redISub(e)).redMul(j); - // Y3 = c * E * (C - D) - ny = this.curve._mulC(e).redMul(c.redISub(d)); - // Z3 = E * J - nz = e.redMul(j); - } - return this.curve.point(nx, ny, nz); -}; - -Point.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; - - // Double in extended coordinates - if (this.curve.extended) - return this._extDbl(); - else - return this._projDbl(); -}; - -Point.prototype._extAdd = function _extAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #addition-add-2008-hwcd-3 - // 8M - - // A = (Y1 - X1) * (Y2 - X2) - var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); - // B = (Y1 + X1) * (Y2 + X2) - var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); - // C = T1 * k * T2 - var c = this.t.redMul(this.curve.dd).redMul(p.t); - // D = Z1 * 2 * Z2 - var d = this.z.redMul(p.z.redAdd(p.z)); - // E = B - A - var e = b.redSub(a); - // F = D - C - var f = d.redSub(c); - // G = D + C - var g = d.redAdd(c); - // H = B + A - var h = b.redAdd(a); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); -}; - -Point.prototype._projAdd = function _projAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #addition-add-2008-bbjlp - // #addition-add-2007-bl - // 10M + 1S - - // A = Z1 * Z2 - var a = this.z.redMul(p.z); - // B = A^2 - var b = a.redSqr(); - // C = X1 * X2 - var c = this.x.redMul(p.x); - // D = Y1 * Y2 - var d = this.y.redMul(p.y); - // E = d * C * D - var e = this.curve.d.redMul(c).redMul(d); - // F = B - E - var f = b.redSub(e); - // G = B + E - var g = b.redAdd(e); - // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) - var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); - var nx = a.redMul(f).redMul(tmp); - var ny; - var nz; - if (this.curve.twisted) { - // Y3 = A * G * (D - a * C) - ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); - // Z3 = F * G - nz = f.redMul(g); - } else { - // Y3 = A * G * (D - C) - ny = a.redMul(g).redMul(d.redSub(c)); - // Z3 = c * F * G - nz = this.curve._mulC(f).redMul(g); - } - return this.curve.point(nx, ny, nz); -}; - -Point.prototype.add = function add(p) { - if (this.isInfinity()) - return p; - if (p.isInfinity()) - return this; - - if (this.curve.extended) - return this._extAdd(p); - else - return this._projAdd(p); -}; - -Point.prototype.mul = function mul(k) { - if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else - return this.curve._wnafMul(this, k); -}; - -Point.prototype.mulAdd = function mulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); -}; - -Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); -}; - -Point.prototype.normalize = function normalize() { - if (this.zOne) - return this; - - // Normalize coordinates - var zi = this.z.redInvm(); - this.x = this.x.redMul(zi); - this.y = this.y.redMul(zi); - if (this.t) - this.t = this.t.redMul(zi); - this.z = this.curve.one; - this.zOne = true; - return this; -}; - -Point.prototype.neg = function neg() { - return this.curve.point(this.x.redNeg(), - this.y, - this.z, - this.t && this.t.redNeg()); -}; - -Point.prototype.getX = function getX() { - this.normalize(); - return this.x.fromRed(); -}; - -Point.prototype.getY = function getY() { - this.normalize(); - return this.y.fromRed(); -}; - -Point.prototype.eq = function eq(other) { - return this === other || - this.getX().cmp(other.getX()) === 0 && - this.getY().cmp(other.getY()) === 0; -}; - -Point.prototype.eqXToP = function eqXToP(x) { - var rx = x.toRed(this.curve.red).redMul(this.z); - if (this.x.cmp(rx) === 0) - return true; - - var xc = x.clone(); - var t = this.curve.redN.redMul(this.z); - for (;;) { - xc.iadd(this.curve.n); - if (xc.cmp(this.curve.p) >= 0) - return false; - - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; - } -}; - -// Compatibility with BaseCurve -Point.prototype.toP = Point.prototype.normalize; -Point.prototype.mixedAdd = Point.prototype.add; - -},{"../utils":103,"./base":90,"bn.js":18,"inherits":146}],92:[function(require,module,exports){ -'use strict'; - -var curve = exports; - -curve.base = require('./base'); -curve.short = require('./short'); -curve.mont = require('./mont'); -curve.edwards = require('./edwards'); - -},{"./base":90,"./edwards":91,"./mont":93,"./short":94}],93:[function(require,module,exports){ -'use strict'; - -var BN = require('bn.js'); -var inherits = require('inherits'); -var Base = require('./base'); - -var utils = require('../utils'); - -function MontCurve(conf) { - Base.call(this, 'mont', conf); - - this.a = new BN(conf.a, 16).toRed(this.red); - this.b = new BN(conf.b, 16).toRed(this.red); - this.i4 = new BN(4).toRed(this.red).redInvm(); - this.two = new BN(2).toRed(this.red); - this.a24 = this.i4.redMul(this.a.redAdd(this.two)); -} -inherits(MontCurve, Base); -module.exports = MontCurve; - -MontCurve.prototype.validate = function validate(point) { - var x = point.normalize().x; - var x2 = x.redSqr(); - var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); - var y = rhs.redSqrt(); - - return y.redSqr().cmp(rhs) === 0; -}; - -function Point(curve, x, z) { - Base.BasePoint.call(this, curve, 'projective'); - if (x === null && z === null) { - this.x = this.curve.one; - this.z = this.curve.zero; - } else { - this.x = new BN(x, 16); - this.z = new BN(z, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - } -} -inherits(Point, Base.BasePoint); - -MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - return this.point(utils.toArray(bytes, enc), 1); -}; - -MontCurve.prototype.point = function point(x, z) { - return new Point(this, x, z); -}; - -MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point.fromJSON(this, obj); -}; - -Point.prototype.precompute = function precompute() { - // No-op -}; - -Point.prototype._encode = function _encode() { - return this.getX().toArray('be', this.curve.p.byteLength()); -}; - -Point.fromJSON = function fromJSON(curve, obj) { - return new Point(curve, obj[0], obj[1] || curve.one); -}; - -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -Point.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; -}; - -Point.prototype.dbl = function dbl() { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 - // 2M + 2S + 4A - - // A = X1 + Z1 - var a = this.x.redAdd(this.z); - // AA = A^2 - var aa = a.redSqr(); - // B = X1 - Z1 - var b = this.x.redSub(this.z); - // BB = B^2 - var bb = b.redSqr(); - // C = AA - BB - var c = aa.redSub(bb); - // X3 = AA * BB - var nx = aa.redMul(bb); - // Z3 = C * (BB + A24 * C) - var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); - return this.curve.point(nx, nz); -}; - -Point.prototype.add = function add() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point.prototype.diffAdd = function diffAdd(p, diff) { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 - // 4M + 2S + 6A - - // A = X2 + Z2 - var a = this.x.redAdd(this.z); - // B = X2 - Z2 - var b = this.x.redSub(this.z); - // C = X3 + Z3 - var c = p.x.redAdd(p.z); - // D = X3 - Z3 - var d = p.x.redSub(p.z); - // DA = D * A - var da = d.redMul(a); - // CB = C * B - var cb = c.redMul(b); - // X5 = Z1 * (DA + CB)^2 - var nx = diff.z.redMul(da.redAdd(cb).redSqr()); - // Z5 = X1 * (DA - CB)^2 - var nz = diff.x.redMul(da.redISub(cb).redSqr()); - return this.curve.point(nx, nz); -}; - -Point.prototype.mul = function mul(k) { - var t = k.clone(); - var a = this; // (N / 2) * Q + Q - var b = this.curve.point(null, null); // (N / 2) * Q - var c = this; // Q - - for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) - bits.push(t.andln(1)); - - for (var i = bits.length - 1; i >= 0; i--) { - if (bits[i] === 0) { - // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q - a = a.diffAdd(b, c); - // N * Q = 2 * ((N / 2) * Q + Q)) - b = b.dbl(); - } else { - // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) - b = a.diffAdd(b, c); - // N * Q + Q = 2 * ((N / 2) * Q + Q) - a = a.dbl(); - } - } - return b; -}; - -Point.prototype.mulAdd = function mulAdd() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point.prototype.jumlAdd = function jumlAdd() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point.prototype.eq = function eq(other) { - return this.getX().cmp(other.getX()) === 0; -}; - -Point.prototype.normalize = function normalize() { - this.x = this.x.redMul(this.z.redInvm()); - this.z = this.curve.one; - return this; -}; - -Point.prototype.getX = function getX() { - // Normalize coordinates - this.normalize(); - - return this.x.fromRed(); -}; - -},{"../utils":103,"./base":90,"bn.js":18,"inherits":146}],94:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); -var BN = require('bn.js'); -var inherits = require('inherits'); -var Base = require('./base'); - -var assert = utils.assert; - -function ShortCurve(conf) { - Base.call(this, 'short', conf); - - this.a = new BN(conf.a, 16).toRed(this.red); - this.b = new BN(conf.b, 16).toRed(this.red); - this.tinv = this.two.redInvm(); - - this.zeroA = this.a.fromRed().cmpn(0) === 0; - this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; - - // If the curve is endomorphic, precalculate beta and lambda - this.endo = this._getEndomorphism(conf); - this._endoWnafT1 = new Array(4); - this._endoWnafT2 = new Array(4); -} -inherits(ShortCurve, Base); -module.exports = ShortCurve; - -ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { - // No efficient endomorphism - if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) - return; - - // Compute beta and lambda, that lambda * P = (beta * Px; Py) - var beta; - var lambda; - if (conf.beta) { - beta = new BN(conf.beta, 16).toRed(this.red); - } else { - var betas = this._getEndoRoots(this.p); - // Choose the smallest beta - beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; - beta = beta.toRed(this.red); - } - if (conf.lambda) { - lambda = new BN(conf.lambda, 16); - } else { - // Choose the lambda that is matching selected beta - var lambdas = this._getEndoRoots(this.n); - if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { - lambda = lambdas[0]; - } else { - lambda = lambdas[1]; - assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); - } - } - - // Get basis vectors, used for balanced length-two representation - var basis; - if (conf.basis) { - basis = conf.basis.map(function(vec) { - return { - a: new BN(vec.a, 16), - b: new BN(vec.b, 16), - }; - }); - } else { - basis = this._getEndoBasis(lambda); - } - - return { - beta: beta, - lambda: lambda, - basis: basis, - }; -}; - -ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { - // Find roots of for x^2 + x + 1 in F - // Root = (-1 +- Sqrt(-3)) / 2 - // - var red = num === this.p ? this.red : BN.mont(num); - var tinv = new BN(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); - - var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv); - - var l1 = ntinv.redAdd(s).fromRed(); - var l2 = ntinv.redSub(s).fromRed(); - return [ l1, l2 ]; -}; - -ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { - // aprxSqrt >= sqrt(this.n) - var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); - - // 3.74 - // Run EGCD, until r(L + 1) < aprxSqrt - var u = lambda; - var v = this.n.clone(); - var x1 = new BN(1); - var y1 = new BN(0); - var x2 = new BN(0); - var y2 = new BN(1); - - // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) - var a0; - var b0; - // First vector - var a1; - var b1; - // Second vector - var a2; - var b2; - - var prevR; - var i = 0; - var r; - var x; - while (u.cmpn(0) !== 0) { - var q = v.div(u); - r = v.sub(q.mul(u)); - x = x2.sub(q.mul(x1)); - var y = y2.sub(q.mul(y1)); - - if (!a1 && r.cmp(aprxSqrt) < 0) { - a0 = prevR.neg(); - b0 = x1; - a1 = r.neg(); - b1 = x; - } else if (a1 && ++i === 2) { - break; - } - prevR = r; - - v = u; - u = r; - x2 = x1; - x1 = x; - y2 = y1; - y1 = y; - } - a2 = r.neg(); - b2 = x; - - var len1 = a1.sqr().add(b1.sqr()); - var len2 = a2.sqr().add(b2.sqr()); - if (len2.cmp(len1) >= 0) { - a2 = a0; - b2 = b0; - } - - // Normalize signs - if (a1.negative) { - a1 = a1.neg(); - b1 = b1.neg(); - } - if (a2.negative) { - a2 = a2.neg(); - b2 = b2.neg(); - } - - return [ - { a: a1, b: b1 }, - { a: a2, b: b2 }, - ]; -}; - -ShortCurve.prototype._endoSplit = function _endoSplit(k) { - var basis = this.endo.basis; - var v1 = basis[0]; - var v2 = basis[1]; - - var c1 = v2.b.mul(k).divRound(this.n); - var c2 = v1.b.neg().mul(k).divRound(this.n); - - var p1 = c1.mul(v1.a); - var p2 = c2.mul(v2.a); - var q1 = c1.mul(v1.b); - var q2 = c2.mul(v2.b); - - // Calculate answer - var k1 = k.sub(p1).sub(p2); - var k2 = q1.add(q2).neg(); - return { k1: k1, k2: k2 }; -}; - -ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new BN(x, 16); - if (!x.red) - x = x.toRed(this.red); - - var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); - - // XXX Is there any way to tell if the number is odd without converting it - // to non-red form? - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); - - return this.point(x, y); -}; - -ShortCurve.prototype.validate = function validate(point) { - if (point.inf) - return true; - - var x = point.x; - var y = point.y; - - var ax = this.a.redMul(x); - var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); - return y.redSqr().redISub(rhs).cmpn(0) === 0; -}; - -ShortCurve.prototype._endoWnafMulAdd = - function _endoWnafMulAdd(points, coeffs, jacobianResult) { - var npoints = this._endoWnafT1; - var ncoeffs = this._endoWnafT2; - for (var i = 0; i < points.length; i++) { - var split = this._endoSplit(coeffs[i]); - var p = points[i]; - var beta = p._getBeta(); - - if (split.k1.negative) { - split.k1.ineg(); - p = p.neg(true); - } - if (split.k2.negative) { - split.k2.ineg(); - beta = beta.neg(true); - } - - npoints[i * 2] = p; - npoints[i * 2 + 1] = beta; - ncoeffs[i * 2] = split.k1; - ncoeffs[i * 2 + 1] = split.k2; - } - var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); - - // Clean-up references to points and coefficients - for (var j = 0; j < i * 2; j++) { - npoints[j] = null; - ncoeffs[j] = null; - } - return res; - }; - -function Point(curve, x, y, isRed) { - Base.BasePoint.call(this, curve, 'affine'); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new BN(x, 16); - this.y = new BN(y, 16); - // Force redgomery representation when loading from JSON - if (isRed) { - this.x.forceRed(this.curve.red); - this.y.forceRed(this.curve.red); - } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - this.inf = false; - } -} -inherits(Point, Base.BasePoint); - -ShortCurve.prototype.point = function point(x, y, isRed) { - return new Point(this, x, y, isRed); -}; - -ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point.fromJSON(this, obj, red); -}; - -Point.prototype._getBeta = function _getBeta() { - if (!this.curve.endo) - return; - - var pre = this.precomputed; - if (pre && pre.beta) - return pre.beta; - - var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); - if (pre) { - var curve = this.curve; - var endoMul = function(p) { - return curve.point(p.x.redMul(curve.endo.beta), p.y); - }; - pre.beta = beta; - beta.precomputed = { - beta: null, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(endoMul), - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(endoMul), - }, - }; - } - return beta; -}; - -Point.prototype.toJSON = function toJSON() { - if (!this.precomputed) - return [ this.x, this.y ]; - - return [ this.x, this.y, this.precomputed && { - doubles: this.precomputed.doubles && { - step: this.precomputed.doubles.step, - points: this.precomputed.doubles.points.slice(1), - }, - naf: this.precomputed.naf && { - wnd: this.precomputed.naf.wnd, - points: this.precomputed.naf.points.slice(1), - }, - } ]; -}; - -Point.fromJSON = function fromJSON(curve, obj, red) { - if (typeof obj === 'string') - obj = JSON.parse(obj); - var res = curve.point(obj[0], obj[1], red); - if (!obj[2]) - return res; - - function obj2point(obj) { - return curve.point(obj[0], obj[1], red); - } - - var pre = obj[2]; - res.precomputed = { - beta: null, - doubles: pre.doubles && { - step: pre.doubles.step, - points: [ res ].concat(pre.doubles.points.map(obj2point)), - }, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: [ res ].concat(pre.naf.points.map(obj2point)), - }, - }; - return res; -}; - -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -Point.prototype.isInfinity = function isInfinity() { - return this.inf; -}; - -Point.prototype.add = function add(p) { - // O + P = P - if (this.inf) - return p; - - // P + O = P - if (p.inf) - return this; - - // P + P = 2P - if (this.eq(p)) - return this.dbl(); - - // P + (-P) = O - if (this.neg().eq(p)) - return this.curve.point(null, null); - - // P + Q = O - if (this.x.cmp(p.x) === 0) - return this.curve.point(null, null); - - var c = this.y.redSub(p.y); - if (c.cmpn(0) !== 0) - c = c.redMul(this.x.redSub(p.x).redInvm()); - var nx = c.redSqr().redISub(this.x).redISub(p.x); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; - -Point.prototype.dbl = function dbl() { - if (this.inf) - return this; - - // 2P = O - var ys1 = this.y.redAdd(this.y); - if (ys1.cmpn(0) === 0) - return this.curve.point(null, null); - - var a = this.curve.a; - - var x2 = this.x.redSqr(); - var dyinv = ys1.redInvm(); - var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); - - var nx = c.redSqr().redISub(this.x.redAdd(this.x)); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; - -Point.prototype.getX = function getX() { - return this.x.fromRed(); -}; - -Point.prototype.getY = function getY() { - return this.y.fromRed(); -}; - -Point.prototype.mul = function mul(k) { - k = new BN(k, 16); - if (this.isInfinity()) - return this; - else if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else if (this.curve.endo) - return this.curve._endoWnafMulAdd([ this ], [ k ]); - else - return this.curve._wnafMul(this, k); -}; - -Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { - var points = [ this, p2 ]; - var coeffs = [ k1, k2 ]; - if (this.curve.endo) - return this.curve._endoWnafMulAdd(points, coeffs); - else - return this.curve._wnafMulAdd(1, points, coeffs, 2); -}; - -Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { - var points = [ this, p2 ]; - var coeffs = [ k1, k2 ]; - if (this.curve.endo) - return this.curve._endoWnafMulAdd(points, coeffs, true); - else - return this.curve._wnafMulAdd(1, points, coeffs, 2, true); -}; - -Point.prototype.eq = function eq(p) { - return this === p || - this.inf === p.inf && - (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); -}; - -Point.prototype.neg = function neg(_precompute) { - if (this.inf) - return this; - - var res = this.curve.point(this.x, this.y.redNeg()); - if (_precompute && this.precomputed) { - var pre = this.precomputed; - var negate = function(p) { - return p.neg(); - }; - res.precomputed = { - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(negate), - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(negate), - }, - }; - } - return res; -}; - -Point.prototype.toJ = function toJ() { - if (this.inf) - return this.curve.jpoint(null, null, null); - - var res = this.curve.jpoint(this.x, this.y, this.curve.one); - return res; -}; - -function JPoint(curve, x, y, z) { - Base.BasePoint.call(this, curve, 'jacobian'); - if (x === null && y === null && z === null) { - this.x = this.curve.one; - this.y = this.curve.one; - this.z = new BN(0); - } else { - this.x = new BN(x, 16); - this.y = new BN(y, 16); - this.z = new BN(z, 16); - } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - - this.zOne = this.z === this.curve.one; -} -inherits(JPoint, Base.BasePoint); - -ShortCurve.prototype.jpoint = function jpoint(x, y, z) { - return new JPoint(this, x, y, z); -}; - -JPoint.prototype.toP = function toP() { - if (this.isInfinity()) - return this.curve.point(null, null); - - var zinv = this.z.redInvm(); - var zinv2 = zinv.redSqr(); - var ax = this.x.redMul(zinv2); - var ay = this.y.redMul(zinv2).redMul(zinv); - - return this.curve.point(ax, ay); -}; - -JPoint.prototype.neg = function neg() { - return this.curve.jpoint(this.x, this.y.redNeg(), this.z); -}; - -JPoint.prototype.add = function add(p) { - // O + P = P - if (this.isInfinity()) - return p; - - // P + O = P - if (p.isInfinity()) - return this; - - // 12M + 4S + 7A - var pz2 = p.z.redSqr(); - var z2 = this.z.redSqr(); - var u1 = this.x.redMul(pz2); - var u2 = p.x.redMul(z2); - var s1 = this.y.redMul(pz2.redMul(p.z)); - var s2 = p.y.redMul(z2.redMul(this.z)); - - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); - } - - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); - - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(p.z).redMul(h); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.mixedAdd = function mixedAdd(p) { - // O + P = P - if (this.isInfinity()) - return p.toJ(); - - // P + O = P - if (p.isInfinity()) - return this; - - // 8M + 3S + 7A - var z2 = this.z.redSqr(); - var u1 = this.x; - var u2 = p.x.redMul(z2); - var s1 = this.y; - var s2 = p.y.redMul(z2).redMul(this.z); - - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); - } - - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); - - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(h); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.dblp = function dblp(pow) { - if (pow === 0) - return this; - if (this.isInfinity()) - return this; - if (!pow) - return this.dbl(); - - var i; - if (this.curve.zeroA || this.curve.threeA) { - var r = this; - for (i = 0; i < pow; i++) - r = r.dbl(); - return r; - } - - // 1M + 2S + 1A + N * (4S + 5M + 8A) - // N = 1 => 6M + 6S + 9A - var a = this.curve.a; - var tinv = this.curve.tinv; - - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); - - // Reuse results - var jyd = jy.redAdd(jy); - for (i = 0; i < pow; i++) { - var jx2 = jx.redSqr(); - var jyd2 = jyd.redSqr(); - var jyd4 = jyd2.redSqr(); - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); - - var t1 = jx.redMul(jyd2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); - var dny = c.redMul(t2); - dny = dny.redIAdd(dny).redISub(jyd4); - var nz = jyd.redMul(jz); - if (i + 1 < pow) - jz4 = jz4.redMul(jyd4); - - jx = nx; - jz = nz; - jyd = dny; - } - - return this.curve.jpoint(jx, jyd.redMul(tinv), jz); -}; - -JPoint.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; - - if (this.curve.zeroA) - return this._zeroDbl(); - else if (this.curve.threeA) - return this._threeDbl(); - else - return this._dbl(); -}; - -JPoint.prototype._zeroDbl = function _zeroDbl() { - var nx; - var ny; - var nz; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 14A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // T = M ^ 2 - 2*S - var t = m.redSqr().redISub(s).redISub(s); - - // 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2*Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-dbl-2009-l - // 2M + 5S + 13A - - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = B^2 - var c = b.redSqr(); - // D = 2 * ((X1 + B)^2 - A - C) - var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); - d = d.redIAdd(d); - // E = 3 * A - var e = a.redAdd(a).redIAdd(a); - // F = E^2 - var f = e.redSqr(); - - // 8 * C - var c8 = c.redIAdd(c); - c8 = c8.redIAdd(c8); - c8 = c8.redIAdd(c8); - - // X3 = F - 2 * D - nx = f.redISub(d).redISub(d); - // Y3 = E * (D - X3) - 8 * C - ny = e.redMul(d.redISub(nx)).redISub(c8); - // Z3 = 2 * Y1 * Z1 - nz = this.y.redMul(this.z); - nz = nz.redIAdd(nz); - } - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype._threeDbl = function _threeDbl() { - var nx; - var ny; - var nz; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 15A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a - var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); - // T = M^2 - 2 * S - var t = m.redSqr().redISub(s).redISub(s); - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2 * Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b - // 3M + 5S - - // delta = Z1^2 - var delta = this.z.redSqr(); - // gamma = Y1^2 - var gamma = this.y.redSqr(); - // beta = X1 * gamma - var beta = this.x.redMul(gamma); - // alpha = 3 * (X1 - delta) * (X1 + delta) - var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); - alpha = alpha.redAdd(alpha).redIAdd(alpha); - // X3 = alpha^2 - 8 * beta - var beta4 = beta.redIAdd(beta); - beta4 = beta4.redIAdd(beta4); - var beta8 = beta4.redAdd(beta4); - nx = alpha.redSqr().redISub(beta8); - // Z3 = (Y1 + Z1)^2 - gamma - delta - nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); - // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 - var ggamma8 = gamma.redSqr(); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); - } - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype._dbl = function _dbl() { - var a = this.curve.a; - - // 4M + 6S + 10A - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); - - var jx2 = jx.redSqr(); - var jy2 = jy.redSqr(); - - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); - - var jxd4 = jx.redAdd(jx); - jxd4 = jxd4.redIAdd(jxd4); - var t1 = jxd4.redMul(jy2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); - - var jyd8 = jy2.redSqr(); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - var ny = c.redMul(t2).redISub(jyd8); - var nz = jy.redAdd(jy).redMul(jz); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.trpl = function trpl() { - if (!this.curve.zeroA) - return this.dbl().add(this); - - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl - // 5M + 10S + ... - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // ZZ = Z1^2 - var zz = this.z.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // M = 3 * XX + a * ZZ2; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // MM = M^2 - var mm = m.redSqr(); - // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM - var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - e = e.redIAdd(e); - e = e.redAdd(e).redIAdd(e); - e = e.redISub(mm); - // EE = E^2 - var ee = e.redSqr(); - // T = 16*YYYY - var t = yyyy.redIAdd(yyyy); - t = t.redIAdd(t); - t = t.redIAdd(t); - t = t.redIAdd(t); - // U = (M + E)^2 - MM - EE - T - var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); - // X3 = 4 * (X1 * EE - 4 * YY * U) - var yyu4 = yy.redMul(u); - yyu4 = yyu4.redIAdd(yyu4); - yyu4 = yyu4.redIAdd(yyu4); - var nx = this.x.redMul(ee).redISub(yyu4); - nx = nx.redIAdd(nx); - nx = nx.redIAdd(nx); - // Y3 = 8 * Y1 * (U * (T - U) - E * EE) - var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - // Z3 = (Z1 + E)^2 - ZZ - EE - var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.mul = function mul(k, kbase) { - k = new BN(k, kbase); - - return this.curve._wnafMul(this, k); -}; - -JPoint.prototype.eq = function eq(p) { - if (p.type === 'affine') - return this.eq(p.toJ()); - - if (this === p) - return true; - - // x1 * z2^2 == x2 * z1^2 - var z2 = this.z.redSqr(); - var pz2 = p.z.redSqr(); - if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) - return false; - - // y1 * z2^3 == y2 * z1^3 - var z3 = z2.redMul(this.z); - var pz3 = pz2.redMul(p.z); - return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; -}; - -JPoint.prototype.eqXToP = function eqXToP(x) { - var zs = this.z.redSqr(); - var rx = x.toRed(this.curve.red).redMul(zs); - if (this.x.cmp(rx) === 0) - return true; - - var xc = x.clone(); - var t = this.curve.redN.redMul(zs); - for (;;) { - xc.iadd(this.curve.n); - if (xc.cmp(this.curve.p) >= 0) - return false; - - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; - } -}; - -JPoint.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -JPoint.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; -}; - -},{"../utils":103,"./base":90,"bn.js":18,"inherits":146}],95:[function(require,module,exports){ -'use strict'; - -var curves = exports; - -var hash = require('hash.js'); -var curve = require('./curve'); -var utils = require('./utils'); - -var assert = utils.assert; - -function PresetCurve(options) { - if (options.type === 'short') - this.curve = new curve.short(options); - else if (options.type === 'edwards') - this.curve = new curve.edwards(options); - else - this.curve = new curve.mont(options); - this.g = this.curve.g; - this.n = this.curve.n; - this.hash = options.hash; - - assert(this.g.validate(), 'Invalid curve'); - assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); -} -curves.PresetCurve = PresetCurve; - -function defineCurve(name, options) { - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - get: function() { - var curve = new PresetCurve(options); - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - value: curve, - }); - return curve; - }, - }); -} - -defineCurve('p192', { - type: 'short', - prime: 'p192', - p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', - b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', - n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', - hash: hash.sha256, - gRed: false, - g: [ - '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', - '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811', - ], -}); - -defineCurve('p224', { - type: 'short', - prime: 'p224', - p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', - b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', - n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', - hash: hash.sha256, - gRed: false, - g: [ - 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', - 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34', - ], -}); - -defineCurve('p256', { - type: 'short', - prime: null, - p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', - a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', - b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', - n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', - hash: hash.sha256, - gRed: false, - g: [ - '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', - '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5', - ], -}); - -defineCurve('p384', { - type: 'short', - prime: null, - p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'fffffffe ffffffff 00000000 00000000 ffffffff', - a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'fffffffe ffffffff 00000000 00000000 fffffffc', - b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + - '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', - n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + - 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', - hash: hash.sha384, - gRed: false, - g: [ - 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + - '5502f25d bf55296c 3a545e38 72760ab7', - '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + - '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f', - ], -}); - -defineCurve('p521', { - type: 'short', - prime: null, - p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff', - a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff fffffffc', - b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + - '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + - '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', - n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + - 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', - hash: hash.sha512, - gRed: false, - g: [ - '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + - '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + - 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', - '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + - '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + - '3fad0761 353c7086 a272c240 88be9476 9fd16650', - ], -}); - -defineCurve('curve25519', { - type: 'mont', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '76d06', - b: '1', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - hash: hash.sha256, - gRed: false, - g: [ - '9', - ], -}); - -defineCurve('ed25519', { - type: 'edwards', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '-1', - c: '1', - // -121665 * (121666^(-1)) (mod P) - d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - hash: hash.sha256, - gRed: false, - g: [ - '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', - - // 4/5 - '6666666666666666666666666666666666666666666666666666666666666658', - ], -}); - -var pre; -try { - pre = require('./precomputed/secp256k1'); -} catch (e) { - pre = undefined; -} - -defineCurve('secp256k1', { - type: 'short', - prime: 'k256', - p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', - a: '0', - b: '7', - n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', - h: '1', - hash: hash.sha256, - - // Precomputed endomorphism - beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', - lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', - basis: [ - { - a: '3086d221a7d46bcde86c90e49284eb15', - b: '-e4437ed6010e88286f547fa90abfe4c3', - }, - { - a: '114ca50f7a8e2f3f657c1108d9d44cfd8', - b: '3086d221a7d46bcde86c90e49284eb15', - }, - ], - - gRed: false, - g: [ - '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', - '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', - pre, - ], -}); - -},{"./curve":92,"./precomputed/secp256k1":102,"./utils":103,"hash.js":132}],96:[function(require,module,exports){ -'use strict'; - -var BN = require('bn.js'); -var HmacDRBG = require('hmac-drbg'); -var utils = require('../utils'); -var curves = require('../curves'); -var rand = require('brorand'); -var assert = utils.assert; - -var KeyPair = require('./key'); -var Signature = require('./signature'); - -function EC(options) { - if (!(this instanceof EC)) - return new EC(options); - - // Shortcut `elliptic.ec(curve-name)` - if (typeof options === 'string') { - assert(Object.prototype.hasOwnProperty.call(curves, options), - 'Unknown curve ' + options); - - options = curves[options]; - } - - // Shortcut for `elliptic.ec(elliptic.curves.curveName)` - if (options instanceof curves.PresetCurve) - options = { curve: options }; - - this.curve = options.curve.curve; - this.n = this.curve.n; - this.nh = this.n.ushrn(1); - this.g = this.curve.g; - - // Point on curve - this.g = options.curve.g; - this.g.precompute(options.curve.n.bitLength() + 1); - - // Hash for function for DRBG - this.hash = options.hash || options.curve.hash; -} -module.exports = EC; - -EC.prototype.keyPair = function keyPair(options) { - return new KeyPair(this, options); -}; - -EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { - return KeyPair.fromPrivate(this, priv, enc); -}; - -EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { - return KeyPair.fromPublic(this, pub, enc); -}; - -EC.prototype.genKeyPair = function genKeyPair(options) { - if (!options) - options = {}; - - // Instantiate Hmac_DRBG - var drbg = new HmacDRBG({ - hash: this.hash, - pers: options.pers, - persEnc: options.persEnc || 'utf8', - entropy: options.entropy || rand(this.hash.hmacStrength), - entropyEnc: options.entropy && options.entropyEnc || 'utf8', - nonce: this.n.toArray(), - }); - - var bytes = this.n.byteLength(); - var ns2 = this.n.sub(new BN(2)); - for (;;) { - var priv = new BN(drbg.generate(bytes)); - if (priv.cmp(ns2) > 0) - continue; - - priv.iaddn(1); - return this.keyFromPrivate(priv); - } -}; - -EC.prototype._truncateToN = function _truncateToN(msg, truncOnly) { - var delta = msg.byteLength() * 8 - this.n.bitLength(); - if (delta > 0) - msg = msg.ushrn(delta); - if (!truncOnly && msg.cmp(this.n) >= 0) - return msg.sub(this.n); - else - return msg; -}; - -EC.prototype.sign = function sign(msg, key, enc, options) { - if (typeof enc === 'object') { - options = enc; - enc = null; - } - if (!options) - options = {}; - - key = this.keyFromPrivate(key, enc); - msg = this._truncateToN(new BN(msg, 16)); - - // Zero-extend key to provide enough entropy - var bytes = this.n.byteLength(); - var bkey = key.getPrivate().toArray('be', bytes); - - // Zero-extend nonce to have the same byte size as N - var nonce = msg.toArray('be', bytes); - - // Instantiate Hmac_DRBG - var drbg = new HmacDRBG({ - hash: this.hash, - entropy: bkey, - nonce: nonce, - pers: options.pers, - persEnc: options.persEnc || 'utf8', - }); - - // Number of bytes to generate - var ns1 = this.n.sub(new BN(1)); - - for (var iter = 0; ; iter++) { - var k = options.k ? - options.k(iter) : - new BN(drbg.generate(this.n.byteLength())); - k = this._truncateToN(k, true); - if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) - continue; - - var kp = this.g.mul(k); - if (kp.isInfinity()) - continue; - - var kpX = kp.getX(); - var r = kpX.umod(this.n); - if (r.cmpn(0) === 0) - continue; - - var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); - s = s.umod(this.n); - if (s.cmpn(0) === 0) - continue; - - var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | - (kpX.cmp(r) !== 0 ? 2 : 0); - - // Use complement of `s`, if it is > `n / 2` - if (options.canonical && s.cmp(this.nh) > 0) { - s = this.n.sub(s); - recoveryParam ^= 1; - } - - return new Signature({ r: r, s: s, recoveryParam: recoveryParam }); - } -}; - -EC.prototype.verify = function verify(msg, signature, key, enc) { - msg = this._truncateToN(new BN(msg, 16)); - key = this.keyFromPublic(key, enc); - signature = new Signature(signature, 'hex'); - - // Perform primitive values validation - var r = signature.r; - var s = signature.s; - if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) - return false; - if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) - return false; - - // Validate signature - var sinv = s.invm(this.n); - var u1 = sinv.mul(msg).umod(this.n); - var u2 = sinv.mul(r).umod(this.n); - var p; - - if (!this.curve._maxwellTrick) { - p = this.g.mulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; - - return p.getX().umod(this.n).cmp(r) === 0; - } - - // NOTE: Greg Maxwell's trick, inspired by: - // https://git.io/vad3K - - p = this.g.jmulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; - - // Compare `p.x` of Jacobian point with `r`, - // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the - // inverse of `p.z^2` - return p.eqXToP(r); -}; - -EC.prototype.recoverPubKey = function(msg, signature, j, enc) { - assert((3 & j) === j, 'The recovery param is more than two bits'); - signature = new Signature(signature, enc); - - var n = this.n; - var e = new BN(msg); - var r = signature.r; - var s = signature.s; - - // A set LSB signifies that the y-coordinate is odd - var isYOdd = j & 1; - var isSecondKey = j >> 1; - if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) - throw new Error('Unable to find sencond key candinate'); - - // 1.1. Let x = r + jn. - if (isSecondKey) - r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); - else - r = this.curve.pointFromX(r, isYOdd); - - var rInv = signature.r.invm(n); - var s1 = n.sub(e).mul(rInv).umod(n); - var s2 = s.mul(rInv).umod(n); - - // 1.6.1 Compute Q = r^-1 (sR - eG) - // Q = r^-1 (sR + -eG) - return this.g.mulAdd(s1, r, s2); -}; - -EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { - signature = new Signature(signature, enc); - if (signature.recoveryParam !== null) - return signature.recoveryParam; - - for (var i = 0; i < 4; i++) { - var Qprime; - try { - Qprime = this.recoverPubKey(e, signature, i); - } catch (e) { - continue; - } - - if (Qprime.eq(Q)) - return i; - } - throw new Error('Unable to find valid recovery factor'); -}; - -},{"../curves":95,"../utils":103,"./key":97,"./signature":98,"bn.js":18,"brorand":19,"hmac-drbg":144}],97:[function(require,module,exports){ -'use strict'; - -var BN = require('bn.js'); -var utils = require('../utils'); -var assert = utils.assert; - -function KeyPair(ec, options) { - this.ec = ec; - this.priv = null; - this.pub = null; - - // KeyPair(ec, { priv: ..., pub: ... }) - if (options.priv) - this._importPrivate(options.priv, options.privEnc); - if (options.pub) - this._importPublic(options.pub, options.pubEnc); -} -module.exports = KeyPair; - -KeyPair.fromPublic = function fromPublic(ec, pub, enc) { - if (pub instanceof KeyPair) - return pub; - - return new KeyPair(ec, { - pub: pub, - pubEnc: enc, - }); -}; - -KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { - if (priv instanceof KeyPair) - return priv; - - return new KeyPair(ec, { - priv: priv, - privEnc: enc, - }); -}; - -KeyPair.prototype.validate = function validate() { - var pub = this.getPublic(); - - if (pub.isInfinity()) - return { result: false, reason: 'Invalid public key' }; - if (!pub.validate()) - return { result: false, reason: 'Public key is not a point' }; - if (!pub.mul(this.ec.curve.n).isInfinity()) - return { result: false, reason: 'Public key * N != O' }; - - return { result: true, reason: null }; -}; - -KeyPair.prototype.getPublic = function getPublic(compact, enc) { - // compact is optional argument - if (typeof compact === 'string') { - enc = compact; - compact = null; - } - - if (!this.pub) - this.pub = this.ec.g.mul(this.priv); - - if (!enc) - return this.pub; - - return this.pub.encode(enc, compact); -}; - -KeyPair.prototype.getPrivate = function getPrivate(enc) { - if (enc === 'hex') - return this.priv.toString(16, 2); - else - return this.priv; -}; - -KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { - this.priv = new BN(key, enc || 16); - - // Ensure that the priv won't be bigger than n, otherwise we may fail - // in fixed multiplication method - this.priv = this.priv.umod(this.ec.curve.n); -}; - -KeyPair.prototype._importPublic = function _importPublic(key, enc) { - if (key.x || key.y) { - // Montgomery points only have an `x` coordinate. - // Weierstrass/Edwards points on the other hand have both `x` and - // `y` coordinates. - if (this.ec.curve.type === 'mont') { - assert(key.x, 'Need x coordinate'); - } else if (this.ec.curve.type === 'short' || - this.ec.curve.type === 'edwards') { - assert(key.x && key.y, 'Need both x and y coordinate'); - } - this.pub = this.ec.curve.point(key.x, key.y); - return; - } - this.pub = this.ec.curve.decodePoint(key, enc); -}; - -// ECDH -KeyPair.prototype.derive = function derive(pub) { - if(!pub.validate()) { - assert(pub.validate(), 'public point not validated'); - } - return pub.mul(this.priv).getX(); -}; - -// ECDSA -KeyPair.prototype.sign = function sign(msg, enc, options) { - return this.ec.sign(msg, this, enc, options); -}; - -KeyPair.prototype.verify = function verify(msg, signature) { - return this.ec.verify(msg, signature, this); -}; - -KeyPair.prototype.inspect = function inspect() { - return ''; -}; - -},{"../utils":103,"bn.js":18}],98:[function(require,module,exports){ -'use strict'; - -var BN = require('bn.js'); - -var utils = require('../utils'); -var assert = utils.assert; - -function Signature(options, enc) { - if (options instanceof Signature) - return options; - - if (this._importDER(options, enc)) - return; - - assert(options.r && options.s, 'Signature without r or s'); - this.r = new BN(options.r, 16); - this.s = new BN(options.s, 16); - if (options.recoveryParam === undefined) - this.recoveryParam = null; - else - this.recoveryParam = options.recoveryParam; -} -module.exports = Signature; - -function Position() { - this.place = 0; -} - -function getLength(buf, p) { - var initial = buf[p.place++]; - if (!(initial & 0x80)) { - return initial; - } - var octetLen = initial & 0xf; - - // Indefinite length or overflow - if (octetLen === 0 || octetLen > 4) { - return false; - } - - var val = 0; - for (var i = 0, off = p.place; i < octetLen; i++, off++) { - val <<= 8; - val |= buf[off]; - val >>>= 0; - } - - // Leading zeroes - if (val <= 0x7f) { - return false; - } - - p.place = off; - return val; -} - -function rmPadding(buf) { - var i = 0; - var len = buf.length - 1; - while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { - i++; - } - if (i === 0) { - return buf; - } - return buf.slice(i); -} - -Signature.prototype._importDER = function _importDER(data, enc) { - data = utils.toArray(data, enc); - var p = new Position(); - if (data[p.place++] !== 0x30) { - return false; - } - var len = getLength(data, p); - if (len === false) { - return false; - } - if ((len + p.place) !== data.length) { - return false; - } - if (data[p.place++] !== 0x02) { - return false; - } - var rlen = getLength(data, p); - if (rlen === false) { - return false; - } - var r = data.slice(p.place, rlen + p.place); - p.place += rlen; - if (data[p.place++] !== 0x02) { - return false; - } - var slen = getLength(data, p); - if (slen === false) { - return false; - } - if (data.length !== slen + p.place) { - return false; - } - var s = data.slice(p.place, slen + p.place); - if (r[0] === 0) { - if (r[1] & 0x80) { - r = r.slice(1); - } else { - // Leading zeroes - return false; - } - } - if (s[0] === 0) { - if (s[1] & 0x80) { - s = s.slice(1); - } else { - // Leading zeroes - return false; - } - } - - this.r = new BN(r); - this.s = new BN(s); - this.recoveryParam = null; - - return true; -}; - -function constructLength(arr, len) { - if (len < 0x80) { - arr.push(len); - return; - } - var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); - arr.push(octets | 0x80); - while (--octets) { - arr.push((len >>> (octets << 3)) & 0xff); - } - arr.push(len); -} - -Signature.prototype.toDER = function toDER(enc) { - var r = this.r.toArray(); - var s = this.s.toArray(); - - // Pad values - if (r[0] & 0x80) - r = [ 0 ].concat(r); - // Pad values - if (s[0] & 0x80) - s = [ 0 ].concat(s); - - r = rmPadding(r); - s = rmPadding(s); - - while (!s[0] && !(s[1] & 0x80)) { - s = s.slice(1); - } - var arr = [ 0x02 ]; - constructLength(arr, r.length); - arr = arr.concat(r); - arr.push(0x02); - constructLength(arr, s.length); - var backHalf = arr.concat(s); - var res = [ 0x30 ]; - constructLength(res, backHalf.length); - res = res.concat(backHalf); - return utils.encode(res, enc); -}; - -},{"../utils":103,"bn.js":18}],99:[function(require,module,exports){ -'use strict'; - -var hash = require('hash.js'); -var curves = require('../curves'); -var utils = require('../utils'); -var assert = utils.assert; -var parseBytes = utils.parseBytes; -var KeyPair = require('./key'); -var Signature = require('./signature'); - -function EDDSA(curve) { - assert(curve === 'ed25519', 'only tested with ed25519 so far'); - - if (!(this instanceof EDDSA)) - return new EDDSA(curve); - - curve = curves[curve].curve; - this.curve = curve; - this.g = curve.g; - this.g.precompute(curve.n.bitLength() + 1); - - this.pointClass = curve.point().constructor; - this.encodingLength = Math.ceil(curve.n.bitLength() / 8); - this.hash = hash.sha512; -} - -module.exports = EDDSA; - -/** -* @param {Array|String} message - message bytes -* @param {Array|String|KeyPair} secret - secret bytes or a keypair -* @returns {Signature} - signature -*/ -EDDSA.prototype.sign = function sign(message, secret) { - message = parseBytes(message); - var key = this.keyFromSecret(secret); - var r = this.hashInt(key.messagePrefix(), message); - var R = this.g.mul(r); - var Rencoded = this.encodePoint(R); - var s_ = this.hashInt(Rencoded, key.pubBytes(), message) - .mul(key.priv()); - var S = r.add(s_).umod(this.curve.n); - return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); -}; - -/** -* @param {Array} message - message bytes -* @param {Array|String|Signature} sig - sig bytes -* @param {Array|String|Point|KeyPair} pub - public key -* @returns {Boolean} - true if public key matches sig of message -*/ -EDDSA.prototype.verify = function verify(message, sig, pub) { - message = parseBytes(message); - sig = this.makeSignature(sig); - var key = this.keyFromPublic(pub); - var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); - var SG = this.g.mul(sig.S()); - var RplusAh = sig.R().add(key.pub().mul(h)); - return RplusAh.eq(SG); -}; - -EDDSA.prototype.hashInt = function hashInt() { - var hash = this.hash(); - for (var i = 0; i < arguments.length; i++) - hash.update(arguments[i]); - return utils.intFromLE(hash.digest()).umod(this.curve.n); -}; - -EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { - return KeyPair.fromPublic(this, pub); -}; - -EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { - return KeyPair.fromSecret(this, secret); -}; - -EDDSA.prototype.makeSignature = function makeSignature(sig) { - if (sig instanceof Signature) - return sig; - return new Signature(this, sig); -}; - -/** -* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 -* -* EDDSA defines methods for encoding and decoding points and integers. These are -* helper convenience methods, that pass along to utility functions implied -* parameters. -* -*/ -EDDSA.prototype.encodePoint = function encodePoint(point) { - var enc = point.getY().toArray('le', this.encodingLength); - enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; - return enc; -}; - -EDDSA.prototype.decodePoint = function decodePoint(bytes) { - bytes = utils.parseBytes(bytes); - - var lastIx = bytes.length - 1; - var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); - var xIsOdd = (bytes[lastIx] & 0x80) !== 0; - - var y = utils.intFromLE(normed); - return this.curve.pointFromY(y, xIsOdd); -}; - -EDDSA.prototype.encodeInt = function encodeInt(num) { - return num.toArray('le', this.encodingLength); -}; - -EDDSA.prototype.decodeInt = function decodeInt(bytes) { - return utils.intFromLE(bytes); -}; - -EDDSA.prototype.isPoint = function isPoint(val) { - return val instanceof this.pointClass; -}; - -},{"../curves":95,"../utils":103,"./key":100,"./signature":101,"hash.js":132}],100:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); -var assert = utils.assert; -var parseBytes = utils.parseBytes; -var cachedProperty = utils.cachedProperty; - -/** -* @param {EDDSA} eddsa - instance -* @param {Object} params - public/private key parameters -* -* @param {Array} [params.secret] - secret seed bytes -* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) -* @param {Array} [params.pub] - public key point encoded as bytes -* -*/ -function KeyPair(eddsa, params) { - this.eddsa = eddsa; - this._secret = parseBytes(params.secret); - if (eddsa.isPoint(params.pub)) - this._pub = params.pub; - else - this._pubBytes = parseBytes(params.pub); -} - -KeyPair.fromPublic = function fromPublic(eddsa, pub) { - if (pub instanceof KeyPair) - return pub; - return new KeyPair(eddsa, { pub: pub }); -}; - -KeyPair.fromSecret = function fromSecret(eddsa, secret) { - if (secret instanceof KeyPair) - return secret; - return new KeyPair(eddsa, { secret: secret }); -}; - -KeyPair.prototype.secret = function secret() { - return this._secret; -}; - -cachedProperty(KeyPair, 'pubBytes', function pubBytes() { - return this.eddsa.encodePoint(this.pub()); -}); - -cachedProperty(KeyPair, 'pub', function pub() { - if (this._pubBytes) - return this.eddsa.decodePoint(this._pubBytes); - return this.eddsa.g.mul(this.priv()); -}); - -cachedProperty(KeyPair, 'privBytes', function privBytes() { - var eddsa = this.eddsa; - var hash = this.hash(); - var lastIx = eddsa.encodingLength - 1; - - var a = hash.slice(0, eddsa.encodingLength); - a[0] &= 248; - a[lastIx] &= 127; - a[lastIx] |= 64; - - return a; -}); - -cachedProperty(KeyPair, 'priv', function priv() { - return this.eddsa.decodeInt(this.privBytes()); -}); - -cachedProperty(KeyPair, 'hash', function hash() { - return this.eddsa.hash().update(this.secret()).digest(); -}); - -cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() { - return this.hash().slice(this.eddsa.encodingLength); -}); - -KeyPair.prototype.sign = function sign(message) { - assert(this._secret, 'KeyPair can only verify'); - return this.eddsa.sign(message, this); -}; - -KeyPair.prototype.verify = function verify(message, sig) { - return this.eddsa.verify(message, sig, this); -}; - -KeyPair.prototype.getSecret = function getSecret(enc) { - assert(this._secret, 'KeyPair is public only'); - return utils.encode(this.secret(), enc); -}; - -KeyPair.prototype.getPublic = function getPublic(enc) { - return utils.encode(this.pubBytes(), enc); -}; - -module.exports = KeyPair; - -},{"../utils":103}],101:[function(require,module,exports){ -'use strict'; - -var BN = require('bn.js'); -var utils = require('../utils'); -var assert = utils.assert; -var cachedProperty = utils.cachedProperty; -var parseBytes = utils.parseBytes; - -/** -* @param {EDDSA} eddsa - eddsa instance -* @param {Array|Object} sig - -* @param {Array|Point} [sig.R] - R point as Point or bytes -* @param {Array|bn} [sig.S] - S scalar as bn or bytes -* @param {Array} [sig.Rencoded] - R point encoded -* @param {Array} [sig.Sencoded] - S scalar encoded -*/ -function Signature(eddsa, sig) { - this.eddsa = eddsa; - - if (typeof sig !== 'object') - sig = parseBytes(sig); - - if (Array.isArray(sig)) { - sig = { - R: sig.slice(0, eddsa.encodingLength), - S: sig.slice(eddsa.encodingLength), - }; - } - - assert(sig.R && sig.S, 'Signature without R or S'); - - if (eddsa.isPoint(sig.R)) - this._R = sig.R; - if (sig.S instanceof BN) - this._S = sig.S; - - this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; - this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; -} - -cachedProperty(Signature, 'S', function S() { - return this.eddsa.decodeInt(this.Sencoded()); -}); - -cachedProperty(Signature, 'R', function R() { - return this.eddsa.decodePoint(this.Rencoded()); -}); - -cachedProperty(Signature, 'Rencoded', function Rencoded() { - return this.eddsa.encodePoint(this.R()); -}); - -cachedProperty(Signature, 'Sencoded', function Sencoded() { - return this.eddsa.encodeInt(this.S()); -}); - -Signature.prototype.toBytes = function toBytes() { - return this.Rencoded().concat(this.Sencoded()); -}; - -Signature.prototype.toHex = function toHex() { - return utils.encode(this.toBytes(), 'hex').toUpperCase(); -}; - -module.exports = Signature; - -},{"../utils":103,"bn.js":18}],102:[function(require,module,exports){ -module.exports = { - doubles: { - step: 4, - points: [ - [ - 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', - 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821', - ], - [ - '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', - '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf', - ], - [ - '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', - 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695', - ], - [ - '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', - '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9', - ], - [ - '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', - '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36', - ], - [ - '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', - '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f', - ], - [ - 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', - '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999', - ], - [ - '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', - 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09', - ], - [ - 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', - '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d', - ], - [ - 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', - 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088', - ], - [ - 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', - '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d', - ], - [ - '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', - '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8', - ], - [ - '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', - '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a', - ], - [ - '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', - '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453', - ], - [ - '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', - '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160', - ], - [ - '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', - '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0', - ], - [ - '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', - '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6', - ], - [ - '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', - '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589', - ], - [ - '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', - 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17', - ], - [ - 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', - '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda', - ], - [ - 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', - '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd', - ], - [ - '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', - '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2', - ], - [ - '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', - '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6', - ], - [ - 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', - '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f', - ], - [ - '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', - 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01', - ], - [ - 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', - '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3', - ], - [ - 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', - 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f', - ], - [ - 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', - '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7', - ], - [ - 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', - 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78', - ], - [ - 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', - '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1', - ], - [ - '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', - 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150', - ], - [ - '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', - '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82', - ], - [ - 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', - '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc', - ], - [ - '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', - 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b', - ], - [ - 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', - '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51', - ], - [ - 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', - '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45', - ], - [ - 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', - 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120', - ], - [ - '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', - '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84', - ], - [ - '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', - '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d', - ], - [ - '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', - 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d', - ], - [ - '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', - '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8', - ], - [ - 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', - '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8', - ], - [ - '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', - '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac', - ], - [ - '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', - 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f', - ], - [ - '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', - '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962', - ], - [ - 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', - '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907', - ], - [ - '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', - 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec', - ], - [ - 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', - 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d', - ], - [ - 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', - '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414', - ], - [ - '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', - 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd', - ], - [ - '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', - 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0', - ], - [ - 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', - '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811', - ], - [ - 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', - '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1', - ], - [ - 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', - '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c', - ], - [ - '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', - 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73', - ], - [ - '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', - '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd', - ], - [ - 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', - 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405', - ], - [ - '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', - 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589', - ], - [ - '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', - '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e', - ], - [ - '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', - '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27', - ], - [ - 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', - 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1', - ], - [ - '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', - '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482', - ], - [ - '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', - '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945', - ], - [ - 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', - '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573', - ], - [ - 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', - 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82', - ], - ], - }, - naf: { - wnd: 7, - points: [ - [ - 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', - '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672', - ], - [ - '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', - 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6', - ], - [ - '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', - '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da', - ], - [ - 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', - 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37', - ], - [ - '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', - 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b', - ], - [ - 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', - 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81', - ], - [ - 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', - '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58', - ], - [ - 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', - '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77', - ], - [ - '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', - '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a', - ], - [ - '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', - '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c', - ], - [ - '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', - '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67', - ], - [ - '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', - '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402', - ], - [ - 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', - 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55', - ], - [ - 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', - '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482', - ], - [ - '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', - 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82', - ], - [ - '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', - 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396', - ], - [ - '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', - '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49', - ], - [ - '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', - '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf', - ], - [ - '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', - '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a', - ], - [ - '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', - 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7', - ], - [ - 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', - 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933', - ], - [ - '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', - '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a', - ], - [ - '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', - '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6', - ], - [ - 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', - 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37', - ], - [ - '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', - '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e', - ], - [ - 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', - 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6', - ], - [ - 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', - 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476', - ], - [ - '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', - '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40', - ], - [ - '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', - '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61', - ], - [ - '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', - '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683', - ], - [ - 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', - '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5', - ], - [ - '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', - '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b', - ], - [ - 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', - '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417', - ], - [ - '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', - 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868', - ], - [ - '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', - 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a', - ], - [ - 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', - 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6', - ], - [ - '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', - '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996', - ], - [ - '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', - 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e', - ], - [ - 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', - 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d', - ], - [ - '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', - '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2', - ], - [ - '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', - 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e', - ], - [ - '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', - '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437', - ], - [ - '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', - 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311', - ], - [ - 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', - '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4', - ], - [ - '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', - '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575', - ], - [ - '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', - 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d', - ], - [ - '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', - 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d', - ], - [ - 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', - 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629', - ], - [ - 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', - 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06', - ], - [ - '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', - '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374', - ], - [ - '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', - '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee', - ], - [ - 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', - '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1', - ], - [ - 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', - 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b', - ], - [ - '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', - '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661', - ], - [ - '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', - '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6', - ], - [ - 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', - '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e', - ], - [ - '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', - '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d', - ], - [ - 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', - 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc', - ], - [ - '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', - 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4', - ], - [ - '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', - '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c', - ], - [ - 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', - '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b', - ], - [ - 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', - '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913', - ], - [ - '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', - '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154', - ], - [ - '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', - '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865', - ], - [ - '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', - 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc', - ], - [ - '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', - 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224', - ], - [ - '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', - '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e', - ], - [ - '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', - '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6', - ], - [ - '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', - '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511', - ], - [ - '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', - 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b', - ], - [ - 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', - 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2', - ], - [ - '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', - 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c', - ], - [ - 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', - '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3', - ], - [ - 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', - '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d', - ], - [ - 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', - '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700', - ], - [ - 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', - '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4', - ], - [ - '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', - 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196', - ], - [ - '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', - '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4', - ], - [ - '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', - 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257', - ], - [ - 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', - 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13', - ], - [ - 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', - '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096', - ], - [ - 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', - 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38', - ], - [ - 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', - '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f', - ], - [ - '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', - '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448', - ], - [ - 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', - '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a', - ], - [ - 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', - '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4', - ], - [ - '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', - '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437', - ], - [ - '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', - 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7', - ], - [ - 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', - '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d', - ], - [ - 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', - '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a', - ], - [ - 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', - '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54', - ], - [ - '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', - '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77', - ], - [ - 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', - 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517', - ], - [ - '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', - 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10', - ], - [ - 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', - 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125', - ], - [ - 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', - '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e', - ], - [ - '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', - 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1', - ], - [ - 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', - '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2', - ], - [ - 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', - '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423', - ], - [ - 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', - '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8', - ], - [ - '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', - 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758', - ], - [ - '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', - 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375', - ], - [ - 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', - '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d', - ], - [ - '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', - 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec', - ], - [ - '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', - '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0', - ], - [ - '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', - 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c', - ], - [ - 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', - 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4', - ], - [ - '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', - 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f', - ], - [ - '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', - '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649', - ], - [ - '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', - 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826', - ], - [ - '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', - '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5', - ], - [ - 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', - 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87', - ], - [ - '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', - '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b', - ], - [ - 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', - '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc', - ], - [ - '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', - '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c', - ], - [ - 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', - 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f', - ], - [ - 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', - '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a', - ], - [ - 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', - 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46', - ], - [ - '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', - 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f', - ], - [ - '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', - '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03', - ], - [ - '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', - 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08', - ], - [ - '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', - '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8', - ], - [ - '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', - '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373', - ], - [ - '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', - 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3', - ], - [ - '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', - '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8', - ], - [ - '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', - '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1', - ], - [ - '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', - '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9', - ], - ], - }, -}; - -},{}],103:[function(require,module,exports){ -'use strict'; - -var utils = exports; -var BN = require('bn.js'); -var minAssert = require('minimalistic-assert'); -var minUtils = require('minimalistic-crypto-utils'); - -utils.assert = minAssert; -utils.toArray = minUtils.toArray; -utils.zero2 = minUtils.zero2; -utils.toHex = minUtils.toHex; -utils.encode = minUtils.encode; - -// Represent num in a w-NAF form -function getNAF(num, w, bits) { - var naf = new Array(Math.max(num.bitLength(), bits) + 1); - naf.fill(0); - - var ws = 1 << (w + 1); - var k = num.clone(); - - for (var i = 0; i < naf.length; i++) { - var z; - var mod = k.andln(ws - 1); - if (k.isOdd()) { - if (mod > (ws >> 1) - 1) - z = (ws >> 1) - mod; - else - z = mod; - k.isubn(z); - } else { - z = 0; - } - - naf[i] = z; - k.iushrn(1); - } - - return naf; -} -utils.getNAF = getNAF; - -// Represent k1, k2 in a Joint Sparse Form -function getJSF(k1, k2) { - var jsf = [ - [], - [], - ]; - - k1 = k1.clone(); - k2 = k2.clone(); - var d1 = 0; - var d2 = 0; - var m8; - while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { - // First phase - var m14 = (k1.andln(3) + d1) & 3; - var m24 = (k2.andln(3) + d2) & 3; - if (m14 === 3) - m14 = -1; - if (m24 === 3) - m24 = -1; - var u1; - if ((m14 & 1) === 0) { - u1 = 0; - } else { - m8 = (k1.andln(7) + d1) & 7; - if ((m8 === 3 || m8 === 5) && m24 === 2) - u1 = -m14; - else - u1 = m14; - } - jsf[0].push(u1); - - var u2; - if ((m24 & 1) === 0) { - u2 = 0; - } else { - m8 = (k2.andln(7) + d2) & 7; - if ((m8 === 3 || m8 === 5) && m14 === 2) - u2 = -m24; - else - u2 = m24; - } - jsf[1].push(u2); - - // Second phase - if (2 * d1 === u1 + 1) - d1 = 1 - d1; - if (2 * d2 === u2 + 1) - d2 = 1 - d2; - k1.iushrn(1); - k2.iushrn(1); - } - - return jsf; -} -utils.getJSF = getJSF; - -function cachedProperty(obj, name, computer) { - var key = '_' + name; - obj.prototype[name] = function cachedProperty() { - return this[key] !== undefined ? this[key] : - this[key] = computer.call(this); - }; -} -utils.cachedProperty = cachedProperty; - -function parseBytes(bytes) { - return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : - bytes; -} -utils.parseBytes = parseBytes; - -function intFromLE(bytes) { - return new BN(bytes, 'hex', 'le'); -} -utils.intFromLE = intFromLE; - - -},{"bn.js":18,"minimalistic-assert":223,"minimalistic-crypto-utils":224}],104:[function(require,module,exports){ -module.exports={ - "name": "elliptic", - "version": "6.5.4", - "description": "EC cryptography", - "main": "lib/elliptic.js", - "files": [ - "lib" - ], - "scripts": { - "lint": "eslint lib test", - "lint:fix": "npm run lint -- --fix", - "unit": "istanbul test _mocha --reporter=spec test/index.js", - "test": "npm run lint && npm run unit", - "version": "grunt dist && git add dist/" - }, - "repository": { - "type": "git", - "url": "git@github.com:indutny/elliptic" - }, - "keywords": [ - "EC", - "Elliptic", - "curve", - "Cryptography" - ], - "author": "Fedor Indutny ", - "license": "MIT", - "bugs": { - "url": "https://github.com/indutny/elliptic/issues" - }, - "homepage": "https://github.com/indutny/elliptic", - "devDependencies": { - "brfs": "^2.0.2", - "coveralls": "^3.1.0", - "eslint": "^7.6.0", - "grunt": "^1.2.1", - "grunt-browserify": "^5.3.0", - "grunt-cli": "^1.3.2", - "grunt-contrib-connect": "^3.0.0", - "grunt-contrib-copy": "^1.0.0", - "grunt-contrib-uglify": "^5.0.0", - "grunt-mocha-istanbul": "^5.0.2", - "grunt-saucelabs": "^9.0.1", - "istanbul": "^0.4.5", - "mocha": "^8.0.1" - }, - "dependencies": { - "bn.js": "^4.11.9", - "brorand": "^1.1.0", - "hash.js": "^1.0.0", - "hmac-drbg": "^1.0.1", - "inherits": "^2.0.4", - "minimalistic-assert": "^1.0.1", - "minimalistic-crypto-utils": "^1.0.1" - } -} - -},{}],105:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -var R = typeof Reflect === 'object' ? Reflect : null -var ReflectApply = R && typeof R.apply === 'function' - ? R.apply - : function ReflectApply(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - } - -var ReflectOwnKeys -if (R && typeof R.ownKeys === 'function') { - ReflectOwnKeys = R.ownKeys -} else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target) - .concat(Object.getOwnPropertySymbols(target)); - }; -} else { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target); - }; -} - -function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); -} - -var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; -} - -function EventEmitter() { - EventEmitter.init.call(this); -} -module.exports = EventEmitter; -module.exports.once = once; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._eventsCount = 0; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; - -function checkListener(listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } -} - -Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); - } - defaultMaxListeners = arg; - } -}); - -EventEmitter.init = function() { - - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; -}; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); - } - this._maxListeners = n; - return this; -}; - -function _getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; -} - -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return _getMaxListeners(this); -}; - -EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); - - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; - - // If there is no 'error' event listener then throw. - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - // Note: The comments on the `throw` lines are intentional, they show - // up in Node's output if this results in an unhandled exception. - throw er; // Unhandled 'error' event - } - // At least give some kind of context to the user - var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); - err.context = er; - throw err; // Unhandled 'error' event - } - - var handler = events[type]; - - if (handler === undefined) - return false; - - if (typeof handler === 'function') { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - ReflectApply(listeners[i], this, args); - } - - return true; -}; - -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - checkListener(listener); - - events = target._events; - if (events === undefined) { - events = target._events = Object.create(null); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener !== undefined) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); - - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; - } - existing = events[type]; - } - - if (existing === undefined) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - // If we've already got an array, just append. - } else if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - - // Check for listener leak - m = _getMaxListeners(target); - if (m > 0 && existing.length > m && !existing.warned) { - existing.warned = true; - // No error code for this since it is a Warning - // eslint-disable-next-line no-restricted-syntax - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + String(type) + ' listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - ProcessEmitWarning(w); - } - } - - return target; -} - -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - -function onceWrapper() { - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - if (arguments.length === 0) - return this.listener.call(this.target); - return this.listener.apply(this.target, arguments); - } -} - -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; -} - -EventEmitter.prototype.once = function once(type, listener) { - checkListener(listener); - this.on(type, _onceWrap(this, type, listener)); - return this; -}; - -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - checkListener(listener); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - checkListener(listener); - - events = this._events; - if (events === undefined) - return this; - - list = events[type]; - if (list === undefined) - return this; - - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); - } - } else if (typeof list !== 'function') { - position = -1; - - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } - - if (list.length === 1) - events[type] = list[0]; - - if (events.removeListener !== undefined) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; - if (events === undefined) - return this; - - // not listening for removeListener, no need to emit - if (events.removeListener === undefined) { - if (arguments.length === 0) { - this._events = Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== undefined) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = Object.create(null); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners !== undefined) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); - } - } - - return this; - }; - -function _listeners(target, type, unwrap) { - var events = target._events; - - if (events === undefined) - return []; - - var evlistener = events[type]; - if (evlistener === undefined) - return []; - - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} - -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; - -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; - -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } -}; - -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; - - if (events !== undefined) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; - } - } - - return 0; -} - -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; -}; - -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; -} - -function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); -} - -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} - -function once(emitter, name) { - return new Promise(function (resolve, reject) { - function errorListener(err) { - emitter.removeListener(name, resolver); - reject(err); - } - - function resolver() { - if (typeof emitter.removeListener === 'function') { - emitter.removeListener('error', errorListener); - } - resolve([].slice.call(arguments)); - }; - - eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); - if (name !== 'error') { - addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); - } - }); -} - -function addErrorHandlerIfEventEmitter(emitter, handler, flags) { - if (typeof emitter.on === 'function') { - eventTargetAgnosticAddListener(emitter, 'error', handler, flags); - } -} - -function eventTargetAgnosticAddListener(emitter, name, listener, flags) { - if (typeof emitter.on === 'function') { - if (flags.once) { - emitter.once(name, listener); - } else { - emitter.on(name, listener); - } - } else if (typeof emitter.addEventListener === 'function') { - // EventTarget does not have `error` event semantics like Node - // EventEmitters, we do not listen for `error` events here. - emitter.addEventListener(name, function wrapListener(arg) { - // IE does not have builtin `{ once: true }` support so we - // have to do it manually. - if (flags.once) { - emitter.removeEventListener(name, wrapListener); - } - listener(arg); - }); - } else { - throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); - } -} - -},{}],106:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var MD5 = require('md5.js') - -/* eslint-disable camelcase */ -function EVP_BytesToKey (password, salt, keyBits, ivLen) { - if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary') - if (salt) { - if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary') - if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length') - } - - var keyLen = keyBits / 8 - var key = Buffer.alloc(keyLen) - var iv = Buffer.alloc(ivLen || 0) - var tmp = Buffer.alloc(0) - - while (keyLen > 0 || ivLen > 0) { - var hash = new MD5() - hash.update(tmp) - hash.update(password) - if (salt) hash.update(salt) - tmp = hash.digest() - - var used = 0 - - if (keyLen > 0) { - var keyStart = key.length - keyLen - used = Math.min(keyLen, tmp.length) - tmp.copy(key, keyStart, 0, used) - keyLen -= used - } - - if (used < tmp.length && ivLen > 0) { - var ivStart = iv.length - ivLen - var length = Math.min(ivLen, tmp.length - used) - tmp.copy(iv, ivStart, used, used + length) - ivLen -= length - } - } - - tmp.fill(0) - return { key: key, iv: iv } -} - -module.exports = EVP_BytesToKey - -},{"md5.js":221,"safe-buffer":250}],107:[function(require,module,exports){ -'use strict'; - -var isCallable = require('is-callable'); - -var toStr = Object.prototype.toString; -var hasOwnProperty = Object.prototype.hasOwnProperty; - -var forEachArray = function forEachArray(array, iterator, receiver) { - for (var i = 0, len = array.length; i < len; i++) { - if (hasOwnProperty.call(array, i)) { - if (receiver == null) { - iterator(array[i], i, array); - } else { - iterator.call(receiver, array[i], i, array); - } - } - } -}; - -var forEachString = function forEachString(string, iterator, receiver) { - for (var i = 0, len = string.length; i < len; i++) { - // no such thing as a sparse string. - if (receiver == null) { - iterator(string.charAt(i), i, string); - } else { - iterator.call(receiver, string.charAt(i), i, string); - } - } -}; - -var forEachObject = function forEachObject(object, iterator, receiver) { - for (var k in object) { - if (hasOwnProperty.call(object, k)) { - if (receiver == null) { - iterator(object[k], k, object); - } else { - iterator.call(receiver, object[k], k, object); - } - } - } -}; - -var forEach = function forEach(list, iterator, thisArg) { - if (!isCallable(iterator)) { - throw new TypeError('iterator must be a function'); - } - - var receiver; - if (arguments.length >= 3) { - receiver = thisArg; - } - - if (toStr.call(list) === '[object Array]') { - forEachArray(list, iterator, receiver); - } else if (typeof list === 'string') { - forEachString(list, iterator, receiver); - } else { - forEachObject(list, iterator, receiver); - } -}; - -module.exports = forEach; - -},{"is-callable":148}],108:[function(require,module,exports){ -'use strict'; - -/* eslint no-invalid-this: 1 */ - -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; -var toStr = Object.prototype.toString; -var funcType = '[object Function]'; - -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slice.call(arguments, 1); - - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - args.concat(slice.call(arguments)) - ); - if (Object(result) === result) { - return result; - } - return this; - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); - } - }; - - var boundLength = Math.max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); - } - - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); - - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } - - return bound; -}; - -},{}],109:[function(require,module,exports){ -'use strict'; - -var implementation = require('./implementation'); - -module.exports = Function.prototype.bind || implementation; - -},{"./implementation":108}],110:[function(require,module,exports){ -'use strict'; - -var undefined; - -var $SyntaxError = SyntaxError; -var $Function = Function; -var $TypeError = TypeError; - -// eslint-disable-next-line consistent-return -var getEvalledConstructor = function (expressionSyntax) { - try { - return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); - } catch (e) {} -}; - -var $gOPD = Object.getOwnPropertyDescriptor; -if ($gOPD) { - try { - $gOPD({}, ''); - } catch (e) { - $gOPD = null; // this is IE 8, which has a broken gOPD - } -} - -var throwTypeError = function () { - throw new $TypeError(); -}; -var ThrowTypeError = $gOPD - ? (function () { - try { - // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties - arguments.callee; // IE 8 does not throw here - return throwTypeError; - } catch (calleeThrows) { - try { - // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') - return $gOPD(arguments, 'callee').get; - } catch (gOPDthrows) { - return throwTypeError; - } - } - }()) - : throwTypeError; - -var hasSymbols = require('has-symbols')(); - -var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto - -var needsEval = {}; - -var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); - -var INTRINSICS = { - '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, - '%Array%': Array, - '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, - '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, - '%AsyncFromSyncIteratorPrototype%': undefined, - '%AsyncFunction%': needsEval, - '%AsyncGenerator%': needsEval, - '%AsyncGeneratorFunction%': needsEval, - '%AsyncIteratorPrototype%': needsEval, - '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, - '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, - '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, - '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, - '%Boolean%': Boolean, - '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, - '%Date%': Date, - '%decodeURI%': decodeURI, - '%decodeURIComponent%': decodeURIComponent, - '%encodeURI%': encodeURI, - '%encodeURIComponent%': encodeURIComponent, - '%Error%': Error, - '%eval%': eval, // eslint-disable-line no-eval - '%EvalError%': EvalError, - '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, - '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, - '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, - '%Function%': $Function, - '%GeneratorFunction%': needsEval, - '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, - '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, - '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, - '%isFinite%': isFinite, - '%isNaN%': isNaN, - '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, - '%JSON%': typeof JSON === 'object' ? JSON : undefined, - '%Map%': typeof Map === 'undefined' ? undefined : Map, - '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), - '%Math%': Math, - '%Number%': Number, - '%Object%': Object, - '%parseFloat%': parseFloat, - '%parseInt%': parseInt, - '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, - '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, - '%RangeError%': RangeError, - '%ReferenceError%': ReferenceError, - '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, - '%RegExp%': RegExp, - '%Set%': typeof Set === 'undefined' ? undefined : Set, - '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), - '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, - '%String%': String, - '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, - '%Symbol%': hasSymbols ? Symbol : undefined, - '%SyntaxError%': $SyntaxError, - '%ThrowTypeError%': ThrowTypeError, - '%TypedArray%': TypedArray, - '%TypeError%': $TypeError, - '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, - '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, - '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, - '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, - '%URIError%': URIError, - '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, - '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, - '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet -}; - -try { - null.error; // eslint-disable-line no-unused-expressions -} catch (e) { - // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 - var errorProto = getProto(getProto(e)); - INTRINSICS['%Error.prototype%'] = errorProto; -} - -var doEval = function doEval(name) { - var value; - if (name === '%AsyncFunction%') { - value = getEvalledConstructor('async function () {}'); - } else if (name === '%GeneratorFunction%') { - value = getEvalledConstructor('function* () {}'); - } else if (name === '%AsyncGeneratorFunction%') { - value = getEvalledConstructor('async function* () {}'); - } else if (name === '%AsyncGenerator%') { - var fn = doEval('%AsyncGeneratorFunction%'); - if (fn) { - value = fn.prototype; - } - } else if (name === '%AsyncIteratorPrototype%') { - var gen = doEval('%AsyncGenerator%'); - if (gen) { - value = getProto(gen.prototype); - } - } - - INTRINSICS[name] = value; - - return value; -}; - -var LEGACY_ALIASES = { - '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], - '%ArrayPrototype%': ['Array', 'prototype'], - '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], - '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], - '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], - '%ArrayProto_values%': ['Array', 'prototype', 'values'], - '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], - '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], - '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], - '%BooleanPrototype%': ['Boolean', 'prototype'], - '%DataViewPrototype%': ['DataView', 'prototype'], - '%DatePrototype%': ['Date', 'prototype'], - '%ErrorPrototype%': ['Error', 'prototype'], - '%EvalErrorPrototype%': ['EvalError', 'prototype'], - '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], - '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], - '%FunctionPrototype%': ['Function', 'prototype'], - '%Generator%': ['GeneratorFunction', 'prototype'], - '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], - '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], - '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], - '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], - '%JSONParse%': ['JSON', 'parse'], - '%JSONStringify%': ['JSON', 'stringify'], - '%MapPrototype%': ['Map', 'prototype'], - '%NumberPrototype%': ['Number', 'prototype'], - '%ObjectPrototype%': ['Object', 'prototype'], - '%ObjProto_toString%': ['Object', 'prototype', 'toString'], - '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], - '%PromisePrototype%': ['Promise', 'prototype'], - '%PromiseProto_then%': ['Promise', 'prototype', 'then'], - '%Promise_all%': ['Promise', 'all'], - '%Promise_reject%': ['Promise', 'reject'], - '%Promise_resolve%': ['Promise', 'resolve'], - '%RangeErrorPrototype%': ['RangeError', 'prototype'], - '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], - '%RegExpPrototype%': ['RegExp', 'prototype'], - '%SetPrototype%': ['Set', 'prototype'], - '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], - '%StringPrototype%': ['String', 'prototype'], - '%SymbolPrototype%': ['Symbol', 'prototype'], - '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], - '%TypedArrayPrototype%': ['TypedArray', 'prototype'], - '%TypeErrorPrototype%': ['TypeError', 'prototype'], - '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], - '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], - '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], - '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], - '%URIErrorPrototype%': ['URIError', 'prototype'], - '%WeakMapPrototype%': ['WeakMap', 'prototype'], - '%WeakSetPrototype%': ['WeakSet', 'prototype'] -}; - -var bind = require('function-bind'); -var hasOwn = require('has'); -var $concat = bind.call(Function.call, Array.prototype.concat); -var $spliceApply = bind.call(Function.apply, Array.prototype.splice); -var $replace = bind.call(Function.call, String.prototype.replace); -var $strSlice = bind.call(Function.call, String.prototype.slice); -var $exec = bind.call(Function.call, RegExp.prototype.exec); - -/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ -var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; -var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ -var stringToPath = function stringToPath(string) { - var first = $strSlice(string, 0, 1); - var last = $strSlice(string, -1); - if (first === '%' && last !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); - } else if (last === '%' && first !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); - } - var result = []; - $replace(string, rePropName, function (match, number, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; - }); - return result; -}; -/* end adaptation */ - -var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { - var intrinsicName = name; - var alias; - if (hasOwn(LEGACY_ALIASES, intrinsicName)) { - alias = LEGACY_ALIASES[intrinsicName]; - intrinsicName = '%' + alias[0] + '%'; - } - - if (hasOwn(INTRINSICS, intrinsicName)) { - var value = INTRINSICS[intrinsicName]; - if (value === needsEval) { - value = doEval(intrinsicName); - } - if (typeof value === 'undefined' && !allowMissing) { - throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); - } - - return { - alias: alias, - name: intrinsicName, - value: value - }; - } - - throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); -}; - -module.exports = function GetIntrinsic(name, allowMissing) { - if (typeof name !== 'string' || name.length === 0) { - throw new $TypeError('intrinsic name must be a non-empty string'); - } - if (arguments.length > 1 && typeof allowMissing !== 'boolean') { - throw new $TypeError('"allowMissing" argument must be a boolean'); - } - - if ($exec(/^%?[^%]*%?$/, name) === null) { - throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); - } - var parts = stringToPath(name); - var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; - - var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); - var intrinsicRealName = intrinsic.name; - var value = intrinsic.value; - var skipFurtherCaching = false; - - var alias = intrinsic.alias; - if (alias) { - intrinsicBaseName = alias[0]; - $spliceApply(parts, $concat([0, 1], alias)); - } - - for (var i = 1, isOwn = true; i < parts.length; i += 1) { - var part = parts[i]; - var first = $strSlice(part, 0, 1); - var last = $strSlice(part, -1); - if ( - ( - (first === '"' || first === "'" || first === '`') - || (last === '"' || last === "'" || last === '`') - ) - && first !== last - ) { - throw new $SyntaxError('property names with quotes must have matching quotes'); - } - if (part === 'constructor' || !isOwn) { - skipFurtherCaching = true; - } - - intrinsicBaseName += '.' + part; - intrinsicRealName = '%' + intrinsicBaseName + '%'; - - if (hasOwn(INTRINSICS, intrinsicRealName)) { - value = INTRINSICS[intrinsicRealName]; - } else if (value != null) { - if (!(part in value)) { - if (!allowMissing) { - throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); - } - return void undefined; - } - if ($gOPD && (i + 1) >= parts.length) { - var desc = $gOPD(value, part); - isOwn = !!desc; - - // By convention, when a data property is converted to an accessor - // property to emulate a data property that does not suffer from - // the override mistake, that accessor's getter is marked with - // an `originalValue` property. Here, when we detect this, we - // uphold the illusion by pretending to see that original data - // property, i.e., returning the value rather than the getter - // itself. - if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { - value = desc.get; - } else { - value = value[part]; - } - } else { - isOwn = hasOwn(value, part); - value = value[part]; - } - - if (isOwn && !skipFurtherCaching) { - INTRINSICS[intrinsicRealName] = value; - } - } - } - return value; -}; - -},{"function-bind":109,"has":115,"has-symbols":112}],111:[function(require,module,exports){ -'use strict'; - -var GetIntrinsic = require('get-intrinsic'); - -var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); - -if ($gOPD) { - try { - $gOPD([], 'length'); - } catch (e) { - // IE 8 has a broken gOPD - $gOPD = null; - } -} - -module.exports = $gOPD; - -},{"get-intrinsic":110}],112:[function(require,module,exports){ -'use strict'; - -var origSymbol = typeof Symbol !== 'undefined' && Symbol; -var hasSymbolSham = require('./shams'); - -module.exports = function hasNativeSymbols() { - if (typeof origSymbol !== 'function') { return false; } - if (typeof Symbol !== 'function') { return false; } - if (typeof origSymbol('foo') !== 'symbol') { return false; } - if (typeof Symbol('bar') !== 'symbol') { return false; } - - return hasSymbolSham(); -}; - -},{"./shams":113}],113:[function(require,module,exports){ -'use strict'; - -/* eslint complexity: [2, 18], max-statements: [2, 33] */ -module.exports = function hasSymbols() { - if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } - if (typeof Symbol.iterator === 'symbol') { return true; } - - var obj = {}; - var sym = Symbol('test'); - var symObj = Object(sym); - if (typeof sym === 'string') { return false; } - - if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } - if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } - - // temp disabled per https://github.com/ljharb/object.assign/issues/17 - // if (sym instanceof Symbol) { return false; } - // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 - // if (!(symObj instanceof Symbol)) { return false; } - - // if (typeof Symbol.prototype.toString !== 'function') { return false; } - // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } - - var symVal = 42; - obj[sym] = symVal; - for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop - if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } - - if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } - - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { return false; } - - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } - - if (typeof Object.getOwnPropertyDescriptor === 'function') { - var descriptor = Object.getOwnPropertyDescriptor(obj, sym); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } - } - - return true; -}; - -},{}],114:[function(require,module,exports){ -'use strict'; - -var hasSymbols = require('has-symbols/shams'); - -module.exports = function hasToStringTagShams() { - return hasSymbols() && !!Symbol.toStringTag; -}; - -},{"has-symbols/shams":113}],115:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); - -module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); - -},{"function-bind":109}],116:[function(require,module,exports){ -'use strict' -var Buffer = require('safe-buffer').Buffer -var Transform = require('readable-stream').Transform -var inherits = require('inherits') - -function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer.isBuffer(val) && typeof val !== 'string') { - throw new TypeError(prefix + ' must be a string or a buffer') - } -} - -function HashBase (blockSize) { - Transform.call(this) - - this._block = Buffer.allocUnsafe(blockSize) - this._blockSize = blockSize - this._blockOffset = 0 - this._length = [0, 0, 0, 0] - - this._finalized = false -} - -inherits(HashBase, Transform) - -HashBase.prototype._transform = function (chunk, encoding, callback) { - var error = null - try { - this.update(chunk, encoding) - } catch (err) { - error = err - } - - callback(error) -} - -HashBase.prototype._flush = function (callback) { - var error = null - try { - this.push(this.digest()) - } catch (err) { - error = err - } - - callback(error) -} - -HashBase.prototype.update = function (data, encoding) { - throwIfNotStringOrBuffer(data, 'Data') - if (this._finalized) throw new Error('Digest already called') - if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) - - // consume data - var block = this._block - var offset = 0 - while (this._blockOffset + data.length - offset >= this._blockSize) { - for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] - this._update() - this._blockOffset = 0 - } - while (offset < data.length) block[this._blockOffset++] = data[offset++] - - // update length - for (var j = 0, carry = data.length * 8; carry > 0; ++j) { - this._length[j] += carry - carry = (this._length[j] / 0x0100000000) | 0 - if (carry > 0) this._length[j] -= 0x0100000000 * carry - } - - return this -} - -HashBase.prototype._update = function () { - throw new Error('_update is not implemented') -} - -HashBase.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true - - var digest = this._digest() - if (encoding !== undefined) digest = digest.toString(encoding) - - // reset state - this._block.fill(0) - this._blockOffset = 0 - for (var i = 0; i < 4; ++i) this._length[i] = 0 - - return digest -} - -HashBase.prototype._digest = function () { - throw new Error('_digest is not implemented') -} - -module.exports = HashBase - -},{"inherits":146,"readable-stream":131,"safe-buffer":250}],117:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"dup":50}],118:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. -'use strict'; -/**/ - -var objectKeys = Object.keys || function (obj) { - var keys = []; - - for (var key in obj) { - keys.push(key); - } - - return keys; -}; -/**/ - - -module.exports = Duplex; - -var Readable = require('./_stream_readable'); - -var Writable = require('./_stream_writable'); - -require('inherits')(Duplex, Readable); - -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } -} - -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); // the no-half-open enforcer - -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. - - process.nextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); -}).call(this)}).call(this,require('_process')) - -},{"./_stream_readable":120,"./_stream_writable":122,"_process":237,"inherits":146}],119:[function(require,module,exports){ -arguments[4][52][0].apply(exports,arguments) -},{"./_stream_transform":121,"dup":52,"inherits":146}],120:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -'use strict'; - -module.exports = Readable; -/**/ - -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; -/**/ - -var EE = require('events').EventEmitter; - -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ - - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ - - -var debugUtil = require('util'); - -var debug; - -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ - - -var BufferList = require('./internal/streams/buffer_list'); - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - - -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; - -require('inherits')(Readable, Stream); - -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} - -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - - this.autoDestroy = !!options.autoDestroy; // has it been destroyed - - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; - - if (options.encoding) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); // legacy - - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; - -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; // Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. - - -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; // Unshift should *always* be something directly out of read() - - -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } - - return er; -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; // backwards compatibility. - - -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; - - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - - this._readableState.buffer.clear(); - - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; // Don't raise the hwm > 1GB - - -var MAX_HWM = 0x40000000; - -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. - - -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - - - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - - if (!state.ended) { - state.needReadable = true; - return 0; - } - - return state.length; -} // you can override either this method, or the async _read(n) below. - - -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - - - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - - - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - - if (state.length === 0) state.needReadable = true; // call internal read method - - this._read(state.highWaterMark); - - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - return ret; -}; - -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; - - if (state.decoder) { - var chunk = state.decoder.end(); - - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - - state.ended = true; - - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } -} // Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. - - -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } -} - -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} // at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. - - -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } - - state.readingMore = false; -} // abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. - - -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - - case 1: - state.pipes = [state.pipes, dest]; - break; - - default: - state.pipes.push(dest); - break; - } - - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); - - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } - - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - - - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. - - - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - - dest.once('close', onclose); - - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - - - dest.emit('pipe', src); // start the flow if it hasn't been started already. - - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. - - if (state.pipesCount === 0) return this; // just one destination. most common case. - - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. - - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. - - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } - - return this; - } // try to find the right one. - - - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; // set up data events if they are asked for -// Ensure readable listeners eventually get something - - -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } - } - } - - return res; -}; - -Readable.prototype.addListener = Readable.prototype.on; - -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } -} - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} // pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. - - -Readable.prototype.resume = function () { - var state = this._readableState; - - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() - - state.flowing = !state.readableListening; - resume(this, state); - } - - state.paused = false; - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - debug('resume', state.reading); - - if (!state.reading) { - stream.read(0); - } - - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - - this._readableState.paused = true; - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - - while (state.flowing && stream.read() !== null) { - ; - } -} // wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. - - -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. - - - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. - - - this._read = function (n) { - debug('wrapped _read', n); - - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; -}; - -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); - } - - return createReadableStreamAsyncIterator(this); - }; -} - -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } -}); // exposed for testing purposes only. - -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } -}); // Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. - -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); - - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } -} - -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = require('./internal/streams/from'); - } - - return from(Readable, iterable, opts); - }; -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - - return -1; -} -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"../errors":117,"./_stream_duplex":118,"./internal/streams/async_iterator":123,"./internal/streams/buffer_list":124,"./internal/streams/destroy":125,"./internal/streams/from":127,"./internal/streams/state":129,"./internal/streams/stream":130,"_process":237,"buffer":68,"events":105,"inherits":146,"string_decoder/":279,"util":20}],121:[function(require,module,exports){ -arguments[4][54][0].apply(exports,arguments) -},{"../errors":117,"./_stream_duplex":118,"dup":54,"inherits":146}],122:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. -'use strict'; - -module.exports = Writable; -/* */ - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} // It seems a linked list but it is not -// there will be only 2 of these for each stream - - -function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ - - -var Duplex; -/**/ - -Writable.WritableState = WritableState; -/**/ - -var internalUtil = { - deprecate: require('util-deprecate') -}; -/**/ - -/**/ - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - -var errorOrDestroy = destroyImpl.errorOrDestroy; - -require('inherits')(Writable, Stream); - -function nop() {} - -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream - // contains buffers or objects. - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. - - this.needDrain = false; // at the start of calling end() - - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted - - this.finished = false; // has it been destroyed - - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - - this.length = 0; // a flag to see when we're in the middle of a write. - - this.writing = false; // when true all writes will be buffered until .uncork() call - - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - - - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again - - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - - this.autoDestroy = !!options.autoDestroy; // count buffered requests - - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - - while (current) { - out.push(current); - current = current.next; - } - - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); // Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. - - -var realHasInstance; - -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. - - -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; - -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} // Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. - - -function validChunk(stream, state, chunk, cb) { - var er; - - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } - - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; - } - - return true; -} - -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; -}; - -Writable.prototype.cork = function () { - this._writableState.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - - return chunk; -} - -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); // if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. - -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen - // after error - - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); // this can emit finish, but finish must - // always follow error - - finishMaybe(stream, state); - } -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} // Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. - - -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} // if there's something in the buffer waiting, then process it - - -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - - state.pendingcb++; - state.lastBufferedRequest = null; - - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending) endWritable(this, state, cb); - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} - -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy(stream, err); - } - - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} - -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - - if (need) { - prefinish(stream, state); - - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } - - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; - -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"../errors":117,"./_stream_duplex":118,"./internal/streams/destroy":125,"./internal/streams/state":129,"./internal/streams/stream":130,"_process":237,"buffer":68,"inherits":146,"util-deprecate":283}],123:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; - -var _Object$setPrototypeO; - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var finished = require('./end-of-stream'); - -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); - -function createIterResult(value, done) { - return { - value: value, - done: done - }; -} - -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' - - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } -} - -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} - -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - - iter[kHandlePromise](resolve, reject); - }, reject); - }; -} - -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); - } - - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } - - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; - - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - - promise = new Promise(this[kHandlePromise]); - } - - this[kLastPromise] = promise; - return promise; - } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); - -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - - iterator[kError] = err; - return; - } - - var resolve = iterator[kLastResolve]; - - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } - - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; - -module.exports = createReadableStreamAsyncIterator; -}).call(this)}).call(this,require('_process')) - -},{"./end-of-stream":126,"_process":237}],124:[function(require,module,exports){ -arguments[4][57][0].apply(exports,arguments) -},{"buffer":68,"dup":57,"util":20}],125:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; // undocumented cb() API, needed for core, not for public API - -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } - - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); - } - }); - - return this; -} - -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); -} - -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; -}).call(this)}).call(this,require('_process')) - -},{"_process":237}],126:[function(require,module,exports){ -arguments[4][59][0].apply(exports,arguments) -},{"../../../errors":117,"dup":59}],127:[function(require,module,exports){ -arguments[4][60][0].apply(exports,arguments) -},{"dup":60}],128:[function(require,module,exports){ -arguments[4][61][0].apply(exports,arguments) -},{"../../../errors":117,"./end-of-stream":126,"dup":61}],129:[function(require,module,exports){ -arguments[4][62][0].apply(exports,arguments) -},{"../../../errors":117,"dup":62}],130:[function(require,module,exports){ -arguments[4][63][0].apply(exports,arguments) -},{"dup":63,"events":105}],131:[function(require,module,exports){ -arguments[4][64][0].apply(exports,arguments) -},{"./lib/_stream_duplex.js":118,"./lib/_stream_passthrough.js":119,"./lib/_stream_readable.js":120,"./lib/_stream_transform.js":121,"./lib/_stream_writable.js":122,"./lib/internal/streams/end-of-stream.js":126,"./lib/internal/streams/pipeline.js":128,"dup":64}],132:[function(require,module,exports){ -var hash = exports; - -hash.utils = require('./hash/utils'); -hash.common = require('./hash/common'); -hash.sha = require('./hash/sha'); -hash.ripemd = require('./hash/ripemd'); -hash.hmac = require('./hash/hmac'); - -// Proxy hash functions to the main object -hash.sha1 = hash.sha.sha1; -hash.sha256 = hash.sha.sha256; -hash.sha224 = hash.sha.sha224; -hash.sha384 = hash.sha.sha384; -hash.sha512 = hash.sha.sha512; -hash.ripemd160 = hash.ripemd.ripemd160; - -},{"./hash/common":133,"./hash/hmac":134,"./hash/ripemd":135,"./hash/sha":136,"./hash/utils":143}],133:[function(require,module,exports){ -'use strict'; - -var utils = require('./utils'); -var assert = require('minimalistic-assert'); - -function BlockHash() { - this.pending = null; - this.pendingTotal = 0; - this.blockSize = this.constructor.blockSize; - this.outSize = this.constructor.outSize; - this.hmacStrength = this.constructor.hmacStrength; - this.padLength = this.constructor.padLength / 8; - this.endian = 'big'; - - this._delta8 = this.blockSize / 8; - this._delta32 = this.blockSize / 32; -} -exports.BlockHash = BlockHash; - -BlockHash.prototype.update = function update(msg, enc) { - // Convert message to array, pad it, and join into 32bit blocks - msg = utils.toArray(msg, enc); - if (!this.pending) - this.pending = msg; - else - this.pending = this.pending.concat(msg); - this.pendingTotal += msg.length; - - // Enough data, try updating - if (this.pending.length >= this._delta8) { - msg = this.pending; - - // Process pending data in blocks - var r = msg.length % this._delta8; - this.pending = msg.slice(msg.length - r, msg.length); - if (this.pending.length === 0) - this.pending = null; - - msg = utils.join32(msg, 0, msg.length - r, this.endian); - for (var i = 0; i < msg.length; i += this._delta32) - this._update(msg, i, i + this._delta32); - } - - return this; -}; - -BlockHash.prototype.digest = function digest(enc) { - this.update(this._pad()); - assert(this.pending === null); - - return this._digest(enc); -}; - -BlockHash.prototype._pad = function pad() { - var len = this.pendingTotal; - var bytes = this._delta8; - var k = bytes - ((len + this.padLength) % bytes); - var res = new Array(k + this.padLength); - res[0] = 0x80; - for (var i = 1; i < k; i++) - res[i] = 0; - - // Append length - len <<= 3; - if (this.endian === 'big') { - for (var t = 8; t < this.padLength; t++) - res[i++] = 0; - - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = (len >>> 24) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = len & 0xff; - } else { - res[i++] = len & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 24) & 0xff; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - - for (t = 8; t < this.padLength; t++) - res[i++] = 0; - } - - return res; -}; - -},{"./utils":143,"minimalistic-assert":223}],134:[function(require,module,exports){ -'use strict'; - -var utils = require('./utils'); -var assert = require('minimalistic-assert'); - -function Hmac(hash, key, enc) { - if (!(this instanceof Hmac)) - return new Hmac(hash, key, enc); - this.Hash = hash; - this.blockSize = hash.blockSize / 8; - this.outSize = hash.outSize / 8; - this.inner = null; - this.outer = null; - - this._init(utils.toArray(key, enc)); -} -module.exports = Hmac; - -Hmac.prototype._init = function init(key) { - // Shorten key, if needed - if (key.length > this.blockSize) - key = new this.Hash().update(key).digest(); - assert(key.length <= this.blockSize); - - // Add padding to key - for (var i = key.length; i < this.blockSize; i++) - key.push(0); - - for (i = 0; i < key.length; i++) - key[i] ^= 0x36; - this.inner = new this.Hash().update(key); - - // 0x36 ^ 0x5c = 0x6a - for (i = 0; i < key.length; i++) - key[i] ^= 0x6a; - this.outer = new this.Hash().update(key); -}; - -Hmac.prototype.update = function update(msg, enc) { - this.inner.update(msg, enc); - return this; -}; - -Hmac.prototype.digest = function digest(enc) { - this.outer.update(this.inner.digest()); - return this.outer.digest(enc); -}; - -},{"./utils":143,"minimalistic-assert":223}],135:[function(require,module,exports){ -'use strict'; - -var utils = require('./utils'); -var common = require('./common'); - -var rotl32 = utils.rotl32; -var sum32 = utils.sum32; -var sum32_3 = utils.sum32_3; -var sum32_4 = utils.sum32_4; -var BlockHash = common.BlockHash; - -function RIPEMD160() { - if (!(this instanceof RIPEMD160)) - return new RIPEMD160(); - - BlockHash.call(this); - - this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; - this.endian = 'little'; -} -utils.inherits(RIPEMD160, BlockHash); -exports.ripemd160 = RIPEMD160; - -RIPEMD160.blockSize = 512; -RIPEMD160.outSize = 160; -RIPEMD160.hmacStrength = 192; -RIPEMD160.padLength = 64; - -RIPEMD160.prototype._update = function update(msg, start) { - var A = this.h[0]; - var B = this.h[1]; - var C = this.h[2]; - var D = this.h[3]; - var E = this.h[4]; - var Ah = A; - var Bh = B; - var Ch = C; - var Dh = D; - var Eh = E; - for (var j = 0; j < 80; j++) { - var T = sum32( - rotl32( - sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), - s[j]), - E); - A = E; - E = D; - D = rotl32(C, 10); - C = B; - B = T; - T = sum32( - rotl32( - sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), - sh[j]), - Eh); - Ah = Eh; - Eh = Dh; - Dh = rotl32(Ch, 10); - Ch = Bh; - Bh = T; - } - T = sum32_3(this.h[1], C, Dh); - this.h[1] = sum32_3(this.h[2], D, Eh); - this.h[2] = sum32_3(this.h[3], E, Ah); - this.h[3] = sum32_3(this.h[4], A, Bh); - this.h[4] = sum32_3(this.h[0], B, Ch); - this.h[0] = T; -}; - -RIPEMD160.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'little'); - else - return utils.split32(this.h, 'little'); -}; - -function f(j, x, y, z) { - if (j <= 15) - return x ^ y ^ z; - else if (j <= 31) - return (x & y) | ((~x) & z); - else if (j <= 47) - return (x | (~y)) ^ z; - else if (j <= 63) - return (x & z) | (y & (~z)); - else - return x ^ (y | (~z)); -} - -function K(j) { - if (j <= 15) - return 0x00000000; - else if (j <= 31) - return 0x5a827999; - else if (j <= 47) - return 0x6ed9eba1; - else if (j <= 63) - return 0x8f1bbcdc; - else - return 0xa953fd4e; -} - -function Kh(j) { - if (j <= 15) - return 0x50a28be6; - else if (j <= 31) - return 0x5c4dd124; - else if (j <= 47) - return 0x6d703ef3; - else if (j <= 63) - return 0x7a6d76e9; - else - return 0x00000000; -} - -var r = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 -]; - -var rh = [ - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 -]; - -var s = [ - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 -]; - -var sh = [ - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 -]; - -},{"./common":133,"./utils":143}],136:[function(require,module,exports){ -'use strict'; - -exports.sha1 = require('./sha/1'); -exports.sha224 = require('./sha/224'); -exports.sha256 = require('./sha/256'); -exports.sha384 = require('./sha/384'); -exports.sha512 = require('./sha/512'); - -},{"./sha/1":137,"./sha/224":138,"./sha/256":139,"./sha/384":140,"./sha/512":141}],137:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); -var common = require('../common'); -var shaCommon = require('./common'); - -var rotl32 = utils.rotl32; -var sum32 = utils.sum32; -var sum32_5 = utils.sum32_5; -var ft_1 = shaCommon.ft_1; -var BlockHash = common.BlockHash; - -var sha1_K = [ - 0x5A827999, 0x6ED9EBA1, - 0x8F1BBCDC, 0xCA62C1D6 -]; - -function SHA1() { - if (!(this instanceof SHA1)) - return new SHA1(); - - BlockHash.call(this); - this.h = [ - 0x67452301, 0xefcdab89, 0x98badcfe, - 0x10325476, 0xc3d2e1f0 ]; - this.W = new Array(80); -} - -utils.inherits(SHA1, BlockHash); -module.exports = SHA1; - -SHA1.blockSize = 512; -SHA1.outSize = 160; -SHA1.hmacStrength = 80; -SHA1.padLength = 64; - -SHA1.prototype._update = function _update(msg, start) { - var W = this.W; - - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; - - for(; i < W.length; i++) - W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); - - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; - - for (i = 0; i < W.length; i++) { - var s = ~~(i / 20); - var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); - e = d; - d = c; - c = rotl32(b, 30); - b = a; - a = t; - } - - this.h[0] = sum32(this.h[0], a); - this.h[1] = sum32(this.h[1], b); - this.h[2] = sum32(this.h[2], c); - this.h[3] = sum32(this.h[3], d); - this.h[4] = sum32(this.h[4], e); -}; - -SHA1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - -},{"../common":133,"../utils":143,"./common":142}],138:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); -var SHA256 = require('./256'); - -function SHA224() { - if (!(this instanceof SHA224)) - return new SHA224(); - - SHA256.call(this); - this.h = [ - 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, - 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; -} -utils.inherits(SHA224, SHA256); -module.exports = SHA224; - -SHA224.blockSize = 512; -SHA224.outSize = 224; -SHA224.hmacStrength = 192; -SHA224.padLength = 64; - -SHA224.prototype._digest = function digest(enc) { - // Just truncate output - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 7), 'big'); - else - return utils.split32(this.h.slice(0, 7), 'big'); -}; - - -},{"../utils":143,"./256":139}],139:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); -var common = require('../common'); -var shaCommon = require('./common'); -var assert = require('minimalistic-assert'); - -var sum32 = utils.sum32; -var sum32_4 = utils.sum32_4; -var sum32_5 = utils.sum32_5; -var ch32 = shaCommon.ch32; -var maj32 = shaCommon.maj32; -var s0_256 = shaCommon.s0_256; -var s1_256 = shaCommon.s1_256; -var g0_256 = shaCommon.g0_256; -var g1_256 = shaCommon.g1_256; - -var BlockHash = common.BlockHash; - -var sha256_K = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]; - -function SHA256() { - if (!(this instanceof SHA256)) - return new SHA256(); - - BlockHash.call(this); - this.h = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 - ]; - this.k = sha256_K; - this.W = new Array(64); -} -utils.inherits(SHA256, BlockHash); -module.exports = SHA256; - -SHA256.blockSize = 512; -SHA256.outSize = 256; -SHA256.hmacStrength = 192; -SHA256.padLength = 64; - -SHA256.prototype._update = function _update(msg, start) { - var W = this.W; - - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; - for (; i < W.length; i++) - W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); - - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; - var f = this.h[5]; - var g = this.h[6]; - var h = this.h[7]; - - assert(this.k.length === W.length); - for (i = 0; i < W.length; i++) { - var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); - var T2 = sum32(s0_256(a), maj32(a, b, c)); - h = g; - g = f; - f = e; - e = sum32(d, T1); - d = c; - c = b; - b = a; - a = sum32(T1, T2); - } - - this.h[0] = sum32(this.h[0], a); - this.h[1] = sum32(this.h[1], b); - this.h[2] = sum32(this.h[2], c); - this.h[3] = sum32(this.h[3], d); - this.h[4] = sum32(this.h[4], e); - this.h[5] = sum32(this.h[5], f); - this.h[6] = sum32(this.h[6], g); - this.h[7] = sum32(this.h[7], h); -}; - -SHA256.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - -},{"../common":133,"../utils":143,"./common":142,"minimalistic-assert":223}],140:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); - -var SHA512 = require('./512'); - -function SHA384() { - if (!(this instanceof SHA384)) - return new SHA384(); - - SHA512.call(this); - this.h = [ - 0xcbbb9d5d, 0xc1059ed8, - 0x629a292a, 0x367cd507, - 0x9159015a, 0x3070dd17, - 0x152fecd8, 0xf70e5939, - 0x67332667, 0xffc00b31, - 0x8eb44a87, 0x68581511, - 0xdb0c2e0d, 0x64f98fa7, - 0x47b5481d, 0xbefa4fa4 ]; -} -utils.inherits(SHA384, SHA512); -module.exports = SHA384; - -SHA384.blockSize = 1024; -SHA384.outSize = 384; -SHA384.hmacStrength = 192; -SHA384.padLength = 128; - -SHA384.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 12), 'big'); - else - return utils.split32(this.h.slice(0, 12), 'big'); -}; - -},{"../utils":143,"./512":141}],141:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); -var common = require('../common'); -var assert = require('minimalistic-assert'); - -var rotr64_hi = utils.rotr64_hi; -var rotr64_lo = utils.rotr64_lo; -var shr64_hi = utils.shr64_hi; -var shr64_lo = utils.shr64_lo; -var sum64 = utils.sum64; -var sum64_hi = utils.sum64_hi; -var sum64_lo = utils.sum64_lo; -var sum64_4_hi = utils.sum64_4_hi; -var sum64_4_lo = utils.sum64_4_lo; -var sum64_5_hi = utils.sum64_5_hi; -var sum64_5_lo = utils.sum64_5_lo; - -var BlockHash = common.BlockHash; - -var sha512_K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 -]; - -function SHA512() { - if (!(this instanceof SHA512)) - return new SHA512(); - - BlockHash.call(this); - this.h = [ - 0x6a09e667, 0xf3bcc908, - 0xbb67ae85, 0x84caa73b, - 0x3c6ef372, 0xfe94f82b, - 0xa54ff53a, 0x5f1d36f1, - 0x510e527f, 0xade682d1, - 0x9b05688c, 0x2b3e6c1f, - 0x1f83d9ab, 0xfb41bd6b, - 0x5be0cd19, 0x137e2179 ]; - this.k = sha512_K; - this.W = new Array(160); -} -utils.inherits(SHA512, BlockHash); -module.exports = SHA512; - -SHA512.blockSize = 1024; -SHA512.outSize = 512; -SHA512.hmacStrength = 192; -SHA512.padLength = 128; - -SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { - var W = this.W; - - // 32 x 32bit words - for (var i = 0; i < 32; i++) - W[i] = msg[start + i]; - for (; i < W.length; i += 2) { - var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 - var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); - var c1_hi = W[i - 14]; // i - 7 - var c1_lo = W[i - 13]; - var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 - var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); - var c3_hi = W[i - 32]; // i - 16 - var c3_lo = W[i - 31]; - - W[i] = sum64_4_hi( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); - W[i + 1] = sum64_4_lo( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); - } -}; - -SHA512.prototype._update = function _update(msg, start) { - this._prepareBlock(msg, start); - - var W = this.W; - - var ah = this.h[0]; - var al = this.h[1]; - var bh = this.h[2]; - var bl = this.h[3]; - var ch = this.h[4]; - var cl = this.h[5]; - var dh = this.h[6]; - var dl = this.h[7]; - var eh = this.h[8]; - var el = this.h[9]; - var fh = this.h[10]; - var fl = this.h[11]; - var gh = this.h[12]; - var gl = this.h[13]; - var hh = this.h[14]; - var hl = this.h[15]; - - assert(this.k.length === W.length); - for (var i = 0; i < W.length; i += 2) { - var c0_hi = hh; - var c0_lo = hl; - var c1_hi = s1_512_hi(eh, el); - var c1_lo = s1_512_lo(eh, el); - var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl); - var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); - var c3_hi = this.k[i]; - var c3_lo = this.k[i + 1]; - var c4_hi = W[i]; - var c4_lo = W[i + 1]; - - var T1_hi = sum64_5_hi( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo, - c4_hi, c4_lo); - var T1_lo = sum64_5_lo( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo, - c4_hi, c4_lo); - - c0_hi = s0_512_hi(ah, al); - c0_lo = s0_512_lo(ah, al); - c1_hi = maj64_hi(ah, al, bh, bl, ch, cl); - c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); - - var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); - var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); - - hh = gh; - hl = gl; - - gh = fh; - gl = fl; - - fh = eh; - fl = el; - - eh = sum64_hi(dh, dl, T1_hi, T1_lo); - el = sum64_lo(dl, dl, T1_hi, T1_lo); - - dh = ch; - dl = cl; - - ch = bh; - cl = bl; - - bh = ah; - bl = al; - - ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); - al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); - } - - sum64(this.h, 0, ah, al); - sum64(this.h, 2, bh, bl); - sum64(this.h, 4, ch, cl); - sum64(this.h, 6, dh, dl); - sum64(this.h, 8, eh, el); - sum64(this.h, 10, fh, fl); - sum64(this.h, 12, gh, gl); - sum64(this.h, 14, hh, hl); -}; - -SHA512.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - -function ch64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ ((~xh) & zh); - if (r < 0) - r += 0x100000000; - return r; -} - -function ch64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ ((~xl) & zl); - if (r < 0) - r += 0x100000000; - return r; -} - -function maj64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); - if (r < 0) - r += 0x100000000; - return r; -} - -function maj64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); - if (r < 0) - r += 0x100000000; - return r; -} - -function s0_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 28); - var c1_hi = rotr64_hi(xl, xh, 2); // 34 - var c2_hi = rotr64_hi(xl, xh, 7); // 39 - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function s0_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 28); - var c1_lo = rotr64_lo(xl, xh, 2); // 34 - var c2_lo = rotr64_lo(xl, xh, 7); // 39 - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function s1_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 14); - var c1_hi = rotr64_hi(xh, xl, 18); - var c2_hi = rotr64_hi(xl, xh, 9); // 41 - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function s1_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 14); - var c1_lo = rotr64_lo(xh, xl, 18); - var c2_lo = rotr64_lo(xl, xh, 9); // 41 - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function g0_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 1); - var c1_hi = rotr64_hi(xh, xl, 8); - var c2_hi = shr64_hi(xh, xl, 7); - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function g0_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 1); - var c1_lo = rotr64_lo(xh, xl, 8); - var c2_lo = shr64_lo(xh, xl, 7); - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function g1_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 19); - var c1_hi = rotr64_hi(xl, xh, 29); // 61 - var c2_hi = shr64_hi(xh, xl, 6); - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function g1_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 19); - var c1_lo = rotr64_lo(xl, xh, 29); // 61 - var c2_lo = shr64_lo(xh, xl, 6); - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -},{"../common":133,"../utils":143,"minimalistic-assert":223}],142:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); -var rotr32 = utils.rotr32; - -function ft_1(s, x, y, z) { - if (s === 0) - return ch32(x, y, z); - if (s === 1 || s === 3) - return p32(x, y, z); - if (s === 2) - return maj32(x, y, z); -} -exports.ft_1 = ft_1; - -function ch32(x, y, z) { - return (x & y) ^ ((~x) & z); -} -exports.ch32 = ch32; - -function maj32(x, y, z) { - return (x & y) ^ (x & z) ^ (y & z); -} -exports.maj32 = maj32; - -function p32(x, y, z) { - return x ^ y ^ z; -} -exports.p32 = p32; - -function s0_256(x) { - return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); -} -exports.s0_256 = s0_256; - -function s1_256(x) { - return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); -} -exports.s1_256 = s1_256; - -function g0_256(x) { - return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); -} -exports.g0_256 = g0_256; - -function g1_256(x) { - return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); -} -exports.g1_256 = g1_256; - -},{"../utils":143}],143:[function(require,module,exports){ -'use strict'; - -var assert = require('minimalistic-assert'); -var inherits = require('inherits'); - -exports.inherits = inherits; - -function isSurrogatePair(msg, i) { - if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) { - return false; - } - if (i < 0 || i + 1 >= msg.length) { - return false; - } - return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00; -} - -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg === 'string') { - if (!enc) { - // Inspired by stringToUtf8ByteArray() in closure-library by Google - // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143 - // Apache License 2.0 - // https://github.com/google/closure-library/blob/master/LICENSE - var p = 0; - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - if (c < 128) { - res[p++] = c; - } else if (c < 2048) { - res[p++] = (c >> 6) | 192; - res[p++] = (c & 63) | 128; - } else if (isSurrogatePair(msg, i)) { - c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF); - res[p++] = (c >> 18) | 240; - res[p++] = ((c >> 12) & 63) | 128; - res[p++] = ((c >> 6) & 63) | 128; - res[p++] = (c & 63) | 128; - } else { - res[p++] = (c >> 12) | 224; - res[p++] = ((c >> 6) & 63) | 128; - res[p++] = (c & 63) | 128; - } - } - } else if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } - } else { - for (i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; - } - return res; -} -exports.toArray = toArray; - -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; -} -exports.toHex = toHex; - -function htonl(w) { - var res = (w >>> 24) | - ((w >>> 8) & 0xff00) | - ((w << 8) & 0xff0000) | - ((w & 0xff) << 24); - return res >>> 0; -} -exports.htonl = htonl; - -function toHex32(msg, endian) { - var res = ''; - for (var i = 0; i < msg.length; i++) { - var w = msg[i]; - if (endian === 'little') - w = htonl(w); - res += zero8(w.toString(16)); - } - return res; -} -exports.toHex32 = toHex32; - -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; -} -exports.zero2 = zero2; - -function zero8(word) { - if (word.length === 7) - return '0' + word; - else if (word.length === 6) - return '00' + word; - else if (word.length === 5) - return '000' + word; - else if (word.length === 4) - return '0000' + word; - else if (word.length === 3) - return '00000' + word; - else if (word.length === 2) - return '000000' + word; - else if (word.length === 1) - return '0000000' + word; - else - return word; -} -exports.zero8 = zero8; - -function join32(msg, start, end, endian) { - var len = end - start; - assert(len % 4 === 0); - var res = new Array(len / 4); - for (var i = 0, k = start; i < res.length; i++, k += 4) { - var w; - if (endian === 'big') - w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; - else - w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; - res[i] = w >>> 0; - } - return res; -} -exports.join32 = join32; - -function split32(msg, endian) { - var res = new Array(msg.length * 4); - for (var i = 0, k = 0; i < msg.length; i++, k += 4) { - var m = msg[i]; - if (endian === 'big') { - res[k] = m >>> 24; - res[k + 1] = (m >>> 16) & 0xff; - res[k + 2] = (m >>> 8) & 0xff; - res[k + 3] = m & 0xff; - } else { - res[k + 3] = m >>> 24; - res[k + 2] = (m >>> 16) & 0xff; - res[k + 1] = (m >>> 8) & 0xff; - res[k] = m & 0xff; - } - } - return res; -} -exports.split32 = split32; - -function rotr32(w, b) { - return (w >>> b) | (w << (32 - b)); -} -exports.rotr32 = rotr32; - -function rotl32(w, b) { - return (w << b) | (w >>> (32 - b)); -} -exports.rotl32 = rotl32; - -function sum32(a, b) { - return (a + b) >>> 0; -} -exports.sum32 = sum32; - -function sum32_3(a, b, c) { - return (a + b + c) >>> 0; -} -exports.sum32_3 = sum32_3; - -function sum32_4(a, b, c, d) { - return (a + b + c + d) >>> 0; -} -exports.sum32_4 = sum32_4; - -function sum32_5(a, b, c, d, e) { - return (a + b + c + d + e) >>> 0; -} -exports.sum32_5 = sum32_5; - -function sum64(buf, pos, ah, al) { - var bh = buf[pos]; - var bl = buf[pos + 1]; - - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - buf[pos] = hi >>> 0; - buf[pos + 1] = lo; -} -exports.sum64 = sum64; - -function sum64_hi(ah, al, bh, bl) { - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - return hi >>> 0; -} -exports.sum64_hi = sum64_hi; - -function sum64_lo(ah, al, bh, bl) { - var lo = al + bl; - return lo >>> 0; -} -exports.sum64_lo = sum64_lo; - -function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; - - var hi = ah + bh + ch + dh + carry; - return hi >>> 0; -} -exports.sum64_4_hi = sum64_4_hi; - -function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { - var lo = al + bl + cl + dl; - return lo >>> 0; -} -exports.sum64_4_lo = sum64_4_lo; - -function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; - lo = (lo + el) >>> 0; - carry += lo < el ? 1 : 0; - - var hi = ah + bh + ch + dh + eh + carry; - return hi >>> 0; -} -exports.sum64_5_hi = sum64_5_hi; - -function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var lo = al + bl + cl + dl + el; - - return lo >>> 0; -} -exports.sum64_5_lo = sum64_5_lo; - -function rotr64_hi(ah, al, num) { - var r = (al << (32 - num)) | (ah >>> num); - return r >>> 0; -} -exports.rotr64_hi = rotr64_hi; - -function rotr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; -} -exports.rotr64_lo = rotr64_lo; - -function shr64_hi(ah, al, num) { - return ah >>> num; -} -exports.shr64_hi = shr64_hi; - -function shr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; -} -exports.shr64_lo = shr64_lo; - -},{"inherits":146,"minimalistic-assert":223}],144:[function(require,module,exports){ -'use strict'; - -var hash = require('hash.js'); -var utils = require('minimalistic-crypto-utils'); -var assert = require('minimalistic-assert'); - -function HmacDRBG(options) { - if (!(this instanceof HmacDRBG)) - return new HmacDRBG(options); - this.hash = options.hash; - this.predResist = !!options.predResist; - - this.outLen = this.hash.outSize; - this.minEntropy = options.minEntropy || this.hash.hmacStrength; - - this._reseed = null; - this.reseedInterval = null; - this.K = null; - this.V = null; - - var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex'); - var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex'); - var pers = utils.toArray(options.pers, options.persEnc || 'hex'); - assert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - this._init(entropy, nonce, pers); -} -module.exports = HmacDRBG; - -HmacDRBG.prototype._init = function init(entropy, nonce, pers) { - var seed = entropy.concat(nonce).concat(pers); - - this.K = new Array(this.outLen / 8); - this.V = new Array(this.outLen / 8); - for (var i = 0; i < this.V.length; i++) { - this.K[i] = 0x00; - this.V[i] = 0x01; - } - - this._update(seed); - this._reseed = 1; - this.reseedInterval = 0x1000000000000; // 2^48 -}; - -HmacDRBG.prototype._hmac = function hmac() { - return new hash.hmac(this.hash, this.K); -}; - -HmacDRBG.prototype._update = function update(seed) { - var kmac = this._hmac() - .update(this.V) - .update([ 0x00 ]); - if (seed) - kmac = kmac.update(seed); - this.K = kmac.digest(); - this.V = this._hmac().update(this.V).digest(); - if (!seed) - return; - - this.K = this._hmac() - .update(this.V) - .update([ 0x01 ]) - .update(seed) - .digest(); - this.V = this._hmac().update(this.V).digest(); -}; - -HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { - // Optional entropy enc - if (typeof entropyEnc !== 'string') { - addEnc = add; - add = entropyEnc; - entropyEnc = null; - } - - entropy = utils.toArray(entropy, entropyEnc); - add = utils.toArray(add, addEnc); - - assert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - - this._update(entropy.concat(add || [])); - this._reseed = 1; -}; - -HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { - if (this._reseed > this.reseedInterval) - throw new Error('Reseed is required'); - - // Optional encoding - if (typeof enc !== 'string') { - addEnc = add; - add = enc; - enc = null; - } - - // Optional additional data - if (add) { - add = utils.toArray(add, addEnc || 'hex'); - this._update(add); - } - - var temp = []; - while (temp.length < len) { - this.V = this._hmac().update(this.V).digest(); - temp = temp.concat(this.V); - } - - var res = temp.slice(0, len); - this._update(add); - this._reseed++; - return utils.encode(res, enc); -}; - -},{"hash.js":132,"minimalistic-assert":223,"minimalistic-crypto-utils":224}],145:[function(require,module,exports){ -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - -},{}],146:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} - -},{}],147:[function(require,module,exports){ -'use strict'; - -var hasToStringTag = require('has-tostringtag/shams')(); -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); - -var isStandardArguments = function isArguments(value) { - if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) { - return false; - } - return $toString(value) === '[object Arguments]'; -}; - -var isLegacyArguments = function isArguments(value) { - if (isStandardArguments(value)) { - return true; - } - return value !== null && - typeof value === 'object' && - typeof value.length === 'number' && - value.length >= 0 && - $toString(value) !== '[object Array]' && - $toString(value.callee) === '[object Function]'; -}; - -var supportsStandardArguments = (function () { - return isStandardArguments(arguments); -}()); - -isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests - -module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; - -},{"call-bind/callBound":69,"has-tostringtag/shams":114}],148:[function(require,module,exports){ -'use strict'; - -var fnToStr = Function.prototype.toString; -var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply; -var badArrayLike; -var isCallableMarker; -if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') { - try { - badArrayLike = Object.defineProperty({}, 'length', { - get: function () { - throw isCallableMarker; - } - }); - isCallableMarker = {}; - // eslint-disable-next-line no-throw-literal - reflectApply(function () { throw 42; }, null, badArrayLike); - } catch (_) { - if (_ !== isCallableMarker) { - reflectApply = null; - } - } -} else { - reflectApply = null; -} - -var constructorRegex = /^\s*class\b/; -var isES6ClassFn = function isES6ClassFunction(value) { - try { - var fnStr = fnToStr.call(value); - return constructorRegex.test(fnStr); - } catch (e) { - return false; // not a function - } -}; - -var tryFunctionObject = function tryFunctionToStr(value) { - try { - if (isES6ClassFn(value)) { return false; } - fnToStr.call(value); - return true; - } catch (e) { - return false; - } -}; -var toStr = Object.prototype.toString; -var objectClass = '[object Object]'; -var fnClass = '[object Function]'; -var genClass = '[object GeneratorFunction]'; -var ddaClass = '[object HTMLAllCollection]'; // IE 11 -var ddaClass2 = '[object HTML document.all class]'; -var ddaClass3 = '[object HTMLCollection]'; // IE 9-10 -var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag` - -var isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing - -var isDDA = function isDocumentDotAll() { return false; }; -if (typeof document === 'object') { - // Firefox 3 canonicalizes DDA to undefined when it's not accessed directly - var all = document.all; - if (toStr.call(all) === toStr.call(document.all)) { - isDDA = function isDocumentDotAll(value) { - /* globals document: false */ - // in IE 6-8, typeof document.all is "object" and it's truthy - if ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) { - try { - var str = toStr.call(value); - return ( - str === ddaClass - || str === ddaClass2 - || str === ddaClass3 // opera 12.16 - || str === objectClass // IE 6-8 - ) && value('') == null; // eslint-disable-line eqeqeq - } catch (e) { /**/ } - } - return false; - }; - } -} - -module.exports = reflectApply - ? function isCallable(value) { - if (isDDA(value)) { return true; } - if (!value) { return false; } - if (typeof value !== 'function' && typeof value !== 'object') { return false; } - try { - reflectApply(value, null, badArrayLike); - } catch (e) { - if (e !== isCallableMarker) { return false; } - } - return !isES6ClassFn(value) && tryFunctionObject(value); - } - : function isCallable(value) { - if (isDDA(value)) { return true; } - if (!value) { return false; } - if (typeof value !== 'function' && typeof value !== 'object') { return false; } - if (hasToStringTag) { return tryFunctionObject(value); } - if (isES6ClassFn(value)) { return false; } - var strClass = toStr.call(value); - if (strClass !== fnClass && strClass !== genClass && !(/^\[object HTML/).test(strClass)) { return false; } - return tryFunctionObject(value); - }; - -},{}],149:[function(require,module,exports){ -'use strict'; - -var toStr = Object.prototype.toString; -var fnToStr = Function.prototype.toString; -var isFnRegex = /^\s*(?:function)?\*/; -var hasToStringTag = require('has-tostringtag/shams')(); -var getProto = Object.getPrototypeOf; -var getGeneratorFunc = function () { // eslint-disable-line consistent-return - if (!hasToStringTag) { - return false; - } - try { - return Function('return function*() {}')(); - } catch (e) { - } -}; -var GeneratorFunction; - -module.exports = function isGeneratorFunction(fn) { - if (typeof fn !== 'function') { - return false; - } - if (isFnRegex.test(fnToStr.call(fn))) { - return true; - } - if (!hasToStringTag) { - var str = toStr.call(fn); - return str === '[object GeneratorFunction]'; - } - if (!getProto) { - return false; - } - if (typeof GeneratorFunction === 'undefined') { - var generatorFunc = getGeneratorFunc(); - GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false; - } - return getProto(fn) === GeneratorFunction; -}; - -},{"has-tostringtag/shams":114}],150:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var forEach = require('for-each'); -var availableTypedArrays = require('available-typed-arrays'); -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); -var hasToStringTag = require('has-tostringtag/shams')(); -var gOPD = require('gopd'); - -var g = typeof globalThis === 'undefined' ? global : globalThis; -var typedArrays = availableTypedArrays(); - -var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { - for (var i = 0; i < array.length; i += 1) { - if (array[i] === value) { - return i; - } - } - return -1; -}; -var $slice = callBound('String.prototype.slice'); -var toStrTags = {}; -var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); -if (hasToStringTag && gOPD && getPrototypeOf) { - forEach(typedArrays, function (typedArray) { - var arr = new g[typedArray](); - if (Symbol.toStringTag in arr) { - var proto = getPrototypeOf(arr); - var descriptor = gOPD(proto, Symbol.toStringTag); - if (!descriptor) { - var superProto = getPrototypeOf(proto); - descriptor = gOPD(superProto, Symbol.toStringTag); - } - toStrTags[typedArray] = descriptor.get; - } - }); -} - -var tryTypedArrays = function tryAllTypedArrays(value) { - var anyTrue = false; - forEach(toStrTags, function (getter, typedArray) { - if (!anyTrue) { - try { - anyTrue = getter.call(value) === typedArray; - } catch (e) { /**/ } - } - }); - return anyTrue; -}; - -module.exports = function isTypedArray(value) { - if (!value || typeof value !== 'object') { return false; } - if (!hasToStringTag || !(Symbol.toStringTag in value)) { - var tag = $slice($toString(value), 8, -1); - return $indexOf(typedArrays, tag) > -1; - } - if (!gOPD) { return false; } - return tryTypedArrays(value); -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"available-typed-arrays":16,"call-bind/callBound":69,"for-each":107,"gopd":111,"has-tostringtag/shams":114}],151:[function(require,module,exports){ -/* -* loglevel - https://github.com/pimterry/loglevel -* -* Copyright (c) 2013 Tim Perry -* Licensed under the MIT license. -*/ -(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(); - } -}(this, function () { - "use strict"; - - // Slightly dubious tricks to cut down minimized file size - 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" - ]; - - // Cross-browser bind equivalent that works at least back to IE6 - 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) { - // Missing bind shim or IE8 + Modernizr, fallback to wrapping - return function() { - return Function.prototype.apply.apply(method, [obj, arguments]); - }; - } - } - } - - // Trace() doesn't print the message in IE, so for that case we need to wrap it - function traceForIE() { - if (console.log) { - if (console.log.apply) { - console.log.apply(console, arguments); - } else { - // In old IE, native console methods themselves don't have apply(). - Function.prototype.apply.apply(console.log, [console, arguments]); - } - } - if (console.trace) console.trace(); - } - - // Build the best logging method possible for this env - // Wherever possible we want to bind, not wrap, to preserve stack traces - function realMethod(methodName) { - if (methodName === 'debug') { - methodName = 'log'; - } - - if (typeof console === undefinedType) { - return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives - } else if (methodName === 'trace' && isIE) { - return traceForIE; - } else if (console[methodName] !== undefined) { - return bindMethod(console, methodName); - } else if (console.log !== undefined) { - return bindMethod(console, 'log'); - } else { - return noop; - } - } - - // These private functions always need `this` to be set properly - - function replaceLoggingMethods(level, loggerName) { - /*jshint validthis:true */ - for (var i = 0; i < logMethods.length; i++) { - var methodName = logMethods[i]; - this[methodName] = (i < level) ? - noop : - this.methodFactory(methodName, level, loggerName); - } - - // Define log.log as an alias for log.debug - this.log = this.debug; - } - - // In old IE versions, the console isn't present until you first open it. - // We build realMethod() replacements here that regenerate logging methods - function enableLoggingWhenConsoleArrives(methodName, level, loggerName) { - return function () { - if (typeof console !== undefinedType) { - replaceLoggingMethods.call(this, level, loggerName); - this[methodName].apply(this, arguments); - } - }; - } - - // By default, we use closely bound real methods wherever possible, and - // otherwise we wait for a console to appear, and then try again. - function defaultMethodFactory(methodName, level, loggerName) { - /*jshint validthis:true */ - return realMethod(methodName) || - enableLoggingWhenConsoleArrives.apply(this, arguments); - } - - function Logger(name, defaultLevel, factory) { - var self = this; - var currentLevel; - defaultLevel = defaultLevel == null ? "WARN" : defaultLevel; - - var storageKey = "loglevel"; - if (typeof name === "string") { - storageKey += ":" + name; - } else if (typeof name === "symbol") { - storageKey = undefined; - } - - function persistLevelIfPossible(levelNum) { - var levelName = (logMethods[levelNum] || 'silent').toUpperCase(); - - if (typeof window === undefinedType || !storageKey) return; - - // Use localStorage if available - try { - window.localStorage[storageKey] = levelName; - return; - } catch (ignore) {} - - // Use session cookie as fallback - 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) {} - - // Fallback to cookies if local storage gives us nothing - if (typeof storedLevel === undefinedType) { - try { - var cookie = window.document.cookie; - var location = cookie.indexOf( - encodeURIComponent(storageKey) + "="); - if (location !== -1) { - storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1]; - } - } catch (ignore) {} - } - - // If the stored level is not valid, treat it as if nothing was stored. - if (self.levels[storedLevel] === undefined) { - storedLevel = undefined; - } - - return storedLevel; - } - - function clearPersistedLevel() { - if (typeof window === undefinedType || !storageKey) return; - - // Use localStorage if available - try { - window.localStorage.removeItem(storageKey); - return; - } catch (ignore) {} - - // Use session cookie as fallback - try { - window.document.cookie = - encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC"; - } catch (ignore) {} - } - - /* - * - * Public logger API - see https://github.com/pimterry/loglevel for details - * - */ - - self.name = name; - - self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3, - "ERROR": 4, "SILENT": 5}; - - self.methodFactory = factory || defaultMethodFactory; - - self.getLevel = function () { - return currentLevel; - }; - - self.setLevel = function (level, persist) { - if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) { - level = self.levels[level.toUpperCase()]; - } - if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) { - currentLevel = level; - if (persist !== false) { // defaults to true - persistLevelIfPossible(level); - } - replaceLoggingMethods.call(self, level, name); - if (typeof console === undefinedType && level < self.levels.SILENT) { - return "No console available for logging"; - } - } else { - throw "log.setLevel() called with invalid level: " + level; - } - }; - - self.setDefaultLevel = function (level) { - defaultLevel = level; - if (!getPersistedLevel()) { - self.setLevel(level, false); - } - }; - - self.resetLevel = function () { - self.setLevel(defaultLevel, false); - clearPersistedLevel(); - }; - - self.enableAll = function(persist) { - self.setLevel(self.levels.TRACE, persist); - }; - - self.disableAll = function(persist) { - self.setLevel(self.levels.SILENT, persist); - }; - - // Initialize with the right level - var initialLevel = getPersistedLevel(); - if (initialLevel == null) { - initialLevel = defaultLevel; - } - self.setLevel(initialLevel, false); - } - - /* - * - * Top-level API - * - */ - - var defaultLogger = new Logger(); - - var _loggersByName = {}; - 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.getLevel(), defaultLogger.methodFactory); - } - return logger; - }; - - // Grab the current global log variable in case of overwrite - var _log = (typeof window !== undefinedType) ? window.log : undefined; - defaultLogger.noConflict = function() { - if (typeof window !== undefinedType && - window.log === defaultLogger) { - window.log = _log; - } - - return defaultLogger; - }; - - defaultLogger.getLoggers = function getLoggers() { - return _loggersByName; - }; - - // ES6 default export, for compatibility - defaultLogger['default'] = defaultLogger; - - return defaultLogger; -})); - -},{}],152:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.ExtensibleEvents = void 0; - -var _NamespacedMap = require("./NamespacedMap"); - -var _InvalidEventError = require("./InvalidEventError"); - -var _MRoomMessage = require("./interpreters/legacy/MRoomMessage"); - -var _MMessage = require("./interpreters/modern/MMessage"); - -var _message_types = require("./events/message_types"); - -var _poll_types = require("./events/poll_types"); - -var _MPoll = require("./interpreters/modern/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: 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([// Remember to add your unit test when adding to this! ("known events" test description) - [_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: - /** - * Gets the order the internal processor will use for unknown primary - * event types. - */ - function get() { - var _this$_unknownInterpr; - - return (_this$_unknownInterpr = this._unknownInterpretOrder) !== null && _this$_unknownInterpr !== void 0 ? _this$_unknownInterpr : []; - } - /** - * Sets the order the internal processor will use for unknown primary - * event types. - * @param {NamespacedValue[]} val The parsing order. - */ - , - set: function set(val) { - this._unknownInterpretOrder = val; - } - /** - * Gets the order the internal processor will use for unknown primary - * event types. - */ - - }, { - key: "registerInterpreter", - value: - /** - * Registers a primary event type interpreter. Note that the interpreter might be - * called with non-primary events if the event is being parsed as a fallback. - * @param {NamespacedValue} wireEventType The event type. - * @param {EventInterpreter} interpreter The interpreter. - */ - function registerInterpreter(wireEventType, interpreter) { - this.interpreters.set(wireEventType, interpreter); - } - /** - * Registers a primary event type interpreter. Note that the interpreter might be - * called with non-primary events if the event is being parsed as a fallback. - * @param {NamespacedValue} wireEventType The event type. - * @param {EventInterpreter} interpreter The interpreter. - */ - - }, { - key: "parse", - value: - /** - * Parses an event, trying the primary event type first. If the primary type is not known - * then the content will be inspected to find the most suitable fallback. - * - * If the parsing failed or was a completely unknown type, this will return falsy. - * @param {IPartialEvent} wireFormat The event to parse. - * @returns {Optional} The parsed extensible event. - */ - 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; // cannot be parsed - } catch (e) { - if (e instanceof _InvalidEventError.InvalidEventError) { - return null; // fail parsing and move on - } - - throw e; // re-throw everything else - } - } - /** - * Parses an event, trying the primary event type first. If the primary type is not known - * then the content will be inspected to find the most suitable fallback. - * - * If the parsing failed or was a completely unknown type, this will return falsy. - * @param {IPartialEvent} wireFormat The event to parse. - * @returns {Optional} The parsed extensible event. - */ - - }], [{ - key: "defaultInstance", - get: function get() { - return ExtensibleEvents._defaultInstance; - } - }, { - key: "unknownInterpretOrder", - get: function get() { - return ExtensibleEvents.defaultInstance.unknownInterpretOrder; - } - /** - * Sets the order the internal processor will use for unknown primary - * event types. - * @param {NamespacedValue[]} val The parsing order. - */ - , - 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()); -},{"./InvalidEventError":154,"./NamespacedMap":155,"./events/message_types":164,"./events/poll_types":165,"./interpreters/legacy/MRoomMessage":168,"./interpreters/modern/MMessage":169,"./interpreters/modern/MPoll":170}],153:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -},{}],154:[function(require,module,exports){ -"use strict"; - -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" ? new Map() : undefined; _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 Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); 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); } - -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -/** - * Thrown when an event is unforgivably unparsable. - */ -var 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)); - -exports.InvalidEventError = InvalidEventError; -},{}],155:[function(require,module,exports){ -"use strict"; - -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: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -/** - * A `Map` implementation which accepts a NamespacedValue as a key, and arbitrary value. The - * namespaced value must be a string type. - */ -var NamespacedMap = /*#__PURE__*/function () { - // protected to make tests happy for access - - /** - * 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", 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} 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; - } - /** - * Sets a value in the map. - * @param {NS} key The key. - * @param {V} val The value. - */ - - }, { - 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); - } - } - /** - * Determines if any of the valid namespaced values are present - * in the map. - * @param {NS} key The key. - * @returns {boolean} True if present. - */ - - }, { - key: "has", - value: function has(key) { - return !!this.get(key); - } - /** - * Removes all the namespaced values from the map. - * @param {NS} key The key. - */ - - }, { - key: "delete", - value: function _delete(key) { - if (key.name) { - this.internalMap["delete"](key.name); - } - - if (key.altName) { - this.internalMap["delete"](key.altName); - } - } - /** - * Determines if the map contains a specific namespaced value - * instead of the parent NS type. - * @param {string} key The key. - * @returns {boolean} True if present. - */ - - }, { - key: "hasNamespaced", - value: function hasNamespaced(key) { - return this.internalMap.has(key); - } - /** - * Gets a specific namespaced value from the map instead of the - * parent NS type. Returns falsy if not found. - * @param {string} key The key. - * @returns {Optional} The value, or falsy. - */ - - }, { - key: "getNamespaced", - value: function getNamespaced(key) { - return this.internalMap.get(key); - } - }]); - - return NamespacedMap; -}(); - -exports.NamespacedMap = NamespacedMap; -},{}],156:[function(require,module,exports){ -"use strict"; - -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; } - -/* -Copyright 2021 - 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -/** - * 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 () { - // Stable is optional, but one of the two parameters is required, hence the weird-looking types. - // Goal is to have developers explicitly say there is no stable value (if applicable). - 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; - } // this desperately wants https://github.com/microsoft/TypeScript/pull/26349 at the top level of the class - // so we can instantiate `NamespacedValue` as a default type for that namespace. - - }, { - 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; - -var UnstableValue = /*#__PURE__*/function (_NamespacedValue) { - _inherits(UnstableValue, _NamespacedValue); - - var _super = _createSuper(UnstableValue); - - // Note: Constructor difference is that `unstable` is *required*. - 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); - -exports.UnstableValue = UnstableValue; -},{}],157:[function(require,module,exports){ -"use strict"; - -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("../utility/events"); - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: 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); } - -// Emote events are just decorated message events - -/** - * Represents an emote. This is essentially a MessageEvent with - * emote characteristics considered. - */ -var 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; // override - } - }, { - 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; - } - /** - * Creates a new EmoteEvent from text and HTML. - * @param {string} text The text. - * @param {string} html Optional HTML. - * @returns {MessageEvent} The representative message event. - */ - - }], [{ - 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); - -exports.EmoteEvent = EmoteEvent; -},{"../utility/events":173,"./MessageEvent":159,"./message_types":164}],158:[function(require,module,exports){ -"use strict"; - -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; } - -/* -Copyright 2021 - 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -/** - * Represents an Extensible Event in Matrix. - */ -var 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; - } - /** - * Serializes the event into a format which can be used to send the - * event to the room. - * @returns {IPartialEvent} The serialized event. - */ - - }]); - - return ExtensibleEvent; -}(); - -exports.ExtensibleEvent = ExtensibleEvent; -},{}],159:[function(require,module,exports){ -"use strict"; - -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("../utility/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: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -/** - * Represents a message event. Message events are the simplest form of event with - * just text (optionally of different mimetypes, like HTML). - * - * Message events can additionally be an Emote or Notice, though typically those - * are represented as EmoteEvent and NoticeEvent respectively. - */ -var 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} 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)); - } - /** - * Gets whether this message is considered a "notice". 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. - */ - - }, { - 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); // Use the shorthand if it's just a simple text event - - - if (this.renderings.length === 1) { - var mime = this.renderings[0].mimetype; - - if (mime === undefined || 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" : undefined, - formatted_body: (_this$html = this.html) !== null && _this$html !== void 0 ? _this$html : undefined - }) - }; - } - /** - * Creates a new MessageEvent from text and HTML. - * @param {string} text The text. - * @param {string} html Optional HTML. - * @returns {MessageEvent} The representative message event. - */ - - }], [{ - 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); - -exports.MessageEvent = MessageEvent; -},{"../InvalidEventError":154,"../types":171,"../utility/events":173,"./ExtensibleEvent":158,"./message_types":164}],160:[function(require,module,exports){ -"use strict"; - -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("../utility/events"); - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: 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); } - -// Notice events are just decorated message events - -/** - * Represents a notice. This is essentially a MessageEvent with - * notice characteristics considered. - */ -var 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; // override - } - }, { - 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; - } - /** - * Creates a new NoticeEvent from text and HTML. - * @param {string} text The text. - * @param {string} html Optional HTML. - * @returns {MessageEvent} The representative message event. - */ - - }], [{ - 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); - -exports.NoticeEvent = NoticeEvent; -},{"../utility/events":173,"./MessageEvent":159,"./message_types":164}],161:[function(require,module,exports){ -"use strict"; - -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("../utility/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: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -/** - * Represents a poll end/closure event. - */ -var 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} 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) - }; - } - /** - * Creates a new PollEndEvent from a poll event ID. - * @param {string} pollEventId The poll start event ID. - * @param {string} message A closing message, typically revealing the top answer. - * @returns {PollStartEvent} The representative poll closure event. - */ - - }], [{ - 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); - -exports.PollEndEvent = PollEndEvent; -},{"../InvalidEventError":154,"../utility/events":173,"./ExtensibleEvent":158,"./MessageEvent":159,"./message_types":164,"./poll_types":165,"./relationship_types":166}],162:[function(require,module,exports){ -"use strict"; - -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("../utility/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: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -/** - * Represents a poll response event. - */ -var 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} 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: - /** - * The provided answers for the poll. Note that this may be falsy/unpredictable if - * the `spoiled` property is true. - */ - function get() { - return this.internalAnswerIds; - } - /** - * The poll start event ID referenced by the response. - */ - - }, { - key: "spoiled", - get: - /** - * Whether the vote is spoiled. - */ - 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 ? undefined : this.answerIds - }) - }; - } - /** - * Creates a new PollResponseEvent from a set of answers. To spoil the vote, pass an empty - * answers array. - * @param {string} answers The user's answers. Should be valid from a poll's answer IDs. - * @param {string} pollEventId The poll start event ID. - * @returns {PollStartEvent} The representative poll response event. - */ - - }], [{ - 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: answers - }) - }); - } - }]); - - return PollResponseEvent; -}(_ExtensibleEvent2.ExtensibleEvent); - -exports.PollResponseEvent = PollResponseEvent; -},{"../InvalidEventError":154,"../utility/events":173,"./ExtensibleEvent":158,"./poll_types":165,"./relationship_types":166}],163:[function(require,module,exports){ -"use strict"; - -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("../utility/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: 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()) - }; - } - /** - * Creates a new PollAnswerSubevent from ID and text. - * @param {string} id The answer ID (unique within the poll). - * @param {string} text The text. - * @returns {PollAnswerSubevent} The representative answer. - */ - - }], [{ - key: "from", - value: function from(id, text) { - return new PollAnswerSubevent({ - type: "org.matrix.sdk.poll.answer", - content: _defineProperty({ - id: id - }, _message_types.M_TEXT.name, text) - }); - } - }]); - - return PollAnswerSubevent; -}(_MessageEvent2.MessageEvent); -/** - * Represents a poll start event. - */ - - -exports.PollAnswerSubevent = PollAnswerSubevent; - -var 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} 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; // default & assumed value - } - - _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) - }; - } - /** - * Creates a new PollStartEvent from question, answers, and metadata. - * @param {string} question The question to ask. - * @param {string} answers The answers. Should be unique within each other. - * @param {KNOWN_POLL_KIND|string} kind The kind of poll. - * @param {number} maxSelections The maximum number of selections. Must be 1 or higher. - * @returns {PollStartEvent} The representative poll start event. - */ - - }], [{ - key: "from", - value: function from(question, answers, kind) { - var _content3; - - var maxSelections = arguments.length > 3 && arguments[3] !== undefined ? 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); - -exports.PollStartEvent = PollStartEvent; -var LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - -function makeId() { - return _toConsumableArray(Array(16)).map(function () { - return LETTERS.charAt(Math.floor(Math.random() * LETTERS.length)); - }).join(''); -} -},{"../InvalidEventError":154,"../NamespacedValue":156,"../utility/events":173,"./ExtensibleEvent":158,"./MessageEvent":159,"./message_types":164,"./poll_types":165}],164:[function(require,module,exports){ -"use strict"; - -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"); - -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -/** - * The namespaced value for m.message - */ -var M_MESSAGE = new _NamespacedValue.UnstableValue("m.message", "org.matrix.msc1767.message"); -/** - * An m.message event rendering - */ - -exports.M_MESSAGE = M_MESSAGE; - -/** - * The namespaced value for m.text - */ -var M_TEXT = new _NamespacedValue.UnstableValue("m.text", "org.matrix.msc1767.text"); -/** - * The content for an m.text event - */ - -exports.M_TEXT = M_TEXT; - -/** - * The namespaced value for m.html - */ -var M_HTML = new _NamespacedValue.UnstableValue("m.html", "org.matrix.msc1767.html"); -/** - * The content for an m.html event - */ - -exports.M_HTML = M_HTML; - -/** - * The namespaced value for m.emote - */ -var M_EMOTE = new _NamespacedValue.UnstableValue("m.emote", "org.matrix.msc1767.emote"); -/** - * The event definition for an m.emote event (in content) - */ - -exports.M_EMOTE = M_EMOTE; - -/** - * The namespaced value for m.notice - */ -var M_NOTICE = new _NamespacedValue.UnstableValue("m.notice", "org.matrix.msc1767.notice"); -/** - * The event definition for an m.notice event (in content) - */ - -exports.M_NOTICE = M_NOTICE; -},{"../NamespacedValue":156}],165:[function(require,module,exports){ -"use strict"; - -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"); - -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -/** - * Identifier for a disclosed poll. - */ -var M_POLL_KIND_DISCLOSED = new _NamespacedValue.UnstableValue("m.poll.disclosed", "org.matrix.msc3381.poll.disclosed"); -/** - * Identifier for an undisclosed poll. - */ - -exports.M_POLL_KIND_DISCLOSED = M_POLL_KIND_DISCLOSED; -var M_POLL_KIND_UNDISCLOSED = new _NamespacedValue.UnstableValue("m.poll.undisclosed", "org.matrix.msc3381.poll.undisclosed"); -/** - * Any poll kind. - */ - -exports.M_POLL_KIND_UNDISCLOSED = M_POLL_KIND_UNDISCLOSED; - -/** - * The namespaced value for m.poll.start - */ -var M_POLL_START = new _NamespacedValue.UnstableValue("m.poll.start", "org.matrix.msc3381.poll.start"); -/** - * The m.poll.start type within event content - */ - -exports.M_POLL_START = M_POLL_START; - -/** - * The namespaced value for m.poll.response - */ -var M_POLL_RESPONSE = new _NamespacedValue.UnstableValue("m.poll.response", "org.matrix.msc3381.poll.response"); -/** - * The m.poll.response type within event content - */ - -exports.M_POLL_RESPONSE = M_POLL_RESPONSE; - -/** - * The namespaced value for m.poll.end - */ -var M_POLL_END = new _NamespacedValue.UnstableValue("m.poll.end", "org.matrix.msc3381.poll.end"); -/** - * The event definition for an m.poll.end event (in content) - */ - -exports.M_POLL_END = M_POLL_END; -},{"../NamespacedValue":156}],166:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.REFERENCE_RELATION = void 0; - -var _NamespacedValue = require("../NamespacedValue"); - -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -/** - * The namespaced value for an m.reference relation - */ -var REFERENCE_RELATION = new _NamespacedValue.NamespacedValue("m.reference"); -/** - * Represents any relation type - */ - -exports.REFERENCE_RELATION = REFERENCE_RELATION; -},{"../NamespacedValue":156}],167:[function(require,module,exports){ -"use strict"; - -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("./utility/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("./utility/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("./interpreters/legacy/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("./interpreters/modern/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("./interpreters/modern/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("./events/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("./events/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("./events/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("./events/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("./events/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("./events/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("./events/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("./events/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("./events/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("./events/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]; - } - }); -}); -},{"./ExtensibleEvents":152,"./IPartialEvent":153,"./InvalidEventError":154,"./NamespacedMap":155,"./NamespacedValue":156,"./events/EmoteEvent":157,"./events/ExtensibleEvent":158,"./events/MessageEvent":159,"./events/NoticeEvent":160,"./events/PollEndEvent":161,"./events/PollResponseEvent":162,"./events/PollStartEvent":163,"./events/message_types":164,"./events/poll_types":165,"./events/relationship_types":166,"./interpreters/legacy/MRoomMessage":168,"./interpreters/modern/MMessage":169,"./interpreters/modern/MPoll":170,"./types":171,"./utility/MessageMatchers":172,"./utility/events":173}],168:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.LEGACY_M_ROOM_MESSAGE = void 0; -exports.parseMRoomMessage = parseMRoomMessage; - -var _MessageEvent = require("../../events/MessageEvent"); - -var _NoticeEvent = require("../../events/NoticeEvent"); - -var _EmoteEvent = require("../../events/EmoteEvent"); - -var _NamespacedValue = require("../../NamespacedValue"); - -var _message_types = require("../../events/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: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var LEGACY_M_ROOM_MESSAGE = new _NamespacedValue.NamespacedValue("m.room.message"); -exports.LEGACY_M_ROOM_MESSAGE = LEGACY_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)) { - // We know enough about the event to coerce it into the right type - 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 { - // TODO: Handle other types - return null; - } -} -},{"../../NamespacedValue":156,"../../events/EmoteEvent":157,"../../events/MessageEvent":159,"../../events/NoticeEvent":160,"../../events/message_types":164}],169:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.parseMMessage = parseMMessage; - -var _MessageEvent = require("../../events/MessageEvent"); - -var _message_types = require("../../events/message_types"); - -var _EmoteEvent = require("../../events/EmoteEvent"); - -var _NoticeEvent = require("../../events/NoticeEvent"); - -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -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); - } // default: return a generic message - - - return new _MessageEvent.MessageEvent(wireEvent); -} -},{"../../events/EmoteEvent":157,"../../events/MessageEvent":159,"../../events/NoticeEvent":160,"../../events/message_types":164}],170:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.parseMPoll = parseMPoll; - -var _poll_types = require("../../events/poll_types"); - -var _PollStartEvent = require("../../events/PollStartEvent"); - -var _PollResponseEvent = require("../../events/PollResponseEvent"); - -var _PollEndEvent = require("../../events/PollEndEvent"); - -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -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; // not a poll event -} -},{"../../events/PollEndEvent":161,"../../events/PollResponseEvent":162,"../../events/PollStartEvent":163,"../../events/poll_types":165}],171:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isOptionalAString = isOptionalAString; -exports.isProvided = isProvided; - -/* -Copyright 2021 - 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -/** - * Represents an optional type: can either be T or a falsy value. - */ - -/** - * Determines if the given optional string is a defined string. - * @param {Optional} 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} s The optional to test. - * @returns {boolean} True if the value is defined. - */ - - -function isProvided(s) { - return s !== null && s !== undefined; -} -/** - * Represents either just T1, just T2, or T1 and T2 mixed. - */ -},{}],172:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.LegacyMsgType = void 0; -exports.isEventLike = isEventLike; - -var _message_types = require("../events/message_types"); - -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -/** - * 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>} 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; -} -},{"../events/message_types":164}],173:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isEventTypeSame = isEventTypeSame; - -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -/** - * 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); - } - } -} -},{}],174:[function(require,module,exports){ -"use strict"; - -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.ClientWidgetApi = void 0; - -var _events = require("events"); - -var _PostmessageTransport = require("./transport/PostmessageTransport"); - -var _WidgetApiDirection = require("./interfaces/WidgetApiDirection"); - -var _WidgetApiAction = require("./interfaces/WidgetApiAction"); - -var _Capabilities = require("./interfaces/Capabilities"); - -var _ApiVersion = require("./interfaces/ApiVersion"); - -var _WidgetEventCapability = require("./models/WidgetEventCapability"); - -var _GetOpenIDAction = require("./interfaces/GetOpenIDAction"); - -var _SimpleObservable = require("./util/SimpleObservable"); - -var _Symbols = require("./Symbols"); - -function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return generator._invoke = function (innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; }(innerFn, self, context), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; this._invoke = function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); }; } function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (undefined === method) { if (context.delegate = null, "throw" === context.method) { if (delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (object) { var keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } - -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - -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 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 ? Object.setPrototypeOf.bind() : 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.bind() : 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: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _asyncIterator(iterable) { var method, async, sync, retry = 2; for ("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;) { if (async && null != (method = iterable[async])) return method.call(iterable); if (sync && null != (method = iterable[sync])) return new AsyncFromSyncIterator(method.call(iterable)); async = "@@asyncIterator", sync = "@@iterator"; } throw new TypeError("Object is not async iterable"); } - -function AsyncFromSyncIterator(s) { function AsyncFromSyncIteratorContinuation(r) { if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object.")); var done = r.done; return Promise.resolve(r.value).then(function (value) { return { value: value, done: done }; }); } return AsyncFromSyncIterator = function AsyncFromSyncIterator(s) { this.s = s, this.n = s.next; }, AsyncFromSyncIterator.prototype = { s: null, n: null, next: function next() { return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); }, "return": function _return(value) { var ret = this.s["return"]; return void 0 === ret ? Promise.resolve({ value: value, done: !0 }) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments)); }, "throw": function _throw(value) { var thr = this.s["return"]; return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments)); } }, new AsyncFromSyncIterator(s); } - -/** - * API handler for the client side of widgets. This raises events - * for each action received as `action:${action}` (eg: "action:screenshot"). - * Default handling can be prevented by using preventDefault() on the - * raised event. The default handling varies for each action: ones - * which the SDK can handle safely are acknowledged appropriately and - * ones which are unhandled (custom or require the client to do something) - * are rejected with an error. - * - * Events which are preventDefault()ed must reply using the transport. - * The events raised will have a default of an IWidgetApiRequest - * interface. - * - * When the ClientWidgetApi is ready to start sending requests, it will - * raise a "ready" CustomEvent. After the ready event fires, actions can - * be sent and the transport will be ready. - * - * When the widget has indicated it has loaded, this class raises a - * "preparing" CustomEvent. The preparing event does not indicate that - * the widget is ready to receive communications - that is signified by - * the ready event exclusively. - * - * This class only handles one widget at a time. - */ -var ClientWidgetApi = /*#__PURE__*/function (_EventEmitter) { - _inherits(ClientWidgetApi, _EventEmitter); - - var _super = _createSuper(ClientWidgetApi); - - // contentLoadedActionSent is used to check that only one ContentLoaded request is send. - - /** - * Creates a new client widget API. This will instantiate the transport - * and start everything. When the iframe is loaded under the widget's - * conditions, a "ready" event will be raised. - * @param {Widget} widget The widget to communicate with. - * @param {HTMLIFrameElement} iframe The iframe the widget is in. - * @param {WidgetDriver} driver The driver for this widget/client. - */ - function ClientWidgetApi(widget, iframe, driver) { - var _this; - - _classCallCheck(this, ClientWidgetApi); - - _this = _super.call(this); - _this.widget = widget; - _this.iframe = iframe; - _this.driver = driver; - - _defineProperty(_assertThisInitialized(_this), "transport", void 0); - - _defineProperty(_assertThisInitialized(_this), "contentLoadedActionSent", false); - - _defineProperty(_assertThisInitialized(_this), "allowedCapabilities", new Set()); - - _defineProperty(_assertThisInitialized(_this), "allowedEvents", []); - - _defineProperty(_assertThisInitialized(_this), "isStopped", false); - - _defineProperty(_assertThisInitialized(_this), "turnServers", null); - - if (!(iframe !== null && iframe !== void 0 && iframe.contentWindow)) { - throw new Error("No iframe supplied"); - } - - if (!widget) { - throw new Error("Invalid widget"); - } - - if (!driver) { - throw new Error("Invalid driver"); - } - - _this.transport = new _PostmessageTransport.PostmessageTransport(_WidgetApiDirection.WidgetApiDirection.ToWidget, widget.id, iframe.contentWindow, window); - _this.transport.targetOrigin = widget.origin; - - _this.transport.on("message", _this.handleMessage.bind(_assertThisInitialized(_this))); - - iframe.addEventListener("load", _this.onIframeLoad.bind(_assertThisInitialized(_this))); - - _this.transport.start(); - - return _this; - } - - _createClass(ClientWidgetApi, [{ - key: "hasCapability", - value: function hasCapability(capability) { - return this.allowedCapabilities.has(capability); - } - }, { - key: "canUseRoomTimeline", - value: function canUseRoomTimeline(roomId) { - return this.hasCapability("org.matrix.msc2762.timeline:".concat(_Symbols.Symbols.AnyRoom)) || this.hasCapability("org.matrix.msc2762.timeline:".concat(roomId)); - } - }, { - key: "canSendRoomEvent", - value: function canSendRoomEvent(eventType) { - var msgtype = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; - return this.allowedEvents.some(function (e) { - return e.matchesAsRoomEvent(_WidgetEventCapability.EventDirection.Send, eventType, msgtype); - }); - } - }, { - key: "canSendStateEvent", - value: function canSendStateEvent(eventType, stateKey) { - return this.allowedEvents.some(function (e) { - return e.matchesAsStateEvent(_WidgetEventCapability.EventDirection.Send, eventType, stateKey); - }); - } - }, { - key: "canSendToDeviceEvent", - value: function canSendToDeviceEvent(eventType) { - return this.allowedEvents.some(function (e) { - return e.matchesAsToDeviceEvent(_WidgetEventCapability.EventDirection.Send, eventType); - }); - } - }, { - key: "canReceiveRoomEvent", - value: function canReceiveRoomEvent(eventType) { - var msgtype = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; - return this.allowedEvents.some(function (e) { - return e.matchesAsRoomEvent(_WidgetEventCapability.EventDirection.Receive, eventType, msgtype); - }); - } - }, { - key: "canReceiveStateEvent", - value: function canReceiveStateEvent(eventType, stateKey) { - return this.allowedEvents.some(function (e) { - return e.matchesAsStateEvent(_WidgetEventCapability.EventDirection.Receive, eventType, stateKey); - }); - } - }, { - key: "canReceiveToDeviceEvent", - value: function canReceiveToDeviceEvent(eventType) { - return this.allowedEvents.some(function (e) { - return e.matchesAsToDeviceEvent(_WidgetEventCapability.EventDirection.Receive, eventType); - }); - } - }, { - key: "stop", - value: function stop() { - this.isStopped = true; - this.transport.stop(); - } - }, { - key: "beginCapabilities", - value: function beginCapabilities() { - var _this2 = this; - - // widget has loaded - tell all the listeners that - this.emit("preparing"); - var requestedCaps; - this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.Capabilities, {}).then(function (caps) { - requestedCaps = caps.capabilities; - return _this2.driver.validateCapabilities(new Set(caps.capabilities)); - }).then(function (allowedCaps) { - console.log("Widget ".concat(_this2.widget.id, " is allowed capabilities:"), Array.from(allowedCaps)); - _this2.allowedCapabilities = allowedCaps; - _this2.allowedEvents = _WidgetEventCapability.WidgetEventCapability.findEventCapabilities(allowedCaps); - - _this2.notifyCapabilities(requestedCaps); - - _this2.emit("ready"); - }); - } - }, { - key: "notifyCapabilities", - value: function notifyCapabilities(requested) { - var _this3 = this; - - this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.NotifyCapabilities, { - requested: requested, - approved: Array.from(this.allowedCapabilities) - })["catch"](function (e) { - console.warn("non-fatal error notifying widget of approved capabilities:", e); - }).then(function () { - _this3.emit("capabilitiesNotified"); - }); - } - }, { - key: "onIframeLoad", - value: function onIframeLoad(ev) { - if (this.widget.waitForIframeLoad) { - // If the widget is set to waitForIframeLoad the capabilities immediatly get setup after load. - // The client does not wait for the ContentLoaded action. - this.beginCapabilities(); - } else { - // Reaching this means, that the Iframe got reloaded/loaded and - // the clientApi is awaiting the FIRST ContentLoaded action. - this.contentLoadedActionSent = false; - } - } - }, { - key: "handleContentLoadedAction", - value: function handleContentLoadedAction(action) { - if (this.contentLoadedActionSent) { - throw new Error("Improper sequence: ContentLoaded Action can only be send once after the widget loaded " + "and should only be used if waitForIframeLoad is false (default=true)"); - } - - if (this.widget.waitForIframeLoad) { - this.transport.reply(action, { - error: { - message: "Improper sequence: not expecting ContentLoaded event if " + "waitForIframLoad is true (default=true)" - } - }); - } else { - this.transport.reply(action, {}); - this.beginCapabilities(); - } - - this.contentLoadedActionSent = true; - } - }, { - key: "replyVersions", - value: function replyVersions(request) { - this.transport.reply(request, { - supported_versions: _ApiVersion.CurrentApiVersions - }); - } - }, { - key: "handleCapabilitiesRenegotiate", - value: function handleCapabilitiesRenegotiate(request) { - var _request$data, - _this4 = this; - - // acknowledge first - this.transport.reply(request, {}); - var requested = ((_request$data = request.data) === null || _request$data === void 0 ? void 0 : _request$data.capabilities) || []; - var newlyRequested = new Set(requested.filter(function (r) { - return !_this4.hasCapability(r); - })); - - if (newlyRequested.size === 0) { - // Nothing to do - notify capabilities - return this.notifyCapabilities([]); - } - - this.driver.validateCapabilities(newlyRequested).then(function (allowed) { - allowed.forEach(function (c) { - return _this4.allowedCapabilities.add(c); - }); - - var allowedEvents = _WidgetEventCapability.WidgetEventCapability.findEventCapabilities(allowed); - - allowedEvents.forEach(function (c) { - return _this4.allowedEvents.push(c); - }); - return _this4.notifyCapabilities(Array.from(newlyRequested)); - }); - } - }, { - key: "handleNavigate", - value: function handleNavigate(request) { - var _request$data2, - _request$data3, - _this5 = this; - - if (!this.hasCapability(_Capabilities.MatrixCapabilities.MSC2931Navigate)) { - return this.transport.reply(request, { - error: { - message: "Missing capability" - } - }); - } - - if (!((_request$data2 = request.data) !== null && _request$data2 !== void 0 && _request$data2.uri) || !((_request$data3 = request.data) !== null && _request$data3 !== void 0 && _request$data3.uri.toString().startsWith("https://matrix.to/#"))) { - return this.transport.reply(request, { - error: { - message: "Invalid matrix.to URI" - } - }); - } - - var onErr = function onErr(e) { - console.error("[ClientWidgetApi] Failed to handle navigation: ", e); - return _this5.transport.reply(request, { - error: { - message: "Error handling navigation" - } - }); - }; - - try { - this.driver.navigate(request.data.uri.toString())["catch"](function (e) { - return onErr(e); - }).then(function () { - return _this5.transport.reply(request, {}); - }); - } catch (e) { - return onErr(e); - } - } - }, { - key: "handleOIDC", - value: function handleOIDC(request) { - var _this6 = this; - - var phase = 1; // 1 = initial request, 2 = after user manual confirmation - - var replyState = function replyState(state, credential) { - credential = credential || {}; - - if (phase > 1) { - return _this6.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.OpenIDCredentials, _objectSpread({ - state: state, - original_request_id: request.requestId - }, credential)); - } else { - return _this6.transport.reply(request, _objectSpread({ - state: state - }, credential)); - } - }; - - var replyError = function replyError(msg) { - console.error("[ClientWidgetApi] Failed to handle OIDC: ", msg); - - if (phase > 1) { - // We don't have a way to indicate that a random error happened in this flow, so - // just block the attempt. - return replyState(_GetOpenIDAction.OpenIDRequestState.Blocked); - } else { - return _this6.transport.reply(request, { - error: { - message: msg - } - }); - } - }; - - var observer = new _SimpleObservable.SimpleObservable(function (update) { - if (update.state === _GetOpenIDAction.OpenIDRequestState.PendingUserConfirmation && phase > 1) { - observer.close(); - return replyError("client provided out-of-phase response to OIDC flow"); - } - - if (update.state === _GetOpenIDAction.OpenIDRequestState.PendingUserConfirmation) { - replyState(update.state); - phase++; - return; - } - - if (update.state === _GetOpenIDAction.OpenIDRequestState.Allowed && !update.token) { - return replyError("client provided invalid OIDC token for an allowed request"); - } - - if (update.state === _GetOpenIDAction.OpenIDRequestState.Blocked) { - update.token = undefined; // just in case the client did something weird - } - - observer.close(); - return replyState(update.state, update.token); - }); - this.driver.askOpenID(observer); - } - }, { - key: "handleReadEvents", - value: function handleReadEvents(request) { - var _this7 = this; - - if (!request.data.type) { - return this.transport.reply(request, { - error: { - message: "Invalid request - missing event type" - } - }); - } - - if (request.data.limit !== undefined && (!request.data.limit || request.data.limit < 0)) { - return this.transport.reply(request, { - error: { - message: "Invalid request - limit out of range" - } - }); - } - - var askRoomIds = null; // null denotes current room only - - if (request.data.room_ids) { - askRoomIds = request.data.room_ids; - - if (!Array.isArray(askRoomIds)) { - askRoomIds = [askRoomIds]; - } - - var _iterator2 = _createForOfIteratorHelper(askRoomIds), - _step2; - - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var roomId = _step2.value; - - if (!this.canUseRoomTimeline(roomId)) { - return this.transport.reply(request, { - error: { - message: "Unable to access room timeline: ".concat(roomId) - } - }); - } - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - } - - var limit = request.data.limit || 0; - var events = Promise.resolve([]); - - if (request.data.state_key !== undefined) { - var stateKey = request.data.state_key === true ? undefined : request.data.state_key.toString(); - - if (!this.canReceiveStateEvent(request.data.type, stateKey !== null && stateKey !== void 0 ? stateKey : null)) { - return this.transport.reply(request, { - error: { - message: "Cannot read state events of this type" - } - }); - } - - events = this.driver.readStateEvents(request.data.type, stateKey, limit, askRoomIds); - } else { - if (!this.canReceiveRoomEvent(request.data.type, request.data.msgtype)) { - return this.transport.reply(request, { - error: { - message: "Cannot read room events of this type" - } - }); - } - - events = this.driver.readRoomEvents(request.data.type, request.data.msgtype, limit, askRoomIds); - } - - return events.then(function (evs) { - return _this7.transport.reply(request, { - events: evs - }); - }); - } - }, { - key: "handleSendEvent", - value: function handleSendEvent(request) { - var _this8 = this; - - if (!request.data.type) { - return this.transport.reply(request, { - error: { - message: "Invalid request - missing event type" - } - }); - } - - if (!!request.data.room_id && !this.canUseRoomTimeline(request.data.room_id)) { - return this.transport.reply(request, { - error: { - message: "Unable to access room timeline: ".concat(request.data.room_id) - } - }); - } - - var isState = request.data.state_key !== null && request.data.state_key !== undefined; - var sendEventPromise; - - if (isState) { - if (!this.canSendStateEvent(request.data.type, request.data.state_key)) { - return this.transport.reply(request, { - error: { - message: "Cannot send state events of this type" - } - }); - } - - sendEventPromise = this.driver.sendEvent(request.data.type, request.data.content || {}, request.data.state_key, request.data.room_id); - } else { - var content = request.data.content || {}; - var msgtype = content['msgtype']; - - if (!this.canSendRoomEvent(request.data.type, msgtype)) { - return this.transport.reply(request, { - error: { - message: "Cannot send room events of this type" - } - }); - } - - sendEventPromise = this.driver.sendEvent(request.data.type, content, null, // not sending a state event - request.data.room_id); - } - - sendEventPromise.then(function (sentEvent) { - return _this8.transport.reply(request, { - room_id: sentEvent.roomId, - event_id: sentEvent.eventId - }); - })["catch"](function (e) { - console.error("error sending event: ", e); - return _this8.transport.reply(request, { - error: { - message: "Error sending event" - } - }); - }); - } - }, { - key: "handleSendToDevice", - value: function () { - var _handleSendToDevice = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request) { - return _regeneratorRuntime().wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (request.data.type) { - _context.next = 5; - break; - } - - _context.next = 3; - return this.transport.reply(request, { - error: { - message: "Invalid request - missing event type" - } - }); - - case 3: - _context.next = 32; - break; - - case 5: - if (request.data.messages) { - _context.next = 10; - break; - } - - _context.next = 8; - return this.transport.reply(request, { - error: { - message: "Invalid request - missing event contents" - } - }); - - case 8: - _context.next = 32; - break; - - case 10: - if (!(typeof request.data.encrypted !== "boolean")) { - _context.next = 15; - break; - } - - _context.next = 13; - return this.transport.reply(request, { - error: { - message: "Invalid request - missing encryption flag" - } - }); - - case 13: - _context.next = 32; - break; - - case 15: - if (this.canSendToDeviceEvent(request.data.type)) { - _context.next = 20; - break; - } - - _context.next = 18; - return this.transport.reply(request, { - error: { - message: "Cannot send to-device events of this type" - } - }); - - case 18: - _context.next = 32; - break; - - case 20: - _context.prev = 20; - _context.next = 23; - return this.driver.sendToDevice(request.data.type, request.data.encrypted, request.data.messages); - - case 23: - _context.next = 25; - return this.transport.reply(request, {}); - - case 25: - _context.next = 32; - break; - - case 27: - _context.prev = 27; - _context.t0 = _context["catch"](20); - console.error("error sending to-device event", _context.t0); - _context.next = 32; - return this.transport.reply(request, { - error: { - message: "Error sending event" - } - }); - - case 32: - case "end": - return _context.stop(); - } - } - }, _callee, this, [[20, 27]]); - })); - - function handleSendToDevice(_x) { - return _handleSendToDevice.apply(this, arguments); - } - - return handleSendToDevice; - }() - }, { - key: "pollTurnServers", - value: function () { - var _pollTurnServers = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(turnServers, initialServer) { - var _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, server; - - return _regeneratorRuntime().wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.prev = 0; - _context2.next = 3; - return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.UpdateTurnServers, initialServer // it's compatible, but missing the index signature - ); - - case 3: - // Pick the generator up where we left off - _iteratorAbruptCompletion = false; - _didIteratorError = false; - _context2.prev = 5; - _iterator = _asyncIterator(turnServers); - - case 7: - _context2.next = 9; - return _iterator.next(); - - case 9: - if (!(_iteratorAbruptCompletion = !(_step = _context2.sent).done)) { - _context2.next = 16; - break; - } - - server = _step.value; - _context2.next = 13; - return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.UpdateTurnServers, server // it's compatible, but missing the index signature - ); - - case 13: - _iteratorAbruptCompletion = false; - _context2.next = 7; - break; - - case 16: - _context2.next = 22; - break; - - case 18: - _context2.prev = 18; - _context2.t0 = _context2["catch"](5); - _didIteratorError = true; - _iteratorError = _context2.t0; - - case 22: - _context2.prev = 22; - _context2.prev = 23; - - if (!(_iteratorAbruptCompletion && _iterator["return"] != null)) { - _context2.next = 27; - break; - } - - _context2.next = 27; - return _iterator["return"](); - - case 27: - _context2.prev = 27; - - if (!_didIteratorError) { - _context2.next = 30; - break; - } - - throw _iteratorError; - - case 30: - return _context2.finish(27); - - case 31: - return _context2.finish(22); - - case 32: - _context2.next = 37; - break; - - case 34: - _context2.prev = 34; - _context2.t1 = _context2["catch"](0); - console.error("error polling for TURN servers", _context2.t1); - - case 37: - case "end": - return _context2.stop(); - } - } - }, _callee2, this, [[0, 34], [5, 18, 22, 32], [23,, 27, 31]]); - })); - - function pollTurnServers(_x2, _x3) { - return _pollTurnServers.apply(this, arguments); - } - - return pollTurnServers; - }() - }, { - key: "handleWatchTurnServers", - value: function () { - var _handleWatchTurnServers = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(request) { - var turnServers, _yield$turnServers$ne, done, value; - - return _regeneratorRuntime().wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - if (this.hasCapability(_Capabilities.MatrixCapabilities.MSC3846TurnServers)) { - _context3.next = 5; - break; - } - - _context3.next = 3; - return this.transport.reply(request, { - error: { - message: "Missing capability" - } - }); - - case 3: - _context3.next = 30; - break; - - case 5: - if (!this.turnServers) { - _context3.next = 10; - break; - } - - _context3.next = 8; - return this.transport.reply(request, {}); - - case 8: - _context3.next = 30; - break; - - case 10: - _context3.prev = 10; - turnServers = this.driver.getTurnServers(); // Peek at the first result, so we can at least verify that the - // client isn't banned from getting TURN servers entirely - - _context3.next = 14; - return turnServers.next(); - - case 14: - _yield$turnServers$ne = _context3.sent; - done = _yield$turnServers$ne.done; - value = _yield$turnServers$ne.value; - - if (!done) { - _context3.next = 19; - break; - } - - throw new Error("Client refuses to provide any TURN servers"); - - case 19: - _context3.next = 21; - return this.transport.reply(request, {}); - - case 21: - // Start the poll loop, sending the widget the initial result - this.pollTurnServers(turnServers, value); - this.turnServers = turnServers; - _context3.next = 30; - break; - - case 25: - _context3.prev = 25; - _context3.t0 = _context3["catch"](10); - console.error("error getting first TURN server results", _context3.t0); - _context3.next = 30; - return this.transport.reply(request, { - error: { - message: "TURN servers not available" - } - }); - - case 30: - case "end": - return _context3.stop(); - } - } - }, _callee3, this, [[10, 25]]); - })); - - function handleWatchTurnServers(_x4) { - return _handleWatchTurnServers.apply(this, arguments); - } - - return handleWatchTurnServers; - }() - }, { - key: "handleUnwatchTurnServers", - value: function () { - var _handleUnwatchTurnServers = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(request) { - return _regeneratorRuntime().wrap(function _callee4$(_context4) { - while (1) { - switch (_context4.prev = _context4.next) { - case 0: - if (this.hasCapability(_Capabilities.MatrixCapabilities.MSC3846TurnServers)) { - _context4.next = 5; - break; - } - - _context4.next = 3; - return this.transport.reply(request, { - error: { - message: "Missing capability" - } - }); - - case 3: - _context4.next = 15; - break; - - case 5: - if (this.turnServers) { - _context4.next = 10; - break; - } - - _context4.next = 8; - return this.transport.reply(request, {}); - - case 8: - _context4.next = 15; - break; - - case 10: - _context4.next = 12; - return this.turnServers["return"](undefined); - - case 12: - this.turnServers = null; - _context4.next = 15; - return this.transport.reply(request, {}); - - case 15: - case "end": - return _context4.stop(); - } - } - }, _callee4, this); - })); - - function handleUnwatchTurnServers(_x5) { - return _handleUnwatchTurnServers.apply(this, arguments); - } - - return handleUnwatchTurnServers; - }() - }, { - key: "handleReadRelations", - value: function () { - var _handleReadRelations = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(request) { - var _this9 = this; - - var result, chunk; - return _regeneratorRuntime().wrap(function _callee5$(_context5) { - while (1) { - switch (_context5.prev = _context5.next) { - case 0: - if (request.data.event_id) { - _context5.next = 2; - break; - } - - return _context5.abrupt("return", this.transport.reply(request, { - error: { - message: "Invalid request - missing event ID" - } - })); - - case 2: - if (!(request.data.limit !== undefined && request.data.limit < 0)) { - _context5.next = 4; - break; - } - - return _context5.abrupt("return", this.transport.reply(request, { - error: { - message: "Invalid request - limit out of range" - } - })); - - case 4: - if (!(request.data.room_id !== undefined && !this.canUseRoomTimeline(request.data.room_id))) { - _context5.next = 6; - break; - } - - return _context5.abrupt("return", this.transport.reply(request, { - error: { - message: "Unable to access room timeline: ".concat(request.data.room_id) - } - })); - - case 6: - _context5.prev = 6; - _context5.next = 9; - return this.driver.readEventRelations(request.data.event_id, request.data.room_id, request.data.rel_type, request.data.event_type, request.data.from, request.data.to, request.data.limit, request.data.direction); - - case 9: - result = _context5.sent; - // only return events that the user has the permission to receive - chunk = result.chunk.filter(function (e) { - if (e.state_key !== undefined) { - return _this9.canReceiveStateEvent(e.type, e.state_key); - } else { - return _this9.canReceiveRoomEvent(e.type, e.content['msgtype']); - } - }); - return _context5.abrupt("return", this.transport.reply(request, { - chunk: chunk, - prev_batch: result.prevBatch, - next_batch: result.nextBatch - })); - - case 14: - _context5.prev = 14; - _context5.t0 = _context5["catch"](6); - console.error("error getting the relations", _context5.t0); - _context5.next = 19; - return this.transport.reply(request, { - error: { - message: "Unexpected error while reading relations" - } - }); - - case 19: - case "end": - return _context5.stop(); - } - } - }, _callee5, this, [[6, 14]]); - })); - - function handleReadRelations(_x6) { - return _handleReadRelations.apply(this, arguments); - } - - return handleReadRelations; - }() - }, { - key: "handleUserDirectorySearch", - value: function () { - var _handleUserDirectorySearch = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(request) { - var result; - return _regeneratorRuntime().wrap(function _callee6$(_context6) { - while (1) { - switch (_context6.prev = _context6.next) { - case 0: - if (this.hasCapability(_Capabilities.MatrixCapabilities.MSC3973UserDirectorySearch)) { - _context6.next = 2; - break; - } - - return _context6.abrupt("return", this.transport.reply(request, { - error: { - message: "Missing capability" - } - })); - - case 2: - if (!(typeof request.data.search_term !== 'string')) { - _context6.next = 4; - break; - } - - return _context6.abrupt("return", this.transport.reply(request, { - error: { - message: "Invalid request - missing search term" - } - })); - - case 4: - if (!(request.data.limit !== undefined && request.data.limit < 0)) { - _context6.next = 6; - break; - } - - return _context6.abrupt("return", this.transport.reply(request, { - error: { - message: "Invalid request - limit out of range" - } - })); - - case 6: - _context6.prev = 6; - _context6.next = 9; - return this.driver.searchUserDirectory(request.data.search_term, request.data.limit); - - case 9: - result = _context6.sent; - return _context6.abrupt("return", this.transport.reply(request, { - limited: result.limited, - results: result.results.map(function (r) { - return { - user_id: r.userId, - display_name: r.displayName, - avatar_url: r.avatarUrl - }; - }) - })); - - case 13: - _context6.prev = 13; - _context6.t0 = _context6["catch"](6); - console.error("error searching in the user directory", _context6.t0); - _context6.next = 18; - return this.transport.reply(request, { - error: { - message: "Unexpected error while searching in the user directory" - } - }); - - case 18: - case "end": - return _context6.stop(); - } - } - }, _callee6, this, [[6, 13]]); - })); - - function handleUserDirectorySearch(_x7) { - return _handleUserDirectorySearch.apply(this, arguments); - } - - return handleUserDirectorySearch; - }() - }, { - key: "handleMessage", - value: function handleMessage(ev) { - if (this.isStopped) return; - var actionEv = new CustomEvent("action:".concat(ev.detail.action), { - detail: ev.detail, - cancelable: true - }); - this.emit("action:".concat(ev.detail.action), actionEv); - - if (!actionEv.defaultPrevented) { - switch (ev.detail.action) { - case _WidgetApiAction.WidgetApiFromWidgetAction.ContentLoaded: - return this.handleContentLoadedAction(ev.detail); - - case _WidgetApiAction.WidgetApiFromWidgetAction.SupportedApiVersions: - return this.replyVersions(ev.detail); - - case _WidgetApiAction.WidgetApiFromWidgetAction.SendEvent: - return this.handleSendEvent(ev.detail); - - case _WidgetApiAction.WidgetApiFromWidgetAction.SendToDevice: - return this.handleSendToDevice(ev.detail); - - case _WidgetApiAction.WidgetApiFromWidgetAction.GetOpenIDCredentials: - return this.handleOIDC(ev.detail); - - case _WidgetApiAction.WidgetApiFromWidgetAction.MSC2931Navigate: - return this.handleNavigate(ev.detail); - - case _WidgetApiAction.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities: - return this.handleCapabilitiesRenegotiate(ev.detail); - - case _WidgetApiAction.WidgetApiFromWidgetAction.MSC2876ReadEvents: - return this.handleReadEvents(ev.detail); - - case _WidgetApiAction.WidgetApiFromWidgetAction.WatchTurnServers: - return this.handleWatchTurnServers(ev.detail); - - case _WidgetApiAction.WidgetApiFromWidgetAction.UnwatchTurnServers: - return this.handleUnwatchTurnServers(ev.detail); - - case _WidgetApiAction.WidgetApiFromWidgetAction.MSC3869ReadRelations: - return this.handleReadRelations(ev.detail); - - case _WidgetApiAction.WidgetApiFromWidgetAction.MSC3973UserDirectorySearch: - return this.handleUserDirectorySearch(ev.detail); - - default: - return this.transport.reply(ev.detail, { - error: { - message: "Unknown or unsupported action: " + ev.detail.action - } - }); - } - } - } - /** - * Takes a screenshot of the widget. - * @returns Resolves to the widget's screenshot. - * @throws Throws if there is a problem. - */ - - }, { - key: "takeScreenshot", - value: function takeScreenshot() { - return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.TakeScreenshot, {}); - } - /** - * Alerts the widget to whether or not it is currently visible. - * @param {boolean} isVisible Whether the widget is visible or not. - * @returns {Promise} Resolves when the widget acknowledges the update. - */ - - }, { - key: "updateVisibility", - value: function updateVisibility(isVisible) { - return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.UpdateVisibility, { - visible: isVisible - }); - } - }, { - key: "sendWidgetConfig", - value: function sendWidgetConfig(data) { - return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.WidgetConfig, data).then(); - } - }, { - key: "notifyModalWidgetButtonClicked", - value: function notifyModalWidgetButtonClicked(id) { - return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.ButtonClicked, { - id: id - }).then(); - } - }, { - key: "notifyModalWidgetClose", - value: function notifyModalWidgetClose(data) { - return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.CloseModalWidget, data).then(); - } - /** - * Feeds an event to the widget. If the widget is not able to accept the event due to - * permissions, this will no-op and return calmly. If the widget failed to handle the - * event, this will raise an error. - * @param {IRoomEvent} rawEvent The event to (try to) send to the widget. - * @param {string} currentViewedRoomId The room ID the user is currently interacting with. - * Not the room ID of the event. - * @returns {Promise} Resolves when complete, rejects if there was an error sending. - */ - - }, { - key: "feedEvent", - value: function () { - var _feedEvent = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(rawEvent, currentViewedRoomId) { - var _rawEvent$content; - - return _regeneratorRuntime().wrap(function _callee7$(_context7) { - while (1) { - switch (_context7.prev = _context7.next) { - case 0: - if (!(rawEvent.room_id !== currentViewedRoomId && !this.canUseRoomTimeline(rawEvent.room_id))) { - _context7.next = 2; - break; - } - - return _context7.abrupt("return"); - - case 2: - if (!(rawEvent.state_key !== undefined && rawEvent.state_key !== null)) { - _context7.next = 7; - break; - } - - if (this.canReceiveStateEvent(rawEvent.type, rawEvent.state_key)) { - _context7.next = 5; - break; - } - - return _context7.abrupt("return"); - - case 5: - _context7.next = 9; - break; - - case 7: - if (this.canReceiveRoomEvent(rawEvent.type, (_rawEvent$content = rawEvent.content) === null || _rawEvent$content === void 0 ? void 0 : _rawEvent$content["msgtype"])) { - _context7.next = 9; - break; - } - - return _context7.abrupt("return"); - - case 9: - _context7.next = 11; - return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.SendEvent, rawEvent // it's compatible, but missing the index signature - ); - - case 11: - case "end": - return _context7.stop(); - } - } - }, _callee7, this); - })); - - function feedEvent(_x8, _x9) { - return _feedEvent.apply(this, arguments); - } - - return feedEvent; - }() - /** - * Feeds a to-device event to the widget. If the widget is not able to accept the - * event due to permissions, this will no-op and return calmly. If the widget failed - * to handle the event, this will raise an error. - * @param {IRoomEvent} rawEvent The event to (try to) send to the widget. - * @param {boolean} encrypted Whether the event contents were encrypted. - * @returns {Promise} Resolves when complete, rejects if there was an error sending. - */ - - }, { - key: "feedToDevice", - value: function () { - var _feedToDevice = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(rawEvent, encrypted) { - return _regeneratorRuntime().wrap(function _callee8$(_context8) { - while (1) { - switch (_context8.prev = _context8.next) { - case 0: - if (!this.canReceiveToDeviceEvent(rawEvent.type)) { - _context8.next = 3; - break; - } - - _context8.next = 3; - return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.SendToDevice, // it's compatible, but missing the index signature - _objectSpread(_objectSpread({}, rawEvent), {}, { - encrypted: encrypted - })); - - case 3: - case "end": - return _context8.stop(); - } - } - }, _callee8, this); - })); - - function feedToDevice(_x10, _x11) { - return _feedToDevice.apply(this, arguments); - } - - return feedToDevice; - }() - }]); - - return ClientWidgetApi; -}(_events.EventEmitter); - -exports.ClientWidgetApi = ClientWidgetApi; -},{"./Symbols":175,"./interfaces/ApiVersion":179,"./interfaces/Capabilities":180,"./interfaces/GetOpenIDAction":183,"./interfaces/WidgetApiAction":207,"./interfaces/WidgetApiDirection":208,"./models/WidgetEventCapability":213,"./transport/PostmessageTransport":219,"./util/SimpleObservable":220,"events":105}],175:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.Symbols = void 0; - -/* - * Copyright 2021 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var Symbols; -exports.Symbols = Symbols; - -(function (Symbols) { - Symbols["AnyRoom"] = "*"; -})(Symbols || (exports.Symbols = Symbols = {})); -},{}],176:[function(require,module,exports){ -"use strict"; - -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.WidgetApi = void 0; - -var _events = require("events"); - -var _WidgetApiDirection = require("./interfaces/WidgetApiDirection"); - -var _ApiVersion = require("./interfaces/ApiVersion"); - -var _PostmessageTransport = require("./transport/PostmessageTransport"); - -var _WidgetApiAction = require("./interfaces/WidgetApiAction"); - -var _GetOpenIDAction = require("./interfaces/GetOpenIDAction"); - -var _WidgetType = require("./interfaces/WidgetType"); - -var _ModalWidgetActions = require("./interfaces/ModalWidgetActions"); - -var _WidgetEventCapability = require("./models/WidgetEventCapability"); - -var _Symbols = require("./Symbols"); - -function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return generator._invoke = function (innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; }(innerFn, self, context), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; this._invoke = function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); }; } function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (undefined === method) { if (context.delegate = null, "throw" === context.method) { if (delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (object) { var keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } - -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - -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 ? Object.setPrototypeOf.bind() : 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.bind() : 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: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _awaitAsyncGenerator(value) { return new _AwaitValue(value); } - -function _wrapAsyncGenerator(fn) { return function () { return new _AsyncGenerator(fn.apply(this, arguments)); }; } - -function _AsyncGenerator(gen) { var front, back; function send(key, arg) { return new Promise(function (resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null }; if (back) { back = back.next = request; } else { front = back = request; resume(key, arg); } }); } function resume(key, arg) { try { var result = gen[key](arg); var value = result.value; var wrappedAwait = value instanceof _AwaitValue; Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { if (wrappedAwait) { resume(key === "return" ? "return" : "next", arg); return; } settle(result.done ? "return" : "normal", arg); }, function (err) { resume("throw", err); }); } catch (err) { settle("throw", err); } } function settle(type, value) { switch (type) { case "return": front.resolve({ value: value, done: true }); break; case "throw": front.reject(value); break; default: front.resolve({ value: value, done: false }); break; } front = front.next; if (front) { resume(front.key, front.arg); } else { back = null; } } this._invoke = send; if (typeof gen["return"] !== "function") { this["return"] = undefined; } } - -_AsyncGenerator.prototype[typeof Symbol === "function" && Symbol.asyncIterator || "@@asyncIterator"] = function () { return this; }; - -_AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); }; - -_AsyncGenerator.prototype["throw"] = function (arg) { return this._invoke("throw", arg); }; - -_AsyncGenerator.prototype["return"] = function (arg) { return this._invoke("return", arg); }; - -function _AwaitValue(value) { this.wrapped = value; } - -/** - * API handler for widgets. This raises events for each action - * received as `action:${action}` (eg: "action:screenshot"). - * Default handling can be prevented by using preventDefault() - * on the raised event. The default handling varies for each - * action: ones which the SDK can handle safely are acknowledged - * appropriately and ones which are unhandled (custom or require - * the widget to do something) are rejected with an error. - * - * Events which are preventDefault()ed must reply using the - * transport. The events raised will have a detail of an - * IWidgetApiRequest interface. - * - * When the WidgetApi is ready to start sending requests, it will - * raise a "ready" CustomEvent. After the ready event fires, actions - * can be sent and the transport will be ready. - */ -var WidgetApi = /*#__PURE__*/function (_EventEmitter) { - _inherits(WidgetApi, _EventEmitter); - - var _super = _createSuper(WidgetApi); - - /** - * Creates a new API handler for the given widget. - * @param {string} widgetId The widget ID to listen for. If not supplied then - * the API will use the widget ID from the first valid request it receives. - * @param {string} clientOrigin The origin of the client, or null if not known. - */ - function WidgetApi() { - var _this2; - - var widgetId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - var clientOrigin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; - - _classCallCheck(this, WidgetApi); - - _this2 = _super.call(this); - _this2.clientOrigin = clientOrigin; - - _defineProperty(_assertThisInitialized(_this2), "transport", void 0); - - _defineProperty(_assertThisInitialized(_this2), "capabilitiesFinished", false); - - _defineProperty(_assertThisInitialized(_this2), "supportsMSC2974Renegotiate", false); - - _defineProperty(_assertThisInitialized(_this2), "requestedCapabilities", []); - - _defineProperty(_assertThisInitialized(_this2), "approvedCapabilities", void 0); - - _defineProperty(_assertThisInitialized(_this2), "cachedClientVersions", void 0); - - _defineProperty(_assertThisInitialized(_this2), "turnServerWatchers", 0); - - if (!window.parent) { - throw new Error("No parent window. This widget doesn't appear to be embedded properly."); - } - - _this2.transport = new _PostmessageTransport.PostmessageTransport(_WidgetApiDirection.WidgetApiDirection.FromWidget, widgetId, window.parent, window); - _this2.transport.targetOrigin = clientOrigin; - - _this2.transport.on("message", _this2.handleMessage.bind(_assertThisInitialized(_this2))); - - return _this2; - } - /** - * Determines if the widget was granted a particular capability. Note that on - * clients where the capabilities are not fed back to the widget this function - * will rely on requested capabilities instead. - * @param {Capability} capability The capability to check for approval of. - * @returns {boolean} True if the widget has approval for the given capability. - */ - - - _createClass(WidgetApi, [{ - key: "hasCapability", - value: function hasCapability(capability) { - if (Array.isArray(this.approvedCapabilities)) { - return this.approvedCapabilities.includes(capability); - } - - return this.requestedCapabilities.includes(capability); - } - /** - * Request a capability from the client. It is not guaranteed to be allowed, - * but will be asked for. - * @param {Capability} capability The capability to request. - * @throws Throws if the capabilities negotiation has already started and the - * widget is unable to request additional capabilities. - */ - - }, { - key: "requestCapability", - value: function requestCapability(capability) { - if (this.capabilitiesFinished && !this.supportsMSC2974Renegotiate) { - throw new Error("Capabilities have already been negotiated"); - } - - this.requestedCapabilities.push(capability); - } - /** - * Request capabilities from the client. They are not guaranteed to be allowed, - * but will be asked for if the negotiation has not already happened. - * @param {Capability[]} capabilities The capabilities to request. - * @throws Throws if the capabilities negotiation has already started. - */ - - }, { - key: "requestCapabilities", - value: function requestCapabilities(capabilities) { - var _this3 = this; - - capabilities.forEach(function (cap) { - return _this3.requestCapability(cap); - }); - } - /** - * Requests the capability to interact with rooms other than the user's currently - * viewed room. Applies to event receiving and sending. - * @param {string | Symbols.AnyRoom} roomId The room ID, or `Symbols.AnyRoom` to - * denote all known rooms. - */ - - }, { - key: "requestCapabilityForRoomTimeline", - value: function requestCapabilityForRoomTimeline(roomId) { - this.requestCapability("org.matrix.msc2762.timeline:".concat(roomId)); - } - /** - * Requests the capability to send a given state event with optional explicit - * state key. It is not guaranteed to be allowed, but will be asked for if the - * negotiation has not already happened. - * @param {string} eventType The state event type to ask for. - * @param {string} stateKey If specified, the specific state key to request. - * Otherwise all state keys will be requested. - */ - - }, { - key: "requestCapabilityToSendState", - value: function requestCapabilityToSendState(eventType, stateKey) { - this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forStateEvent(_WidgetEventCapability.EventDirection.Send, eventType, stateKey).raw); - } - /** - * Requests the capability to receive a given state event with optional explicit - * state key. It is not guaranteed to be allowed, but will be asked for if the - * negotiation has not already happened. - * @param {string} eventType The state event type to ask for. - * @param {string} stateKey If specified, the specific state key to request. - * Otherwise all state keys will be requested. - */ - - }, { - key: "requestCapabilityToReceiveState", - value: function requestCapabilityToReceiveState(eventType, stateKey) { - this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forStateEvent(_WidgetEventCapability.EventDirection.Receive, eventType, stateKey).raw); - } - /** - * Requests the capability to send a given to-device event. It is not - * guaranteed to be allowed, but will be asked for if the negotiation has - * not already happened. - * @param {string} eventType The room event type to ask for. - */ - - }, { - key: "requestCapabilityToSendToDevice", - value: function requestCapabilityToSendToDevice(eventType) { - this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forToDeviceEvent(_WidgetEventCapability.EventDirection.Send, eventType).raw); - } - /** - * Requests the capability to receive a given to-device event. It is not - * guaranteed to be allowed, but will be asked for if the negotiation has - * not already happened. - * @param {string} eventType The room event type to ask for. - */ - - }, { - key: "requestCapabilityToReceiveToDevice", - value: function requestCapabilityToReceiveToDevice(eventType) { - this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forToDeviceEvent(_WidgetEventCapability.EventDirection.Receive, eventType).raw); - } - /** - * Requests the capability to send a given room event. It is not guaranteed to be - * allowed, but will be asked for if the negotiation has not already happened. - * @param {string} eventType The room event type to ask for. - */ - - }, { - key: "requestCapabilityToSendEvent", - value: function requestCapabilityToSendEvent(eventType) { - this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forRoomEvent(_WidgetEventCapability.EventDirection.Send, eventType).raw); - } - /** - * Requests the capability to receive a given room event. It is not guaranteed to be - * allowed, but will be asked for if the negotiation has not already happened. - * @param {string} eventType The room event type to ask for. - */ - - }, { - key: "requestCapabilityToReceiveEvent", - value: function requestCapabilityToReceiveEvent(eventType) { - this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forRoomEvent(_WidgetEventCapability.EventDirection.Receive, eventType).raw); - } - /** - * Requests the capability to send a given message event with optional explicit - * `msgtype`. It is not guaranteed to be allowed, but will be asked for if the - * negotiation has not already happened. - * @param {string} msgtype If specified, the specific msgtype to request. - * Otherwise all message types will be requested. - */ - - }, { - key: "requestCapabilityToSendMessage", - value: function requestCapabilityToSendMessage(msgtype) { - this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forRoomMessageEvent(_WidgetEventCapability.EventDirection.Send, msgtype).raw); - } - /** - * Requests the capability to receive a given message event with optional explicit - * `msgtype`. It is not guaranteed to be allowed, but will be asked for if the - * negotiation has not already happened. - * @param {string} msgtype If specified, the specific msgtype to request. - * Otherwise all message types will be requested. - */ - - }, { - key: "requestCapabilityToReceiveMessage", - value: function requestCapabilityToReceiveMessage(msgtype) { - this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forRoomMessageEvent(_WidgetEventCapability.EventDirection.Receive, msgtype).raw); - } - /** - * Requests an OpenID Connect token from the client for the currently logged in - * user. This token can be validated server-side with the federation API. Note - * that the widget is responsible for validating the token and caching any results - * it needs. - * @returns {Promise} Resolves to a token for verification. - * @throws Throws if the user rejected the request or the request failed. - */ - - }, { - key: "requestOpenIDConnectToken", - value: function requestOpenIDConnectToken() { - var _this4 = this; - - return new Promise(function (resolve, reject) { - _this4.transport.sendComplete(_WidgetApiAction.WidgetApiFromWidgetAction.GetOpenIDCredentials, {}).then(function (response) { - var rdata = response.response; - - if (rdata.state === _GetOpenIDAction.OpenIDRequestState.Allowed) { - resolve(rdata); - } else if (rdata.state === _GetOpenIDAction.OpenIDRequestState.Blocked) { - reject(new Error("User declined to verify their identity")); - } else if (rdata.state === _GetOpenIDAction.OpenIDRequestState.PendingUserConfirmation) { - var handlerFn = function handlerFn(ev) { - ev.preventDefault(); - var request = ev.detail; - if (request.data.original_request_id !== response.requestId) return; - - if (request.data.state === _GetOpenIDAction.OpenIDRequestState.Allowed) { - resolve(request.data); - - _this4.transport.reply(request, {}); // ack - - } else if (request.data.state === _GetOpenIDAction.OpenIDRequestState.Blocked) { - reject(new Error("User declined to verify their identity")); - - _this4.transport.reply(request, {}); // ack - - } else { - reject(new Error("Invalid state on reply: " + rdata.state)); - - _this4.transport.reply(request, { - error: { - message: "Invalid state" - } - }); - } - - _this4.off("action:".concat(_WidgetApiAction.WidgetApiToWidgetAction.OpenIDCredentials), handlerFn); - }; - - _this4.on("action:".concat(_WidgetApiAction.WidgetApiToWidgetAction.OpenIDCredentials), handlerFn); - } else { - reject(new Error("Invalid state: " + rdata.state)); - } - })["catch"](reject); - }); - } - /** - * Asks the client for additional capabilities. Capabilities can be queued for this - * request with the requestCapability() functions. - * @returns {Promise} Resolves when complete. Note that the promise resolves when - * the capabilities request has gone through, not when the capabilities are approved/denied. - * Use the WidgetApiToWidgetAction.NotifyCapabilities action to detect changes. - */ - - }, { - key: "updateRequestedCapabilities", - value: function updateRequestedCapabilities() { - return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities, { - capabilities: this.requestedCapabilities - }).then(); - } - /** - * Tell the client that the content has been loaded. - * @returns {Promise} Resolves when the client acknowledges the request. - */ - - }, { - key: "sendContentLoaded", - value: function sendContentLoaded() { - return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.ContentLoaded, {}).then(); - } - /** - * Sends a sticker to the client. - * @param {IStickerActionRequestData} sticker The sticker to send. - * @returns {Promise} Resolves when the client acknowledges the request. - */ - - }, { - key: "sendSticker", - value: function sendSticker(sticker) { - return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SendSticker, sticker).then(); - } - /** - * Asks the client to set the always-on-screen status for this widget. - * @param {boolean} value The new state to request. - * @returns {Promise} Resolve with true if the client was able to fulfill - * the request, resolves to false otherwise. Rejects if an error occurred. - */ - - }, { - key: "setAlwaysOnScreen", - value: function setAlwaysOnScreen(value) { - return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.UpdateAlwaysOnScreen, { - value: value - }).then(function (res) { - return res.success; - }); - } - /** - * Opens a modal widget. - * @param {string} url The URL to the modal widget. - * @param {string} name The name of the widget. - * @param {IModalWidgetOpenRequestDataButton[]} buttons The buttons to have on the widget. - * @param {IModalWidgetCreateData} data Data to supply to the modal widget. - * @param {WidgetType} type The type of modal widget. - * @returns {Promise} Resolves when the modal widget has been opened. - */ - - }, { - key: "openModalWidget", - value: function openModalWidget(url, name) { - var buttons = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; - var data = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; - var type = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : _WidgetType.MatrixWidgetType.Custom; - return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.OpenModalWidget, { - type: type, - url: url, - name: name, - buttons: buttons, - data: data - }).then(); - } - /** - * Closes the modal widget. The widget's session will be terminated shortly after. - * @param {IModalWidgetReturnData} data Optional data to close the modal widget with. - * @returns {Promise} Resolves when complete. - */ - - }, { - key: "closeModalWidget", - value: function closeModalWidget() { - var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.CloseModalWidget, data).then(); - } - }, { - key: "sendRoomEvent", - value: function sendRoomEvent(eventType, content, roomId) { - return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SendEvent, { - type: eventType, - content: content, - room_id: roomId - }); - } - }, { - key: "sendStateEvent", - value: function sendStateEvent(eventType, stateKey, content, roomId) { - return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SendEvent, { - type: eventType, - content: content, - state_key: stateKey, - room_id: roomId - }); - } - /** - * Sends a to-device event. - * @param {string} eventType The type of events being sent. - * @param {boolean} encrypted Whether to encrypt the message contents. - * @param {Object} contentMap A map from user IDs to device IDs to message contents. - * @returns {Promise} Resolves when complete. - */ - - }, { - key: "sendToDevice", - value: function sendToDevice(eventType, encrypted, contentMap) { - return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SendToDevice, { - type: eventType, - encrypted: encrypted, - messages: contentMap - }); - } - }, { - key: "readRoomEvents", - value: function readRoomEvents(eventType, limit, msgtype, roomIds) { - var data = { - type: eventType, - msgtype: msgtype - }; - - if (limit !== undefined) { - data.limit = limit; - } - - if (roomIds) { - if (roomIds.includes(_Symbols.Symbols.AnyRoom)) { - data.room_ids = _Symbols.Symbols.AnyRoom; - } else { - data.room_ids = roomIds; - } - } - - return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC2876ReadEvents, data).then(function (r) { - return r.events; - }); - } - /** - * Reads all related events given a known eventId. - * @param eventId The id of the parent event to be read. - * @param roomId The room to look within. When undefined, the user's currently - * viewed room. - * @param relationType The relationship type of child events to search for. - * When undefined, all relations are returned. - * @param eventType The event type of child events to search for. When undefined, - * all related events are returned. - * @param limit The maximum number of events to retrieve per room. If not - * supplied, the server will apply a default limit. - * @param from The pagination token to start returning results from, as - * received from a previous call. If not supplied, results start at the most - * recent topological event known to the server. - * @param to The pagination token to stop returning results at. If not - * supplied, results continue up to limit or until there are no more events. - * @param direction The direction to search for according to MSC3715. - * @returns Resolves to the room relations. - */ - - }, { - key: "readEventRelations", - value: function () { - var _readEventRelations = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(eventId, roomId, relationType, eventType, limit, from, to, direction) { - var versions, data; - return _regeneratorRuntime().wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return this.getClientVersions(); - - case 2: - versions = _context.sent; - - if (versions.includes(_ApiVersion.UnstableApiVersion.MSC3869)) { - _context.next = 5; - break; - } - - throw new Error("The read_relations action is not supported by the client."); - - case 5: - data = { - event_id: eventId, - rel_type: relationType, - event_type: eventType, - room_id: roomId, - to: to, - from: from, - limit: limit, - direction: direction - }; - return _context.abrupt("return", this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC3869ReadRelations, data)); - - case 7: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - function readEventRelations(_x, _x2, _x3, _x4, _x5, _x6, _x7, _x8) { - return _readEventRelations.apply(this, arguments); - } - - return readEventRelations; - }() - }, { - key: "readStateEvents", - value: function readStateEvents(eventType, limit, stateKey, roomIds) { - var data = { - type: eventType, - state_key: stateKey === undefined ? true : stateKey - }; - - if (limit !== undefined) { - data.limit = limit; - } - - if (roomIds) { - if (roomIds.includes(_Symbols.Symbols.AnyRoom)) { - data.room_ids = _Symbols.Symbols.AnyRoom; - } else { - data.room_ids = roomIds; - } - } - - return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC2876ReadEvents, data).then(function (r) { - return r.events; - }); - } - /** - * Sets a button as disabled or enabled on the modal widget. Buttons are enabled by default. - * @param {ModalButtonID} buttonId The button ID to enable/disable. - * @param {boolean} isEnabled Whether or not the button is enabled. - * @returns {Promise} Resolves when complete. - * @throws Throws if the button cannot be disabled, or the client refuses to disable the button. - */ - - }, { - key: "setModalButtonEnabled", - value: function setModalButtonEnabled(buttonId, isEnabled) { - if (buttonId === _ModalWidgetActions.BuiltInModalButtonID.Close) { - throw new Error("The close button cannot be disabled"); - } - - return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SetModalButtonEnabled, { - button: buttonId, - enabled: isEnabled - }).then(); - } - /** - * Attempts to navigate the client to the given URI. This can only be called with Matrix URIs - * (currently only matrix.to, but in future a Matrix URI scheme will be defined). - * @param {string} uri The URI to navigate to. - * @returns {Promise} Resolves when complete. - * @throws Throws if the URI is invalid or cannot be processed. - * @deprecated This currently relies on an unstable MSC (MSC2931). - */ - - }, { - key: "navigateTo", - value: function navigateTo(uri) { - if (!uri || !uri.startsWith("https://matrix.to/#")) { - throw new Error("Invalid matrix.to URI"); - } - - return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC2931Navigate, { - uri: uri - }).then(); - } - /** - * Starts watching for TURN servers, yielding an initial set of credentials as soon as possible, - * and thereafter yielding new credentials whenever the previous ones expire. - * @yields {ITurnServer} The TURN server URIs and credentials currently available to the widget. - */ - - }, { - key: "getTurnServers", - value: function getTurnServers() { - var _this = this; - - return _wrapAsyncGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() { - var setTurnServer, onUpdateTurnServers; - return _regeneratorRuntime().wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - onUpdateTurnServers = /*#__PURE__*/function () { - var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(ev) { - return _regeneratorRuntime().wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - ev.preventDefault(); - setTurnServer(ev.detail.data); - _context2.next = 4; - return _this.transport.reply(ev.detail, {}); - - case 4: - case "end": - return _context2.stop(); - } - } - }, _callee2); - })); - - return function onUpdateTurnServers(_x9) { - return _ref.apply(this, arguments); - }; - }(); // Start listening for updates before we even start watching, to catch - // TURN data that is sent immediately - - - _this.on("action:".concat(_WidgetApiAction.WidgetApiToWidgetAction.UpdateTurnServers), onUpdateTurnServers); // Only send the 'watch' action if we aren't already watching - - - if (!(_this.turnServerWatchers === 0)) { - _context3.next = 12; - break; - } - - _context3.prev = 3; - _context3.next = 6; - return _awaitAsyncGenerator(_this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.WatchTurnServers, {})); - - case 6: - _context3.next = 12; - break; - - case 8: - _context3.prev = 8; - _context3.t0 = _context3["catch"](3); - - _this.off("action:".concat(_WidgetApiAction.WidgetApiToWidgetAction.UpdateTurnServers), onUpdateTurnServers); - - throw _context3.t0; - - case 12: - _this.turnServerWatchers++; - _context3.prev = 13; - - case 14: - if (!true) { - _context3.next = 21; - break; - } - - _context3.next = 17; - return _awaitAsyncGenerator(new Promise(function (resolve) { - return setTurnServer = resolve; - })); - - case 17: - _context3.next = 19; - return _context3.sent; - - case 19: - _context3.next = 14; - break; - - case 21: - _context3.prev = 21; - - // The loop was broken by the caller - clean up - _this.off("action:".concat(_WidgetApiAction.WidgetApiToWidgetAction.UpdateTurnServers), onUpdateTurnServers); // Since sending the 'unwatch' action will end updates for all other - // consumers, only send it if we're the only consumer remaining - - - _this.turnServerWatchers--; - - if (!(_this.turnServerWatchers === 0)) { - _context3.next = 27; - break; - } - - _context3.next = 27; - return _awaitAsyncGenerator(_this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.UnwatchTurnServers, {})); - - case 27: - return _context3.finish(21); - - case 28: - case "end": - return _context3.stop(); - } - } - }, _callee3, null, [[3, 8], [13,, 21, 28]]); - }))(); - } - /** - * Search for users in the user directory. - * @param searchTerm The term to search for. - * @param limit The maximum number of results to return. If not supplied, the - * @returns Resolves to the search results. - */ - - }, { - key: "searchUserDirectory", - value: function () { - var _searchUserDirectory = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(searchTerm, limit) { - var versions, data; - return _regeneratorRuntime().wrap(function _callee4$(_context4) { - while (1) { - switch (_context4.prev = _context4.next) { - case 0: - _context4.next = 2; - return this.getClientVersions(); - - case 2: - versions = _context4.sent; - - if (versions.includes(_ApiVersion.UnstableApiVersion.MSC3973)) { - _context4.next = 5; - break; - } - - throw new Error("The user_directory_search action is not supported by the client."); - - case 5: - data = { - search_term: searchTerm, - limit: limit - }; - return _context4.abrupt("return", this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC3973UserDirectorySearch, data)); - - case 7: - case "end": - return _context4.stop(); - } - } - }, _callee4, this); - })); - - function searchUserDirectory(_x10, _x11) { - return _searchUserDirectory.apply(this, arguments); - } - - return searchUserDirectory; - }() - /** - * Starts the communication channel. This should be done early to ensure - * that messages are not missed. Communication can only be stopped by the client. - */ - - }, { - key: "start", - value: function start() { - var _this5 = this; - - this.transport.start(); - this.getClientVersions().then(function (v) { - if (v.includes(_ApiVersion.UnstableApiVersion.MSC2974)) { - _this5.supportsMSC2974Renegotiate = true; - } - }); - } - }, { - key: "handleMessage", - value: function handleMessage(ev) { - var actionEv = new CustomEvent("action:".concat(ev.detail.action), { - detail: ev.detail, - cancelable: true - }); - this.emit("action:".concat(ev.detail.action), actionEv); - - if (!actionEv.defaultPrevented) { - switch (ev.detail.action) { - case _WidgetApiAction.WidgetApiToWidgetAction.SupportedApiVersions: - return this.replyVersions(ev.detail); - - case _WidgetApiAction.WidgetApiToWidgetAction.Capabilities: - return this.handleCapabilities(ev.detail); - - case _WidgetApiAction.WidgetApiToWidgetAction.UpdateVisibility: - return this.transport.reply(ev.detail, {}); - // ack to avoid error spam - - case _WidgetApiAction.WidgetApiToWidgetAction.NotifyCapabilities: - return this.transport.reply(ev.detail, {}); - // ack to avoid error spam - - default: - return this.transport.reply(ev.detail, { - error: { - message: "Unknown or unsupported action: " + ev.detail.action - } - }); - } - } - } - }, { - key: "replyVersions", - value: function replyVersions(request) { - this.transport.reply(request, { - supported_versions: _ApiVersion.CurrentApiVersions - }); - } - }, { - key: "getClientVersions", - value: function getClientVersions() { - var _this6 = this; - - if (Array.isArray(this.cachedClientVersions)) { - return Promise.resolve(this.cachedClientVersions); - } - - return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SupportedApiVersions, {}).then(function (r) { - _this6.cachedClientVersions = r.supported_versions; - return r.supported_versions; - })["catch"](function (e) { - console.warn("non-fatal error getting supported client versions: ", e); - return []; - }); - } - }, { - key: "handleCapabilities", - value: function handleCapabilities(request) { - var _this7 = this; - - if (this.capabilitiesFinished) { - return this.transport.reply(request, { - error: { - message: "Capability negotiation already completed" - } - }); - } // See if we can expect a capabilities notification or not - - - return this.getClientVersions().then(function (v) { - if (v.includes(_ApiVersion.UnstableApiVersion.MSC2871)) { - _this7.once("action:".concat(_WidgetApiAction.WidgetApiToWidgetAction.NotifyCapabilities), function (ev) { - _this7.approvedCapabilities = ev.detail.data.approved; - - _this7.emit("ready"); - }); - } else { - // if we can't expect notification, we're as done as we can be - _this7.emit("ready"); - } // in either case, reply to that capabilities request - - - _this7.capabilitiesFinished = true; - return _this7.transport.reply(request, { - capabilities: _this7.requestedCapabilities - }); - }); - } - }]); - - return WidgetApi; -}(_events.EventEmitter); - -exports.WidgetApi = WidgetApi; -},{"./Symbols":175,"./interfaces/ApiVersion":179,"./interfaces/GetOpenIDAction":183,"./interfaces/ModalWidgetActions":193,"./interfaces/WidgetApiAction":207,"./interfaces/WidgetApiDirection":208,"./interfaces/WidgetType":211,"./models/WidgetEventCapability":213,"./transport/PostmessageTransport":219,"events":105}],177:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.WidgetDriver = void 0; - -var _ = require(".."); - -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 the functions and behaviour the widget-api is unable to - * do, such as prompting the user for information or interacting with - * the UI. Clients are expected to implement this class and override - * any functions they need/want to support. - * - * This class assumes the client will have a context of a Widget - * instance already. - */ -var WidgetDriver = /*#__PURE__*/function () { - function WidgetDriver() { - _classCallCheck(this, WidgetDriver); - } - - _createClass(WidgetDriver, [{ - key: "validateCapabilities", - value: - /** - * Verifies the widget's requested capabilities, returning the ones - * it is approved to use. Mutating the requested capabilities will - * have no effect. - * - * This SHOULD result in the user being prompted to approve/deny - * capabilities. - * - * By default this rejects all capabilities (returns an empty set). - * @param {Set} requested The set of requested capabilities. - * @returns {Promise>} Resolves to the allowed capabilities. - */ - function validateCapabilities(requested) { - return Promise.resolve(new Set()); - } - /** - * Sends an event into a room. If `roomId` is falsy, the client should send the event - * into the room the user is currently looking at. The widget API will have already - * verified that the widget is capable of sending the event to that room. - * @param {string} eventType The event type to be sent. - * @param {*} content The content for the event. - * @param {string|null} stateKey The state key if this is a state event, otherwise null. - * May be an empty string. - * @param {string|null} roomId The room ID to send the event to. If falsy, the room the - * user is currently looking at. - * @returns {Promise} Resolves when the event has been sent with - * details of that event. - * @throws Rejected when the event could not be sent. - */ - - }, { - key: "sendEvent", - value: function sendEvent(eventType, content) { - var stateKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; - var roomId = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - return Promise.reject(new Error("Failed to override function")); - } - /** - * Sends a to-device event. The widget API will have already verified that the widget - * is capable of sending the event. - * @param {string} eventType The event type to be sent. - * @param {boolean} encrypted Whether to encrypt the message contents. - * @param {Object} contentMap A map from user ID and device ID to event content. - * @returns {Promise} Resolves when the event has been sent. - * @throws Rejected when the event could not be sent. - */ - - }, { - key: "sendToDevice", - value: function sendToDevice(eventType, encrypted, contentMap) { - return Promise.reject(new Error("Failed to override function")); - } - /** - * Reads all events of the given type, and optionally `msgtype` (if applicable/defined), - * the user has access to. The widget API will have already verified that the widget is - * capable of receiving the events. Less events than the limit are allowed to be returned, - * but not more. If `roomIds` is supplied, it may contain `Symbols.AnyRoom` to denote that - * `limit` in each of the client's known rooms should be returned. When `null`, only the - * room the user is currently looking at should be considered. - * @param eventType The event type to be read. - * @param msgtype The msgtype of the events to be read, if applicable/defined. - * @param limit The maximum number of events to retrieve per room. Will be zero to denote "as many - * as possible". - * @param roomIds When null, the user's currently viewed room. Otherwise, the list of room IDs - * to look within, possibly containing Symbols.AnyRoom to denote all known rooms. - * @returns {Promise} Resolves to the room events, or an empty array. - */ - - }, { - key: "readRoomEvents", - value: function readRoomEvents(eventType, msgtype, limit) { - var roomIds = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - return Promise.resolve([]); - } - /** - * Reads all events of the given type, and optionally state key (if applicable/defined), - * the user has access to. The widget API will have already verified that the widget is - * capable of receiving the events. Less events than the limit are allowed to be returned, - * but not more. If `roomIds` is supplied, it may contain `Symbols.AnyRoom` to denote that - * `limit` in each of the client's known rooms should be returned. When `null`, only the - * room the user is currently looking at should be considered. - * @param eventType The event type to be read. - * @param stateKey The state key of the events to be read, if applicable/defined. - * @param limit The maximum number of events to retrieve. Will be zero to denote "as many - * as possible". - * @param roomIds When null, the user's currently viewed room. Otherwise, the list of room IDs - * to look within, possibly containing Symbols.AnyRoom to denote all known rooms. - * @returns {Promise} Resolves to the state events, or an empty array. - */ - - }, { - key: "readStateEvents", - value: function readStateEvents(eventType, stateKey, limit) { - var roomIds = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - return Promise.resolve([]); - } - /** - * Reads all events that are related to a given event. The widget API will - * have already verified that the widget is capable of receiving the event, - * or will make sure to reject access to events which are returned from this - * function, but are not capable of receiving. If `relationType` or `eventType` - * are set, the returned events should already be filtered. Less events than - * the limit are allowed to be returned, but not more. - * @param eventId The id of the parent event to be read. - * @param roomId The room to look within. When undefined, the user's - * currently viewed room. - * @param relationType The relationship type of child events to search for. - * When undefined, all relations are returned. - * @param eventType The event type of child events to search for. When undefined, - * all related events are returned. - * @param from The pagination token to start returning results from, as - * received from a previous call. If not supplied, results start at the most - * recent topological event known to the server. - * @param to The pagination token to stop returning results at. If not - * supplied, results continue up to limit or until there are no more events. - * @param limit The maximum number of events to retrieve per room. If not - * supplied, the server will apply a default limit. - * @param direction The direction to search for according to MSC3715 - * @returns Resolves to the room relations. - */ - - }, { - key: "readEventRelations", - value: function readEventRelations(eventId, roomId, relationType, eventType, from, to, limit, direction) { - return Promise.resolve({ - chunk: [] - }); - } - /** - * Asks the user for permission to validate their identity through OpenID Connect. The - * interface for this function is an observable which accepts the state machine of the - * OIDC exchange flow. For example, if the client/user blocks the request then it would - * feed back a `{state: Blocked}` into the observable. Similarly, if the user already - * approved the widget then a `{state: Allowed}` would be fed into the observable alongside - * the token itself. If the client is asking for permission, it should feed in a - * `{state: PendingUserConfirmation}` followed by the relevant Allowed or Blocked state. - * - * The widget API will reject the widget's request with an error if this contract is not - * met properly. By default, the widget driver will block all OIDC requests. - * @param {SimpleObservable} observer The observable to feed updates into. - */ - - }, { - key: "askOpenID", - value: function askOpenID(observer) { - observer.update({ - state: _.OpenIDRequestState.Blocked - }); - } - /** - * Navigates the client with a matrix.to URI. In future this function will also be provided - * with the Matrix URIs once matrix.to is replaced. The given URI will have already been - * lightly checked to ensure it looks like a valid URI, though the implementation is recommended - * to do further checks on the URI. - * @param {string} uri The URI to navigate to. - * @returns {Promise} Resolves when complete. - * @throws Throws if there's a problem with the navigation, such as invalid format. - */ - - }, { - key: "navigate", - value: function navigate(uri) { - throw new Error("Navigation is not implemented"); - } - /** - * Polls for TURN server data, yielding an initial set of credentials as soon as possible, and - * thereafter yielding new credentials whenever the previous ones expire. The widget API will - * have already verified that the widget has permission to access TURN servers. - * @yields {ITurnServer} The TURN server URIs and credentials currently available to the client. - */ - - }, { - key: "getTurnServers", - value: function getTurnServers() { - throw new Error("TURN server support is not implemented"); - } - /** - * Search for users in the user directory. - * @param searchTerm The term to search for. - * @param limit The maximum number of results to return. If not supplied, the - * @returns Resolves to the search results. - */ - - }, { - key: "searchUserDirectory", - value: function searchUserDirectory(searchTerm, limit) { - return Promise.resolve({ - limited: false, - results: [] - }); - } - }]); - - return WidgetDriver; -}(); - -exports.WidgetDriver = WidgetDriver; -},{"..":178}],178:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _WidgetApi = require("./WidgetApi"); - -Object.keys(_WidgetApi).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _WidgetApi[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _WidgetApi[key]; - } - }); -}); - -var _ClientWidgetApi = require("./ClientWidgetApi"); - -Object.keys(_ClientWidgetApi).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _ClientWidgetApi[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _ClientWidgetApi[key]; - } - }); -}); - -var _Symbols = require("./Symbols"); - -Object.keys(_Symbols).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _Symbols[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _Symbols[key]; - } - }); -}); - -var _ITransport = require("./transport/ITransport"); - -Object.keys(_ITransport).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _ITransport[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _ITransport[key]; - } - }); -}); - -var _PostmessageTransport = require("./transport/PostmessageTransport"); - -Object.keys(_PostmessageTransport).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _PostmessageTransport[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _PostmessageTransport[key]; - } - }); -}); - -var _ICustomWidgetData = require("./interfaces/ICustomWidgetData"); - -Object.keys(_ICustomWidgetData).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _ICustomWidgetData[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _ICustomWidgetData[key]; - } - }); -}); - -var _IJitsiWidgetData = require("./interfaces/IJitsiWidgetData"); - -Object.keys(_IJitsiWidgetData).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _IJitsiWidgetData[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _IJitsiWidgetData[key]; - } - }); -}); - -var _IStickerpickerWidgetData = require("./interfaces/IStickerpickerWidgetData"); - -Object.keys(_IStickerpickerWidgetData).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _IStickerpickerWidgetData[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _IStickerpickerWidgetData[key]; - } - }); -}); - -var _IWidget = require("./interfaces/IWidget"); - -Object.keys(_IWidget).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _IWidget[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _IWidget[key]; - } - }); -}); - -var _WidgetType = require("./interfaces/WidgetType"); - -Object.keys(_WidgetType).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _WidgetType[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _WidgetType[key]; - } - }); -}); - -var _IWidgetApiErrorResponse = require("./interfaces/IWidgetApiErrorResponse"); - -Object.keys(_IWidgetApiErrorResponse).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _IWidgetApiErrorResponse[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _IWidgetApiErrorResponse[key]; - } - }); -}); - -var _IWidgetApiRequest = require("./interfaces/IWidgetApiRequest"); - -Object.keys(_IWidgetApiRequest).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _IWidgetApiRequest[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _IWidgetApiRequest[key]; - } - }); -}); - -var _IWidgetApiResponse = require("./interfaces/IWidgetApiResponse"); - -Object.keys(_IWidgetApiResponse).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _IWidgetApiResponse[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _IWidgetApiResponse[key]; - } - }); -}); - -var _WidgetApiAction = require("./interfaces/WidgetApiAction"); - -Object.keys(_WidgetApiAction).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _WidgetApiAction[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _WidgetApiAction[key]; - } - }); -}); - -var _WidgetApiDirection = require("./interfaces/WidgetApiDirection"); - -Object.keys(_WidgetApiDirection).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _WidgetApiDirection[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _WidgetApiDirection[key]; - } - }); -}); - -var _ApiVersion = require("./interfaces/ApiVersion"); - -Object.keys(_ApiVersion).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _ApiVersion[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _ApiVersion[key]; - } - }); -}); - -var _Capabilities = require("./interfaces/Capabilities"); - -Object.keys(_Capabilities).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _Capabilities[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _Capabilities[key]; - } - }); -}); - -var _CapabilitiesAction = require("./interfaces/CapabilitiesAction"); - -Object.keys(_CapabilitiesAction).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _CapabilitiesAction[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _CapabilitiesAction[key]; - } - }); -}); - -var _ContentLoadedAction = require("./interfaces/ContentLoadedAction"); - -Object.keys(_ContentLoadedAction).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _ContentLoadedAction[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _ContentLoadedAction[key]; - } - }); -}); - -var _ScreenshotAction = require("./interfaces/ScreenshotAction"); - -Object.keys(_ScreenshotAction).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _ScreenshotAction[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _ScreenshotAction[key]; - } - }); -}); - -var _StickerAction = require("./interfaces/StickerAction"); - -Object.keys(_StickerAction).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _StickerAction[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _StickerAction[key]; - } - }); -}); - -var _StickyAction = require("./interfaces/StickyAction"); - -Object.keys(_StickyAction).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _StickyAction[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _StickyAction[key]; - } - }); -}); - -var _SupportedVersionsAction = require("./interfaces/SupportedVersionsAction"); - -Object.keys(_SupportedVersionsAction).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _SupportedVersionsAction[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _SupportedVersionsAction[key]; - } - }); -}); - -var _VisibilityAction = require("./interfaces/VisibilityAction"); - -Object.keys(_VisibilityAction).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _VisibilityAction[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _VisibilityAction[key]; - } - }); -}); - -var _GetOpenIDAction = require("./interfaces/GetOpenIDAction"); - -Object.keys(_GetOpenIDAction).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _GetOpenIDAction[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _GetOpenIDAction[key]; - } - }); -}); - -var _OpenIDCredentialsAction = require("./interfaces/OpenIDCredentialsAction"); - -Object.keys(_OpenIDCredentialsAction).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _OpenIDCredentialsAction[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _OpenIDCredentialsAction[key]; - } - }); -}); - -var _WidgetKind = require("./interfaces/WidgetKind"); - -Object.keys(_WidgetKind).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _WidgetKind[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _WidgetKind[key]; - } - }); -}); - -var _ModalButtonKind = require("./interfaces/ModalButtonKind"); - -Object.keys(_ModalButtonKind).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _ModalButtonKind[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _ModalButtonKind[key]; - } - }); -}); - -var _ModalWidgetActions = require("./interfaces/ModalWidgetActions"); - -Object.keys(_ModalWidgetActions).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _ModalWidgetActions[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _ModalWidgetActions[key]; - } - }); -}); - -var _SetModalButtonEnabledAction = require("./interfaces/SetModalButtonEnabledAction"); - -Object.keys(_SetModalButtonEnabledAction).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _SetModalButtonEnabledAction[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _SetModalButtonEnabledAction[key]; - } - }); -}); - -var _WidgetConfigAction = require("./interfaces/WidgetConfigAction"); - -Object.keys(_WidgetConfigAction).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _WidgetConfigAction[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _WidgetConfigAction[key]; - } - }); -}); - -var _SendEventAction = require("./interfaces/SendEventAction"); - -Object.keys(_SendEventAction).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _SendEventAction[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _SendEventAction[key]; - } - }); -}); - -var _SendToDeviceAction = require("./interfaces/SendToDeviceAction"); - -Object.keys(_SendToDeviceAction).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _SendToDeviceAction[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _SendToDeviceAction[key]; - } - }); -}); - -var _ReadEventAction = require("./interfaces/ReadEventAction"); - -Object.keys(_ReadEventAction).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _ReadEventAction[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _ReadEventAction[key]; - } - }); -}); - -var _IRoomEvent = require("./interfaces/IRoomEvent"); - -Object.keys(_IRoomEvent).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _IRoomEvent[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _IRoomEvent[key]; - } - }); -}); - -var _NavigateAction = require("./interfaces/NavigateAction"); - -Object.keys(_NavigateAction).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _NavigateAction[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _NavigateAction[key]; - } - }); -}); - -var _TurnServerActions = require("./interfaces/TurnServerActions"); - -Object.keys(_TurnServerActions).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _TurnServerActions[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _TurnServerActions[key]; - } - }); -}); - -var _ReadRelationsAction = require("./interfaces/ReadRelationsAction"); - -Object.keys(_ReadRelationsAction).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _ReadRelationsAction[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _ReadRelationsAction[key]; - } - }); -}); - -var _WidgetEventCapability = require("./models/WidgetEventCapability"); - -Object.keys(_WidgetEventCapability).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _WidgetEventCapability[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _WidgetEventCapability[key]; - } - }); -}); - -var _url = require("./models/validation/url"); - -Object.keys(_url).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _url[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _url[key]; - } - }); -}); - -var _utils = require("./models/validation/utils"); - -Object.keys(_utils).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _utils[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _utils[key]; - } - }); -}); - -var _Widget = require("./models/Widget"); - -Object.keys(_Widget).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _Widget[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _Widget[key]; - } - }); -}); - -var _WidgetParser = require("./models/WidgetParser"); - -Object.keys(_WidgetParser).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _WidgetParser[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _WidgetParser[key]; - } - }); -}); - -var _urlTemplate = require("./templating/url-template"); - -Object.keys(_urlTemplate).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _urlTemplate[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _urlTemplate[key]; - } - }); -}); - -var _SimpleObservable = require("./util/SimpleObservable"); - -Object.keys(_SimpleObservable).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _SimpleObservable[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _SimpleObservable[key]; - } - }); -}); - -var _WidgetDriver = require("./driver/WidgetDriver"); - -Object.keys(_WidgetDriver).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (key in exports && exports[key] === _WidgetDriver[key]) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _WidgetDriver[key]; - } - }); -}); -},{"./ClientWidgetApi":174,"./Symbols":175,"./WidgetApi":176,"./driver/WidgetDriver":177,"./interfaces/ApiVersion":179,"./interfaces/Capabilities":180,"./interfaces/CapabilitiesAction":181,"./interfaces/ContentLoadedAction":182,"./interfaces/GetOpenIDAction":183,"./interfaces/ICustomWidgetData":184,"./interfaces/IJitsiWidgetData":185,"./interfaces/IRoomEvent":186,"./interfaces/IStickerpickerWidgetData":187,"./interfaces/IWidget":188,"./interfaces/IWidgetApiErrorResponse":189,"./interfaces/IWidgetApiRequest":190,"./interfaces/IWidgetApiResponse":191,"./interfaces/ModalButtonKind":192,"./interfaces/ModalWidgetActions":193,"./interfaces/NavigateAction":194,"./interfaces/OpenIDCredentialsAction":195,"./interfaces/ReadEventAction":196,"./interfaces/ReadRelationsAction":197,"./interfaces/ScreenshotAction":198,"./interfaces/SendEventAction":199,"./interfaces/SendToDeviceAction":200,"./interfaces/SetModalButtonEnabledAction":201,"./interfaces/StickerAction":202,"./interfaces/StickyAction":203,"./interfaces/SupportedVersionsAction":204,"./interfaces/TurnServerActions":205,"./interfaces/VisibilityAction":206,"./interfaces/WidgetApiAction":207,"./interfaces/WidgetApiDirection":208,"./interfaces/WidgetConfigAction":209,"./interfaces/WidgetKind":210,"./interfaces/WidgetType":211,"./models/Widget":212,"./models/WidgetEventCapability":213,"./models/WidgetParser":214,"./models/validation/url":215,"./models/validation/utils":216,"./templating/url-template":217,"./transport/ITransport":218,"./transport/PostmessageTransport":219,"./util/SimpleObservable":220}],179:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.UnstableApiVersion = exports.MatrixApiVersion = exports.CurrentApiVersions = void 0; - -/* - * Copyright 2020 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var MatrixApiVersion; -exports.MatrixApiVersion = MatrixApiVersion; - -(function (MatrixApiVersion) { - MatrixApiVersion["Prerelease1"] = "0.0.1"; - MatrixApiVersion["Prerelease2"] = "0.0.2"; -})(MatrixApiVersion || (exports.MatrixApiVersion = MatrixApiVersion = {})); - -var UnstableApiVersion; -exports.UnstableApiVersion = UnstableApiVersion; - -(function (UnstableApiVersion) { - UnstableApiVersion["MSC2762"] = "org.matrix.msc2762"; - UnstableApiVersion["MSC2871"] = "org.matrix.msc2871"; - UnstableApiVersion["MSC2931"] = "org.matrix.msc2931"; - UnstableApiVersion["MSC2974"] = "org.matrix.msc2974"; - UnstableApiVersion["MSC2876"] = "org.matrix.msc2876"; - UnstableApiVersion["MSC3819"] = "org.matrix.msc3819"; - UnstableApiVersion["MSC3846"] = "town.robin.msc3846"; - UnstableApiVersion["MSC3869"] = "org.matrix.msc3869"; - UnstableApiVersion["MSC3973"] = "org.matrix.msc3973"; -})(UnstableApiVersion || (exports.UnstableApiVersion = UnstableApiVersion = {})); - -var CurrentApiVersions = [MatrixApiVersion.Prerelease1, MatrixApiVersion.Prerelease2, //MatrixApiVersion.V010, -UnstableApiVersion.MSC2762, UnstableApiVersion.MSC2871, UnstableApiVersion.MSC2931, UnstableApiVersion.MSC2974, UnstableApiVersion.MSC2876, UnstableApiVersion.MSC3819, UnstableApiVersion.MSC3846, UnstableApiVersion.MSC3869, UnstableApiVersion.MSC3973]; -exports.CurrentApiVersions = CurrentApiVersions; -},{}],180:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.VideoConferenceCapabilities = exports.StickerpickerCapabilities = exports.MatrixCapabilities = void 0; -exports.getTimelineRoomIDFromCapability = getTimelineRoomIDFromCapability; -exports.isTimelineCapability = isTimelineCapability; -exports.isTimelineCapabilityFor = isTimelineCapabilityFor; - -/* - * Copyright 2020 - 2021 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var MatrixCapabilities; -exports.MatrixCapabilities = MatrixCapabilities; - -(function (MatrixCapabilities) { - MatrixCapabilities["Screenshots"] = "m.capability.screenshot"; - MatrixCapabilities["StickerSending"] = "m.sticker"; - MatrixCapabilities["AlwaysOnScreen"] = "m.always_on_screen"; - MatrixCapabilities["RequiresClient"] = "io.element.requires_client"; - MatrixCapabilities["MSC2931Navigate"] = "org.matrix.msc2931.navigate"; - MatrixCapabilities["MSC3846TurnServers"] = "town.robin.msc3846.turn_servers"; - MatrixCapabilities["MSC3973UserDirectorySearch"] = "org.matrix.msc3973.user_directory_search"; -})(MatrixCapabilities || (exports.MatrixCapabilities = MatrixCapabilities = {})); - -var StickerpickerCapabilities = [MatrixCapabilities.StickerSending]; -exports.StickerpickerCapabilities = StickerpickerCapabilities; -var VideoConferenceCapabilities = [MatrixCapabilities.AlwaysOnScreen]; -/** - * Determines if a capability is a capability for a timeline. - * @param {Capability} capability The capability to test. - * @returns {boolean} True if a timeline capability, false otherwise. - */ - -exports.VideoConferenceCapabilities = VideoConferenceCapabilities; - -function isTimelineCapability(capability) { - // TODO: Change when MSC2762 becomes stable. - return capability === null || capability === void 0 ? void 0 : capability.startsWith("org.matrix.msc2762.timeline:"); -} -/** - * Determines if a capability is a timeline capability for the given room. - * @param {Capability} capability The capability to test. - * @param {string | Symbols.AnyRoom} roomId The room ID, or `Symbols.AnyRoom` for that designation. - * @returns {boolean} True if a matching capability, false otherwise. - */ - - -function isTimelineCapabilityFor(capability, roomId) { - return capability === "org.matrix.msc2762.timeline:".concat(roomId); -} -/** - * Gets the room ID described by a timeline capability. - * @param {string} capability The capability to parse. - * @returns {string} The room ID. - */ - - -function getTimelineRoomIDFromCapability(capability) { - return capability.substring(capability.indexOf(":") + 1); -} -},{}],181:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],182:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],183:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.OpenIDRequestState = void 0; - -/* - * Copyright 2020 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var OpenIDRequestState; -exports.OpenIDRequestState = OpenIDRequestState; - -(function (OpenIDRequestState) { - OpenIDRequestState["Allowed"] = "allowed"; - OpenIDRequestState["Blocked"] = "blocked"; - OpenIDRequestState["PendingUserConfirmation"] = "request"; -})(OpenIDRequestState || (exports.OpenIDRequestState = OpenIDRequestState = {})); -},{}],184:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],185:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],186:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],187:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],188:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],189:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isErrorResponse = isErrorResponse; - -/* - * Copyright 2020 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function isErrorResponse(responseData) { - if ("error" in responseData) { - var err = responseData; - return !!err.error.message; - } - - return false; -} -},{}],190:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],191:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],192:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.ModalButtonKind = void 0; - -/* - * Copyright 2020 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var ModalButtonKind; -exports.ModalButtonKind = ModalButtonKind; - -(function (ModalButtonKind) { - ModalButtonKind["Primary"] = "m.primary"; - ModalButtonKind["Secondary"] = "m.secondary"; - ModalButtonKind["Warning"] = "m.warning"; - ModalButtonKind["Danger"] = "m.danger"; - ModalButtonKind["Link"] = "m.link"; -})(ModalButtonKind || (exports.ModalButtonKind = ModalButtonKind = {})); -},{}],193:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.BuiltInModalButtonID = void 0; - -/* - * Copyright 2020 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var BuiltInModalButtonID; -exports.BuiltInModalButtonID = BuiltInModalButtonID; - -(function (BuiltInModalButtonID) { - BuiltInModalButtonID["Close"] = "m.close"; -})(BuiltInModalButtonID || (exports.BuiltInModalButtonID = BuiltInModalButtonID = {})); -},{}],194:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],195:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],196:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],197:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],198:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],199:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],200:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],201:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],202:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],203:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],204:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],205:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],206:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],207:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.WidgetApiToWidgetAction = exports.WidgetApiFromWidgetAction = void 0; - -/* - * Copyright 2020 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var WidgetApiToWidgetAction; -exports.WidgetApiToWidgetAction = WidgetApiToWidgetAction; - -(function (WidgetApiToWidgetAction) { - WidgetApiToWidgetAction["SupportedApiVersions"] = "supported_api_versions"; - WidgetApiToWidgetAction["Capabilities"] = "capabilities"; - WidgetApiToWidgetAction["NotifyCapabilities"] = "notify_capabilities"; - WidgetApiToWidgetAction["TakeScreenshot"] = "screenshot"; - WidgetApiToWidgetAction["UpdateVisibility"] = "visibility"; - WidgetApiToWidgetAction["OpenIDCredentials"] = "openid_credentials"; - WidgetApiToWidgetAction["WidgetConfig"] = "widget_config"; - WidgetApiToWidgetAction["CloseModalWidget"] = "close_modal"; - WidgetApiToWidgetAction["ButtonClicked"] = "button_clicked"; - WidgetApiToWidgetAction["SendEvent"] = "send_event"; - WidgetApiToWidgetAction["SendToDevice"] = "send_to_device"; - WidgetApiToWidgetAction["UpdateTurnServers"] = "update_turn_servers"; -})(WidgetApiToWidgetAction || (exports.WidgetApiToWidgetAction = WidgetApiToWidgetAction = {})); - -var WidgetApiFromWidgetAction; -exports.WidgetApiFromWidgetAction = WidgetApiFromWidgetAction; - -(function (WidgetApiFromWidgetAction) { - WidgetApiFromWidgetAction["SupportedApiVersions"] = "supported_api_versions"; - WidgetApiFromWidgetAction["ContentLoaded"] = "content_loaded"; - WidgetApiFromWidgetAction["SendSticker"] = "m.sticker"; - WidgetApiFromWidgetAction["UpdateAlwaysOnScreen"] = "set_always_on_screen"; - WidgetApiFromWidgetAction["GetOpenIDCredentials"] = "get_openid"; - WidgetApiFromWidgetAction["CloseModalWidget"] = "close_modal"; - WidgetApiFromWidgetAction["OpenModalWidget"] = "open_modal"; - WidgetApiFromWidgetAction["SetModalButtonEnabled"] = "set_button_enabled"; - WidgetApiFromWidgetAction["SendEvent"] = "send_event"; - WidgetApiFromWidgetAction["SendToDevice"] = "send_to_device"; - WidgetApiFromWidgetAction["WatchTurnServers"] = "watch_turn_servers"; - WidgetApiFromWidgetAction["UnwatchTurnServers"] = "unwatch_turn_servers"; - WidgetApiFromWidgetAction["MSC2876ReadEvents"] = "org.matrix.msc2876.read_events"; - WidgetApiFromWidgetAction["MSC2931Navigate"] = "org.matrix.msc2931.navigate"; - WidgetApiFromWidgetAction["MSC2974RenegotiateCapabilities"] = "org.matrix.msc2974.request_capabilities"; - WidgetApiFromWidgetAction["MSC3869ReadRelations"] = "org.matrix.msc3869.read_relations"; - WidgetApiFromWidgetAction["MSC3973UserDirectorySearch"] = "org.matrix.msc3973.user_directory_search"; -})(WidgetApiFromWidgetAction || (exports.WidgetApiFromWidgetAction = WidgetApiFromWidgetAction = {})); -},{}],208:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.WidgetApiDirection = void 0; -exports.invertedDirection = invertedDirection; - -/* - * Copyright 2020 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var WidgetApiDirection; -exports.WidgetApiDirection = WidgetApiDirection; - -(function (WidgetApiDirection) { - WidgetApiDirection["ToWidget"] = "toWidget"; - WidgetApiDirection["FromWidget"] = "fromWidget"; -})(WidgetApiDirection || (exports.WidgetApiDirection = WidgetApiDirection = {})); - -function invertedDirection(dir) { - if (dir === WidgetApiDirection.ToWidget) { - return WidgetApiDirection.FromWidget; - } else if (dir === WidgetApiDirection.FromWidget) { - return WidgetApiDirection.ToWidget; - } else { - throw new Error("Invalid direction"); - } -} -},{}],209:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],210:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.WidgetKind = void 0; - -/* - * Copyright 2020 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var WidgetKind; -exports.WidgetKind = WidgetKind; - -(function (WidgetKind) { - WidgetKind["Room"] = "room"; - WidgetKind["Account"] = "account"; - WidgetKind["Modal"] = "modal"; -})(WidgetKind || (exports.WidgetKind = WidgetKind = {})); -},{}],211:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.MatrixWidgetType = void 0; - -/* - * Copyright 2020 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var MatrixWidgetType; -exports.MatrixWidgetType = MatrixWidgetType; - -(function (MatrixWidgetType) { - MatrixWidgetType["Custom"] = "m.custom"; - MatrixWidgetType["JitsiMeet"] = "m.jitsi"; - MatrixWidgetType["Stickerpicker"] = "m.stickerpicker"; -})(MatrixWidgetType || (exports.MatrixWidgetType = MatrixWidgetType = {})); -},{}],212:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.Widget = void 0; - -var _utils = require("./validation/utils"); - -var _ = require(".."); - -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 the barest form of widget. - */ -var Widget = /*#__PURE__*/function () { - function Widget(definition) { - _classCallCheck(this, Widget); - - this.definition = definition; - if (!this.definition) throw new Error("Definition is required"); - (0, _utils.assertPresent)(definition, "id"); - (0, _utils.assertPresent)(definition, "creatorUserId"); - (0, _utils.assertPresent)(definition, "type"); - (0, _utils.assertPresent)(definition, "url"); - } - /** - * The user ID who created the widget. - */ - - - _createClass(Widget, [{ - key: "creatorUserId", - get: function get() { - return this.definition.creatorUserId; - } - /** - * The type of widget. - */ - - }, { - key: "type", - get: function get() { - return this.definition.type; - } - /** - * The ID of the widget. - */ - - }, { - key: "id", - get: function get() { - return this.definition.id; - } - /** - * The name of the widget, or null if not set. - */ - - }, { - key: "name", - get: function get() { - return this.definition.name || null; - } - /** - * The title for the widget, or null if not set. - */ - - }, { - key: "title", - get: function get() { - return this.rawData.title || null; - } - /** - * The templated URL for the widget. - */ - - }, { - key: "templateUrl", - get: function get() { - return this.definition.url; - } - /** - * The origin for this widget. - */ - - }, { - key: "origin", - get: function get() { - return new URL(this.templateUrl).origin; - } - /** - * Whether or not the client should wait for the iframe to load. Defaults - * to true. - */ - - }, { - key: "waitForIframeLoad", - get: function get() { - if (this.definition.waitForIframeLoad === false) return false; - if (this.definition.waitForIframeLoad === true) return true; - return true; // default true - } - /** - * The raw data for the widget. This will always be defined, though - * may be empty. - */ - - }, { - key: "rawData", - get: function get() { - return this.definition.data || {}; - } - /** - * Gets a complete widget URL for the client to render. - * @param {ITemplateParams} params The template parameters. - * @returns {string} A templated URL. - */ - - }, { - key: "getCompleteUrl", - value: function getCompleteUrl(params) { - return (0, _.runTemplate)(this.templateUrl, this.definition, params); - } - }]); - - return Widget; -}(); - -exports.Widget = Widget; -},{"..":178,"./validation/utils":216}],213:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.WidgetEventCapability = exports.EventKind = exports.EventDirection = 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; } - -/* - * Copyright 2020 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var EventKind; -exports.EventKind = EventKind; - -(function (EventKind) { - EventKind["Event"] = "event"; - EventKind["State"] = "state_event"; - EventKind["ToDevice"] = "to_device"; -})(EventKind || (exports.EventKind = EventKind = {})); - -var EventDirection; -exports.EventDirection = EventDirection; - -(function (EventDirection) { - EventDirection["Send"] = "send"; - EventDirection["Receive"] = "receive"; -})(EventDirection || (exports.EventDirection = EventDirection = {})); - -var WidgetEventCapability = /*#__PURE__*/function () { - function WidgetEventCapability(direction, eventType, kind, keyStr, raw) { - _classCallCheck(this, WidgetEventCapability); - - this.direction = direction; - this.eventType = eventType; - this.kind = kind; - this.keyStr = keyStr; - this.raw = raw; - } - - _createClass(WidgetEventCapability, [{ - key: "matchesAsStateEvent", - value: function matchesAsStateEvent(direction, eventType, stateKey) { - if (this.kind !== EventKind.State) return false; // not a state event - - if (this.direction !== direction) return false; // direction mismatch - - if (this.eventType !== eventType) return false; // event type mismatch - - if (this.keyStr === null) return true; // all state keys are allowed - - if (this.keyStr === stateKey) return true; // this state key is allowed - // Default not allowed - - return false; - } - }, { - key: "matchesAsToDeviceEvent", - value: function matchesAsToDeviceEvent(direction, eventType) { - if (this.kind !== EventKind.ToDevice) return false; // not a to-device event - - if (this.direction !== direction) return false; // direction mismatch - - if (this.eventType !== eventType) return false; // event type mismatch - // Checks passed, the event is allowed - - return true; - } - }, { - key: "matchesAsRoomEvent", - value: function matchesAsRoomEvent(direction, eventType) { - var msgtype = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; - if (this.kind !== EventKind.Event) return false; // not a room event - - if (this.direction !== direction) return false; // direction mismatch - - if (this.eventType !== eventType) return false; // event type mismatch - - if (this.eventType === "m.room.message") { - if (this.keyStr === null) return true; // all message types are allowed - - if (this.keyStr === msgtype) return true; // this message type is allowed - } else { - return true; // already passed the check for if the event is allowed - } // Default not allowed - - - return false; - } - }], [{ - key: "forStateEvent", - value: function forStateEvent(direction, eventType, stateKey) { - // TODO: Enable support for m.* namespace once the MSC lands. - // https://github.com/matrix-org/matrix-widget-api/issues/22 - eventType = eventType.replace(/#/g, '\\#'); - stateKey = stateKey !== null && stateKey !== undefined ? "#".concat(stateKey) : ''; - var str = "org.matrix.msc2762.".concat(direction, ".state_event:").concat(eventType).concat(stateKey); // cheat by sending it through the processor - - return WidgetEventCapability.findEventCapabilities([str])[0]; - } - }, { - key: "forToDeviceEvent", - value: function forToDeviceEvent(direction, eventType) { - // TODO: Enable support for m.* namespace once the MSC lands. - // https://github.com/matrix-org/matrix-widget-api/issues/56 - var str = "org.matrix.msc3819.".concat(direction, ".to_device:").concat(eventType); // cheat by sending it through the processor - - return WidgetEventCapability.findEventCapabilities([str])[0]; - } - }, { - key: "forRoomEvent", - value: function forRoomEvent(direction, eventType) { - // TODO: Enable support for m.* namespace once the MSC lands. - // https://github.com/matrix-org/matrix-widget-api/issues/22 - var str = "org.matrix.msc2762.".concat(direction, ".event:").concat(eventType); // cheat by sending it through the processor - - return WidgetEventCapability.findEventCapabilities([str])[0]; - } - }, { - key: "forRoomMessageEvent", - value: function forRoomMessageEvent(direction, msgtype) { - // TODO: Enable support for m.* namespace once the MSC lands. - // https://github.com/matrix-org/matrix-widget-api/issues/22 - msgtype = msgtype === null || msgtype === undefined ? '' : msgtype; - var str = "org.matrix.msc2762.".concat(direction, ".event:m.room.message#").concat(msgtype); // cheat by sending it through the processor - - return WidgetEventCapability.findEventCapabilities([str])[0]; - } - /** - * Parses a capabilities request to find all the event capability requests. - * @param {Iterable} capabilities The capabilities requested/to parse. - * @returns {WidgetEventCapability[]} An array of event capability requests. May be empty, but never null. - */ - - }, { - key: "findEventCapabilities", - value: function findEventCapabilities(capabilities) { - var parsed = []; - - var _iterator = _createForOfIteratorHelper(capabilities), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var cap = _step.value; - var _direction = null; - var eventSegment = void 0; - var _kind = null; // TODO: Enable support for m.* namespace once the MSCs land. - // https://github.com/matrix-org/matrix-widget-api/issues/22 - // https://github.com/matrix-org/matrix-widget-api/issues/56 - - if (cap.startsWith("org.matrix.msc2762.send.event:")) { - _direction = EventDirection.Send; - _kind = EventKind.Event; - eventSegment = cap.substring("org.matrix.msc2762.send.event:".length); - } else if (cap.startsWith("org.matrix.msc2762.send.state_event:")) { - _direction = EventDirection.Send; - _kind = EventKind.State; - eventSegment = cap.substring("org.matrix.msc2762.send.state_event:".length); - } else if (cap.startsWith("org.matrix.msc3819.send.to_device:")) { - _direction = EventDirection.Send; - _kind = EventKind.ToDevice; - eventSegment = cap.substring("org.matrix.msc3819.send.to_device:".length); - } else if (cap.startsWith("org.matrix.msc2762.receive.event:")) { - _direction = EventDirection.Receive; - _kind = EventKind.Event; - eventSegment = cap.substring("org.matrix.msc2762.receive.event:".length); - } else if (cap.startsWith("org.matrix.msc2762.receive.state_event:")) { - _direction = EventDirection.Receive; - _kind = EventKind.State; - eventSegment = cap.substring("org.matrix.msc2762.receive.state_event:".length); - } else if (cap.startsWith("org.matrix.msc3819.receive.to_device:")) { - _direction = EventDirection.Receive; - _kind = EventKind.ToDevice; - eventSegment = cap.substring("org.matrix.msc3819.receive.to_device:".length); - } - - if (_direction === null || _kind === null || eventSegment === undefined) continue; // The capability uses `#` as a separator between event type and state key/msgtype, - // so we split on that. However, a # is also valid in either one of those so we - // join accordingly. - // Eg: `m.room.message##m.text` is "m.room.message" event with msgtype "#m.text". - - var expectingKeyStr = eventSegment.startsWith("m.room.message#") || _kind === EventKind.State; - - var _keyStr = null; - - if (eventSegment.includes('#') && expectingKeyStr) { - // Dev note: regex is difficult to write, so instead the rules are manually written - // out. This is probably just as understandable as a boring regex though, so win-win? - // Test cases: - // str eventSegment keyStr - // ------------------------------------------------------------- - // m.room.message# m.room.message - // m.room.message#test m.room.message test - // m.room.message\# m.room.message# test - // m.room.message##test m.room.message #test - // m.room.message\##test m.room.message# test - // m.room.message\\##test m.room.message\# test - // m.room.message\\###test m.room.message\# #test - // First step: explode the string - var parts = eventSegment.split('#'); // To form the eventSegment, we'll keep finding parts of the exploded string until - // there's one that doesn't end with the escape character (\). We'll then join those - // segments together with the exploding character. We have to remember to consume the - // escape character as well. - - var idx = parts.findIndex(function (p) { - return !p.endsWith("\\"); - }); - eventSegment = parts.slice(0, idx + 1).map(function (p) { - return p.endsWith('\\') ? p.substring(0, p.length - 1) : p; - }).join('#'); // The keyStr is whatever is left over. - - _keyStr = parts.slice(idx + 1).join('#'); - } - - parsed.push(new WidgetEventCapability(_direction, eventSegment, _kind, _keyStr, cap)); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - return parsed; - } - }]); - - return WidgetEventCapability; -}(); - -exports.WidgetEventCapability = WidgetEventCapability; -},{}],214:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.WidgetParser = void 0; - -var _Widget = require("./Widget"); - -var _url = require("./validation/url"); - -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; } - -var WidgetParser = /*#__PURE__*/function () { - function WidgetParser() {// private constructor because this is a util class - - _classCallCheck(this, WidgetParser); - } - /** - * Parses widgets from the "m.widgets" account data event. This will always - * return an array, though may be empty if no valid widgets were found. - * @param {IAccountDataWidgets} content The content of the "m.widgets" account data. - * @returns {Widget[]} The widgets in account data, or an empty array. - */ - - - _createClass(WidgetParser, null, [{ - key: "parseAccountData", - value: function parseAccountData(content) { - if (!content) return []; - var result = []; - - for (var _i = 0, _Object$keys = Object.keys(content); _i < _Object$keys.length; _i++) { - var _widgetId = _Object$keys[_i]; - var roughWidget = content[_widgetId]; - if (!roughWidget) continue; - if (roughWidget.type !== "m.widget" && roughWidget.type !== "im.vector.modular.widgets") continue; - if (!roughWidget.sender) continue; - var probableWidgetId = roughWidget.state_key || roughWidget.id; - if (probableWidgetId !== _widgetId) continue; - var asStateEvent = { - content: roughWidget.content, - sender: roughWidget.sender, - type: "m.widget", - state_key: _widgetId, - event_id: "$example", - room_id: "!example", - origin_server_ts: 1 - }; - var widget = WidgetParser.parseRoomWidget(asStateEvent); - if (widget) result.push(widget); - } - - return result; - } - /** - * Parses all the widgets possible in the given array. This will always return - * an array, though may be empty if no widgets could be parsed. - * @param {IStateEvent[]} currentState The room state to parse. - * @returns {Widget[]} The widgets in the state, or an empty array. - */ - - }, { - key: "parseWidgetsFromRoomState", - value: function parseWidgetsFromRoomState(currentState) { - if (!currentState) return []; - var result = []; - - var _iterator = _createForOfIteratorHelper(currentState), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var state = _step.value; - var widget = WidgetParser.parseRoomWidget(state); - if (widget) result.push(widget); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - return result; - } - /** - * Parses a state event into a widget. If the state event does not represent - * a widget (wrong event type, invalid widget, etc) then null is returned. - * @param {IStateEvent} stateEvent The state event. - * @returns {Widget|null} The widget, or null if invalid - */ - - }, { - key: "parseRoomWidget", - value: function parseRoomWidget(stateEvent) { - if (!stateEvent) return null; // TODO: [Legacy] Remove legacy support - - if (stateEvent.type !== "m.widget" && stateEvent.type !== "im.vector.modular.widgets") { - return null; - } // Dev note: Throughout this function we have null safety to ensure that - // if the caller did not supply something useful that we don't error. This - // is done against the requirements of the interface because not everyone - // will have an interface to validate against. - - - var content = stateEvent.content || {}; // Form our best approximation of a widget with the information we have - - var estimatedWidget = { - id: stateEvent.state_key, - creatorUserId: content['creatorUserId'] || stateEvent.sender, - name: content['name'], - type: content['type'], - url: content['url'], - waitForIframeLoad: content['waitForIframeLoad'], - data: content['data'] - }; // Finally, process that widget - - return WidgetParser.processEstimatedWidget(estimatedWidget); - } - }, { - key: "processEstimatedWidget", - value: function processEstimatedWidget(widget) { - // Validate that the widget has the best chance of passing as a widget - if (!widget.id || !widget.creatorUserId || !widget.type) { - return null; - } - - if (!(0, _url.isValidUrl)(widget.url)) { - return null; - } // TODO: Validate data for known widget types - - - return new _Widget.Widget(widget); - } - }]); - - return WidgetParser; -}(); - -exports.WidgetParser = WidgetParser; -},{"./Widget":212,"./validation/url":215}],215:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isValidUrl = isValidUrl; - -/* - * Copyright 2020 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function isValidUrl(val) { - if (!val) return false; // easy: not valid if not present - - try { - var parsed = new URL(val); - - if (parsed.protocol !== "http" && parsed.protocol !== "https") { - return false; - } - - return true; - } catch (e) { - if (e instanceof TypeError) { - return false; - } - - throw e; - } -} -},{}],216:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.assertPresent = assertPresent; - -/* - * Copyright 2020 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function assertPresent(obj, key) { - if (!obj[key]) { - throw new Error("".concat(key, " is required")); - } -} -},{}],217:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.runTemplate = runTemplate; -exports.toString = toString; - -/* - * Copyright 2020, 2021 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function runTemplate(url, widget, params) { - // Always apply the supplied params over top of data to ensure the data can't lie about them. - var variables = Object.assign({}, widget.data, { - 'matrix_room_id': params.widgetRoomId || "", - 'matrix_user_id': params.currentUserId, - 'matrix_display_name': params.userDisplayName || params.currentUserId, - 'matrix_avatar_url': params.userHttpAvatarUrl || "", - 'matrix_widget_id': widget.id, - // TODO: Convert to stable (https://github.com/matrix-org/matrix-doc/pull/2873) - 'org.matrix.msc2873.client_id': params.clientId || "", - 'org.matrix.msc2873.client_theme': params.clientTheme || "", - 'org.matrix.msc2873.client_language': params.clientLanguage || "" - }); - var result = url; - - for (var _i = 0, _Object$keys = Object.keys(variables); _i < _Object$keys.length; _i++) { - var key = _Object$keys[_i]; - // Regex escape from https://stackoverflow.com/a/6969486/7037379 - var pattern = "$".concat(key).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string - - var rexp = new RegExp(pattern, 'g'); // This is technically not what we're supposed to do for a couple of reasons: - // 1. We are assuming that there won't later be a $key match after we replace a variable. - // 2. We are assuming that the variable is in a place where it can be escaped (eg: path or query string). - - result = result.replace(rexp, encodeURIComponent(toString(variables[key]))); - } - - return result; -} - -function toString(a) { - if (a === null || a === undefined) { - return "".concat(a); - } - - return String(a); -} -},{}],218:[function(require,module,exports){ -arguments[4][153][0].apply(exports,arguments) -},{"dup":153}],219:[function(require,module,exports){ -"use strict"; - -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.PostmessageTransport = void 0; - -var _events = require("events"); - -var _ = require(".."); - -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 ? Object.setPrototypeOf.bind() : 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.bind() : 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: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -/** - * Transport for the Widget API over postMessage. - */ -var PostmessageTransport = /*#__PURE__*/function (_EventEmitter) { - _inherits(PostmessageTransport, _EventEmitter); - - var _super = _createSuper(PostmessageTransport); - - function PostmessageTransport(sendDirection, initialWidgetId, transportWindow, inboundWindow) { - var _this; - - _classCallCheck(this, PostmessageTransport); - - _this = _super.call(this); - _this.sendDirection = sendDirection; - _this.initialWidgetId = initialWidgetId; - _this.transportWindow = transportWindow; - _this.inboundWindow = inboundWindow; - - _defineProperty(_assertThisInitialized(_this), "strictOriginCheck", false); - - _defineProperty(_assertThisInitialized(_this), "targetOrigin", "*"); - - _defineProperty(_assertThisInitialized(_this), "timeoutSeconds", 10); - - _defineProperty(_assertThisInitialized(_this), "_ready", false); - - _defineProperty(_assertThisInitialized(_this), "_widgetId", null); - - _defineProperty(_assertThisInitialized(_this), "outboundRequests", new Map()); - - _defineProperty(_assertThisInitialized(_this), "stopController", new AbortController()); - - _this._widgetId = initialWidgetId; - return _this; - } - - _createClass(PostmessageTransport, [{ - key: "ready", - get: function get() { - return this._ready; - } - }, { - key: "widgetId", - get: function get() { - return this._widgetId || null; - } - }, { - key: "nextRequestId", - get: function get() { - var idBase = "widgetapi-".concat(Date.now()); - var index = 0; - var id = idBase; - - while (this.outboundRequests.has(id)) { - id = "".concat(idBase, "-").concat(index++); - } // reserve the ID - - - this.outboundRequests.set(id, null); - return id; - } - }, { - key: "sendInternal", - value: function sendInternal(message) { - console.log("[PostmessageTransport] Sending object to ".concat(this.targetOrigin, ": "), message); - this.transportWindow.postMessage(message, this.targetOrigin); - } - }, { - key: "reply", - value: function reply(request, responseData) { - return this.sendInternal(_objectSpread(_objectSpread({}, request), {}, { - response: responseData - })); - } - }, { - key: "send", - value: function send(action, data) { - return this.sendComplete(action, data).then(function (r) { - return r.response; - }); - } - }, { - key: "sendComplete", - value: function sendComplete(action, data) { - var _this2 = this; - - if (!this.ready || !this.widgetId) { - return Promise.reject(new Error("Not ready or unknown widget ID")); - } - - var request = { - api: this.sendDirection, - widgetId: this.widgetId, - requestId: this.nextRequestId, - action: action, - data: data - }; - - if (action === _.WidgetApiToWidgetAction.UpdateVisibility) { - request['visible'] = data['visible']; - } - - return new Promise(function (prResolve, prReject) { - var resolve = function resolve(response) { - cleanUp(); - prResolve(response); - }; - - var reject = function reject(err) { - cleanUp(); - prReject(err); - }; - - var timerId = setTimeout(function () { - return reject(new Error("Request timed out")); - }, (_this2.timeoutSeconds || 1) * 1000); - - var onStop = function onStop() { - return reject(new Error("Transport stopped")); - }; - - _this2.stopController.signal.addEventListener("abort", onStop); - - var cleanUp = function cleanUp() { - _this2.outboundRequests["delete"](request.requestId); - - clearTimeout(timerId); - - _this2.stopController.signal.removeEventListener("abort", onStop); - }; - - _this2.outboundRequests.set(request.requestId, { - request: request, - resolve: resolve, - reject: reject - }); - - _this2.sendInternal(request); - }); - } - }, { - key: "start", - value: function start() { - var _this3 = this; - - this.inboundWindow.addEventListener("message", function (ev) { - _this3.handleMessage(ev); - }); - this._ready = true; - } - }, { - key: "stop", - value: function stop() { - this._ready = false; - this.stopController.abort(); - } - }, { - key: "handleMessage", - value: function handleMessage(ev) { - if (this.stopController.signal.aborted) return; - if (!ev.data) return; // invalid event - - if (this.strictOriginCheck && ev.origin !== window.origin) return; // bad origin - // treat the message as a response first, then downgrade to a request - - var response = ev.data; - if (!response.action || !response.requestId || !response.widgetId) return; // invalid request/response - - if (!response.response) { - // it's a request - var request = response; - if (request.api !== (0, _.invertedDirection)(this.sendDirection)) return; // wrong direction - - this.handleRequest(request); - } else { - // it's a response - if (response.api !== this.sendDirection) return; // wrong direction - - this.handleResponse(response); - } - } - }, { - key: "handleRequest", - value: function handleRequest(request) { - if (this.widgetId) { - if (this.widgetId !== request.widgetId) return; // wrong widget - } else { - this._widgetId = request.widgetId; - } - - this.emit("message", new CustomEvent("message", { - detail: request - })); - } - }, { - key: "handleResponse", - value: function handleResponse(response) { - if (response.widgetId !== this.widgetId) return; // wrong widget - - var req = this.outboundRequests.get(response.requestId); - if (!req) return; // response to an unknown request - - if ((0, _.isErrorResponse)(response.response)) { - var _err = response.response; - req.reject(new Error(_err.error.message)); - } else { - req.resolve(response); - } - } - }]); - - return PostmessageTransport; -}(_events.EventEmitter); - -exports.PostmessageTransport = PostmessageTransport; -},{"..":178,"events":105}],220:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.SimpleObservable = 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: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -/* - * Copyright 2020 The Matrix.org Foundation C.I.C. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var SimpleObservable = /*#__PURE__*/function () { - function SimpleObservable(initialFn) { - _classCallCheck(this, SimpleObservable); - - _defineProperty(this, "listeners", []); - - if (initialFn) this.listeners.push(initialFn); - } - - _createClass(SimpleObservable, [{ - key: "onUpdate", - value: function onUpdate(fn) { - this.listeners.push(fn); - } - }, { - key: "update", - value: function update(val) { - var _iterator = _createForOfIteratorHelper(this.listeners), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var listener = _step.value; - listener(val); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - } - }, { - key: "close", - value: function close() { - this.listeners = []; // reset - } - }]); - - return SimpleObservable; -}(); - -exports.SimpleObservable = SimpleObservable; -},{}],221:[function(require,module,exports){ -'use strict' -var inherits = require('inherits') -var HashBase = require('hash-base') -var Buffer = require('safe-buffer').Buffer - -var ARRAY16 = new Array(16) - -function MD5 () { - HashBase.call(this, 64) - - // state - this._a = 0x67452301 - this._b = 0xefcdab89 - this._c = 0x98badcfe - this._d = 0x10325476 -} - -inherits(MD5, HashBase) - -MD5.prototype._update = function () { - var M = ARRAY16 - for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4) - - var a = this._a - var b = this._b - var c = this._c - var d = this._d - - a = fnF(a, b, c, d, M[0], 0xd76aa478, 7) - d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12) - c = fnF(c, d, a, b, M[2], 0x242070db, 17) - b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22) - a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7) - d = fnF(d, a, b, c, M[5], 0x4787c62a, 12) - c = fnF(c, d, a, b, M[6], 0xa8304613, 17) - b = fnF(b, c, d, a, M[7], 0xfd469501, 22) - a = fnF(a, b, c, d, M[8], 0x698098d8, 7) - d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12) - c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17) - b = fnF(b, c, d, a, M[11], 0x895cd7be, 22) - a = fnF(a, b, c, d, M[12], 0x6b901122, 7) - d = fnF(d, a, b, c, M[13], 0xfd987193, 12) - c = fnF(c, d, a, b, M[14], 0xa679438e, 17) - b = fnF(b, c, d, a, M[15], 0x49b40821, 22) - - a = fnG(a, b, c, d, M[1], 0xf61e2562, 5) - d = fnG(d, a, b, c, M[6], 0xc040b340, 9) - c = fnG(c, d, a, b, M[11], 0x265e5a51, 14) - b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20) - a = fnG(a, b, c, d, M[5], 0xd62f105d, 5) - d = fnG(d, a, b, c, M[10], 0x02441453, 9) - c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14) - b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20) - a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5) - d = fnG(d, a, b, c, M[14], 0xc33707d6, 9) - c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14) - b = fnG(b, c, d, a, M[8], 0x455a14ed, 20) - a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5) - d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9) - c = fnG(c, d, a, b, M[7], 0x676f02d9, 14) - b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20) - - a = fnH(a, b, c, d, M[5], 0xfffa3942, 4) - d = fnH(d, a, b, c, M[8], 0x8771f681, 11) - c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16) - b = fnH(b, c, d, a, M[14], 0xfde5380c, 23) - a = fnH(a, b, c, d, M[1], 0xa4beea44, 4) - d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11) - c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16) - b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23) - a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4) - d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11) - c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16) - b = fnH(b, c, d, a, M[6], 0x04881d05, 23) - a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4) - d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11) - c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16) - b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23) - - a = fnI(a, b, c, d, M[0], 0xf4292244, 6) - d = fnI(d, a, b, c, M[7], 0x432aff97, 10) - c = fnI(c, d, a, b, M[14], 0xab9423a7, 15) - b = fnI(b, c, d, a, M[5], 0xfc93a039, 21) - a = fnI(a, b, c, d, M[12], 0x655b59c3, 6) - d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10) - c = fnI(c, d, a, b, M[10], 0xffeff47d, 15) - b = fnI(b, c, d, a, M[1], 0x85845dd1, 21) - a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6) - d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10) - c = fnI(c, d, a, b, M[6], 0xa3014314, 15) - b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21) - a = fnI(a, b, c, d, M[4], 0xf7537e82, 6) - d = fnI(d, a, b, c, M[11], 0xbd3af235, 10) - c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15) - b = fnI(b, c, d, a, M[9], 0xeb86d391, 21) - - this._a = (this._a + a) | 0 - this._b = (this._b + b) | 0 - this._c = (this._c + c) | 0 - this._d = (this._d + d) | 0 -} - -MD5.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80 - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64) - this._update() - this._blockOffset = 0 - } - - this._block.fill(0, this._blockOffset, 56) - this._block.writeUInt32LE(this._length[0], 56) - this._block.writeUInt32LE(this._length[1], 60) - this._update() - - // produce result - var buffer = Buffer.allocUnsafe(16) - buffer.writeInt32LE(this._a, 0) - buffer.writeInt32LE(this._b, 4) - buffer.writeInt32LE(this._c, 8) - buffer.writeInt32LE(this._d, 12) - return buffer -} - -function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) -} - -function fnF (a, b, c, d, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 -} - -function fnG (a, b, c, d, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 -} - -function fnH (a, b, c, d, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 -} - -function fnI (a, b, c, d, m, k, s) { - return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 -} - -module.exports = MD5 - -},{"hash-base":116,"inherits":146,"safe-buffer":250}],222:[function(require,module,exports){ -var bn = require('bn.js'); -var brorand = require('brorand'); - -function MillerRabin(rand) { - this.rand = rand || new brorand.Rand(); -} -module.exports = MillerRabin; - -MillerRabin.create = function create(rand) { - return new MillerRabin(rand); -}; - -MillerRabin.prototype._randbelow = function _randbelow(n) { - var len = n.bitLength(); - var min_bytes = Math.ceil(len / 8); - - // Generage random bytes until a number less than n is found. - // This ensures that 0..n-1 have an equal probability of being selected. - do - var a = new bn(this.rand.generate(min_bytes)); - while (a.cmp(n) >= 0); - - return a; -}; - -MillerRabin.prototype._randrange = function _randrange(start, stop) { - // Generate a random number greater than or equal to start and less than stop. - var size = stop.sub(start); - return start.add(this._randbelow(size)); -}; - -MillerRabin.prototype.test = function test(n, k, cb) { - var len = n.bitLength(); - var red = bn.mont(n); - var rone = new bn(1).toRed(red); - - if (!k) - k = Math.max(1, (len / 48) | 0); - - // Find d and s, (n - 1) = (2 ^ s) * d; - var n1 = n.subn(1); - for (var s = 0; !n1.testn(s); s++) {} - var d = n.shrn(s); - - var rn1 = n1.toRed(red); - - var prime = true; - for (; k > 0; k--) { - var a = this._randrange(new bn(2), n1); - if (cb) - cb(a); - - var x = a.toRed(red).redPow(d); - if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) - continue; - - for (var i = 1; i < s; i++) { - x = x.redSqr(); - - if (x.cmp(rone) === 0) - return false; - if (x.cmp(rn1) === 0) - break; - } - - if (i === s) - return false; - } - - return prime; -}; - -MillerRabin.prototype.getDivisor = function getDivisor(n, k) { - var len = n.bitLength(); - var red = bn.mont(n); - var rone = new bn(1).toRed(red); - - if (!k) - k = Math.max(1, (len / 48) | 0); - - // Find d and s, (n - 1) = (2 ^ s) * d; - var n1 = n.subn(1); - for (var s = 0; !n1.testn(s); s++) {} - var d = n.shrn(s); - - var rn1 = n1.toRed(red); - - for (; k > 0; k--) { - var a = this._randrange(new bn(2), n1); - - var g = n.gcd(a); - if (g.cmpn(1) !== 0) - return g; - - var x = a.toRed(red).redPow(d); - if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) - continue; - - for (var i = 1; i < s; i++) { - x = x.redSqr(); - - if (x.cmp(rone) === 0) - return x.fromRed().subn(1).gcd(n); - if (x.cmp(rn1) === 0) - break; - } - - if (i === s) { - x = x.redSqr(); - return x.fromRed().subn(1).gcd(n); - } - } - - return false; -}; - -},{"bn.js":18,"brorand":19}],223:[function(require,module,exports){ -module.exports = assert; - -function assert(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); -} - -assert.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); -}; - -},{}],224:[function(require,module,exports){ -'use strict'; - -var utils = exports; - -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg !== 'string') { - for (var i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; - return res; - } - if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (var i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } else { - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - var hi = c >> 8; - var lo = c & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); - } - } - return res; -} -utils.toArray = toArray; - -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; -} -utils.zero2 = zero2; - -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; -} -utils.toHex = toHex; - -utils.encode = function encode(arr, enc) { - if (enc === 'hex') - return toHex(arr); - else - return arr; -}; - -},{}],225:[function(require,module,exports){ -'use strict'; -const retry = require('retry'); - -const networkErrorMsgs = [ - 'Failed to fetch', // Chrome - 'NetworkError when attempting to fetch resource.', // Firefox - 'The Internet connection appears to be offline.', // Safari - 'Network request failed' // `cross-fetch` -]; - -class AbortError 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; - } -} - -const decorateErrorWithCounts = (error, attemptNumber, options) => { - // Minus 1 from attemptNumber because the first attempt does not count as a retry - const retriesLeft = options.retries - (attemptNumber - 1); - - error.attemptNumber = attemptNumber; - error.retriesLeft = retriesLeft; - return error; -}; - -const isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage); - -const pRetry = (input, options) => new Promise((resolve, reject) => { - options = { - onFailedAttempt: () => {}, - retries: 10, - ...options - }; - - const operation = retry.operation(options); - - operation.attempt(async attemptNumber => { - try { - resolve(await input(attemptNumber)); - } catch (error) { - if (!(error instanceof Error)) { - reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); - return; - } - - if (error instanceof AbortError) { - operation.stop(); - reject(error.originalError); - } else if (error instanceof TypeError && !isNetworkError(error.message)) { - operation.stop(); - reject(error); - } else { - decorateErrorWithCounts(error, attemptNumber, options); - - try { - await options.onFailedAttempt(error); - } catch (error) { - reject(error); - return; - } - - if (!operation.retry(error)) { - reject(operation.mainError()); - } - } - } - }); -}); - -module.exports = pRetry; -// TODO: remove this in the next major version -module.exports.default = pRetry; - -module.exports.AbortError = AbortError; - -},{"retry":246}],226:[function(require,module,exports){ -module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb", -"2.16.840.1.101.3.4.1.2": "aes-128-cbc", -"2.16.840.1.101.3.4.1.3": "aes-128-ofb", -"2.16.840.1.101.3.4.1.4": "aes-128-cfb", -"2.16.840.1.101.3.4.1.21": "aes-192-ecb", -"2.16.840.1.101.3.4.1.22": "aes-192-cbc", -"2.16.840.1.101.3.4.1.23": "aes-192-ofb", -"2.16.840.1.101.3.4.1.24": "aes-192-cfb", -"2.16.840.1.101.3.4.1.41": "aes-256-ecb", -"2.16.840.1.101.3.4.1.42": "aes-256-cbc", -"2.16.840.1.101.3.4.1.43": "aes-256-ofb", -"2.16.840.1.101.3.4.1.44": "aes-256-cfb" -} -},{}],227:[function(require,module,exports){ -// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js -// Fedor, you are amazing. -'use strict' - -var asn1 = require('asn1.js') - -exports.certificate = require('./certificate') - -var RSAPrivateKey = asn1.define('RSAPrivateKey', function () { - this.seq().obj( - this.key('version').int(), - this.key('modulus').int(), - this.key('publicExponent').int(), - this.key('privateExponent').int(), - this.key('prime1').int(), - this.key('prime2').int(), - this.key('exponent1').int(), - this.key('exponent2').int(), - this.key('coefficient').int() - ) -}) -exports.RSAPrivateKey = RSAPrivateKey - -var RSAPublicKey = asn1.define('RSAPublicKey', function () { - this.seq().obj( - this.key('modulus').int(), - this.key('publicExponent').int() - ) -}) -exports.RSAPublicKey = RSAPublicKey - -var PublicKey = asn1.define('SubjectPublicKeyInfo', function () { - this.seq().obj( - this.key('algorithm').use(AlgorithmIdentifier), - this.key('subjectPublicKey').bitstr() - ) -}) -exports.PublicKey = PublicKey - -var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () { - this.seq().obj( - this.key('algorithm').objid(), - this.key('none').null_().optional(), - this.key('curve').objid().optional(), - this.key('params').seq().obj( - this.key('p').int(), - this.key('q').int(), - this.key('g').int() - ).optional() - ) -}) - -var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () { - this.seq().obj( - this.key('version').int(), - this.key('algorithm').use(AlgorithmIdentifier), - this.key('subjectPrivateKey').octstr() - ) -}) -exports.PrivateKey = PrivateKeyInfo -var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () { - this.seq().obj( - this.key('algorithm').seq().obj( - this.key('id').objid(), - this.key('decrypt').seq().obj( - this.key('kde').seq().obj( - this.key('id').objid(), - this.key('kdeparams').seq().obj( - this.key('salt').octstr(), - this.key('iters').int() - ) - ), - this.key('cipher').seq().obj( - this.key('algo').objid(), - this.key('iv').octstr() - ) - ) - ), - this.key('subjectPrivateKey').octstr() - ) -}) - -exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo - -var DSAPrivateKey = asn1.define('DSAPrivateKey', function () { - this.seq().obj( - this.key('version').int(), - this.key('p').int(), - this.key('q').int(), - this.key('g').int(), - this.key('pub_key').int(), - this.key('priv_key').int() - ) -}) -exports.DSAPrivateKey = DSAPrivateKey - -exports.DSAparam = asn1.define('DSAparam', function () { - this.int() -}) - -var ECPrivateKey = asn1.define('ECPrivateKey', function () { - this.seq().obj( - this.key('version').int(), - this.key('privateKey').octstr(), - this.key('parameters').optional().explicit(0).use(ECParameters), - this.key('publicKey').optional().explicit(1).bitstr() - ) -}) -exports.ECPrivateKey = ECPrivateKey - -var ECParameters = asn1.define('ECParameters', function () { - this.choice({ - namedCurve: this.objid() - }) -}) - -exports.signature = asn1.define('signature', function () { - this.seq().obj( - this.key('r').int(), - this.key('s').int() - ) -}) - -},{"./certificate":228,"asn1.js":2}],228:[function(require,module,exports){ -// from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js -// thanks to @Rantanen - -'use strict' - -var asn = require('asn1.js') - -var Time = asn.define('Time', function () { - this.choice({ - utcTime: this.utctime(), - generalTime: this.gentime() - }) -}) - -var AttributeTypeValue = asn.define('AttributeTypeValue', function () { - this.seq().obj( - this.key('type').objid(), - this.key('value').any() - ) -}) - -var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () { - this.seq().obj( - this.key('algorithm').objid(), - this.key('parameters').optional(), - this.key('curve').objid().optional() - ) -}) - -var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () { - this.seq().obj( - this.key('algorithm').use(AlgorithmIdentifier), - this.key('subjectPublicKey').bitstr() - ) -}) - -var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () { - this.setof(AttributeTypeValue) -}) - -var RDNSequence = asn.define('RDNSequence', function () { - this.seqof(RelativeDistinguishedName) -}) - -var Name = asn.define('Name', function () { - this.choice({ - rdnSequence: this.use(RDNSequence) - }) -}) - -var Validity = asn.define('Validity', function () { - this.seq().obj( - this.key('notBefore').use(Time), - this.key('notAfter').use(Time) - ) -}) - -var Extension = asn.define('Extension', function () { - this.seq().obj( - this.key('extnID').objid(), - this.key('critical').bool().def(false), - this.key('extnValue').octstr() - ) -}) - -var TBSCertificate = asn.define('TBSCertificate', function () { - this.seq().obj( - this.key('version').explicit(0).int().optional(), - this.key('serialNumber').int(), - this.key('signature').use(AlgorithmIdentifier), - this.key('issuer').use(Name), - this.key('validity').use(Validity), - this.key('subject').use(Name), - this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo), - this.key('issuerUniqueID').implicit(1).bitstr().optional(), - this.key('subjectUniqueID').implicit(2).bitstr().optional(), - this.key('extensions').explicit(3).seqof(Extension).optional() - ) -}) - -var X509Certificate = asn.define('X509Certificate', function () { - this.seq().obj( - this.key('tbsCertificate').use(TBSCertificate), - this.key('signatureAlgorithm').use(AlgorithmIdentifier), - this.key('signatureValue').bitstr() - ) -}) - -module.exports = X509Certificate - -},{"asn1.js":2}],229:[function(require,module,exports){ -// adapted from https://github.com/apatil/pemstrip -var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m -var startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m -var fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m -var evp = require('evp_bytestokey') -var ciphers = require('browserify-aes') -var Buffer = require('safe-buffer').Buffer -module.exports = function (okey, password) { - var key = okey.toString() - var match = key.match(findProc) - var decrypted - if (!match) { - var match2 = key.match(fullRegex) - decrypted = Buffer.from(match2[2].replace(/[\r\n]/g, ''), 'base64') - } else { - var suite = 'aes' + match[1] - var iv = Buffer.from(match[2], 'hex') - var cipherText = Buffer.from(match[3].replace(/[\r\n]/g, ''), 'base64') - var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key - var out = [] - var cipher = ciphers.createDecipheriv(suite, cipherKey, iv) - out.push(cipher.update(cipherText)) - out.push(cipher.final()) - decrypted = Buffer.concat(out) - } - var tag = key.match(startRegex)[1] - return { - tag: tag, - data: decrypted - } -} - -},{"browserify-aes":23,"evp_bytestokey":106,"safe-buffer":250}],230:[function(require,module,exports){ -var asn1 = require('./asn1') -var aesid = require('./aesid.json') -var fixProc = require('./fixProc') -var ciphers = require('browserify-aes') -var compat = require('pbkdf2') -var Buffer = require('safe-buffer').Buffer -module.exports = parseKeys - -function parseKeys (buffer) { - var password - if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) { - password = buffer.passphrase - buffer = buffer.key - } - if (typeof buffer === 'string') { - buffer = Buffer.from(buffer) - } - - var stripped = fixProc(buffer, password) - - var type = stripped.tag - var data = stripped.data - var subtype, ndata - switch (type) { - case 'CERTIFICATE': - ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo - // falls through - case 'PUBLIC KEY': - if (!ndata) { - ndata = asn1.PublicKey.decode(data, 'der') - } - subtype = ndata.algorithm.algorithm.join('.') - switch (subtype) { - case '1.2.840.113549.1.1.1': - return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der') - case '1.2.840.10045.2.1': - ndata.subjectPrivateKey = ndata.subjectPublicKey - return { - type: 'ec', - data: ndata - } - case '1.2.840.10040.4.1': - ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der') - return { - type: 'dsa', - data: ndata.algorithm.params - } - default: throw new Error('unknown key id ' + subtype) - } - // throw new Error('unknown key type ' + type) - case 'ENCRYPTED PRIVATE KEY': - data = asn1.EncryptedPrivateKey.decode(data, 'der') - data = decrypt(data, password) - // falls through - case 'PRIVATE KEY': - ndata = asn1.PrivateKey.decode(data, 'der') - subtype = ndata.algorithm.algorithm.join('.') - switch (subtype) { - case '1.2.840.113549.1.1.1': - return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der') - case '1.2.840.10045.2.1': - return { - curve: ndata.algorithm.curve, - privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey - } - case '1.2.840.10040.4.1': - ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der') - return { - type: 'dsa', - params: ndata.algorithm.params - } - default: throw new Error('unknown key id ' + subtype) - } - // throw new Error('unknown key type ' + type) - case 'RSA PUBLIC KEY': - return asn1.RSAPublicKey.decode(data, 'der') - case 'RSA PRIVATE KEY': - return asn1.RSAPrivateKey.decode(data, 'der') - case 'DSA PRIVATE KEY': - return { - type: 'dsa', - params: asn1.DSAPrivateKey.decode(data, 'der') - } - case 'EC PRIVATE KEY': - data = asn1.ECPrivateKey.decode(data, 'der') - return { - curve: data.parameters.value, - privateKey: data.privateKey - } - default: throw new Error('unknown key type ' + type) - } -} -parseKeys.signature = asn1.signature -function decrypt (data, password) { - var salt = data.algorithm.decrypt.kde.kdeparams.salt - var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10) - var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')] - var iv = data.algorithm.decrypt.cipher.iv - var cipherText = data.subjectPrivateKey - var keylen = parseInt(algo.split('-')[1], 10) / 8 - var key = compat.pbkdf2Sync(password, salt, iters, keylen, 'sha1') - var cipher = ciphers.createDecipheriv(algo, key, iv) - var out = [] - out.push(cipher.update(cipherText)) - out.push(cipher.final()) - return Buffer.concat(out) -} - -},{"./aesid.json":226,"./asn1":227,"./fixProc":229,"browserify-aes":23,"pbkdf2":231,"safe-buffer":250}],231:[function(require,module,exports){ -exports.pbkdf2 = require('./lib/async') -exports.pbkdf2Sync = require('./lib/sync') - -},{"./lib/async":232,"./lib/sync":235}],232:[function(require,module,exports){ -(function (global){(function (){ -var Buffer = require('safe-buffer').Buffer - -var checkParameters = require('./precondition') -var defaultEncoding = require('./default-encoding') -var sync = require('./sync') -var toBuffer = require('./to-buffer') - -var ZERO_BUF -var subtle = global.crypto && global.crypto.subtle -var toBrowser = { - sha: 'SHA-1', - 'sha-1': 'SHA-1', - sha1: 'SHA-1', - sha256: 'SHA-256', - 'sha-256': 'SHA-256', - sha384: 'SHA-384', - 'sha-384': 'SHA-384', - 'sha-512': 'SHA-512', - sha512: 'SHA-512' -} -var checks = [] -function checkNative (algo) { - if (global.process && !global.process.browser) { - return Promise.resolve(false) - } - if (!subtle || !subtle.importKey || !subtle.deriveBits) { - return Promise.resolve(false) - } - if (checks[algo] !== undefined) { - return checks[algo] - } - ZERO_BUF = ZERO_BUF || Buffer.alloc(8) - var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo) - .then(function () { - return true - }).catch(function () { - return false - }) - checks[algo] = prom - return prom -} -var nextTick -function getNextTick () { - if (nextTick) { - return nextTick - } - if (global.process && global.process.nextTick) { - nextTick = global.process.nextTick - } else if (global.queueMicrotask) { - nextTick = global.queueMicrotask - } else if (global.setImmediate) { - nextTick = global.setImmediate - } else { - nextTick = global.setTimeout - } - return nextTick -} -function browserPbkdf2 (password, salt, iterations, length, algo) { - return subtle.importKey( - 'raw', password, { name: 'PBKDF2' }, false, ['deriveBits'] - ).then(function (key) { - return subtle.deriveBits({ - name: 'PBKDF2', - salt: salt, - iterations: iterations, - hash: { - name: algo - } - }, key, length << 3) - }).then(function (res) { - return Buffer.from(res) - }) -} - -function resolvePromise (promise, callback) { - promise.then(function (out) { - getNextTick()(function () { - callback(null, out) - }) - }, function (e) { - getNextTick()(function () { - callback(e) - }) - }) -} -module.exports = function (password, salt, iterations, keylen, digest, callback) { - if (typeof digest === 'function') { - callback = digest - digest = undefined - } - - digest = digest || 'sha1' - var algo = toBrowser[digest.toLowerCase()] - - if (!algo || typeof global.Promise !== 'function') { - getNextTick()(function () { - var out - try { - out = sync(password, salt, iterations, keylen, digest) - } catch (e) { - return callback(e) - } - callback(null, out) - }) - return - } - - checkParameters(iterations, keylen) - password = toBuffer(password, defaultEncoding, 'Password') - salt = toBuffer(salt, defaultEncoding, 'Salt') - if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2') - - resolvePromise(checkNative(algo).then(function (resp) { - if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo) - - return sync(password, salt, iterations, keylen, digest) - }), callback) -} - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"./default-encoding":233,"./precondition":234,"./sync":235,"./to-buffer":236,"safe-buffer":250}],233:[function(require,module,exports){ -(function (process,global){(function (){ -var defaultEncoding -/* istanbul ignore next */ -if (global.process && global.process.browser) { - defaultEncoding = 'utf-8' -} else if (global.process && global.process.version) { - var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10) - - defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary' -} else { - defaultEncoding = 'utf-8' -} -module.exports = defaultEncoding - -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"_process":237}],234:[function(require,module,exports){ -var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs - -module.exports = function (iterations, keylen) { - if (typeof iterations !== 'number') { - throw new TypeError('Iterations not a number') - } - - if (iterations < 0) { - throw new TypeError('Bad iterations') - } - - if (typeof keylen !== 'number') { - throw new TypeError('Key length not a number') - } - - if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */ - throw new TypeError('Bad key length') - } -} - -},{}],235:[function(require,module,exports){ -var md5 = require('create-hash/md5') -var RIPEMD160 = require('ripemd160') -var sha = require('sha.js') -var Buffer = require('safe-buffer').Buffer - -var checkParameters = require('./precondition') -var defaultEncoding = require('./default-encoding') -var toBuffer = require('./to-buffer') - -var ZEROS = Buffer.alloc(128) -var sizes = { - md5: 16, - sha1: 20, - sha224: 28, - sha256: 32, - sha384: 48, - sha512: 64, - rmd160: 20, - ripemd160: 20 -} - -function Hmac (alg, key, saltLen) { - var hash = getDigest(alg) - var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 - - if (key.length > blocksize) { - key = hash(key) - } else if (key.length < blocksize) { - key = Buffer.concat([key, ZEROS], blocksize) - } - - var ipad = Buffer.allocUnsafe(blocksize + sizes[alg]) - var opad = Buffer.allocUnsafe(blocksize + sizes[alg]) - for (var i = 0; i < blocksize; i++) { - ipad[i] = key[i] ^ 0x36 - opad[i] = key[i] ^ 0x5C - } - - var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4) - ipad.copy(ipad1, 0, 0, blocksize) - this.ipad1 = ipad1 - this.ipad2 = ipad - this.opad = opad - this.alg = alg - this.blocksize = blocksize - this.hash = hash - this.size = sizes[alg] -} - -Hmac.prototype.run = function (data, ipad) { - data.copy(ipad, this.blocksize) - var h = this.hash(ipad) - h.copy(this.opad, this.blocksize) - return this.hash(this.opad) -} - -function getDigest (alg) { - function shaFunc (data) { - return sha(alg).update(data).digest() - } - function rmd160Func (data) { - return new RIPEMD160().update(data).digest() - } - - if (alg === 'rmd160' || alg === 'ripemd160') return rmd160Func - if (alg === 'md5') return md5 - return shaFunc -} - -function pbkdf2 (password, salt, iterations, keylen, digest) { - checkParameters(iterations, keylen) - password = toBuffer(password, defaultEncoding, 'Password') - salt = toBuffer(salt, defaultEncoding, 'Salt') - - digest = digest || 'sha1' - - var hmac = new Hmac(digest, password, salt.length) - - var DK = Buffer.allocUnsafe(keylen) - var block1 = Buffer.allocUnsafe(salt.length + 4) - salt.copy(block1, 0, 0, salt.length) - - var destPos = 0 - var hLen = sizes[digest] - var l = Math.ceil(keylen / hLen) - - for (var i = 1; i <= l; i++) { - block1.writeUInt32BE(i, salt.length) - - var T = hmac.run(block1, hmac.ipad1) - var U = T - - for (var j = 1; j < iterations; j++) { - U = hmac.run(U, hmac.ipad2) - for (var k = 0; k < hLen; k++) T[k] ^= U[k] - } - - T.copy(DK, destPos) - destPos += hLen - } - - return DK -} - -module.exports = pbkdf2 - -},{"./default-encoding":233,"./precondition":234,"./to-buffer":236,"create-hash/md5":75,"ripemd160":249,"safe-buffer":250,"sha.js":257}],236:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer - -module.exports = function (thing, encoding, name) { - if (Buffer.isBuffer(thing)) { - return thing - } else if (typeof thing === 'string') { - return Buffer.from(thing, encoding) - } else if (ArrayBuffer.isView(thing)) { - return Buffer.from(thing.buffer) - } else { - throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView') - } -} - -},{"safe-buffer":250}],237:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],238:[function(require,module,exports){ -exports.publicEncrypt = require('./publicEncrypt') -exports.privateDecrypt = require('./privateDecrypt') - -exports.privateEncrypt = function privateEncrypt (key, buf) { - return exports.publicEncrypt(key, buf, true) -} - -exports.publicDecrypt = function publicDecrypt (key, buf) { - return exports.privateDecrypt(key, buf, true) -} - -},{"./privateDecrypt":240,"./publicEncrypt":241}],239:[function(require,module,exports){ -var createHash = require('create-hash') -var Buffer = require('safe-buffer').Buffer - -module.exports = function (seed, len) { - var t = Buffer.alloc(0) - var i = 0 - var c - while (t.length < len) { - c = i2ops(i++) - t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()]) - } - return t.slice(0, len) -} - -function i2ops (c) { - var out = Buffer.allocUnsafe(4) - out.writeUInt32BE(c, 0) - return out -} - -},{"create-hash":74,"safe-buffer":250}],240:[function(require,module,exports){ -var parseKeys = require('parse-asn1') -var mgf = require('./mgf') -var xor = require('./xor') -var BN = require('bn.js') -var crt = require('browserify-rsa') -var createHash = require('create-hash') -var withPublic = require('./withPublic') -var Buffer = require('safe-buffer').Buffer - -module.exports = function privateDecrypt (privateKey, enc, reverse) { - var padding - if (privateKey.padding) { - padding = privateKey.padding - } else if (reverse) { - padding = 1 - } else { - padding = 4 - } - - var key = parseKeys(privateKey) - var k = key.modulus.byteLength() - if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0) { - throw new Error('decryption error') - } - var msg - if (reverse) { - msg = withPublic(new BN(enc), key) - } else { - msg = crt(enc, key) - } - var zBuffer = Buffer.alloc(k - msg.length) - msg = Buffer.concat([zBuffer, msg], k) - if (padding === 4) { - return oaep(key, msg) - } else if (padding === 1) { - return pkcs1(key, msg, reverse) - } else if (padding === 3) { - return msg - } else { - throw new Error('unknown padding') - } -} - -function oaep (key, msg) { - var k = key.modulus.byteLength() - var iHash = createHash('sha1').update(Buffer.alloc(0)).digest() - var hLen = iHash.length - if (msg[0] !== 0) { - throw new Error('decryption error') - } - var maskedSeed = msg.slice(1, hLen + 1) - var maskedDb = msg.slice(hLen + 1) - var seed = xor(maskedSeed, mgf(maskedDb, hLen)) - var db = xor(maskedDb, mgf(seed, k - hLen - 1)) - if (compare(iHash, db.slice(0, hLen))) { - throw new Error('decryption error') - } - var i = hLen - while (db[i] === 0) { - i++ - } - if (db[i++] !== 1) { - throw new Error('decryption error') - } - return db.slice(i) -} - -function pkcs1 (key, msg, reverse) { - var p1 = msg.slice(0, 2) - var i = 2 - var status = 0 - while (msg[i++] !== 0) { - if (i >= msg.length) { - status++ - break - } - } - var ps = msg.slice(2, i - 1) - - if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)) { - status++ - } - if (ps.length < 8) { - status++ - } - if (status) { - throw new Error('decryption error') - } - return msg.slice(i) -} -function compare (a, b) { - a = Buffer.from(a) - b = Buffer.from(b) - var dif = 0 - var len = a.length - if (a.length !== b.length) { - dif++ - len = Math.min(a.length, b.length) - } - var i = -1 - while (++i < len) { - dif += (a[i] ^ b[i]) - } - return dif -} - -},{"./mgf":239,"./withPublic":242,"./xor":243,"bn.js":18,"browserify-rsa":41,"create-hash":74,"parse-asn1":230,"safe-buffer":250}],241:[function(require,module,exports){ -var parseKeys = require('parse-asn1') -var randomBytes = require('randombytes') -var createHash = require('create-hash') -var mgf = require('./mgf') -var xor = require('./xor') -var BN = require('bn.js') -var withPublic = require('./withPublic') -var crt = require('browserify-rsa') -var Buffer = require('safe-buffer').Buffer - -module.exports = function publicEncrypt (publicKey, msg, reverse) { - var padding - if (publicKey.padding) { - padding = publicKey.padding - } else if (reverse) { - padding = 1 - } else { - padding = 4 - } - var key = parseKeys(publicKey) - var paddedMsg - if (padding === 4) { - paddedMsg = oaep(key, msg) - } else if (padding === 1) { - paddedMsg = pkcs1(key, msg, reverse) - } else if (padding === 3) { - paddedMsg = new BN(msg) - if (paddedMsg.cmp(key.modulus) >= 0) { - throw new Error('data too long for modulus') - } - } else { - throw new Error('unknown padding') - } - if (reverse) { - return crt(paddedMsg, key) - } else { - return withPublic(paddedMsg, key) - } -} - -function oaep (key, msg) { - var k = key.modulus.byteLength() - var mLen = msg.length - var iHash = createHash('sha1').update(Buffer.alloc(0)).digest() - var hLen = iHash.length - var hLen2 = 2 * hLen - if (mLen > k - hLen2 - 2) { - throw new Error('message too long') - } - var ps = Buffer.alloc(k - mLen - hLen2 - 2) - var dblen = k - hLen - 1 - var seed = randomBytes(hLen) - var maskedDb = xor(Buffer.concat([iHash, ps, Buffer.alloc(1, 1), msg], dblen), mgf(seed, dblen)) - var maskedSeed = xor(seed, mgf(maskedDb, hLen)) - return new BN(Buffer.concat([Buffer.alloc(1), maskedSeed, maskedDb], k)) -} -function pkcs1 (key, msg, reverse) { - var mLen = msg.length - var k = key.modulus.byteLength() - if (mLen > k - 11) { - throw new Error('message too long') - } - var ps - if (reverse) { - ps = Buffer.alloc(k - mLen - 3, 0xff) - } else { - ps = nonZero(k - mLen - 3) - } - return new BN(Buffer.concat([Buffer.from([0, reverse ? 1 : 2]), ps, Buffer.alloc(1), msg], k)) -} -function nonZero (len) { - var out = Buffer.allocUnsafe(len) - var i = 0 - var cache = randomBytes(len * 2) - var cur = 0 - var num - while (i < len) { - if (cur === cache.length) { - cache = randomBytes(len * 2) - cur = 0 - } - num = cache[cur++] - if (num) { - out[i++] = num - } - } - return out -} - -},{"./mgf":239,"./withPublic":242,"./xor":243,"bn.js":18,"browserify-rsa":41,"create-hash":74,"parse-asn1":230,"randombytes":244,"safe-buffer":250}],242:[function(require,module,exports){ -var BN = require('bn.js') -var Buffer = require('safe-buffer').Buffer - -function withPublic (paddedMsg, key) { - return Buffer.from(paddedMsg - .toRed(BN.mont(key.modulus)) - .redPow(new BN(key.publicExponent)) - .fromRed() - .toArray()) -} - -module.exports = withPublic - -},{"bn.js":18,"safe-buffer":250}],243:[function(require,module,exports){ -module.exports = function xor (a, b) { - var len = a.length - var i = -1 - while (++i < len) { - a[i] ^= b[i] - } - return a -} - -},{}],244:[function(require,module,exports){ -(function (process,global){(function (){ -'use strict' - -// limit of Crypto.getRandomValues() -// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues -var MAX_BYTES = 65536 - -// Node supports requesting up to this number of bytes -// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48 -var MAX_UINT32 = 4294967295 - -function oldBrowser () { - throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') -} - -var Buffer = require('safe-buffer').Buffer -var crypto = global.crypto || global.msCrypto - -if (crypto && crypto.getRandomValues) { - module.exports = randomBytes -} else { - module.exports = oldBrowser -} - -function randomBytes (size, cb) { - // phantomjs needs to throw - if (size > MAX_UINT32) throw new RangeError('requested too many random bytes') - - var bytes = Buffer.allocUnsafe(size) - - if (size > 0) { // getRandomValues fails on IE if size == 0 - if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues - // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues - for (var generated = 0; generated < size; generated += MAX_BYTES) { - // buffer.slice automatically checks if the end is past the end of - // the buffer so we don't have to here - crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES)) - } - } else { - crypto.getRandomValues(bytes) - } - } - - if (typeof cb === 'function') { - return process.nextTick(function () { - cb(null, bytes) - }) - } - - return bytes -} - -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"_process":237,"safe-buffer":250}],245:[function(require,module,exports){ -(function (process,global){(function (){ -'use strict' - -function oldBrowser () { - throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11') -} -var safeBuffer = require('safe-buffer') -var randombytes = require('randombytes') -var Buffer = safeBuffer.Buffer -var kBufferMaxLength = safeBuffer.kMaxLength -var crypto = global.crypto || global.msCrypto -var kMaxUint32 = Math.pow(2, 32) - 1 -function assertOffset (offset, length) { - if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare - throw new TypeError('offset must be a number') - } - - if (offset > kMaxUint32 || offset < 0) { - throw new TypeError('offset must be a uint32') - } - - if (offset > kBufferMaxLength || offset > length) { - throw new RangeError('offset out of range') - } -} - -function assertSize (size, offset, length) { - if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare - throw new TypeError('size must be a number') - } - - if (size > kMaxUint32 || size < 0) { - throw new TypeError('size must be a uint32') - } - - if (size + offset > length || size > kBufferMaxLength) { - throw new RangeError('buffer too small') - } -} -if ((crypto && crypto.getRandomValues) || !process.browser) { - exports.randomFill = randomFill - exports.randomFillSync = randomFillSync -} else { - exports.randomFill = oldBrowser - exports.randomFillSync = oldBrowser -} -function randomFill (buf, offset, size, cb) { - if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) { - throw new TypeError('"buf" argument must be a Buffer or Uint8Array') - } - - if (typeof offset === 'function') { - cb = offset - offset = 0 - size = buf.length - } else if (typeof size === 'function') { - cb = size - size = buf.length - offset - } else if (typeof cb !== 'function') { - throw new TypeError('"cb" argument must be a function') - } - assertOffset(offset, buf.length) - assertSize(size, offset, buf.length) - return actualFill(buf, offset, size, cb) -} - -function actualFill (buf, offset, size, cb) { - if (process.browser) { - var ourBuf = buf.buffer - var uint = new Uint8Array(ourBuf, offset, size) - crypto.getRandomValues(uint) - if (cb) { - process.nextTick(function () { - cb(null, buf) - }) - return - } - return buf - } - if (cb) { - randombytes(size, function (err, bytes) { - if (err) { - return cb(err) - } - bytes.copy(buf, offset) - cb(null, buf) - }) - return - } - var bytes = randombytes(size) - bytes.copy(buf, offset) - return buf -} -function randomFillSync (buf, offset, size) { - if (typeof offset === 'undefined') { - offset = 0 - } - if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) { - throw new TypeError('"buf" argument must be a Buffer or Uint8Array') - } - - assertOffset(offset, buf.length) - - if (size === undefined) size = buf.length - offset - - assertSize(size, offset, buf.length) - - return actualFill(buf, offset, size) -} - -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"_process":237,"randombytes":244,"safe-buffer":250}],246:[function(require,module,exports){ -module.exports = require('./lib/retry'); -},{"./lib/retry":247}],247:[function(require,module,exports){ -var RetryOperation = require('./retry_operation'); - -exports.operation = function(options) { - var timeouts = exports.timeouts(options); - return new RetryOperation(timeouts, { - forever: options && (options.forever || options.retries === Infinity), - unref: options && options.unref, - maxRetryTime: options && options.maxRetryTime - }); -}; - -exports.timeouts = function(options) { - if (options instanceof Array) { - return [].concat(options); - } - - var opts = { - retries: 10, - factor: 2, - minTimeout: 1 * 1000, - maxTimeout: Infinity, - randomize: false - }; - for (var key in options) { - opts[key] = options[key]; - } - - if (opts.minTimeout > opts.maxTimeout) { - throw new Error('minTimeout is greater than maxTimeout'); - } - - var timeouts = []; - for (var i = 0; i < opts.retries; i++) { - timeouts.push(this.createTimeout(i, opts)); - } - - if (options && options.forever && !timeouts.length) { - timeouts.push(this.createTimeout(i, opts)); - } - - // sort the array numerically ascending - timeouts.sort(function(a,b) { - return a - b; - }); - - return timeouts; -}; - -exports.createTimeout = function(attempt, opts) { - var random = (opts.randomize) - ? (Math.random() + 1) - : 1; - - var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); - timeout = Math.min(timeout, opts.maxTimeout); - - return timeout; -}; - -exports.wrap = function(obj, options, methods) { - if (options instanceof Array) { - methods = options; - options = null; - } - - if (!methods) { - methods = []; - for (var key in obj) { - if (typeof obj[key] === 'function') { - methods.push(key); - } - } - } - - for (var i = 0; i < methods.length; i++) { - var method = methods[i]; - var original = obj[method]; - - obj[method] = function retryWrapper(original) { - var op = exports.operation(options); - var args = Array.prototype.slice.call(arguments, 1); - var callback = args.pop(); - - args.push(function(err) { - if (op.retry(err)) { - return; - } - if (err) { - arguments[0] = op.mainError(); - } - callback.apply(this, arguments); - }); - - op.attempt(function() { - original.apply(obj, args); - }); - }.bind(obj, original); - obj[method].options = options; - } -}; - -},{"./retry_operation":248}],248:[function(require,module,exports){ -function RetryOperation(timeouts, options) { - // Compatibility for the old (timeouts, retryForever) signature - if (typeof options === 'boolean') { - options = { forever: options }; - } - - this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); - this._timeouts = timeouts; - this._options = options || {}; - this._maxRetryTime = options && options.maxRetryTime || Infinity; - this._fn = null; - this._errors = []; - this._attempts = 1; - this._operationTimeout = null; - this._operationTimeoutCb = null; - this._timeout = null; - this._operationStart = null; - this._timer = null; - - if (this._options.forever) { - this._cachedTimeouts = this._timeouts.slice(0); - } -} -module.exports = RetryOperation; - -RetryOperation.prototype.reset = function() { - this._attempts = 1; - this._timeouts = this._originalTimeouts.slice(0); -} - -RetryOperation.prototype.stop = function() { - if (this._timeout) { - clearTimeout(this._timeout); - } - if (this._timer) { - clearTimeout(this._timer); - } - - this._timeouts = []; - this._cachedTimeouts = null; -}; - -RetryOperation.prototype.retry = function(err) { - if (this._timeout) { - clearTimeout(this._timeout); - } - - if (!err) { - return false; - } - var currentTime = new Date().getTime(); - if (err && currentTime - this._operationStart >= this._maxRetryTime) { - this._errors.push(err); - this._errors.unshift(new Error('RetryOperation timeout occurred')); - return false; - } - - this._errors.push(err); - - var timeout = this._timeouts.shift(); - if (timeout === undefined) { - if (this._cachedTimeouts) { - // retry forever, only keep last error - this._errors.splice(0, this._errors.length - 1); - timeout = this._cachedTimeouts.slice(-1); - } else { - return false; - } - } - - var self = this; - this._timer = setTimeout(function() { - self._attempts++; - - if (self._operationTimeoutCb) { - self._timeout = setTimeout(function() { - self._operationTimeoutCb(self._attempts); - }, self._operationTimeout); - - if (self._options.unref) { - self._timeout.unref(); - } - } - - self._fn(self._attempts); - }, timeout); - - if (this._options.unref) { - this._timer.unref(); - } - - return true; -}; - -RetryOperation.prototype.attempt = function(fn, timeoutOps) { - this._fn = fn; - - if (timeoutOps) { - if (timeoutOps.timeout) { - this._operationTimeout = timeoutOps.timeout; - } - if (timeoutOps.cb) { - this._operationTimeoutCb = timeoutOps.cb; - } - } - - var self = this; - if (this._operationTimeoutCb) { - this._timeout = setTimeout(function() { - self._operationTimeoutCb(); - }, self._operationTimeout); - } - - this._operationStart = new Date().getTime(); - - this._fn(this._attempts); -}; - -RetryOperation.prototype.try = function(fn) { - console.log('Using RetryOperation.try() is deprecated'); - this.attempt(fn); -}; - -RetryOperation.prototype.start = function(fn) { - console.log('Using RetryOperation.start() is deprecated'); - this.attempt(fn); -}; - -RetryOperation.prototype.start = RetryOperation.prototype.try; - -RetryOperation.prototype.errors = function() { - return this._errors; -}; - -RetryOperation.prototype.attempts = function() { - return this._attempts; -}; - -RetryOperation.prototype.mainError = function() { - if (this._errors.length === 0) { - return null; - } - - var counts = {}; - var mainError = null; - var mainErrorCount = 0; - - for (var i = 0; i < this._errors.length; i++) { - var error = this._errors[i]; - var message = error.message; - var count = (counts[message] || 0) + 1; - - counts[message] = count; - - if (count >= mainErrorCount) { - mainError = error; - mainErrorCount = count; - } - } - - return mainError; -}; - -},{}],249:[function(require,module,exports){ -'use strict' -var Buffer = require('buffer').Buffer -var inherits = require('inherits') -var HashBase = require('hash-base') - -var ARRAY16 = new Array(16) - -var zl = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 -] - -var zr = [ - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 -] - -var sl = [ - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 -] - -var sr = [ - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 -] - -var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e] -var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000] - -function RIPEMD160 () { - HashBase.call(this, 64) - - // state - this._a = 0x67452301 - this._b = 0xefcdab89 - this._c = 0x98badcfe - this._d = 0x10325476 - this._e = 0xc3d2e1f0 -} - -inherits(RIPEMD160, HashBase) - -RIPEMD160.prototype._update = function () { - var words = ARRAY16 - for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4) - - var al = this._a | 0 - var bl = this._b | 0 - var cl = this._c | 0 - var dl = this._d | 0 - var el = this._e | 0 - - var ar = this._a | 0 - var br = this._b | 0 - var cr = this._c | 0 - var dr = this._d | 0 - var er = this._e | 0 - - // computation - for (var i = 0; i < 80; i += 1) { - var tl - var tr - if (i < 16) { - tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]) - tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]) - } else if (i < 32) { - tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]) - tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]) - } else if (i < 48) { - tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]) - tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]) - } else if (i < 64) { - tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]) - tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]) - } else { // if (i<80) { - tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]) - tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]) - } - - al = el - el = dl - dl = rotl(cl, 10) - cl = bl - bl = tl - - ar = er - er = dr - dr = rotl(cr, 10) - cr = br - br = tr - } - - // update state - var t = (this._b + cl + dr) | 0 - this._b = (this._c + dl + er) | 0 - this._c = (this._d + el + ar) | 0 - this._d = (this._e + al + br) | 0 - this._e = (this._a + bl + cr) | 0 - this._a = t -} - -RIPEMD160.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80 - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64) - this._update() - this._blockOffset = 0 - } - - this._block.fill(0, this._blockOffset, 56) - this._block.writeUInt32LE(this._length[0], 56) - this._block.writeUInt32LE(this._length[1], 60) - this._update() - - // produce result - var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20) - buffer.writeInt32LE(this._a, 0) - buffer.writeInt32LE(this._b, 4) - buffer.writeInt32LE(this._c, 8) - buffer.writeInt32LE(this._d, 12) - buffer.writeInt32LE(this._e, 16) - return buffer -} - -function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) -} - -function fn1 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 -} - -function fn2 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 -} - -function fn3 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 -} - -function fn4 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 -} - -function fn5 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 -} - -module.exports = RIPEMD160 - -},{"buffer":68,"hash-base":116,"inherits":146}],250:[function(require,module,exports){ -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.prototype = Object.create(Buffer.prototype) - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} - -},{"buffer":68}],251:[function(require,module,exports){ -(function (process){(function (){ -/* eslint-disable node/no-deprecated-api */ - -'use strict' - -var buffer = require('buffer') -var Buffer = buffer.Buffer - -var safer = {} - -var key - -for (key in buffer) { - if (!buffer.hasOwnProperty(key)) continue - if (key === 'SlowBuffer' || key === 'Buffer') continue - safer[key] = buffer[key] -} - -var Safer = safer.Buffer = {} -for (key in Buffer) { - if (!Buffer.hasOwnProperty(key)) continue - if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue - Safer[key] = Buffer[key] -} - -safer.Buffer.prototype = Buffer.prototype - -if (!Safer.from || Safer.from === Uint8Array.from) { - Safer.from = function (value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) - } - if (value && typeof value.length === 'undefined') { - throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) - } - return Buffer(value, encodingOrOffset, length) - } -} - -if (!Safer.alloc) { - Safer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) - } - if (size < 0 || size >= 2 * (1 << 30)) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } - var buf = Buffer(size) - if (!fill || fill.length === 0) { - buf.fill(0) - } else if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - return buf - } -} - -if (!safer.kStringMaxLength) { - try { - safer.kStringMaxLength = process.binding('buffer').kStringMaxLength - } catch (e) { - // we can't determine kStringMaxLength in environments where process.binding - // is unsupported, so let's not set it - } -} - -if (!safer.constants) { - safer.constants = { - MAX_LENGTH: safer.kMaxLength - } - if (safer.kStringMaxLength) { - safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength - } -} - -module.exports = safer - -}).call(this)}).call(this,require('_process')) - -},{"_process":237,"buffer":68}],252:[function(require,module,exports){ -var grammar = module.exports = { - v: [{ - name: 'version', - reg: /^(\d*)$/ - }], - o: [{ - // o=- 20518 0 IN IP4 203.0.113.1 - // NB: sessionId will be a String in most cases because it is huge - 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' - }], - // default parsing of these only (though some of these feel outdated) - s: [{ name: 'name' }], - i: [{ name: 'description' }], - u: [{ name: 'uri' }], - e: [{ name: 'email' }], - p: [{ name: 'phone' }], - z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly... - r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly - // k: [{}], // outdated thing ignored - t: [{ - // t=0 0 - name: 'timing', - reg: /^(\d*) (\d*)/, - names: ['start', 'stop'], - format: '%d %d' - }], - c: [{ - // c=IN IP4 10.47.197.26 - name: 'connection', - reg: /^IN IP(\d) (\S*)/, - names: ['version', 'ip'], - format: 'IN IP%d %s' - }], - b: [{ - // b=AS:4000 - push: 'bandwidth', - reg: /^(TIAS|AS|CT|RR|RS):(\d*)/, - names: ['type', 'limit'], - format: '%s:%s' - }], - m: [{ - // m=video 51744 RTP/AVP 126 97 98 34 31 - // NB: special - pushes to session - // TODO: rtp/fmtp should be filtered by the payloads found here? - reg: /^(\w*) (\d*) ([\w/]*)(?: (.*))?/, - names: ['type', 'port', 'protocol', 'payloads'], - format: '%s %d %s %s' - }], - a: [ - { - // a=rtpmap:110 opus/48000/2 - 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'; - } - }, - { - // a=fmtp:108 profile-level-id=24;object=23;bitrate=64000 - // a=fmtp:111 minptime=10; useinbandfec=1 - push: 'fmtp', - reg: /^fmtp:(\d*) ([\S| ]*)/, - names: ['payload', 'config'], - format: 'fmtp:%d %s' - }, - { - // a=control:streamid=0 - name: 'control', - reg: /^control:(.*)/, - format: 'control:%s' - }, - { - // a=rtcp:65179 IN IP4 193.84.77.194 - 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'; - } - }, - { - // a=rtcp-fb:98 trr-int 100 - push: 'rtcpFbTrrInt', - reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/, - names: ['payload', 'value'], - format: 'rtcp-fb:%s trr-int %d' - }, - { - // a=rtcp-fb:98 nack rpsi - 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'; - } - }, - { - // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset - // a=extmap:1/recvonly URI-gps-string - // a=extmap:3 urn:ietf:params:rtp-hdrext:encrypt urn:ietf:params:rtp-hdrext:smpte-tc 25@600/24 - 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' : '') - ); - } - }, - { - // a=extmap-allow-mixed - name: 'extmapAllowMixed', - reg: /^(extmap-allow-mixed)/ - }, - { - // a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32 - 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'; - } - }, - { - // a=setup:actpass - name: 'setup', - reg: /^setup:(\w*)/, - format: 'setup:%s' - }, - { - // a=connection:new - name: 'connectionType', - reg: /^connection:(new|existing)/, - format: 'connection:%s' - }, - { - // a=mid:1 - name: 'mid', - reg: /^mid:([^\s]*)/, - format: 'mid:%s' - }, - { - // a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a - name: 'msid', - reg: /^msid:(.*)/, - format: 'msid:%s' - }, - { - // a=ptime:20 - name: 'ptime', - reg: /^ptime:(\d*(?:\.\d*)*)/, - format: 'ptime:%d' - }, - { - // a=maxptime:60 - name: 'maxptime', - reg: /^maxptime:(\d*(?:\.\d*)*)/, - format: 'maxptime:%d' - }, - { - // a=sendrecv - name: 'direction', - reg: /^(sendrecv|recvonly|sendonly|inactive)/ - }, - { - // a=ice-lite - name: 'icelite', - reg: /^(ice-lite)/ - }, - { - // a=ice-ufrag:F7gI - name: 'iceUfrag', - reg: /^ice-ufrag:(\S*)/, - format: 'ice-ufrag:%s' - }, - { - // a=ice-pwd:x9cml/YzichV2+XlhiMu8g - name: 'icePwd', - reg: /^ice-pwd:(\S*)/, - format: 'ice-pwd:%s' - }, - { - // a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33 - name: 'fingerprint', - reg: /^fingerprint:(\S*) (\S*)/, - names: ['type', 'hash'], - format: 'fingerprint:%s %s' - }, - { - // a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host - // a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0 network-id 3 network-cost 10 - // a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0 network-id 3 network-cost 10 - // a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0 network-id 3 network-cost 10 - // a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0 network-id 3 network-cost 10 - 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'; - - // NB: candidate has three optional chunks, so %void middles one if it's missing - 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; - } - }, - { - // a=end-of-candidates (keep after the candidates line for readability) - name: 'endOfCandidates', - reg: /^(end-of-candidates)/ - }, - { - // a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ... - name: 'remoteCandidates', - reg: /^remote-candidates:(.*)/, - format: 'remote-candidates:%s' - }, - { - // a=ice-options:google-ice - name: 'iceOptions', - reg: /^ice-options:(\S*)/, - format: 'ice-options:%s' - }, - { - // a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1 - 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; - } - }, - { - // a=ssrc-group:FEC 1 2 - // a=ssrc-group:FEC-FR 3004364195 1080772241 - push: 'ssrcGroups', - // token-char = %x21 / %x23-27 / %x2A-2B / %x2D-2E / %x30-39 / %x41-5A / %x5E-7E - reg: /^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/, - names: ['semantics', 'ssrcs'], - format: 'ssrc-group:%s %s' - }, - { - // a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV - name: 'msidSemantic', - reg: /^msid-semantic:\s?(\w*) (\S*)/, - names: ['semantic', 'token'], - format: 'msid-semantic: %s %s' // space after ':' is not accidental - }, - { - // a=group:BUNDLE audio video - push: 'groups', - reg: /^group:(\w*) (.*)/, - names: ['type', 'mids'], - format: 'group:%s %s' - }, - { - // a=rtcp-mux - name: 'rtcpMux', - reg: /^(rtcp-mux)/ - }, - { - // a=rtcp-rsize - name: 'rtcpRsize', - reg: /^(rtcp-rsize)/ - }, - { - // a=sctpmap:5000 webrtc-datachannel 1024 - 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'; - } - }, - { - // a=x-google-flag:conference - name: 'xGoogleFlag', - reg: /^x-google-flag:([^\s]*)/, - format: 'x-google-flag:%s' - }, - { - // a=rid:1 send max-width=1280;max-height=720;max-fps=30;depend=0 - 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'; - } - }, - { - // a=imageattr:97 send [x=800,y=640,sar=1.1,q=0.6] [x=480,y=320] recv [x=330,y=250] - // a=imageattr:* send [x=800,y=640] recv * - // a=imageattr:100 recv [x=320,y=240] - push: 'imageattrs', - reg: new RegExp( - // a=imageattr:97 - '^imageattr:(\\d+|\\*)' + - // send [x=800,y=640,sar=1.1,q=0.6] [x=480,y=320] - '[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)' + - // recv [x=330,y=250] - '(?:[\\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' : ''); - } - }, - { - // a=simulcast:send 1,2,3;~4,~5 recv 6;~7,~8 - // a=simulcast:recv 1;4,5 send 6;7 - name: 'simulcast', - reg: new RegExp( - // a=simulcast: - '^simulcast:' + - // send 1,2,3;~4,~5 - '(send|recv) ([a-zA-Z0-9\\-_~;,]+)' + - // space + recv 6;~7,~8 - '(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?' + - // end - '$' - ), - names: ['dir1', 'list1', 'dir2', 'list2'], - format: function (o) { - return 'simulcast:%s %s' + (o.dir2 ? ' %s %s' : ''); - } - }, - { - // old simulcast draft 03 (implemented by Firefox) - // https://tools.ietf.org/html/draft-ietf-mmusic-sdp-simulcast-03 - // a=simulcast: recv pt=97;98 send pt=97 - // a=simulcast: send rid=5;6;7 paused=6,7 - name: 'simulcast_03', - reg: /^simulcast:[\s\t]+([\S+\s\t]+)$/, - names: ['value'], - format: 'simulcast: %s' - }, - { - // a=framerate:25 - // a=framerate:29.97 - name: 'framerate', - reg: /^framerate:(\d+(?:$|\.\d+))/, - format: 'framerate:%s' - }, - { - // RFC4570 - // a=source-filter: incl IN IP4 239.5.2.31 10.1.15.5 - 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' - }, - { - // a=bundle-only - name: 'bundleOnly', - reg: /^(bundle-only)/ - }, - { - // a=label:1 - name: 'label', - reg: /^label:(.+)/, - format: 'label:%s' - }, - { - // RFC version 26 for SCTP over DTLS - // https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-26#section-5 - name: 'sctpPort', - reg: /^sctp-port:(\d+)$/, - format: 'sctp-port:%s' - }, - { - // RFC version 26 for SCTP over DTLS - // https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-26#section-6 - name: 'maxMessageSize', - reg: /^max-message-size:(\d+)$/, - format: 'max-message-size:%s' - }, - { - // RFC7273 - // a=ts-refclk:ptp=IEEE1588-2008:39-A7-94-FF-FE-07-CB-D0:37 - push:'tsRefClocks', - reg: /^ts-refclk:([^\s=]*)(?:=(\S*))?/, - names: ['clksrc', 'clksrcExt'], - format: function (o) { - return 'ts-refclk:%s' + (o.clksrcExt != null ? '=%s' : ''); - } - }, - { - // RFC7273 - // a=mediaclk:direct=963214424 - 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; - } - }, - { - // a=keywds:keywords - name: 'keywords', - reg: /^keywds:(.+)$/, - format: 'keywds:%s' - }, - { - // a=content:main - name: 'content', - reg: /^content:(.+)/, - format: 'content:%s' - }, - // BFCP https://tools.ietf.org/html/rfc4583 - { - // a=floorctrl:c-s - name: 'bfcpFloorCtrl', - reg: /^floorctrl:(c-only|s-only|c-s)/, - format: 'floorctrl:%s' - }, - { - // a=confid:1 - name: 'bfcpConfId', - reg: /^confid:(\d+)/, - format: 'confid:%s' - }, - { - // a=userid:1 - name: 'bfcpUserId', - reg: /^userid:(\d+)/, - format: 'userid:%s' - }, - { - // a=floorid:1 - name: 'bfcpFloorId', - reg: /^floorid:(.+) (?:m-stream|mstrm):(.+)/, - names: ['id', 'mStream'], - format: 'floorid:%s mstrm:%s' - }, - { - // any a= that we don't understand is kept verbatim on media.invalid - push: 'invalid', - names: ['value'] - } - ] -}; - -// set sensible defaults to avoid polluting the grammar with boring details -Object.keys(grammar).forEach(function (key) { - var objs = grammar[key]; - objs.forEach(function (obj) { - if (!obj.reg) { - obj.reg = /(.*)/; - } - if (!obj.format) { - obj.format = '%s'; - } - }); -}); - -},{}],253:[function(require,module,exports){ -var parser = require('./parser'); -var writer = require('./writer'); - -exports.write = writer; -exports.parse = parser.parse; -exports.parseParams = parser.parseParams; -exports.parseFmtpConfig = parser.parseFmtpConfig; // Alias of parseParams(). -exports.parsePayloads = parser.parsePayloads; -exports.parseRemoteCandidates = parser.parseRemoteCandidates; -exports.parseImageAttributes = parser.parseImageAttributes; -exports.parseSimulcastStreamList = parser.parseSimulcastStreamList; - -},{"./parser":254,"./writer":255}],254:[function(require,module,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 ? - {} : // blank object that will be pushed - needsBlank ? location[obj.name] : location; // otherwise, named location or root - - 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; // points at where properties go under (one of the above) - - // parse lines we understand - 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]; // point at latest media line - } - - 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; // link it up - 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]] = undefined; - } - return acc; -}; - -exports.parseParams = function (str) { - return str.split(/;\s?/).reduce(paramReducer, {}); -}; - -// For backward compatibility - alias will be removed in 3.0.0 -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: scid, - paused: paused - }; - }); - }); -}; - -},{"./grammar":252}],255:[function(require,module,exports){ -var grammar = require('./grammar'); - -// customized util.format - discards excess arguments and can void middle ones -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; // missing argument - } - var arg = args[i]; - i += 1; - switch (x) { - case '%%': - return '%'; - case '%s': - return String(arg); - case '%d': - return Number(arg); - case '%v': - return ''; - } - }); - // NB: we discard excess arguments - they are typically undefined from makeLine -}; - -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 { // for mLine and push attributes - args.push(location[obj.names[i]]); - } - } - } - else { - args.push(location[obj.name]); - } - return format.apply(null, args); -}; - -// RFC specified order -// TODO: extend this with all the rest -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 || {}; - // ensure certain properties exist - if (session.version == null) { - session.version = 0; // 'v=0' must be there (only defined version atm) - } - if (session.name == null) { - session.name = ' '; // 's= ' must be there if no meaningful name set - } - session.media.forEach(function (mLine) { - if (mLine.payloads == null) { - mLine.payloads = ''; - } - }); - - var outerOrder = opts.outerOrder || defaultOuterOrder; - var innerOrder = opts.innerOrder || defaultInnerOrder; - var sdp = []; - - // loop through outerOrder for matching properties on session - 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)); - }); - } - }); - }); - - // then for each media line, follow the innerOrder - 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'; -}; - -},{"./grammar":252}],256:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer - -// prototype class for hash functions -function Hash (blockSize, finalSize) { - this._block = Buffer.alloc(blockSize) - this._finalSize = finalSize - this._blockSize = blockSize - this._len = 0 -} - -Hash.prototype.update = function (data, enc) { - if (typeof data === 'string') { - enc = enc || 'utf8' - data = Buffer.from(data, enc) - } - - var block = this._block - var blockSize = this._blockSize - var length = data.length - var accum = this._len - - for (var offset = 0; offset < length;) { - var assigned = accum % blockSize - var remainder = Math.min(length - offset, blockSize - assigned) - - for (var i = 0; i < remainder; i++) { - block[assigned + i] = data[offset + i] - } - - accum += remainder - offset += remainder - - if ((accum % blockSize) === 0) { - this._update(block) - } - } - - this._len += length - return this -} - -Hash.prototype.digest = function (enc) { - var rem = this._len % this._blockSize - - this._block[rem] = 0x80 - - // zero (rem + 1) trailing bits, where (rem + 1) is the smallest - // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize - this._block.fill(0, rem + 1) - - if (rem >= this._finalSize) { - this._update(this._block) - this._block.fill(0) - } - - var bits = this._len * 8 - - // uint32 - if (bits <= 0xffffffff) { - this._block.writeUInt32BE(bits, this._blockSize - 4) - - // uint64 - } else { - var lowBits = (bits & 0xffffffff) >>> 0 - var highBits = (bits - lowBits) / 0x100000000 - - this._block.writeUInt32BE(highBits, this._blockSize - 8) - this._block.writeUInt32BE(lowBits, this._blockSize - 4) - } - - this._update(this._block) - var hash = this._hash() - - return enc ? hash.toString(enc) : hash -} - -Hash.prototype._update = function () { - throw new Error('_update must be implemented by subclass') -} - -module.exports = Hash - -},{"safe-buffer":250}],257:[function(require,module,exports){ -var exports = module.exports = function SHA (algorithm) { - algorithm = algorithm.toLowerCase() - - var Algorithm = exports[algorithm] - if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') - - return new Algorithm() -} - -exports.sha = require('./sha') -exports.sha1 = require('./sha1') -exports.sha224 = require('./sha224') -exports.sha256 = require('./sha256') -exports.sha384 = require('./sha384') -exports.sha512 = require('./sha512') - -},{"./sha":258,"./sha1":259,"./sha224":260,"./sha256":261,"./sha384":262,"./sha512":263}],258:[function(require,module,exports){ -/* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined - * in FIPS PUB 180-1 - * This source code is derived from sha1.js of the same repository. - * The difference between SHA-0 and SHA-1 is just a bitwise rotate left - * operation was added. - */ - -var inherits = require('inherits') -var Hash = require('./hash') -var Buffer = require('safe-buffer').Buffer - -var K = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 -] - -var W = new Array(80) - -function Sha () { - this.init() - this._w = W - - Hash.call(this, 64, 56) -} - -inherits(Sha, Hash) - -Sha.prototype.init = function () { - this._a = 0x67452301 - this._b = 0xefcdab89 - this._c = 0x98badcfe - this._d = 0x10325476 - this._e = 0xc3d2e1f0 - - return this -} - -function rotl5 (num) { - return (num << 5) | (num >>> 27) -} - -function rotl30 (num) { - return (num << 30) | (num >>> 2) -} - -function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d -} - -Sha.prototype._update = function (M) { - var W = this._w - - var a = this._a | 0 - var b = this._b | 0 - var c = this._c | 0 - var d = this._d | 0 - var e = this._e | 0 - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) - for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] - - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20) - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 - - e = d - d = c - c = rotl30(b) - b = a - a = t - } - - this._a = (a + this._a) | 0 - this._b = (b + this._b) | 0 - this._c = (c + this._c) | 0 - this._d = (d + this._d) | 0 - this._e = (e + this._e) | 0 -} - -Sha.prototype._hash = function () { - var H = Buffer.allocUnsafe(20) - - H.writeInt32BE(this._a | 0, 0) - H.writeInt32BE(this._b | 0, 4) - H.writeInt32BE(this._c | 0, 8) - H.writeInt32BE(this._d | 0, 12) - H.writeInt32BE(this._e | 0, 16) - - return H -} - -module.exports = Sha - -},{"./hash":256,"inherits":146,"safe-buffer":250}],259:[function(require,module,exports){ -/* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined - * in FIPS PUB 180-1 - * Version 2.1a Copyright Paul Johnston 2000 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for details. - */ - -var inherits = require('inherits') -var Hash = require('./hash') -var Buffer = require('safe-buffer').Buffer - -var K = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 -] - -var W = new Array(80) - -function Sha1 () { - this.init() - this._w = W - - Hash.call(this, 64, 56) -} - -inherits(Sha1, Hash) - -Sha1.prototype.init = function () { - this._a = 0x67452301 - this._b = 0xefcdab89 - this._c = 0x98badcfe - this._d = 0x10325476 - this._e = 0xc3d2e1f0 - - return this -} - -function rotl1 (num) { - return (num << 1) | (num >>> 31) -} - -function rotl5 (num) { - return (num << 5) | (num >>> 27) -} - -function rotl30 (num) { - return (num << 30) | (num >>> 2) -} - -function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d -} - -Sha1.prototype._update = function (M) { - var W = this._w - - var a = this._a | 0 - var b = this._b | 0 - var c = this._c | 0 - var d = this._d | 0 - var e = this._e | 0 - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) - for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) - - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20) - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 - - e = d - d = c - c = rotl30(b) - b = a - a = t - } - - this._a = (a + this._a) | 0 - this._b = (b + this._b) | 0 - this._c = (c + this._c) | 0 - this._d = (d + this._d) | 0 - this._e = (e + this._e) | 0 -} - -Sha1.prototype._hash = function () { - var H = Buffer.allocUnsafe(20) - - H.writeInt32BE(this._a | 0, 0) - H.writeInt32BE(this._b | 0, 4) - H.writeInt32BE(this._c | 0, 8) - H.writeInt32BE(this._d | 0, 12) - H.writeInt32BE(this._e | 0, 16) - - return H -} - -module.exports = Sha1 - -},{"./hash":256,"inherits":146,"safe-buffer":250}],260:[function(require,module,exports){ -/** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ - -var inherits = require('inherits') -var Sha256 = require('./sha256') -var Hash = require('./hash') -var Buffer = require('safe-buffer').Buffer - -var W = new Array(64) - -function Sha224 () { - this.init() - - this._w = W // new Array(64) - - Hash.call(this, 64, 56) -} - -inherits(Sha224, Sha256) - -Sha224.prototype.init = function () { - this._a = 0xc1059ed8 - this._b = 0x367cd507 - this._c = 0x3070dd17 - this._d = 0xf70e5939 - this._e = 0xffc00b31 - this._f = 0x68581511 - this._g = 0x64f98fa7 - this._h = 0xbefa4fa4 - - return this -} - -Sha224.prototype._hash = function () { - var H = Buffer.allocUnsafe(28) - - H.writeInt32BE(this._a, 0) - H.writeInt32BE(this._b, 4) - H.writeInt32BE(this._c, 8) - H.writeInt32BE(this._d, 12) - H.writeInt32BE(this._e, 16) - H.writeInt32BE(this._f, 20) - H.writeInt32BE(this._g, 24) - - return H -} - -module.exports = Sha224 - -},{"./hash":256,"./sha256":261,"inherits":146,"safe-buffer":250}],261:[function(require,module,exports){ -/** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ - -var inherits = require('inherits') -var Hash = require('./hash') -var Buffer = require('safe-buffer').Buffer - -var K = [ - 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, - 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, - 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, - 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, - 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, - 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, - 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, - 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, - 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, - 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, - 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, - 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, - 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, - 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, - 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, - 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 -] - -var W = new Array(64) - -function Sha256 () { - this.init() - - this._w = W // new Array(64) - - Hash.call(this, 64, 56) -} - -inherits(Sha256, Hash) - -Sha256.prototype.init = function () { - this._a = 0x6a09e667 - this._b = 0xbb67ae85 - this._c = 0x3c6ef372 - this._d = 0xa54ff53a - this._e = 0x510e527f - this._f = 0x9b05688c - this._g = 0x1f83d9ab - this._h = 0x5be0cd19 - - return this -} - -function ch (x, y, z) { - return z ^ (x & (y ^ z)) -} - -function maj (x, y, z) { - return (x & y) | (z & (x | y)) -} - -function sigma0 (x) { - return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) -} - -function sigma1 (x) { - return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) -} - -function gamma0 (x) { - return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) -} - -function gamma1 (x) { - return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) -} - -Sha256.prototype._update = function (M) { - var W = this._w - - var a = this._a | 0 - var b = this._b | 0 - var c = this._c | 0 - var d = this._d | 0 - var e = this._e | 0 - var f = this._f | 0 - var g = this._g | 0 - var h = this._h | 0 - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) - for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 - - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 - var T2 = (sigma0(a) + maj(a, b, c)) | 0 - - h = g - g = f - f = e - e = (d + T1) | 0 - d = c - c = b - b = a - a = (T1 + T2) | 0 - } - - this._a = (a + this._a) | 0 - this._b = (b + this._b) | 0 - this._c = (c + this._c) | 0 - this._d = (d + this._d) | 0 - this._e = (e + this._e) | 0 - this._f = (f + this._f) | 0 - this._g = (g + this._g) | 0 - this._h = (h + this._h) | 0 -} - -Sha256.prototype._hash = function () { - var H = Buffer.allocUnsafe(32) - - H.writeInt32BE(this._a, 0) - H.writeInt32BE(this._b, 4) - H.writeInt32BE(this._c, 8) - H.writeInt32BE(this._d, 12) - H.writeInt32BE(this._e, 16) - H.writeInt32BE(this._f, 20) - H.writeInt32BE(this._g, 24) - H.writeInt32BE(this._h, 28) - - return H -} - -module.exports = Sha256 - -},{"./hash":256,"inherits":146,"safe-buffer":250}],262:[function(require,module,exports){ -var inherits = require('inherits') -var SHA512 = require('./sha512') -var Hash = require('./hash') -var Buffer = require('safe-buffer').Buffer - -var W = new Array(160) - -function Sha384 () { - this.init() - this._w = W - - Hash.call(this, 128, 112) -} - -inherits(Sha384, SHA512) - -Sha384.prototype.init = function () { - this._ah = 0xcbbb9d5d - this._bh = 0x629a292a - this._ch = 0x9159015a - this._dh = 0x152fecd8 - this._eh = 0x67332667 - this._fh = 0x8eb44a87 - this._gh = 0xdb0c2e0d - this._hh = 0x47b5481d - - this._al = 0xc1059ed8 - this._bl = 0x367cd507 - this._cl = 0x3070dd17 - this._dl = 0xf70e5939 - this._el = 0xffc00b31 - this._fl = 0x68581511 - this._gl = 0x64f98fa7 - this._hl = 0xbefa4fa4 - - return this -} - -Sha384.prototype._hash = function () { - var H = Buffer.allocUnsafe(48) - - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset) - H.writeInt32BE(l, offset + 4) - } - - writeInt64BE(this._ah, this._al, 0) - writeInt64BE(this._bh, this._bl, 8) - writeInt64BE(this._ch, this._cl, 16) - writeInt64BE(this._dh, this._dl, 24) - writeInt64BE(this._eh, this._el, 32) - writeInt64BE(this._fh, this._fl, 40) - - return H -} - -module.exports = Sha384 - -},{"./hash":256,"./sha512":263,"inherits":146,"safe-buffer":250}],263:[function(require,module,exports){ -var inherits = require('inherits') -var Hash = require('./hash') -var Buffer = require('safe-buffer').Buffer - -var K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 -] - -var W = new Array(160) - -function Sha512 () { - this.init() - this._w = W - - Hash.call(this, 128, 112) -} - -inherits(Sha512, Hash) - -Sha512.prototype.init = function () { - this._ah = 0x6a09e667 - this._bh = 0xbb67ae85 - this._ch = 0x3c6ef372 - this._dh = 0xa54ff53a - this._eh = 0x510e527f - this._fh = 0x9b05688c - this._gh = 0x1f83d9ab - this._hh = 0x5be0cd19 - - this._al = 0xf3bcc908 - this._bl = 0x84caa73b - this._cl = 0xfe94f82b - this._dl = 0x5f1d36f1 - this._el = 0xade682d1 - this._fl = 0x2b3e6c1f - this._gl = 0xfb41bd6b - this._hl = 0x137e2179 - - return this -} - -function Ch (x, y, z) { - return z ^ (x & (y ^ z)) -} - -function maj (x, y, z) { - return (x & y) | (z & (x | y)) -} - -function sigma0 (x, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) -} - -function sigma1 (x, xl) { - return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) -} - -function Gamma0 (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) -} - -function Gamma0l (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) -} - -function Gamma1 (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) -} - -function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) -} - -function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 -} - -Sha512.prototype._update = function (M) { - var W = this._w - - var ah = this._ah | 0 - var bh = this._bh | 0 - var ch = this._ch | 0 - var dh = this._dh | 0 - var eh = this._eh | 0 - var fh = this._fh | 0 - var gh = this._gh | 0 - var hh = this._hh | 0 - - var al = this._al | 0 - var bl = this._bl | 0 - var cl = this._cl | 0 - var dl = this._dl | 0 - var el = this._el | 0 - var fl = this._fl | 0 - var gl = this._gl | 0 - var hl = this._hl | 0 - - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4) - W[i + 1] = M.readInt32BE(i * 4 + 4) - } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2] - var xl = W[i - 15 * 2 + 1] - var gamma0 = Gamma0(xh, xl) - var gamma0l = Gamma0l(xl, xh) - - xh = W[i - 2 * 2] - xl = W[i - 2 * 2 + 1] - var gamma1 = Gamma1(xh, xl) - var gamma1l = Gamma1l(xl, xh) - - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2] - var Wi7l = W[i - 7 * 2 + 1] - - var Wi16h = W[i - 16 * 2] - var Wi16l = W[i - 16 * 2 + 1] - - var Wil = (gamma0l + Wi7l) | 0 - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 - Wil = (Wil + gamma1l) | 0 - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 - Wil = (Wil + Wi16l) | 0 - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 - - W[i] = Wih - W[i + 1] = Wil - } - - for (var j = 0; j < 160; j += 2) { - Wih = W[j] - Wil = W[j + 1] - - var majh = maj(ah, bh, ch) - var majl = maj(al, bl, cl) - - var sigma0h = sigma0(ah, al) - var sigma0l = sigma0(al, ah) - var sigma1h = sigma1(eh, el) - var sigma1l = sigma1(el, eh) - - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K[j] - var Kil = K[j + 1] - - var chh = Ch(eh, fh, gh) - var chl = Ch(el, fl, gl) - - var t1l = (hl + sigma1l) | 0 - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 - t1l = (t1l + chl) | 0 - t1h = (t1h + chh + getCarry(t1l, chl)) | 0 - t1l = (t1l + Kil) | 0 - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 - t1l = (t1l + Wil) | 0 - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 - - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0 - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 - - hh = gh - hl = gl - gh = fh - gl = fl - fh = eh - fl = el - el = (dl + t1l) | 0 - eh = (dh + t1h + getCarry(el, dl)) | 0 - dh = ch - dl = cl - ch = bh - cl = bl - bh = ah - bl = al - al = (t1l + t2l) | 0 - ah = (t1h + t2h + getCarry(al, t1l)) | 0 - } - - this._al = (this._al + al) | 0 - this._bl = (this._bl + bl) | 0 - this._cl = (this._cl + cl) | 0 - this._dl = (this._dl + dl) | 0 - this._el = (this._el + el) | 0 - this._fl = (this._fl + fl) | 0 - this._gl = (this._gl + gl) | 0 - this._hl = (this._hl + hl) | 0 - - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 -} - -Sha512.prototype._hash = function () { - var H = Buffer.allocUnsafe(64) - - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset) - H.writeInt32BE(l, offset + 4) - } - - writeInt64BE(this._ah, this._al, 0) - writeInt64BE(this._bh, this._bl, 8) - writeInt64BE(this._ch, this._cl, 16) - writeInt64BE(this._dh, this._dl, 24) - writeInt64BE(this._eh, this._el, 32) - writeInt64BE(this._fh, this._fl, 40) - writeInt64BE(this._gh, this._gl, 48) - writeInt64BE(this._hh, this._hl, 56) - - return H -} - -module.exports = Sha512 - -},{"./hash":256,"inherits":146,"safe-buffer":250}],264:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -module.exports = Stream; - -var EE = require('events').EventEmitter; -var inherits = require('inherits'); - -inherits(Stream, EE); -Stream.Readable = require('readable-stream/lib/_stream_readable.js'); -Stream.Writable = require('readable-stream/lib/_stream_writable.js'); -Stream.Duplex = require('readable-stream/lib/_stream_duplex.js'); -Stream.Transform = require('readable-stream/lib/_stream_transform.js'); -Stream.PassThrough = require('readable-stream/lib/_stream_passthrough.js'); -Stream.finished = require('readable-stream/lib/internal/streams/end-of-stream.js') -Stream.pipeline = require('readable-stream/lib/internal/streams/pipeline.js') - -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; - - - -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. - -function Stream() { - EE.call(this); -} - -Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } - - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; - -},{"events":105,"inherits":146,"readable-stream/lib/_stream_duplex.js":266,"readable-stream/lib/_stream_passthrough.js":267,"readable-stream/lib/_stream_readable.js":268,"readable-stream/lib/_stream_transform.js":269,"readable-stream/lib/_stream_writable.js":270,"readable-stream/lib/internal/streams/end-of-stream.js":274,"readable-stream/lib/internal/streams/pipeline.js":276}],265:[function(require,module,exports){ -arguments[4][50][0].apply(exports,arguments) -},{"dup":50}],266:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. -'use strict'; -/**/ - -var objectKeys = Object.keys || function (obj) { - var keys = []; - - for (var key in obj) { - keys.push(key); - } - - return keys; -}; -/**/ - - -module.exports = Duplex; - -var Readable = require('./_stream_readable'); - -var Writable = require('./_stream_writable'); - -require('inherits')(Duplex, Readable); - -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } -} - -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); // the no-half-open enforcer - -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. - - process.nextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); -}).call(this)}).call(this,require('_process')) - -},{"./_stream_readable":268,"./_stream_writable":270,"_process":237,"inherits":146}],267:[function(require,module,exports){ -arguments[4][52][0].apply(exports,arguments) -},{"./_stream_transform":269,"dup":52,"inherits":146}],268:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -'use strict'; - -module.exports = Readable; -/**/ - -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; -/**/ - -var EE = require('events').EventEmitter; - -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ - - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ - - -var debugUtil = require('util'); - -var debug; - -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ - - -var BufferList = require('./internal/streams/buffer_list'); - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - - -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; - -require('inherits')(Readable, Stream); - -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} - -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - - this.autoDestroy = !!options.autoDestroy; // has it been destroyed - - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; - - if (options.encoding) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); // legacy - - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; - -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; // Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. - - -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; // Unshift should *always* be something directly out of read() - - -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } - - return er; -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; // backwards compatibility. - - -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; - - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - - this._readableState.buffer.clear(); - - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; // Don't raise the hwm > 1GB - - -var MAX_HWM = 0x40000000; - -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. - - -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - - - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - - if (!state.ended) { - state.needReadable = true; - return 0; - } - - return state.length; -} // you can override either this method, or the async _read(n) below. - - -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - - - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - - - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - - if (state.length === 0) state.needReadable = true; // call internal read method - - this._read(state.highWaterMark); - - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - return ret; -}; - -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; - - if (state.decoder) { - var chunk = state.decoder.end(); - - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - - state.ended = true; - - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } -} // Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. - - -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } -} - -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} // at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. - - -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } - - state.readingMore = false; -} // abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. - - -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - - case 1: - state.pipes = [state.pipes, dest]; - break; - - default: - state.pipes.push(dest); - break; - } - - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); - - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } - - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - - - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. - - - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - - dest.once('close', onclose); - - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - - - dest.emit('pipe', src); // start the flow if it hasn't been started already. - - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. - - if (state.pipesCount === 0) return this; // just one destination. most common case. - - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. - - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. - - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } - - return this; - } // try to find the right one. - - - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; // set up data events if they are asked for -// Ensure readable listeners eventually get something - - -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } - } - } - - return res; -}; - -Readable.prototype.addListener = Readable.prototype.on; - -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } -} - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} // pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. - - -Readable.prototype.resume = function () { - var state = this._readableState; - - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() - - state.flowing = !state.readableListening; - resume(this, state); - } - - state.paused = false; - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - debug('resume', state.reading); - - if (!state.reading) { - stream.read(0); - } - - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - - this._readableState.paused = true; - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - - while (state.flowing && stream.read() !== null) { - ; - } -} // wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. - - -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. - - - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. - - - this._read = function (n) { - debug('wrapped _read', n); - - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; -}; - -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); - } - - return createReadableStreamAsyncIterator(this); - }; -} - -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } -}); // exposed for testing purposes only. - -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } -}); // Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. - -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); - - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } -} - -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = require('./internal/streams/from'); - } - - return from(Readable, iterable, opts); - }; -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - - return -1; -} -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"../errors":265,"./_stream_duplex":266,"./internal/streams/async_iterator":271,"./internal/streams/buffer_list":272,"./internal/streams/destroy":273,"./internal/streams/from":275,"./internal/streams/state":277,"./internal/streams/stream":278,"_process":237,"buffer":68,"events":105,"inherits":146,"string_decoder/":279,"util":20}],269:[function(require,module,exports){ -arguments[4][54][0].apply(exports,arguments) -},{"../errors":265,"./_stream_duplex":266,"dup":54,"inherits":146}],270:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. -'use strict'; - -module.exports = Writable; -/* */ - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} // It seems a linked list but it is not -// there will be only 2 of these for each stream - - -function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ - - -var Duplex; -/**/ - -Writable.WritableState = WritableState; -/**/ - -var internalUtil = { - deprecate: require('util-deprecate') -}; -/**/ - -/**/ - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - -var errorOrDestroy = destroyImpl.errorOrDestroy; - -require('inherits')(Writable, Stream); - -function nop() {} - -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream - // contains buffers or objects. - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. - - this.needDrain = false; // at the start of calling end() - - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted - - this.finished = false; // has it been destroyed - - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - - this.length = 0; // a flag to see when we're in the middle of a write. - - this.writing = false; // when true all writes will be buffered until .uncork() call - - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - - - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again - - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - - this.autoDestroy = !!options.autoDestroy; // count buffered requests - - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - - while (current) { - out.push(current); - current = current.next; - } - - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); // Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. - - -var realHasInstance; - -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. - - -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; - -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} // Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. - - -function validChunk(stream, state, chunk, cb) { - var er; - - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } - - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; - } - - return true; -} - -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; -}; - -Writable.prototype.cork = function () { - this._writableState.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - - return chunk; -} - -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); // if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. - -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen - // after error - - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); // this can emit finish, but finish must - // always follow error - - finishMaybe(stream, state); - } -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} // Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. - - -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} // if there's something in the buffer waiting, then process it - - -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - - state.pendingcb++; - state.lastBufferedRequest = null; - - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending) endWritable(this, state, cb); - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} - -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy(stream, err); - } - - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} - -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - - if (need) { - prefinish(stream, state); - - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } - - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; - -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"../errors":265,"./_stream_duplex":266,"./internal/streams/destroy":273,"./internal/streams/state":277,"./internal/streams/stream":278,"_process":237,"buffer":68,"inherits":146,"util-deprecate":283}],271:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; - -var _Object$setPrototypeO; - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var finished = require('./end-of-stream'); - -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); - -function createIterResult(value, done) { - return { - value: value, - done: done - }; -} - -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' - - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } -} - -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} - -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - - iter[kHandlePromise](resolve, reject); - }, reject); - }; -} - -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); - } - - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } - - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; - - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - - promise = new Promise(this[kHandlePromise]); - } - - this[kLastPromise] = promise; - return promise; - } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); - -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - - iterator[kError] = err; - return; - } - - var resolve = iterator[kLastResolve]; - - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } - - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; - -module.exports = createReadableStreamAsyncIterator; -}).call(this)}).call(this,require('_process')) - -},{"./end-of-stream":274,"_process":237}],272:[function(require,module,exports){ -arguments[4][57][0].apply(exports,arguments) -},{"buffer":68,"dup":57,"util":20}],273:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; // undocumented cb() API, needed for core, not for public API - -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } - - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); - } - }); - - return this; -} - -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); -} - -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; -}).call(this)}).call(this,require('_process')) - -},{"_process":237}],274:[function(require,module,exports){ -arguments[4][59][0].apply(exports,arguments) -},{"../../../errors":265,"dup":59}],275:[function(require,module,exports){ -arguments[4][60][0].apply(exports,arguments) -},{"dup":60}],276:[function(require,module,exports){ -arguments[4][61][0].apply(exports,arguments) -},{"../../../errors":265,"./end-of-stream":274,"dup":61}],277:[function(require,module,exports){ -arguments[4][62][0].apply(exports,arguments) -},{"../../../errors":265,"dup":62}],278:[function(require,module,exports){ -arguments[4][63][0].apply(exports,arguments) -},{"dup":63,"events":105}],279:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -/**/ - -var Buffer = require('safe-buffer').Buffer; -/**/ - -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; - -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.StringDecoder = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} - -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; - -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; - -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } - } - } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} - -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} - -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} - -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} - -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} - -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} -},{"safe-buffer":250}],280:[function(require,module,exports){ -(function (setImmediate,clearImmediate){(function (){ -var nextTick = require('process/browser.js').nextTick; -var apply = Function.prototype.apply; -var slice = Array.prototype.slice; -var immediateIds = {}; -var nextImmediateId = 0; - -// DOM APIs, for completeness - -exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); -}; -exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); -}; -exports.clearTimeout = -exports.clearInterval = function(timeout) { timeout.close(); }; - -function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; -} -Timeout.prototype.unref = Timeout.prototype.ref = function() {}; -Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); -}; - -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; - -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; -}; - -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } -}; - -// That's not how node.js implements it but the exposed api is the same. -exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { - var id = nextImmediateId++; - var args = arguments.length < 2 ? false : slice.call(arguments, 1); - - immediateIds[id] = true; - - nextTick(function onNextTick() { - if (immediateIds[id]) { - // fn.call() is faster so we optimize for the common use-case - // @see http://jsperf.com/call-apply-segu - if (args) { - fn.apply(null, args); - } else { - fn.call(null); - } - // Prevent ids from leaking - exports.clearImmediate(id); - } - }); - - return id; -}; - -exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { - delete immediateIds[id]; -}; -}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate) - -},{"process/browser.js":237,"timers":280}],281:[function(require,module,exports){ -module.exports={ - "0": "O", - "1": "l", - "֭": "֖", - "֮": "֘", - "֨": "֙", - "֤": "֚", - "᪴": "ۛ", - "⃛": "ۛ", - "ؙ": "̓", - "ࣳ": "̓", - "̓": "̓", - "̕": "̓", - "ُ": "̓", - "ٝ": "̔", - "֜": "́", - "֝": "́", - "ؘ": "́", - "݇": "́", - "́": "́", - "॔": "́", - "َ": "́", - "̀": "̀", - "॓": "̀", - "̌": "̆", - "꙼": "̆", - "٘": "̆", - "ٚ": "̆", - "ͮ": "̆", - "ۨ": "̆̇", - "̐": "̆̇", - "ँ": "̆̇", - "ঁ": "̆̇", - "ઁ": "̆̇", - "ଁ": "̆̇", - "ఀ": "̆̇", - "ಁ": "̆̇", - "ഁ": "̆̇", - "𑒿": "̆̇", - "᳐": "̂", - "̑": "̂", - "ٛ": "̂", - "߮": "̂", - "꛰": "̂", - "֯": "̊", - "۟": "̊", - "៓": "̊", - "゚": "̊", - "ْ": "̊", - "ஂ": "̊", - "ံ": "̊", - "ំ": "̊", - "𑌀": "̊", - "ํ": "̊", - "ໍ": "̊", - "ͦ": "̊", - "ⷪ": "̊", - "࣫": "̈", - "߳": "̈", - "ً": "̋", - "ࣰ": "̋", - "͂": "̃", - "ٓ": "̃", - "ׄ": "̇", - "۬": "̇", - "݀": "̇", - "࣪": "̇", - "݁": "̇", - "͘": "̇", - "ֹ": "̇", - "ֺ": "̇", - "ׂ": "̇", - "ׁ": "̇", - "߭": "̇", - "ं": "̇", - "ਂ": "̇", - "ં": "̇", - "்": "̇", - "̷": "̸", - "᪷": "̨", - "̢": "̨", - "ͅ": "̨", - "᳒": "̄", - "̅": "̄", - "ٙ": "̄", - "߫": "̄", - "꛱": "̄", - "᳚": "̎", - "ٗ": "̒", - "͗": "͐", - "ࣿ": "͐", - "ࣸ": "͐", - "ऀ": "͒", - "᳭": "̖", - "᳜": "̩", - "ٖ": "̩", - "᳕": "̫", - "͇": "̳", - "ࣹ": "͔", - "ࣺ": "͕", - "゛": "゙", - "゜": "゚", - "̶": "̵", - "〬": "̉", - "ׅ": "̣", - "࣭": "̣", - "᳝": "̣", - "ִ": "̣", - "ٜ": "̣", - "़": "̣", - "়": "̣", - "਼": "̣", - "઼": "̣", - "଼": "̣", - "𑇊": "̣", - "𑓃": "̣", - "𐨺": "̣", - "࣮": "̤", - "᳞": "̤", - "༷": "̥", - "〭": "̥", - "̧": "̦", - "̡": "̦", - "̹": "̦", - "᳙": "̭", - "᳘": "̮", - "॒": "̱", - "̠": "̱", - "ࣱ": "ٌ", - "ࣨ": "ٌ", - "ࣥ": "ٌ", - "ﱞ": "ﹲّ", - "ࣲ": "ٍ", - "ﱟ": "ﹴّ", - "ﳲ": "ﹷّ", - "ﱠ": "ﹶّ", - "ﳳ": "ﹹّ", - "ﱡ": "ﹸّ", - "ؚ": "ِ", - "̗": "ِ", - "ﳴ": "ﹻّ", - "ﱢ": "ﹺّ", - "ﱣ": "ﹼٰ", - "ٟ": "ٕ", - "̍": "ٰ", - "݂": "ܼ", - "ਃ": "ঃ", - "ః": "ঃ", - "ಃ": "ঃ", - "ഃ": "ঃ", - "ඃ": "ঃ", - "း": "ঃ", - "𑓁": "ঃ", - "់": "่", - "່": "่", - "້": "้", - "໊": "๊", - "໋": "๋", - "꙯": "⃩", - "\u2028": " ", - "\u2029": " ", - " ": " ", - " ": " ", - " ": " ", - " ": " ", - " ": " ", - " ": " ", - " ": " ", - " ": " ", - " ": " ", - " ": " ", - " ": " ", - " ": " ", - " ": " ", - " ": " ", - " ": " ", - "ߺ": "_", - "﹍": "_", - "﹎": "_", - "﹏": "_", - "‐": "-", - "‑": "-", - "‒": "-", - "–": "-", - "﹘": "-", - "۔": "-", - "⁃": "-", - "˗": "-", - "−": "-", - "➖": "-", - "Ⲻ": "-", - "⨩": "-̓", - "⸚": "-̈", - "﬩": "-̇", - "∸": "-̇", - "⨪": "-̣", - "꓾": "-.", - "~": "〜", - "؍": ",", - "٫": ",", - "‚": ",", - "¸": ",", - "ꓹ": ",", - "⸲": "،", - "٬": "،", - ";": ";", - "⸵": "؛", - "ः": ":", - "ઃ": ":", - ":": ":", - "։": ":", - "܃": ":", - "܄": ":", - "᛬": ":", - "︰": ":", - "᠃": ":", - "᠉": ":", - "⁚": ":", - "׃": ":", - "˸": ":", - "꞉": ":", - "∶": ":", - "ː": ":", - "ꓽ": ":", - "⩴": "::=", - "⧴": ":→", - "!": "!", - "ǃ": "!", - "ⵑ": "!", - "‼": "!!", - "⁉": "!?", - "ʔ": "?", - "Ɂ": "?", - "ॽ": "?", - "Ꭾ": "?", - "ꛫ": "?", - "⁈": "?!", - "⁇": "??", - "⸮": "؟", - "𝅭": ".", - "․": ".", - "܁": ".", - "܂": ".", - "꘎": ".", - "𐩐": ".", - "٠": ".", - "۰": ".", - "ꓸ": ".", - "ꓻ": ".,", - "‥": "..", - "ꓺ": "..", - "…": "...", - "꛴": "꛳꛳", - "・": "·", - "・": "·", - "᛫": "·", - "·": "·", - "⸱": "·", - "𐄁": "·", - "•": "·", - "‧": "·", - "∙": "·", - "⋅": "·", - "ꞏ": "·", - "ᐧ": "·", - "⋯": "···", - "ⵈ": "···", - "ᑄ": "·<", - "⋗": "·>", - "ᐷ": "·>", - "ᑀ": "·>", - "ᔯ": "·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", - "🅭": "㏄\t⃝", - "⋴": "ꞓ", - "ɛ": "ꞓ", - "ε": "ꞓ", - "ϵ": "ꞓ", - "𝛆": "ꞓ", - "𝛜": "ꞓ", - "𝜀": "ꞓ", - "𝜖": "ꞓ", - "𝜺": "ꞓ", - "𝝐": "ꞓ", - "𝝴": "ꞓ", - "𝞊": "ꞓ", - "𝞮": "ꞓ", - "𝟄": "ꞓ", - "ⲉ": "ꞓ", - "є": "ꞓ", - "ԑ": "ꞓ", - "ꮛ": "ꞓ", - "𑣎": "ꞓ", - "𐐩": "ꞓ", - "€": "Ꞓ", - "Ⲉ": "Ꞓ", - "Є": "Ꞓ", - "⍷": "ꞓ̲", - "ͽ": "ꜿ", - "Ͽ": "Ꜿ", - "ⅾ": "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", - "ᙱ": "ᖖᒋ", - "ᙲ": "ᖖᒌ", - "ᙴ": "ᖖᒎ", - "ᙵ": "ᖖᒐ", - "ᙶ": "ᖖᒑ", - "ᣪ": "ᖗ·", - "ᙷ": "ᖧ·", - "ᙸ": "ᖨ·", - "ᙹ": "ᖩ·", - "ᙺ": "ᖪ·", - "ᙻ": "ᖫ·", - "ᙼ": "ᖬ·", - "ᙽ": "ᖭ·", - "⪫": "ᗒ", - "⪪": "ᗕ", - "ꓷ": "ᗡ", - "ᣰ": "ᗴ·", - "ᣲ": "ᘛ·", - "ᶻ": "ᙆ", - "ꓭ": "ᙠ", - "ᶺ": "ᣔ", - "ᴾ": "ᣖ", - "ᣜ": "ᣟᐞ", - "ˡ": "ᣳ", - "ʳ": "ᣴ", - "ˢ": "ᣵ", - "ᣛ": "ᣵ", - "ꚰ": "ᚹ", - "ᛡ": "ᚼ", - "⍿": "ᚽ", - "ᛂ": "ᚽ", - "𝈿": "ᛋ", - "↑": "ᛏ", - "↿": "ᛐ", - "⥮": "ᛐ⇂", - "⥣": "ᛐᛚ", - "ⵣ": "ᛯ", - "↾": "ᛚ", - "⨡": "ᛚ", - "⋄": "ᛜ", - "◇": "ᛜ", - "◊": "ᛜ", - "♢": "ᛜ", - "🝔": "ᛜ", - "𑢷": "ᛜ", - "𐊔": "ᛜ", - "⍚": "ᛜ̲", - "⋈": "ᛞ", - "⨝": "ᛞ", - "𐓐": "ᛦ", - "↕": "ᛨ", - "𐳼": "𐲂", - "𐳺": "𐲥", - "ㄱ": "ᄀ", - "ᆨ": "ᄀ", - "ᄁ": "ᄀᄀ", - "ㄲ": "ᄀᄀ", - "ᆩ": "ᄀᄀ", - "ᇺ": "ᄀᄂ", - "ᅚ": "ᄀᄃ", - "ᇃ": "ᄀᄅ", - "ᇻ": "ᄀᄇ", - "ᆪ": "ᄀᄉ", - "ㄳ": "ᄀᄉ", - "ᇄ": "ᄀᄉᄀ", - "ᇼ": "ᄀᄎ", - "ᇽ": "ᄀᄏ", - "ᇾ": "ᄀᄒ", - "ㄴ": "ᄂ", - "ᆫ": "ᄂ", - "ᄓ": "ᄂᄀ", - "ᇅ": "ᄂᄀ", - "ᄔ": "ᄂᄂ", - "ㅥ": "ᄂᄂ", - "ᇿ": "ᄂᄂ", - "ᄕ": "ᄂᄃ", - "ㅦ": "ᄂᄃ", - "ᇆ": "ᄂᄃ", - "ퟋ": "ᄂᄅ", - "ᄖ": "ᄂᄇ", - "ᅛ": "ᄂᄉ", - "ᇇ": "ᄂᄉ", - "ㅧ": "ᄂᄉ", - "ᅜ": "ᄂᄌ", - "ᆬ": "ᄂᄌ", - "ㄵ": "ᄂᄌ", - "ퟌ": "ᄂᄎ", - "ᇉ": "ᄂᄐ", - "ᅝ": "ᄂᄒ", - "ᆭ": "ᄂᄒ", - "ㄶ": "ᄂᄒ", - "ᇈ": "ᄂᅀ", - "ㅨ": "ᄂᅀ", - "ㄷ": "ᄃ", - "ᆮ": "ᄃ", - "ᄗ": "ᄃᄀ", - "ᇊ": "ᄃᄀ", - "ᄄ": "ᄃᄃ", - "ㄸ": "ᄃᄃ", - "ퟍ": "ᄃᄃ", - "ퟎ": "ᄃᄃᄇ", - "ᅞ": "ᄃᄅ", - "ᇋ": "ᄃᄅ", - "ꥠ": "ᄃᄆ", - "ꥡ": "ᄃᄇ", - "ퟏ": "ᄃᄇ", - "ꥢ": "ᄃᄉ", - "ퟐ": "ᄃᄉ", - "ퟑ": "ᄃᄉᄀ", - "ꥣ": "ᄃᄌ", - "ퟒ": "ᄃᄌ", - "ퟓ": "ᄃᄎ", - "ퟔ": "ᄃᄐ", - "ㄹ": "ᄅ", - "ᆯ": "ᄅ", - "ꥤ": "ᄅᄀ", - "ᆰ": "ᄅᄀ", - "ㄺ": "ᄅᄀ", - "ꥥ": "ᄅᄀᄀ", - "ퟕ": "ᄅᄀᄀ", - "ᇌ": "ᄅᄀᄉ", - "ㅩ": "ᄅᄀᄉ", - "ퟖ": "ᄅᄀᄒ", - "ᄘ": "ᄅᄂ", - "ᇍ": "ᄅᄂ", - "ꥦ": "ᄅᄃ", - "ᇎ": "ᄅᄃ", - "ㅪ": "ᄅᄃ", - "ꥧ": "ᄅᄃᄃ", - "ᇏ": "ᄅᄃᄒ", - "ᄙ": "ᄅᄅ", - "ᇐ": "ᄅᄅ", - "ퟗ": "ᄅᄅᄏ", - "ꥨ": "ᄅᄆ", - "ᆱ": "ᄅᄆ", - "ㄻ": "ᄅᄆ", - "ᇑ": "ᄅᄆᄀ", - "ᇒ": "ᄅᄆᄉ", - "ퟘ": "ᄅᄆᄒ", - "ꥩ": "ᄅᄇ", - "ᆲ": "ᄅᄇ", - "ㄼ": "ᄅᄇ", - "ퟙ": "ᄅᄇᄃ", - "ꥪ": "ᄅᄇᄇ", - "ᇓ": "ᄅᄇᄉ", - "ㅫ": "ᄅᄇᄉ", - "ꥫ": "ᄅᄇᄋ", - "ᇕ": "ᄅᄇᄋ", - "ퟚ": "ᄅᄇᄑ", - "ᇔ": "ᄅᄇᄒ", - "ꥬ": "ᄅᄉ", - "ᆳ": "ᄅᄉ", - "ㄽ": "ᄅᄉ", - "ᇖ": "ᄅᄉᄉ", - "ᄛ": "ᄅᄋ", - "ퟝ": "ᄅᄋ", - "ꥭ": "ᄅᄌ", - "ꥮ": "ᄅᄏ", - "ᇘ": "ᄅᄏ", - "ᆴ": "ᄅᄐ", - "ㄾ": "ᄅᄐ", - "ᆵ": "ᄅᄑ", - "ㄿ": "ᄅᄑ", - "ᄚ": "ᄅᄒ", - "ㅀ": "ᄅᄒ", - "ᄻ": "ᄅᄒ", - "ᆶ": "ᄅᄒ", - "ퟲ": "ᄅᄒ", - "ᇗ": "ᄅᅀ", - "ㅬ": "ᄅᅀ", - "ퟛ": "ᄅᅌ", - "ᇙ": "ᄅᅙ", - "ㅭ": "ᄅᅙ", - "ퟜ": "ᄅᅙᄒ", - "ㅁ": "ᄆ", - "ᆷ": "ᄆ", - "ꥯ": "ᄆᄀ", - "ᇚ": "ᄆᄀ", - "ퟞ": "ᄆᄂ", - "ퟟ": "ᄆᄂᄂ", - "ꥰ": "ᄆᄃ", - "ᇛ": "ᄆᄅ", - "ퟠ": "ᄆᄆ", - "ᄜ": "ᄆᄇ", - "ㅮ": "ᄆᄇ", - "ᇜ": "ᄆᄇ", - "ퟡ": "ᄆᄇᄉ", - "ꥱ": "ᄆᄉ", - "ᇝ": "ᄆᄉ", - "ㅯ": "ᄆᄉ", - "ᇞ": "ᄆᄉᄉ", - "ᄝ": "ᄆᄋ", - "ㅱ": "ᄆᄋ", - "ᇢ": "ᄆᄋ", - "ퟢ": "ᄆᄌ", - "ᇠ": "ᄆᄎ", - "ᇡ": "ᄆᄒ", - "ᇟ": "ᄆᅀ", - "ㅰ": "ᄆᅀ", - "ㅂ": "ᄇ", - "ᆸ": "ᄇ", - "ᄞ": "ᄇᄀ", - "ㅲ": "ᄇᄀ", - "ᄟ": "ᄇᄂ", - "ᄠ": "ᄇᄃ", - "ㅳ": "ᄇᄃ", - "ퟣ": "ᄇᄃ", - "ᇣ": "ᄇᄅ", - "ퟤ": "ᄇᄅᄑ", - "ퟥ": "ᄇᄆ", - "ᄈ": "ᄇᄇ", - "ㅃ": "ᄇᄇ", - "ퟦ": "ᄇᄇ", - "ᄬ": "ᄇᄇᄋ", - "ㅹ": "ᄇᄇᄋ", - "ᄡ": "ᄇᄉ", - "ㅄ": "ᄇᄉ", - "ᆹ": "ᄇᄉ", - "ᄢ": "ᄇᄉᄀ", - "ㅴ": "ᄇᄉᄀ", - "ᄣ": "ᄇᄉᄃ", - "ㅵ": "ᄇᄉᄃ", - "ퟧ": "ᄇᄉᄃ", - "ᄤ": "ᄇᄉᄇ", - "ᄥ": "ᄇᄉᄉ", - "ᄦ": "ᄇᄉᄌ", - "ꥲ": "ᄇᄉᄐ", - "ᄫ": "ᄇᄋ", - "ㅸ": "ᄇᄋ", - "ᇦ": "ᄇᄋ", - "ᄧ": "ᄇᄌ", - "ㅶ": "ᄇᄌ", - "ퟨ": "ᄇᄌ", - "ᄨ": "ᄇᄎ", - "ퟩ": "ᄇᄎ", - "ꥳ": "ᄇᄏ", - "ᄩ": "ᄇᄐ", - "ㅷ": "ᄇᄐ", - "ᄪ": "ᄇᄑ", - "ᇤ": "ᄇᄑ", - "ꥴ": "ᄇᄒ", - "ᇥ": "ᄇᄒ", - "ㅅ": "ᄉ", - "ᆺ": "ᄉ", - "ᄭ": "ᄉᄀ", - "ㅺ": "ᄉᄀ", - "ᇧ": "ᄉᄀ", - "ᄮ": "ᄉᄂ", - "ㅻ": "ᄉᄂ", - "ᄯ": "ᄉᄃ", - "ㅼ": "ᄉᄃ", - "ᇨ": "ᄉᄃ", - "ᄰ": "ᄉᄅ", - "ᇩ": "ᄉᄅ", - "ᄱ": "ᄉᄆ", - "ퟪ": "ᄉᄆ", - "ᄲ": "ᄉᄇ", - "ㅽ": "ᄉᄇ", - "ᇪ": "ᄉᄇ", - "ᄳ": "ᄉᄇᄀ", - "ퟫ": "ᄉᄇᄋ", - "ᄊ": "ᄉᄉ", - "ㅆ": "ᄉᄉ", - "ᆻ": "ᄉᄉ", - "ퟬ": "ᄉᄉᄀ", - "ퟭ": "ᄉᄉᄃ", - "ꥵ": "ᄉᄉᄇ", - "ᄴ": "ᄉᄉᄉ", - "ᄵ": "ᄉᄋ", - "ᄶ": "ᄉᄌ", - "ㅾ": "ᄉᄌ", - "ퟯ": "ᄉᄌ", - "ᄷ": "ᄉᄎ", - "ퟰ": "ᄉᄎ", - "ᄸ": "ᄉᄏ", - "ᄹ": "ᄉᄐ", - "ퟱ": "ᄉᄐ", - "ᄺ": "ᄉᄑ", - "ퟮ": "ᄉᅀ", - "ㅇ": "ᄋ", - "ᆼ": "ᄋ", - "ᅁ": "ᄋᄀ", - "ᇬ": "ᄋᄀ", - "ᇭ": "ᄋᄀᄀ", - "ᅂ": "ᄋᄃ", - "ꥶ": "ᄋᄅ", - "ᅃ": "ᄋᄆ", - "ᅄ": "ᄋᄇ", - "ᅅ": "ᄋᄉ", - "ᇱ": "ᄋᄉ", - "ㆂ": "ᄋᄉ", - "ᅇ": "ᄋᄋ", - "ㆀ": "ᄋᄋ", - "ᇮ": "ᄋᄋ", - "ᅈ": "ᄋᄌ", - "ᅉ": "ᄋᄎ", - "ᇯ": "ᄋᄏ", - "ᅊ": "ᄋᄐ", - "ᅋ": "ᄋᄑ", - "ꥷ": "ᄋᄒ", - "ᅆ": "ᄋᅀ", - "ᇲ": "ᄋᅀ", - "ㆃ": "ᄋᅀ", - "ㅈ": "ᄌ", - "ᆽ": "ᄌ", - "ퟷ": "ᄌᄇ", - "ퟸ": "ᄌᄇᄇ", - "ᅍ": "ᄌᄋ", - "ᄍ": "ᄌᄌ", - "ㅉ": "ᄌᄌ", - "ퟹ": "ᄌᄌ", - "ꥸ": "ᄌᄌᄒ", - "ㅊ": "ᄎ", - "ᆾ": "ᄎ", - "ᅒ": "ᄎᄏ", - "ᅓ": "ᄎᄒ", - "ㅋ": "ᄏ", - "ᆿ": "ᄏ", - "ㅌ": "ᄐ", - "ᇀ": "ᄐ", - "ꥹ": "ᄐᄐ", - "ㅍ": "ᄑ", - "ᇁ": "ᄑ", - "ᅖ": "ᄑᄇ", - "ᇳ": "ᄑᄇ", - "ퟺ": "ᄑᄉ", - "ᅗ": "ᄑᄋ", - "ㆄ": "ᄑᄋ", - "ᇴ": "ᄑᄋ", - "ퟻ": "ᄑᄐ", - "ꥺ": "ᄑᄒ", - "ㅎ": "ᄒ", - "ᇂ": "ᄒ", - "ᇵ": "ᄒᄂ", - "ᇶ": "ᄒᄅ", - "ᇷ": "ᄒᄆ", - "ᇸ": "ᄒᄇ", - "ꥻ": "ᄒᄉ", - "ᅘ": "ᄒᄒ", - "ㆅ": "ᄒᄒ", - "ᄽ": "ᄼᄼ", - "ᄿ": "ᄾᄾ", - "ㅿ": "ᅀ", - "ᇫ": "ᅀ", - "ퟳ": "ᅀᄇ", - "ퟴ": "ᅀᄇᄋ", - "ㆁ": "ᅌ", - "ᇰ": "ᅌ", - "ퟵ": "ᅌᄆ", - "ퟶ": "ᅌᄒ", - "ᅏ": "ᅎᅎ", - "ᅑ": "ᅐᅐ", - "ㆆ": "ᅙ", - "ᇹ": "ᅙ", - "ꥼ": "ᅙᅙ", - "ㅤ": "ᅠ", - "ㅏ": "ᅡ", - "ᆣ": "ᅡー", - "ᅶ": "ᅡᅩ", - "ᅷ": "ᅡᅮ", - "ᅢ": "ᅡ丨", - "ㅐ": "ᅡ丨", - "ㅑ": "ᅣ", - "ᅸ": "ᅣᅩ", - "ᅹ": "ᅣᅭ", - "ᆤ": "ᅣᅮ", - "ᅤ": "ᅣ丨", - "ㅒ": "ᅣ丨", - "ㅓ": "ᅥ", - "ᅼ": "ᅥー", - "ᅺ": "ᅥᅩ", - "ᅻ": "ᅥᅮ", - "ᅦ": "ᅥ丨", - "ㅔ": "ᅥ丨", - "ㅕ": "ᅧ", - "ᆥ": "ᅧᅣ", - "ᅽ": "ᅧᅩ", - "ᅾ": "ᅧᅮ", - "ᅨ": "ᅧ丨", - "ㅖ": "ᅧ丨", - "ㅗ": "ᅩ", - "ᅪ": "ᅩᅡ", - "ㅘ": "ᅩᅡ", - "ᅫ": "ᅩᅡ丨", - "ㅙ": "ᅩᅡ丨", - "ᆦ": "ᅩᅣ", - "ᆧ": "ᅩᅣ丨", - "ᅿ": "ᅩᅥ", - "ᆀ": "ᅩᅥ丨", - "ힰ": "ᅩᅧ", - "ᆁ": "ᅩᅧ丨", - "ᆂ": "ᅩᅩ", - "ힱ": "ᅩᅩ丨", - "ᆃ": "ᅩᅮ", - "ᅬ": "ᅩ丨", - "ㅚ": "ᅩ丨", - "ㅛ": "ᅭ", - "ힲ": "ᅭᅡ", - "ힳ": "ᅭᅡ丨", - "ᆄ": "ᅭᅣ", - "ㆇ": "ᅭᅣ", - "ᆆ": "ᅭᅣ", - "ᆅ": "ᅭᅣ丨", - "ㆈ": "ᅭᅣ丨", - "ힴ": "ᅭᅥ", - "ᆇ": "ᅭᅩ", - "ᆈ": "ᅭ丨", - "ㆉ": "ᅭ丨", - "ㅜ": "ᅮ", - "ᆉ": "ᅮᅡ", - "ᆊ": "ᅮᅡ丨", - "ᅯ": "ᅮᅥ", - "ㅝ": "ᅮᅥ", - "ᆋ": "ᅮᅥー", - "ᅰ": "ᅮᅥ丨", - "ㅞ": "ᅮᅥ丨", - "ힵ": "ᅮᅧ", - "ᆌ": "ᅮᅧ丨", - "ᆍ": "ᅮᅮ", - "ᅱ": "ᅮ丨", - "ㅟ": "ᅮ丨", - "ힶ": "ᅮ丨丨", - "ㅠ": "ᅲ", - "ᆎ": "ᅲᅡ", - "ힷ": "ᅲᅡ丨", - "ᆏ": "ᅲᅥ", - "ᆐ": "ᅲᅥ丨", - "ᆑ": "ᅲᅧ", - "ㆊ": "ᅲᅧ", - "ᆒ": "ᅲᅧ丨", - "ㆋ": "ᅲᅧ丨", - "ힸ": "ᅲᅩ", - "ᆓ": "ᅲᅮ", - "ᆔ": "ᅲ丨", - "ㆌ": "ᅲ丨", - "ㆍ": "ᆞ", - "ퟅ": "ᆞᅡ", - "ᆟ": "ᆞᅥ", - "ퟆ": "ᆞᅥ丨", - "ᆠ": "ᆞᅮ", - "ᆢ": "ᆞᆞ", - "ᆡ": "ᆞ丨", - "ㆎ": "ᆞ丨", - "ヘ": "へ", - "⍁": "〼", - "⧄": "〼", - "꒞": "ꁊ", - "꒬": "ꁐ", - "꒜": "ꃀ", - "꒨": "ꄲ", - "꒿": "ꉙ", - "꒾": "ꊱ", - "꒔": "ꋍ", - "꓀": "ꎫ", - "꓂": "ꎵ", - "꒺": "ꎿ", - "꒰": "ꏂ", - "꒧": "ꑘ", - "⊥": "ꓕ", - "⟂": "ꓕ", - "𝈜": "ꓕ", - "Ʇ": "ꓕ", - "Ꞟ": "ꓤ", - "⅁": "ꓨ", - "⅂": "ꓶ", - "𝈕": "ꓶ", - "𝈫": "ꓶ", - "𖼦": "ꓶ", - "𐐑": "ꓶ", - "⅃": "𖼀", - "𑫦": "𑫥𑫯", - "𑫨": "𑫥𑫥", - "𑫩": "𑫥𑫥𑫯", - "𑫪": "𑫥𑫥𑫰", - "𑫧": "𑫥𑫰", - "𑫴": "𑫳𑫯", - "𑫶": "𑫳𑫳", - "𑫷": "𑫳𑫳𑫯", - "𑫸": "𑫳𑫳𑫰", - "𑫵": "𑫳𑫰", - "𑫬": "𑫫𑫯", - "𑫭": "𑫫𑫫", - "𑫮": "𑫫𑫫𑫯", - "⊕": "𐊨", - "⨁": "𐊨", - "🜨": "𐊨", - "Ꚛ": "𐊨", - "▽": "𐊼", - "𝈔": "𐊼", - "🜄": "𐊼", - "⧖": "𐋀", - "ꞛ": "𐐺", - "Ꞛ": "𐐒", - "𐒠": "𐒆", - "𐏑": "𐎂", - "𐏓": "𐎓", - "𒀸": "𐎚", - "☥": "𐦞", - "𓋹": "𐦞", - "〹": "卄", - "不": "不", - "丽": "丽", - "並": "並", - "⎜": "丨", - "⎟": "丨", - "⎢": "丨", - "⎥": "丨", - "⎪": "丨", - "⎮": "丨", - "㇑": "丨", - "ᅵ": "丨", - "ㅣ": "丨", - "⼁": "丨", - "ᆜ": "丨ー", - "ᆘ": "丨ᅡ", - "ᆙ": "丨ᅣ", - "ힽ": "丨ᅣᅩ", - "ힾ": "丨ᅣ丨", - "ힿ": "丨ᅧ", - "ퟀ": "丨ᅧ丨", - "ᆚ": "丨ᅩ", - "ퟁ": "丨ᅩ丨", - "ퟂ": "丨ᅭ", - "ᆛ": "丨ᅮ", - "ퟃ": "丨ᅲ", - "ᆝ": "丨ᆞ", - "ퟄ": "丨丨", - "串": "串", - "丸": "丸", - "丹": "丹", - "乁": "乁", - "㇠": "乙", - "⼄": "乙", - "㇟": "乚", - "⺃": "乚", - "㇖": "乛", - "⺂": "乛", - "⻲": "亀", - "亂": "亂", - "㇚": "亅", - "⼅": "亅", - "了": "了", - "ニ": "二", - "⼆": "二", - "𠄢": "𠄢", - "⼇": "亠", - "亮": "亮", - "⼈": "人", - "イ": "亻", - "⺅": "亻", - "什": "什", - "仌": "仌", - "令": "令", - "你": "你", - "倂": "併", - "倂": "併", - "侀": "侀", - "來": "來", - "例": "例", - "侮": "侮", - "侮": "侮", - "侻": "侻", - "便": "便", - "值": "値", - "倫": "倫", - "偺": "偺", - "備": "備", - "像": "像", - "僚": "僚", - "僧": "僧", - "僧": "僧", - "㒞": "㒞", - "⼉": "儿", - "兀": "兀", - "⺎": "兀", - "充": "充", - "免": "免", - "免": "免", - "兔": "兔", - "兤": "兤", - "⼊": "入", - "內": "內", - "全": "全", - "兩": "兩", - "ハ": "八", - "⼋": "八", - "六": "六", - "具": "具", - "𠔜": "𠔜", - "𠔥": "𠔥", - "冀": "冀", - "㒹": "㒹", - "⼌": "冂", - "再": "再", - "𠕋": "𠕋", - "冒": "冒", - "冕": "冕", - "㒻": "㒻", - "最": "最", - "⼍": "冖", - "冗": "冗", - "冤": "冤", - "⼎": "冫", - "冬": "冬", - "况": "况", - "况": "况", - "冷": "冷", - "凉": "凉", - "凌": "凌", - "凜": "凜", - "凞": "凞", - "⼏": "几", - "𠘺": "𠘺", - "凵": "凵", - "⼐": "凵", - "⼑": "刀", - "⺉": "刂", - "刃": "刃", - "切": "切", - "切": "切", - "列": "列", - "利": "利", - "㓟": "㓟", - "刺": "刺", - "刻": "刻", - "剆": "剆", - "割": "割", - "剷": "剷", - "劉": "劉", - "𠠄": "𠠄", - "カ": "力", - "力": "力", - "⼒": "力", - "劣": "劣", - "㔕": "㔕", - "劳": "劳", - "勇": "勇", - "勇": "勇", - "勉": "勉", - "勉": "勉", - "勒": "勒", - "勞": "勞", - "勤": "勤", - "勤": "勤", - "勵": "勵", - "⼓": "勹", - "勺": "勺", - "勺": "勺", - "包": "包", - "匆": "匆", - "𠣞": "𠣞", - "⼔": "匕", - "北": "北", - "北": "北", - "⼕": "匚", - "⼖": "匸", - "匿": "匿", - "⼗": "十", - "〸": "十", - "〺": "卅", - "卉": "卉", - "࿖": "卍", - "࿕": "卐", - "卑": "卑", - "卑": "卑", - "博": "博", - "ト": "卜", - "⼘": "卜", - "⼙": "卩", - "⺋": "㔾", - "即": "即", - "卵": "卵", - "卽": "卽", - "卿": "卿", - "卿": "卿", - "卿": "卿", - "⼚": "厂", - "𠨬": "𠨬", - "⼛": "厶", - "參": "參", - "⼜": "又", - "及": "及", - "叟": "叟", - "𠭣": "𠭣", - "ロ": "口", - "⼝": "口", - "囗": "口", - "⼞": "口", - "句": "句", - "叫": "叫", - "叱": "叱", - "吆": "吆", - "吏": "吏", - "吝": "吝", - "吸": "吸", - "呂": "呂", - "呈": "呈", - "周": "周", - "咞": "咞", - "咢": "咢", - "咽": "咽", - "䎛": "㖈", - "哶": "哶", - "唐": "唐", - "啓": "啓", - "啟": "啓", - "啕": "啕", - "啣": "啣", - "善": "善", - "善": "善", - "喇": "喇", - "喙": "喙", - "喙": "喙", - "喝": "喝", - "喝": "喝", - "喫": "喫", - "喳": "喳", - "嗀": "嗀", - "嗂": "嗂", - "嗢": "嗢", - "嘆": "嘆", - "嘆": "嘆", - "噑": "噑", - "噴": "噴", - "器": "器", - "囹": "囹", - "圖": "圖", - "圗": "圗", - "⼟": "土", - "士": "土", - "⼠": "土", - "型": "型", - "城": "城", - "㦳": "㘽", - "埴": "埴", - "堍": "堍", - "報": "報", - "堲": "堲", - "塀": "塀", - "塚": "塚", - "塚": "塚", - "塞": "塞", - "填": "塡", - "壿": "墫", - "墬": "墬", - "墳": "墳", - "壘": "壘", - "壟": "壟", - "𡓤": "𡓤", - "壮": "壮", - "売": "売", - "壷": "壷", - "⼡": "夂", - "夆": "夆", - "⼢": "夊", - "タ": "夕", - "⼣": "夕", - "多": "多", - "夢": "夢", - "⼤": "大", - "奄": "奄", - "奈": "奈", - "契": "契", - "奔": "奔", - "奢": "奢", - "女": "女", - "⼥": "女", - "𡚨": "𡚨", - "𡛪": "𡛪", - "姘": "姘", - "姬": "姬", - "娛": "娛", - "娧": "娧", - "婢": "婢", - "婦": "婦", - "嬀": "媯", - "㛮": "㛮", - "㛼": "㛼", - "媵": "媵", - "嬈": "嬈", - "嬨": "嬨", - "嬾": "嬾", - "嬾": "嬾", - "⼦": "子", - "⼧": "宀", - "宅": "宅", - "𡧈": "𡧈", - "寃": "寃", - "寘": "寘", - "寧": "寧", - "寧": "寧", - "寧": "寧", - "寮": "寮", - "寳": "寳", - "𡬘": "𡬘", - "⼨": "寸", - "寿": "寿", - "将": "将", - "⼩": "小", - "尢": "尢", - "⺐": "尢", - "⼪": "尢", - "⺏": "尣", - "㞁": "㞁", - "⼫": "尸", - "尿": "尿", - "屠": "屠", - "屢": "屢", - "層": "層", - "履": "履", - "屮": "屮", - "屮": "屮", - "⼬": "屮", - "𡴋": "𡴋", - "⼭": "山", - "峀": "峀", - "岍": "岍", - "𡷤": "𡷤", - "𡷦": "𡷦", - "崙": "崙", - "嵃": "嵃", - "嵐": "嵐", - "嵫": "嵫", - "嵮": "嵮", - "嵼": "嵼", - "嶲": "嶲", - "嶺": "嶺", - "⼮": "巛", - "巢": "巢", - "エ": "工", - "⼯": "工", - "⼰": "己", - "⺒": "巳", - "㠯": "㠯", - "巽": "巽", - "⼱": "巾", - "帲": "帡", - "帨": "帨", - "帽": "帽", - "幩": "幩", - "㡢": "㡢", - "𢆃": "𢆃", - "⼲": "干", - "年": "年", - "𢆟": "𢆟", - "⺓": "幺", - "⼳": "幺", - "⼴": "广", - "度": "度", - "㡼": "㡼", - "庰": "庰", - "庳": "庳", - "庶": "庶", - "廊": "廊", - "廊": "廊", - "廉": "廉", - "廒": "廒", - "廓": "廓", - "廙": "廙", - "廬": "廬", - "⼵": "廴", - "廾": "廾", - "⼶": "廾", - "𢌱": "𢌱", - "𢌱": "𢌱", - "弄": "弄", - "⼷": "弋", - "⼸": "弓", - "弢": "弢", - "弢": "弢", - "⼹": "彐", - "⺔": "彑", - "当": "当", - "㣇": "㣇", - "⼺": "彡", - "形": "形", - "彩": "彩", - "彫": "彫", - "⼻": "彳", - "律": "律", - "㣣": "㣣", - "徚": "徚", - "復": "復", - "徭": "徭", - "⼼": "心", - "⺖": "忄", - "⺗": "㣺", - "忍": "忍", - "志": "志", - "念": "念", - "忹": "忹", - "怒": "怒", - "怜": "怜", - "恵": "恵", - "㤜": "㤜", - "㤺": "㤺", - "悁": "悁", - "悔": "悔", - "悔": "悔", - "惇": "惇", - "惘": "惘", - "惡": "惡", - "𢛔": "𢛔", - "愈": "愈", - "慨": "慨", - "慄": "慄", - "慈": "慈", - "慌": "慌", - "慌": "慌", - "慎": "慎", - "慎": "慎", - "慠": "慠", - "慺": "慺", - "憎": "憎", - "憎": "憎", - "憎": "憎", - "憐": "憐", - "憤": "憤", - "憯": "憯", - "憲": "憲", - "𢡄": "𢡄", - "𢡊": "𢡊", - "懞": "懞", - "懲": "懲", - "懲": "懲", - "懲": "懲", - "懶": "懶", - "懶": "懶", - "戀": "戀", - "⼽": "戈", - "成": "成", - "戛": "戛", - "戮": "戮", - "戴": "戴", - "⼾": "戶", - "戸": "戶", - "⼿": "手", - "⺘": "扌", - "扝": "扝", - "抱": "抱", - "拉": "拉", - "拏": "拏", - "拓": "拓", - "拔": "拔", - "拼": "拼", - "拾": "拾", - "𢬌": "𢬌", - "挽": "挽", - "捐": "捐", - "捨": "捨", - "捻": "捻", - "掃": "掃", - "掠": "掠", - "掩": "掩", - "揄": "揄", - "揤": "揤", - "摒": "摒", - "𢯱": "𢯱", - "搜": "搜", - "搢": "搢", - "揅": "揅", - "摩": "摩", - "摷": "摷", - "摾": "摾", - "㨮": "㨮", - "搉": "㩁", - "撚": "撚", - "撝": "撝", - "擄": "擄", - "㩬": "㩬", - "⽀": "支", - "⽁": "攴", - "⺙": "攵", - "敏": "敏", - "敏": "敏", - "敖": "敖", - "敬": "敬", - "數": "數", - "𣀊": "𣀊", - "⽂": "文", - "⻫": "斉", - "⽃": "斗", - "料": "料", - "⽄": "斤", - "⽅": "方", - "旅": "旅", - "⽆": "无", - "⺛": "旡", - "既": "既", - "旣": "旣", - "⽇": "日", - "易": "易", - "曶": "㫚", - "㫤": "㫤", - "晉": "晉", - "晩": "晚", - "晴": "晴", - "晴": "晴", - "暑": "暑", - "暑": "暑", - "暈": "暈", - "㬈": "㬈", - "暜": "暜", - "暴": "暴", - "曆": "曆", - "㬙": "㬙", - "𣊸": "𣊸", - "⽈": "曰", - "更": "更", - "書": "書", - "⽉": "月", - "𣍟": "𣍟", - "肦": "朌", - "胐": "朏", - "胊": "朐", - "脁": "朓", - "胶": "㬵", - "朗": "朗", - "朗": "朗", - "朗": "朗", - "脧": "朘", - "望": "望", - "望": "望", - "幐": "㬺", - "䐠": "㬻", - "𣎓": "𣎓", - "膧": "朣", - "𣎜": "𣎜", - "⽊": "木", - "李": "李", - "杓": "杓", - "杖": "杖", - "杞": "杞", - "𣏃": "𣏃", - "柿": "杮", - "杻": "杻", - "枅": "枅", - "林": "林", - "㭉": "㭉", - "𣏕": "𣏕", - "柳": "柳", - "柺": "柺", - "栗": "栗", - "栟": "栟", - "桒": "桒", - "𣑭": "𣑭", - "梁": "梁", - "梅": "梅", - "梅": "梅", - "梎": "梎", - "梨": "梨", - "椔": "椔", - "楂": "楂", - "㮝": "㮝", - "㮝": "㮝", - "槩": "㮣", - "樧": "榝", - "榣": "榣", - "槪": "槪", - "樂": "樂", - "樂": "樂", - "樂": "樂", - "樓": "樓", - "𣚣": "𣚣", - "檨": "檨", - "櫓": "櫓", - "櫛": "櫛", - "欄": "欄", - "㰘": "㰘", - "⽋": "欠", - "次": "次", - "𣢧": "𣢧", - "歔": "歔", - "㱎": "㱎", - "⽌": "止", - "⻭": "歯", - "歲": "歲", - "歷": "歷", - "歹": "歹", - "⽍": "歹", - "⺞": "歺", - "殟": "殟", - "殮": "殮", - "⽎": "殳", - "殺": "殺", - "殺": "殺", - "殺": "殺", - "殻": "殻", - "𣪍": "𣪍", - "⽏": "毋", - "⺟": "母", - "𣫺": "𣫺", - "⽐": "比", - "⽑": "毛", - "⽒": "氏", - "⺠": "民", - "⽓": "气", - "⽔": "水", - "⺡": "氵", - "⺢": "氺", - "汎": "汎", - "汧": "汧", - "沈": "沈", - "沿": "沿", - "泌": "泌", - "泍": "泍", - "泥": "泥", - "𣲼": "𣲼", - "洛": "洛", - "洞": "洞", - "洴": "洴", - "派": "派", - "流": "流", - "流": "流", - "流": "流", - "洖": "洖", - "浩": "浩", - "浪": "浪", - "海": "海", - "海": "海", - "浸": "浸", - "涅": "涅", - "𣴞": "𣴞", - "淋": "淋", - "淚": "淚", - "淪": "淪", - "淹": "淹", - "渚": "渚", - "港": "港", - "湮": "湮", - "潙": "溈", - "滋": "滋", - "滋": "滋", - "溜": "溜", - "溺": "溺", - "滇": "滇", - "滑": "滑", - "滛": "滛", - "㴳": "㴳", - "漏": "漏", - "漢": "漢", - "漢": "漢", - "漣": "漣", - "𣻑": "𣻑", - "潮": "潮", - "𣽞": "𣽞", - "𣾎": "𣾎", - "濆": "濆", - "濫": "濫", - "濾": "濾", - "瀛": "瀛", - "瀞": "瀞", - "瀞": "瀞", - "瀹": "瀹", - "灊": "灊", - "㶖": "㶖", - "⽕": "火", - "⺣": "灬", - "灰": "灰", - "灷": "灷", - "災": "災", - "炙": "炙", - "炭": "炭", - "烈": "烈", - "烙": "烙", - "煮": "煮", - "煮": "煮", - "𤉣": "𤉣", - "煅": "煅", - "煉": "煉", - "𤋮": "𤋮", - "熜": "熜", - "燎": "燎", - "燐": "燐", - "𤎫": "𤎫", - "爐": "爐", - "爛": "爛", - "爨": "爨", - "⽖": "爪", - "爫": "爫", - "⺤": "爫", - "爵": "爵", - "爵": "爵", - "⽗": "父", - "⽘": "爻", - "⺦": "丬", - "⽙": "爿", - "⽚": "片", - "牐": "牐", - "⽛": "牙", - "𤘈": "𤘈", - "⽜": "牛", - "牢": "牢", - "犀": "犀", - "犕": "犕", - "⽝": "犬", - "⺨": "犭", - "犯": "犯", - "狀": "狀", - "𤜵": "𤜵", - "狼": "狼", - "猪": "猪", - "猪": "猪", - "𤠔": "𤠔", - "獵": "獵", - "獺": "獺", - "⽞": "玄", - "率": "率", - "率": "率", - "⽟": "玉", - "王": "王", - "㺬": "㺬", - "玥": "玥", - "玲": "玲", - "㺸": "㺸", - "㺸": "㺸", - "珞": "珞", - "琉": "琉", - "理": "理", - "琢": "琢", - "瑇": "瑇", - "瑜": "瑜", - "瑩": "瑩", - "瑱": "瑱", - "瑱": "瑱", - "璅": "璅", - "璉": "璉", - "璘": "璘", - "瓊": "瓊", - "⽠": "瓜", - "⽡": "瓦", - "㼛": "㼛", - "甆": "甆", - "⽢": "甘", - "⽣": "生", - "甤": "甤", - "⽤": "用", - "⽥": "田", - "画": "画", - "甾": "甾", - "𤰶": "𤰶", - "留": "留", - "略": "略", - "異": "異", - "異": "異", - "𤲒": "𤲒", - "⽦": "疋", - "⽧": "疒", - "痢": "痢", - "瘐": "瘐", - "瘟": "瘟", - "瘝": "瘝", - "療": "療", - "癩": "癩", - "⽨": "癶", - "⽩": "白", - "𤾡": "𤾡", - "𤾸": "𤾸", - "⽪": "皮", - "⽫": "皿", - "𥁄": "𥁄", - "㿼": "㿼", - "益": "益", - "益": "益", - "盛": "盛", - "盧": "盧", - "䀈": "䀈", - "⽬": "目", - "直": "直", - "直": "直", - "𥃲": "𥃲", - "𥃳": "𥃳", - "省": "省", - "䀘": "䀘", - "𥄙": "𥄙", - "眞": "眞", - "真": "真", - "真": "真", - "𥄳": "𥄳", - "着": "着", - "睊": "睊", - "睊": "睊", - "鿃": "䀹", - "䀹": "䀹", - "䀹": "䀹", - "晣": "䀿", - "䁆": "䁆", - "瞋": "瞋", - "𥉉": "𥉉", - "瞧": "瞧", - "⽭": "矛", - "⽮": "矢", - "⽯": "石", - "䂖": "䂖", - "𥐝": "𥐝", - "硏": "研", - "硎": "硎", - "硫": "硫", - "碌": "碌", - "碌": "碌", - "碑": "碑", - "磊": "磊", - "磌": "磌", - "磌": "磌", - "磻": "磻", - "䃣": "䃣", - "礪": "礪", - "⽰": "示", - "⺭": "礻", - "礼": "礼", - "社": "社", - "祈": "祈", - "祉": "祉", - "𥘦": "𥘦", - "祐": "祐", - "祖": "祖", - "祖": "祖", - "祝": "祝", - "神": "神", - "祥": "祥", - "視": "視", - "視": "視", - "祿": "祿", - "𥚚": "𥚚", - "禍": "禍", - "禎": "禎", - "福": "福", - "福": "福", - "𥛅": "𥛅", - "禮": "禮", - "⽱": "禸", - "⽲": "禾", - "秊": "秊", - "䄯": "䄯", - "秫": "秫", - "稜": "稜", - "穊": "穊", - "穀": "穀", - "穀": "穀", - "穏": "穏", - "⽳": "穴", - "突": "突", - "𥥼": "𥥼", - "窱": "窱", - "立": "立", - "⽴": "立", - "⻯": "竜", - "𥪧": "𥪧", - "𥪧": "𥪧", - "竮": "竮", - "⽵": "竹", - "笠": "笠", - "節": "節", - "節": "節", - "䈂": "䈂", - "𥮫": "𥮫", - "篆": "篆", - "䈧": "䈧", - "築": "築", - "𥲀": "𥲀", - "𥳐": "𥳐", - "簾": "簾", - "籠": "籠", - "⽶": "米", - "类": "类", - "粒": "粒", - "精": "精", - "糒": "糒", - "糖": "糖", - "糨": "糨", - "䊠": "䊠", - "糣": "糣", - "糧": "糧", - "⽷": "糸", - "⺯": "糹", - "𥾆": "𥾆", - "紀": "紀", - "紐": "紐", - "索": "索", - "累": "累", - "絶": "絕", - "絣": "絣", - "絛": "絛", - "綠": "綠", - "綾": "綾", - "緇": "緇", - "練": "練", - "練": "練", - "練": "練", - "縂": "縂", - "䌁": "䌁", - "縉": "縉", - "縷": "縷", - "繁": "繁", - "繅": "繅", - "𦇚": "𦇚", - "䌴": "䌴", - "⽸": "缶", - "𦈨": "𦈨", - "缾": "缾", - "𦉇": "𦉇", - "⽹": "网", - "⺫": "罒", - "⺲": "罒", - "⺱": "罓", - "䍙": "䍙", - "署": "署", - "𦋙": "𦋙", - "罹": "罹", - "罺": "罺", - "羅": "羅", - "𦌾": "𦌾", - "⽺": "羊", - "羕": "羕", - "羚": "羚", - "羽": "羽", - "⽻": "羽", - "翺": "翺", - "老": "老", - "⽼": "老", - "⺹": "耂", - "者": "者", - "者": "者", - "者": "者", - "⽽": "而", - "𦓚": "𦓚", - "⽾": "耒", - "𦔣": "𦔣", - "⽿": "耳", - "聆": "聆", - "聠": "聠", - "𦖨": "𦖨", - "聯": "聯", - "聰": "聰", - "聾": "聾", - "⾀": "聿", - "⺺": "肀", - "⾁": "肉", - "肋": "肋", - "肭": "肭", - "育": "育", - "䏕": "䏕", - "䏙": "䏙", - "腁": "胼", - "脃": "脃", - "脾": "脾", - "䐋": "䐋", - "朡": "朡", - "𦞧": "𦞧", - "𦞵": "𦞵", - "朦": "䑃", - "臘": "臘", - "⾂": "臣", - "臨": "臨", - "⾃": "自", - "臭": "臭", - "⾄": "至", - "⾅": "臼", - "舁": "舁", - "舁": "舁", - "舄": "舄", - "⾆": "舌", - "舘": "舘", - "⾇": "舛", - "⾈": "舟", - "䑫": "䑫", - "⾉": "艮", - "良": "良", - "⾊": "色", - "⾋": "艸", - "艹": "艹", - "艹": "艹", - "⺾": "艹", - "⺿": "艹", - "⻀": "艹", - "芋": "芋", - "芑": "芑", - "芝": "芝", - "花": "花", - "芳": "芳", - "芽": "芽", - "若": "若", - "若": "若", - "苦": "苦", - "𦬼": "𦬼", - "茶": "茶", - "荒": "荒", - "荣": "荣", - "茝": "茝", - "茣": "茣", - "莽": "莽", - "荓": "荓", - "菉": "菉", - "菊": "菊", - "菌": "菌", - "菜": "菜", - "菧": "菧", - "華": "華", - "菱": "菱", - "著": "著", - "著": "著", - "𦰶": "𦰶", - "莭": "莭", - "落": "落", - "葉": "葉", - "蔿": "蒍", - "𦳕": "𦳕", - "𦵫": "𦵫", - "蓮": "蓮", - "蓱": "蓱", - "蓳": "蓳", - "蓼": "蓼", - "蔖": "蔖", - "䔫": "䔫", - "蕤": "蕤", - "𦼬": "𦼬", - "藍": "藍", - "䕝": "䕝", - "𦾱": "𦾱", - "䕡": "䕡", - "藺": "藺", - "蘆": "蘆", - "䕫": "䕫", - "蘒": "蘒", - "蘭": "蘭", - "𧃒": "𧃒", - "虁": "蘷", - "蘿": "蘿", - "⾌": "虍", - "⻁": "虎", - "虐": "虐", - "虜": "虜", - "虜": "虜", - "虧": "虧", - "虩": "虩", - "⾍": "虫", - "蚩": "蚩", - "蚈": "蚈", - "蛢": "蛢", - "蜎": "蜎", - "蜨": "蜨", - "蝫": "蝫", - "蟡": "蟡", - "蝹": "蝹", - "蝹": "蝹", - "螆": "螆", - "䗗": "䗗", - "𧏊": "𧏊", - "螺": "螺", - "蠁": "蠁", - "䗹": "䗹", - "蠟": "蠟", - "⾎": "血", - "行": "行", - "⾏": "行", - "衠": "衠", - "衣": "衣", - "⾐": "衣", - "⻂": "衤", - "裂": "裂", - "𧙧": "𧙧", - "裏": "裏", - "裗": "裗", - "裞": "裞", - "裡": "裡", - "裸": "裸", - "裺": "裺", - "䘵": "䘵", - "褐": "褐", - "襁": "襁", - "襤": "襤", - "⾑": "襾", - "⻄": "西", - "⻃": "覀", - "覆": "覆", - "見": "見", - "⾒": "見", - "𧢮": "𧢮", - "⻅": "见", - "⾓": "角", - "⾔": "言", - "𧥦": "𧥦", - "詽": "訮", - "訞": "䚶", - "䚾": "䚾", - "䛇": "䛇", - "誠": "誠", - "說": "說", - "說": "說", - "調": "調", - "請": "請", - "諒": "諒", - "論": "論", - "諭": "諭", - "諭": "諭", - "諸": "諸", - "諸": "諸", - "諾": "諾", - "諾": "諾", - "謁": "謁", - "謁": "謁", - "謹": "謹", - "謹": "謹", - "識": "識", - "讀": "讀", - "讏": "讆", - "變": "變", - "變": "變", - "⻈": "讠", - "⾕": "谷", - "⾖": "豆", - "豈": "豈", - "豕": "豕", - "⾗": "豕", - "豣": "豜", - "⾘": "豸", - "𧲨": "𧲨", - "⾙": "貝", - "貫": "貫", - "賁": "賁", - "賂": "賂", - "賈": "賈", - "賓": "賓", - "贈": "贈", - "贈": "贈", - "贛": "贛", - "⻉": "贝", - "⾚": "赤", - "⾛": "走", - "起": "起", - "趆": "赿", - "𧻓": "𧻓", - "𧼯": "𧼯", - "⾜": "足", - "跋": "跋", - "趼": "趼", - "跺": "跥", - "路": "路", - "跰": "跰", - "躛": "躗", - "⾝": "身", - "車": "車", - "⾞": "車", - "軔": "軔", - "輧": "軿", - "輦": "輦", - "輪": "輪", - "輸": "輸", - "輸": "輸", - "輻": "輻", - "轢": "轢", - "⻋": "车", - "⾟": "辛", - "辞": "辞", - "辰": "辰", - "⾠": "辰", - "⾡": "辵", - "辶": "辶", - "⻌": "辶", - "⻍": "辶", - "巡": "巡", - "連": "連", - "逸": "逸", - "逸": "逸", - "遲": "遲", - "遼": "遼", - "𨗒": "𨗒", - "𨗭": "𨗭", - "邏": "邏", - "⾢": "邑", - "邔": "邔", - "郎": "郎", - "郞": "郎", - "郞": "郎", - "郱": "郱", - "都": "都", - "𨜮": "𨜮", - "鄑": "鄑", - "鄛": "鄛", - "⾣": "酉", - "酪": "酪", - "醙": "醙", - "醴": "醴", - "⾤": "釆", - "里": "里", - "⾥": "里", - "量": "量", - "金": "金", - "⾦": "金", - "鈴": "鈴", - "鈸": "鈸", - "鉶": "鉶", - "鋗": "鋗", - "鋘": "鋘", - "鉼": "鉼", - "錄": "錄", - "鍊": "鍊", - "鎮": "鎭", - "鏹": "鏹", - "鐕": "鐕", - "𨯺": "𨯺", - "⻐": "钅", - "⻑": "長", - "⾧": "長", - "⻒": "镸", - "⻓": "长", - "⾨": "門", - "開": "開", - "䦕": "䦕", - "閭": "閭", - "閷": "閷", - "𨵷": "𨵷", - "⻔": "门", - "⾩": "阜", - "⻏": "阝", - "⻖": "阝", - "阮": "阮", - "陋": "陋", - "降": "降", - "陵": "陵", - "陸": "陸", - "陼": "陼", - "隆": "隆", - "隣": "隣", - "䧦": "䧦", - "⾪": "隶", - "隷": "隷", - "隸": "隷", - "隸": "隷", - "⾫": "隹", - "雃": "雃", - "離": "離", - "難": "難", - "難": "難", - "⾬": "雨", - "零": "零", - "雷": "雷", - "霣": "霣", - "𩅅": "𩅅", - "露": "露", - "靈": "靈", - "⾭": "靑", - "⻘": "青", - "靖": "靖", - "靖": "靖", - "𩇟": "𩇟", - "⾮": "非", - "⾯": "面", - "𩈚": "𩈚", - "⾰": "革", - "䩮": "䩮", - "䩶": "䩶", - "⾱": "韋", - "韛": "韛", - "韠": "韠", - "⻙": "韦", - "⾲": "韭", - "𩐊": "𩐊", - "⾳": "音", - "響": "響", - "響": "響", - "⾴": "頁", - "䪲": "䪲", - "頋": "頋", - "頋": "頋", - "頋": "頋", - "領": "領", - "頩": "頩", - "𩒖": "𩒖", - "頻": "頻", - "頻": "頻", - "類": "類", - "⻚": "页", - "⾵": "風", - "𩖶": "𩖶", - "⻛": "风", - "⾶": "飛", - "⻜": "飞", - "⻝": "食", - "⾷": "食", - "⻟": "飠", - "飢": "飢", - "飯": "飯", - "飼": "飼", - "䬳": "䬳", - "館": "館", - "餩": "餩", - "⻠": "饣", - "⾸": "首", - "⾹": "香", - "馧": "馧", - "⾺": "馬", - "駂": "駂", - "駱": "駱", - "駾": "駾", - "驪": "驪", - "⻢": "马", - "⾻": "骨", - "䯎": "䯎", - "⾼": "高", - "⾽": "髟", - "𩬰": "𩬰", - "鬒": "鬒", - "鬒": "鬒", - "⾾": "鬥", - "⾿": "鬯", - "⿀": "鬲", - "⿁": "鬼", - "⻤": "鬼", - "⿂": "魚", - "魯": "魯", - "鱀": "鱀", - "鱗": "鱗", - "⻥": "鱼", - "⿃": "鳥", - "鳽": "鳽", - "䳎": "䳎", - "鵧": "鵧", - "䳭": "䳭", - "𪃎": "𪃎", - "鶴": "鶴", - "𪄅": "𪄅", - "䳸": "䳸", - "鷺": "鷺", - "𪈎": "𪈎", - "鸞": "鸞", - "鹃": "鹂", - "⿄": "鹵", - "鹿": "鹿", - "⿅": "鹿", - "𪊑": "𪊑", - "麗": "麗", - "麟": "麟", - "⿆": "麥", - "⻨": "麦", - "麻": "麻", - "⿇": "麻", - "𪎒": "𪎒", - "⿈": "黃", - "⻩": "黄", - "⿉": "黍", - "黎": "黎", - "䵖": "䵖", - "⿊": "黑", - "黒": "黑", - "墨": "墨", - "黹": "黹", - "⿋": "黹", - "⿌": "黽", - "鼅": "鼅", - "黾": "黾", - "⿍": "鼎", - "鼏": "鼏", - "⿎": "鼓", - "鼖": "鼖", - "⿏": "鼠", - "鼻": "鼻", - "⿐": "鼻", - "齃": "齃", - "⿑": "齊", - "⻬": "齐", - "⿒": "齒", - "𪘀": "𪘀", - "⻮": "齿", - "龍": "龍", - "⿓": "龍", - "龎": "龎", - "⻰": "龙", - "龜": "龜", - "龜": "龜", - "龜": "龜", - "⿔": "龜", - "⻳": "龟", - "⿕": "龠" -} -},{}],282:[function(require,module,exports){ -'use strict'; - - -var data = require('./data.json'); - -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; - -},{"./data.json":281}],283:[function(require,module,exports){ -(function (global){(function (){ - -/** - * Module exports. - */ - -module.exports = deprecate; - -/** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ - -function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -} - -/** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ - -function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!global.localStorage) return false; - } catch (_) { - return false; - } - var val = global.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; -} - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{}],284:[function(require,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -},{}],285:[function(require,module,exports){ -// Currently in sync with Node.js lib/internal/util/types.js -// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 - -'use strict'; - -var isArgumentsObject = require('is-arguments'); -var isGeneratorFunction = require('is-generator-function'); -var whichTypedArray = require('which-typed-array'); -var isTypedArray = require('is-typed-array'); - -function uncurryThis(f) { - return f.call.bind(f); -} - -var BigIntSupported = typeof BigInt !== 'undefined'; -var SymbolSupported = typeof Symbol !== 'undefined'; - -var ObjectToString = uncurryThis(Object.prototype.toString); - -var numberValue = uncurryThis(Number.prototype.valueOf); -var stringValue = uncurryThis(String.prototype.valueOf); -var booleanValue = uncurryThis(Boolean.prototype.valueOf); - -if (BigIntSupported) { - var bigIntValue = uncurryThis(BigInt.prototype.valueOf); -} - -if (SymbolSupported) { - var symbolValue = uncurryThis(Symbol.prototype.valueOf); -} - -function checkBoxedPrimitive(value, prototypeValueOf) { - if (typeof value !== 'object') { - return false; - } - try { - prototypeValueOf(value); - return true; - } catch(e) { - return false; - } -} - -exports.isArgumentsObject = isArgumentsObject; -exports.isGeneratorFunction = isGeneratorFunction; -exports.isTypedArray = isTypedArray; - -// Taken from here and modified for better browser support -// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js -function isPromise(input) { - return ( - ( - typeof Promise !== 'undefined' && - input instanceof Promise - ) || - ( - input !== null && - typeof input === 'object' && - typeof input.then === 'function' && - typeof input.catch === 'function' - ) - ); -} -exports.isPromise = isPromise; - -function isArrayBufferView(value) { - if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { - return ArrayBuffer.isView(value); - } - - return ( - isTypedArray(value) || - isDataView(value) - ); -} -exports.isArrayBufferView = isArrayBufferView; - - -function isUint8Array(value) { - return whichTypedArray(value) === 'Uint8Array'; -} -exports.isUint8Array = isUint8Array; - -function isUint8ClampedArray(value) { - return whichTypedArray(value) === 'Uint8ClampedArray'; -} -exports.isUint8ClampedArray = isUint8ClampedArray; - -function isUint16Array(value) { - return whichTypedArray(value) === 'Uint16Array'; -} -exports.isUint16Array = isUint16Array; - -function isUint32Array(value) { - return whichTypedArray(value) === 'Uint32Array'; -} -exports.isUint32Array = isUint32Array; - -function isInt8Array(value) { - return whichTypedArray(value) === 'Int8Array'; -} -exports.isInt8Array = isInt8Array; - -function isInt16Array(value) { - return whichTypedArray(value) === 'Int16Array'; -} -exports.isInt16Array = isInt16Array; - -function isInt32Array(value) { - return whichTypedArray(value) === 'Int32Array'; -} -exports.isInt32Array = isInt32Array; - -function isFloat32Array(value) { - return whichTypedArray(value) === 'Float32Array'; -} -exports.isFloat32Array = isFloat32Array; - -function isFloat64Array(value) { - return whichTypedArray(value) === 'Float64Array'; -} -exports.isFloat64Array = isFloat64Array; - -function isBigInt64Array(value) { - return whichTypedArray(value) === 'BigInt64Array'; -} -exports.isBigInt64Array = isBigInt64Array; - -function isBigUint64Array(value) { - return whichTypedArray(value) === 'BigUint64Array'; -} -exports.isBigUint64Array = isBigUint64Array; - -function isMapToString(value) { - return ObjectToString(value) === '[object Map]'; -} -isMapToString.working = ( - typeof Map !== 'undefined' && - isMapToString(new Map()) -); - -function isMap(value) { - if (typeof Map === 'undefined') { - return false; - } - - return isMapToString.working - ? isMapToString(value) - : value instanceof Map; -} -exports.isMap = isMap; - -function isSetToString(value) { - return ObjectToString(value) === '[object Set]'; -} -isSetToString.working = ( - typeof Set !== 'undefined' && - isSetToString(new Set()) -); -function isSet(value) { - if (typeof Set === 'undefined') { - return false; - } - - return isSetToString.working - ? isSetToString(value) - : value instanceof Set; -} -exports.isSet = isSet; - -function isWeakMapToString(value) { - return ObjectToString(value) === '[object WeakMap]'; -} -isWeakMapToString.working = ( - typeof WeakMap !== 'undefined' && - isWeakMapToString(new WeakMap()) -); -function isWeakMap(value) { - if (typeof WeakMap === 'undefined') { - return false; - } - - return isWeakMapToString.working - ? isWeakMapToString(value) - : value instanceof WeakMap; -} -exports.isWeakMap = isWeakMap; - -function isWeakSetToString(value) { - return ObjectToString(value) === '[object WeakSet]'; -} -isWeakSetToString.working = ( - typeof WeakSet !== 'undefined' && - isWeakSetToString(new WeakSet()) -); -function isWeakSet(value) { - return isWeakSetToString(value); -} -exports.isWeakSet = isWeakSet; - -function isArrayBufferToString(value) { - return ObjectToString(value) === '[object ArrayBuffer]'; -} -isArrayBufferToString.working = ( - typeof ArrayBuffer !== 'undefined' && - isArrayBufferToString(new ArrayBuffer()) -); -function isArrayBuffer(value) { - if (typeof ArrayBuffer === 'undefined') { - return false; - } - - return isArrayBufferToString.working - ? isArrayBufferToString(value) - : value instanceof ArrayBuffer; -} -exports.isArrayBuffer = isArrayBuffer; - -function isDataViewToString(value) { - return ObjectToString(value) === '[object DataView]'; -} -isDataViewToString.working = ( - typeof ArrayBuffer !== 'undefined' && - typeof DataView !== 'undefined' && - isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)) -); -function isDataView(value) { - if (typeof DataView === 'undefined') { - return false; - } - - return isDataViewToString.working - ? isDataViewToString(value) - : value instanceof DataView; -} -exports.isDataView = isDataView; - -// Store a copy of SharedArrayBuffer in case it's deleted elsewhere -var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined; -function isSharedArrayBufferToString(value) { - return ObjectToString(value) === '[object SharedArrayBuffer]'; -} -function isSharedArrayBuffer(value) { - if (typeof SharedArrayBufferCopy === 'undefined') { - return false; - } - - if (typeof isSharedArrayBufferToString.working === 'undefined') { - isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy()); - } - - return isSharedArrayBufferToString.working - ? isSharedArrayBufferToString(value) - : value instanceof SharedArrayBufferCopy; -} -exports.isSharedArrayBuffer = isSharedArrayBuffer; - -function isAsyncFunction(value) { - return ObjectToString(value) === '[object AsyncFunction]'; -} -exports.isAsyncFunction = isAsyncFunction; - -function isMapIterator(value) { - return ObjectToString(value) === '[object Map Iterator]'; -} -exports.isMapIterator = isMapIterator; - -function isSetIterator(value) { - return ObjectToString(value) === '[object Set Iterator]'; -} -exports.isSetIterator = isSetIterator; - -function isGeneratorObject(value) { - return ObjectToString(value) === '[object Generator]'; -} -exports.isGeneratorObject = isGeneratorObject; - -function isWebAssemblyCompiledModule(value) { - return ObjectToString(value) === '[object WebAssembly.Module]'; -} -exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; - -function isNumberObject(value) { - return checkBoxedPrimitive(value, numberValue); -} -exports.isNumberObject = isNumberObject; - -function isStringObject(value) { - return checkBoxedPrimitive(value, stringValue); -} -exports.isStringObject = isStringObject; - -function isBooleanObject(value) { - return checkBoxedPrimitive(value, booleanValue); -} -exports.isBooleanObject = isBooleanObject; - -function isBigIntObject(value) { - return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); -} -exports.isBigIntObject = isBigIntObject; - -function isSymbolObject(value) { - return SymbolSupported && checkBoxedPrimitive(value, symbolValue); -} -exports.isSymbolObject = isSymbolObject; - -function isBoxedPrimitive(value) { - return ( - isNumberObject(value) || - isStringObject(value) || - isBooleanObject(value) || - isBigIntObject(value) || - isSymbolObject(value) - ); -} -exports.isBoxedPrimitive = isBoxedPrimitive; - -function isAnyArrayBuffer(value) { - return typeof Uint8Array !== 'undefined' && ( - isArrayBuffer(value) || - isSharedArrayBuffer(value) - ); -} -exports.isAnyArrayBuffer = isAnyArrayBuffer; - -['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) { - Object.defineProperty(exports, method, { - enumerable: false, - value: function() { - throw new Error(method + ' is not supported in userland'); - } - }); -}); - -},{"is-arguments":147,"is-generator-function":149,"is-typed-array":150,"which-typed-array":303}],286:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || - function getOwnPropertyDescriptors(obj) { - var keys = Object.keys(obj); - var descriptors = {}; - for (var i = 0; i < keys.length; i++) { - descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); - } - return descriptors; - }; - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - if (typeof process !== 'undefined' && process.noDeprecation === true) { - return fn; - } - - // Allow for deprecating things in the process of starting up. - if (typeof process === 'undefined') { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnvRegex = /^$/; - -if (process.env.NODE_DEBUG) { - var debugEnv = process.env.NODE_DEBUG; - debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&') - .replace(/\*/g, '.*') - .replace(/,/g, '$|^') - .toUpperCase(); - debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i'); -} -exports.debuglog = function(set) { - set = set.toUpperCase(); - if (!debugs[set]) { - if (debugEnvRegex.test(set)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').slice(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.slice(1, -1); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -exports.types = require('./support/types'); - -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; -exports.types.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; -exports.types.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; -exports.types.isNativeError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; - -exports.promisify = function promisify(original) { - if (typeof original !== 'function') - throw new TypeError('The "original" argument must be of type Function'); - - if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { - var fn = original[kCustomPromisifiedSymbol]; - if (typeof fn !== 'function') { - throw new TypeError('The "util.promisify.custom" argument must be of type Function'); - } - Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return fn; - } - - function fn() { - var promiseResolve, promiseReject; - var promise = new Promise(function (resolve, reject) { - promiseResolve = resolve; - promiseReject = reject; - }); - - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - args.push(function (err, value) { - if (err) { - promiseReject(err); - } else { - promiseResolve(value); - } - }); - - try { - original.apply(this, args); - } catch (err) { - promiseReject(err); - } - - return promise; - } - - Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); - - if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return Object.defineProperties( - fn, - getOwnPropertyDescriptors(original) - ); -} - -exports.promisify.custom = kCustomPromisifiedSymbol - -function callbackifyOnRejected(reason, cb) { - // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). - // Because `null` is a special error value in callbacks which means "no error - // occurred", we error-wrap so the callback consumer can distinguish between - // "the promise rejected with null" or "the promise fulfilled with undefined". - if (!reason) { - var newReason = new Error('Promise was rejected with a falsy value'); - newReason.reason = reason; - reason = newReason; - } - return cb(reason); -} - -function callbackify(original) { - if (typeof original !== 'function') { - throw new TypeError('The "original" argument must be of type Function'); - } - - // We DO NOT return the promise as it gives the user a false sense that - // the promise is actually somehow related to the callback's execution - // and that the callback throwing will reject the promise. - function callbackified() { - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - - var maybeCb = args.pop(); - if (typeof maybeCb !== 'function') { - throw new TypeError('The last argument must be of type Function'); - } - var self = this; - var cb = function() { - return maybeCb.apply(self, arguments); - }; - // In true node style we process the callback on `nextTick` with all the - // implications (stack, `uncaughtException`, `async_hooks`) - original.apply(this, args) - .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, - function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); - } - - Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); - Object.defineProperties(callbackified, - getOwnPropertyDescriptors(original)); - return callbackified; -} -exports.callbackify = callbackify; - -}).call(this)}).call(this,require('_process')) - -},{"./support/isBuffer":284,"./support/types":285,"_process":237,"inherits":146}],287:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -Object.defineProperty(exports, "NIL", { - enumerable: true, - get: function () { - return _nil.default; - } -}); -Object.defineProperty(exports, "parse", { - enumerable: true, - get: function () { - return _parse.default; - } -}); -Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function () { - return _stringify.default; - } -}); -Object.defineProperty(exports, "v1", { - enumerable: true, - get: function () { - return _v.default; - } -}); -Object.defineProperty(exports, "v3", { - enumerable: true, - get: function () { - return _v2.default; - } -}); -Object.defineProperty(exports, "v4", { - enumerable: true, - get: function () { - return _v3.default; - } -}); -Object.defineProperty(exports, "v5", { - enumerable: true, - get: function () { - return _v4.default; - } -}); -Object.defineProperty(exports, "validate", { - enumerable: true, - get: function () { - return _validate.default; - } -}); -Object.defineProperty(exports, "version", { - enumerable: true, - get: function () { - return _version.default; - } -}); - -var _v = _interopRequireDefault(require("./v1.js")); - -var _v2 = _interopRequireDefault(require("./v3.js")); - -var _v3 = _interopRequireDefault(require("./v4.js")); - -var _v4 = _interopRequireDefault(require("./v5.js")); - -var _nil = _interopRequireDefault(require("./nil.js")); - -var _version = _interopRequireDefault(require("./version.js")); - -var _validate = _interopRequireDefault(require("./validate.js")); - -var _stringify = _interopRequireDefault(require("./stringify.js")); - -var _parse = _interopRequireDefault(require("./parse.js")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -},{"./nil.js":290,"./parse.js":291,"./stringify.js":295,"./v1.js":296,"./v3.js":297,"./v4.js":299,"./v5.js":300,"./validate.js":301,"./version.js":302}],288:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -/* - * Browser-compatible JavaScript MD5 - * - * Modification of JavaScript MD5 - * https://github.com/blueimp/JavaScript-MD5 - * - * Copyright 2011, Sebastian Tschan - * https://blueimp.net - * - * Licensed under the MIT license: - * https://opensource.org/licenses/MIT - * - * Based on - * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message - * Digest Algorithm, as defined in RFC 1321. - * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for more info. - */ -function md5(bytes) { - if (typeof bytes === 'string') { - const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape - - bytes = new Uint8Array(msg.length); - - for (let i = 0; i < msg.length; ++i) { - bytes[i] = msg.charCodeAt(i); - } - } - - return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); -} -/* - * Convert an array of little-endian words to an array of bytes - */ - - -function md5ToHexEncodedArray(input) { - const output = []; - const length32 = input.length * 32; - const hexTab = '0123456789abcdef'; - - for (let i = 0; i < length32; i += 8) { - const x = input[i >> 5] >>> i % 32 & 0xff; - const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); - output.push(hex); - } - - return output; -} -/** - * Calculate output length with padding and bit length - */ - - -function getOutputLength(inputLength8) { - return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; -} -/* - * Calculate the MD5 of an array of little-endian words, and a bit length. - */ - - -function wordsToMd5(x, len) { - /* append padding */ - x[len >> 5] |= 0x80 << len % 32; - x[getOutputLength(len) - 1] = len; - let a = 1732584193; - let b = -271733879; - let c = -1732584194; - let d = 271733878; - - for (let i = 0; i < x.length; i += 16) { - const olda = a; - const oldb = b; - const oldc = c; - const oldd = d; - a = md5ff(a, b, c, d, x[i], 7, -680876936); - d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); - c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); - b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); - a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); - d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); - c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); - b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); - a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); - d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); - c = md5ff(c, d, a, b, x[i + 10], 17, -42063); - b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); - a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); - d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); - c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); - b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); - a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); - d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); - c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); - b = md5gg(b, c, d, a, x[i], 20, -373897302); - a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); - d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); - c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); - b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); - a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); - d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); - c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); - b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); - a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); - d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); - c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); - b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); - a = md5hh(a, b, c, d, x[i + 5], 4, -378558); - d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); - c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); - b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); - a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); - d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); - c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); - b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); - a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); - d = md5hh(d, a, b, c, x[i], 11, -358537222); - c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); - b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); - a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); - d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); - c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); - b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); - a = md5ii(a, b, c, d, x[i], 6, -198630844); - d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); - c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); - b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); - a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); - d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); - c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); - b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); - a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); - d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); - c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); - b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); - a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); - d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); - c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); - b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); - a = safeAdd(a, olda); - b = safeAdd(b, oldb); - c = safeAdd(c, oldc); - d = safeAdd(d, oldd); - } - - return [a, b, c, d]; -} -/* - * Convert an array bytes to an array of little-endian words - * Characters >255 have their high-byte silently ignored. - */ - - -function bytesToWords(input) { - if (input.length === 0) { - return []; - } - - const length8 = input.length * 8; - const output = new Uint32Array(getOutputLength(length8)); - - for (let i = 0; i < length8; i += 8) { - output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; - } - - return output; -} -/* - * Add integers, wrapping at 2^32. This uses 16-bit operations internally - * to work around bugs in some JS interpreters. - */ - - -function safeAdd(x, y) { - const lsw = (x & 0xffff) + (y & 0xffff); - const msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return msw << 16 | lsw & 0xffff; -} -/* - * Bitwise rotate a 32-bit number to the left. - */ - - -function bitRotateLeft(num, cnt) { - return num << cnt | num >>> 32 - cnt; -} -/* - * These functions implement the four basic operations the algorithm uses. - */ - - -function md5cmn(q, a, b, x, s, t) { - return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); -} - -function md5ff(a, b, c, d, x, s, t) { - return md5cmn(b & c | ~b & d, a, b, x, s, t); -} - -function md5gg(a, b, c, d, x, s, t) { - return md5cmn(b & d | c & ~d, a, b, x, s, t); -} - -function md5hh(a, b, c, d, x, s, t) { - return md5cmn(b ^ c ^ d, a, b, x, s, t); -} - -function md5ii(a, b, c, d, x, s, t) { - return md5cmn(c ^ (b | ~d), a, b, x, s, t); -} - -var _default = md5; -exports.default = _default; -},{}],289:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; -const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); -var _default = { - randomUUID -}; -exports.default = _default; -},{}],290:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; -var _default = '00000000-0000-0000-0000-000000000000'; -exports.default = _default; -},{}],291:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _validate = _interopRequireDefault(require("./validate.js")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function parse(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - - let v; - const arr = new Uint8Array(16); // Parse ########-....-....-....-............ - - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; // Parse ........-####-....-....-............ - - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; // Parse ........-....-####-....-............ - - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; // Parse ........-....-....-####-............ - - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) - - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; -} - -var _default = parse; -exports.default = _default; -},{"./validate.js":301}],292:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; -var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; -exports.default = _default; -},{}],293:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = rng; -// Unique ID creation requires a high quality random # generator. In the browser we therefore -// require the crypto API and do not support built-in fallback to lower quality random number -// generators (like Math.random()). -let getRandomValues; -const rnds8 = new Uint8Array(16); - -function rng() { - // lazy load so that environments that need to polyfill have a chance to do so - if (!getRandomValues) { - // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. - getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto); - - if (!getRandomValues) { - throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); - } - } - - return getRandomValues(rnds8); -} -},{}],294:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -// Adapted from Chris Veness' SHA1 code at -// http://www.movable-type.co.uk/scripts/sha1.html -function f(s, x, y, z) { - switch (s) { - case 0: - return x & y ^ ~x & z; - - case 1: - return x ^ y ^ z; - - case 2: - return x & y ^ x & z ^ y & z; - - case 3: - return x ^ y ^ z; - } -} - -function ROTL(x, n) { - return x << n | x >>> 32 - n; -} - -function sha1(bytes) { - const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; - const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; - - if (typeof bytes === 'string') { - const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape - - bytes = []; - - for (let i = 0; i < msg.length; ++i) { - bytes.push(msg.charCodeAt(i)); - } - } else if (!Array.isArray(bytes)) { - // Convert Array-like to Array - bytes = Array.prototype.slice.call(bytes); - } - - bytes.push(0x80); - const l = bytes.length / 4 + 2; - const N = Math.ceil(l / 16); - const M = new Array(N); - - for (let i = 0; i < N; ++i) { - const arr = new Uint32Array(16); - - for (let j = 0; j < 16; ++j) { - arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; - } - - M[i] = arr; - } - - M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); - M[N - 1][14] = Math.floor(M[N - 1][14]); - M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; - - for (let i = 0; i < N; ++i) { - const W = new Uint32Array(80); - - for (let t = 0; t < 16; ++t) { - W[t] = M[i][t]; - } - - for (let t = 16; t < 80; ++t) { - W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); - } - - let a = H[0]; - let b = H[1]; - let c = H[2]; - let d = H[3]; - let e = H[4]; - - for (let t = 0; t < 80; ++t) { - const s = Math.floor(t / 20); - const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; - e = d; - d = c; - c = ROTL(b, 30) >>> 0; - b = a; - a = T; - } - - H[0] = H[0] + a >>> 0; - H[1] = H[1] + b >>> 0; - H[2] = H[2] + c >>> 0; - H[3] = H[3] + d >>> 0; - H[4] = H[4] + e >>> 0; - } - - return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; -} - -var _default = sha1; -exports.default = _default; -},{}],295:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; -exports.unsafeStringify = unsafeStringify; - -var _validate = _interopRequireDefault(require("./validate.js")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -const byteToHex = []; - -for (let i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).slice(1)); -} - -function unsafeStringify(arr, offset = 0) { - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); -} - -function stringify(arr, offset = 0) { - const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields - - if (!(0, _validate.default)(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } - - return uuid; -} - -var _default = stringify; -exports.default = _default; -},{"./validate.js":301}],296:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _rng = _interopRequireDefault(require("./rng.js")); - -var _stringify = require("./stringify.js"); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html -let _nodeId; - -let _clockseq; // Previous uuid creation time - - -let _lastMSecs = 0; -let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details - -function v1(options, buf, offset) { - let i = buf && offset || 0; - const b = buf || new Array(16); - options = options || {}; - let node = options.node || _nodeId; - let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not - // specified. We do this lazily to minimize issues related to insufficient - // system entropy. See #189 - - if (node == null || clockseq == null) { - const seedBytes = options.random || (options.rng || _rng.default)(); - - if (node == null) { - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - } - - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - } - } // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - - - let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - - let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) - - const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression - - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - - - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } // Per 4.2.1.2 Throw error if too many uuids are requested - - - if (nsecs >= 10000) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); - } - - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - - msecs += 12219292800000; // `time_low` - - const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; // `time_mid` - - const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; // `time_high_and_version` - - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - - b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - - b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` - - b[i++] = clockseq & 0xff; // `node` - - for (let n = 0; n < 6; ++n) { - b[i + n] = node[n]; - } - - return buf || (0, _stringify.unsafeStringify)(b); -} - -var _default = v1; -exports.default = _default; -},{"./rng.js":293,"./stringify.js":295}],297:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _v = _interopRequireDefault(require("./v35.js")); - -var _md = _interopRequireDefault(require("./md5.js")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const v3 = (0, _v.default)('v3', 0x30, _md.default); -var _default = v3; -exports.default = _default; -},{"./md5.js":288,"./v35.js":298}],298:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.URL = exports.DNS = void 0; -exports.default = v35; - -var _stringify = require("./stringify.js"); - -var _parse = _interopRequireDefault(require("./parse.js")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape - - const bytes = []; - - for (let i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); - } - - return bytes; -} - -const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -exports.DNS = DNS; -const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -exports.URL = URL; - -function v35(name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - var _namespace; - - if (typeof value === 'string') { - value = stringToBytes(value); - } - - if (typeof namespace === 'string') { - namespace = (0, _parse.default)(namespace); - } - - if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` - - - let bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; - - if (buf) { - offset = offset || 0; - - for (let i = 0; i < 16; ++i) { - buf[offset + i] = bytes[i]; - } - - return buf; - } - - return (0, _stringify.unsafeStringify)(bytes); - } // Function#name is not settable on some platforms (#270) - - - try { - generateUUID.name = name; // eslint-disable-next-line no-empty - } catch (err) {} // For CommonJS default export support - - - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; -} -},{"./parse.js":291,"./stringify.js":295}],299:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _native = _interopRequireDefault(require("./native.js")); - -var _rng = _interopRequireDefault(require("./rng.js")); - -var _stringify = require("./stringify.js"); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function v4(options, buf, offset) { - if (_native.default.randomUUID && !buf && !options) { - return _native.default.randomUUID(); - } - - options = options || {}; - - const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - - - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided - - if (buf) { - offset = offset || 0; - - for (let i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; - } - - return buf; - } - - return (0, _stringify.unsafeStringify)(rnds); -} - -var _default = v4; -exports.default = _default; -},{"./native.js":289,"./rng.js":293,"./stringify.js":295}],300:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _v = _interopRequireDefault(require("./v35.js")); - -var _sha = _interopRequireDefault(require("./sha1.js")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const v5 = (0, _v.default)('v5', 0x50, _sha.default); -var _default = v5; -exports.default = _default; -},{"./sha1.js":294,"./v35.js":298}],301:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _regex = _interopRequireDefault(require("./regex.js")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function validate(uuid) { - return typeof uuid === 'string' && _regex.default.test(uuid); -} - -var _default = validate; -exports.default = _default; -},{"./regex.js":292}],302:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _validate = _interopRequireDefault(require("./validate.js")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function version(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - - return parseInt(uuid.slice(14, 15), 16); -} - -var _default = version; -exports.default = _default; -},{"./validate.js":301}],303:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var forEach = require('for-each'); -var availableTypedArrays = require('available-typed-arrays'); -var callBound = require('call-bind/callBound'); -var gOPD = require('gopd'); - -var $toString = callBound('Object.prototype.toString'); -var hasToStringTag = require('has-tostringtag/shams')(); - -var g = typeof globalThis === 'undefined' ? global : globalThis; -var typedArrays = availableTypedArrays(); - -var $slice = callBound('String.prototype.slice'); -var toStrTags = {}; -var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); -if (hasToStringTag && gOPD && getPrototypeOf) { - forEach(typedArrays, function (typedArray) { - if (typeof g[typedArray] === 'function') { - var arr = new g[typedArray](); - if (Symbol.toStringTag in arr) { - var proto = getPrototypeOf(arr); - var descriptor = gOPD(proto, Symbol.toStringTag); - if (!descriptor) { - var superProto = getPrototypeOf(proto); - descriptor = gOPD(superProto, Symbol.toStringTag); - } - toStrTags[typedArray] = descriptor.get; - } - } - }); -} - -var tryTypedArrays = function tryAllTypedArrays(value) { - var foundName = false; - forEach(toStrTags, function (getter, typedArray) { - if (!foundName) { - try { - var name = getter.call(value); - if (name === typedArray) { - foundName = name; - } - } catch (e) {} - } - }); - return foundName; -}; - -var isTypedArray = require('is-typed-array'); - -module.exports = function whichTypedArray(value) { - if (!isTypedArray(value)) { return false; } - if (!hasToStringTag || !(Symbol.toStringTag in value)) { return $slice($toString(value), 8, -1); } - return tryTypedArrays(value); -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"available-typed-arrays":16,"call-bind/callBound":69,"for-each":107,"gopd":111,"has-tostringtag/shams":114,"is-typed-array":150}],304:[function(require,module,exports){ -"use strict"; -/* -Copyright 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RuleId = exports.PushRuleKind = exports.ConditionKind = exports.isDmMemberCountCondition = exports.DMMemberCountCondition = exports.ConditionOperator = exports.TweakName = exports.PushRuleActionName = void 0; -// allow camelcase as these are things that go onto the wire -/* eslint-disable camelcase */ -var PushRuleActionName; -(function (PushRuleActionName) { - PushRuleActionName["DontNotify"] = "dont_notify"; - PushRuleActionName["Notify"] = "notify"; - PushRuleActionName["Coalesce"] = "coalesce"; -})(PushRuleActionName = exports.PushRuleActionName || (exports.PushRuleActionName = {})); -var TweakName; -(function (TweakName) { - TweakName["Highlight"] = "highlight"; - TweakName["Sound"] = "sound"; -})(TweakName = exports.TweakName || (exports.TweakName = {})); -var ConditionOperator; -(function (ConditionOperator) { - ConditionOperator["ExactEquals"] = "=="; - ConditionOperator["LessThan"] = "<"; - ConditionOperator["GreaterThan"] = ">"; - ConditionOperator["GreaterThanOrEqual"] = ">="; - ConditionOperator["LessThanOrEqual"] = "<="; -})(ConditionOperator = exports.ConditionOperator || (exports.ConditionOperator = {})); -exports.DMMemberCountCondition = "2"; -function isDmMemberCountCondition(condition) { - return condition === "==2" || condition === "2"; -} -exports.isDmMemberCountCondition = isDmMemberCountCondition; -var ConditionKind; -(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"; -})(ConditionKind = exports.ConditionKind || (exports.ConditionKind = {})); -var PushRuleKind; -(function (PushRuleKind) { - PushRuleKind["Override"] = "override"; - PushRuleKind["ContentSpecific"] = "content"; - PushRuleKind["RoomSpecific"] = "room"; - PushRuleKind["SenderSpecific"] = "sender"; - PushRuleKind["Underride"] = "underride"; -})(PushRuleKind = exports.PushRuleKind || (exports.PushRuleKind = {})); -var RuleId; -(function (RuleId) { - RuleId["Master"] = ".m.rule.master"; - RuleId["IsUserMention"] = ".org.matrix.msc3952.is_user_mention"; - RuleId["IsRoomMention"] = ".org.matrix.msc3952.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"; -})(RuleId = exports.RuleId || (exports.RuleId = {})); -/* eslint-enable camelcase */ - -},{}],305:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.M_BEACON = exports.M_BEACON_INFO = void 0; -const NamespacedValue_1 = require("../NamespacedValue"); -/** - * 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 - */ -exports.M_BEACON_INFO = new NamespacedValue_1.UnstableValue("m.beacon_info", "org.matrix.msc3672.beacon_info"); -exports.M_BEACON = new NamespacedValue_1.UnstableValue("m.beacon", "org.matrix.msc3672.beacon"); - -},{"../NamespacedValue":316}],306:[function(require,module,exports){ -"use strict"; -/* -Copyright 2020 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.LOCAL_NOTIFICATION_SETTINGS_PREFIX = exports.PUSHER_DEVICE_ID = exports.PUSHER_ENABLED = exports.EVENT_VISIBILITY_CHANGE_TYPE = exports.UNSTABLE_ELEMENT_FUNCTIONAL_USERS = exports.MSC3912_RELATION_BASED_REDACTIONS_PROP = exports.UNSTABLE_MSC2716_MARKER = exports.UNSTABLE_MSC3089_BRANCH = exports.UNSTABLE_MSC3089_LEAF = exports.UNSTABLE_MSC3089_TREE_SUBTYPE = exports.UNSTABLE_MSC3088_ENABLED = exports.UNSTABLE_MSC3088_PURPOSE = exports.ToDeviceMessageId = exports.RoomType = exports.RoomCreateTypeField = exports.MsgType = exports.RelationType = exports.EventType = void 0; -const NamespacedValue_1 = require("../NamespacedValue"); -var EventType; -(function (EventType) { - // Room state events - 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["SpaceChild"] = "m.space.child"; - EventType["SpaceParent"] = "m.space.parent"; - // Room timeline events - 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["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"; - // Not used directly - see READY_TYPE in VerificationRequest. - EventType["KeyVerificationReady"] = "m.key.verification.ready"; - // use of this is discouraged https://matrix.org/docs/spec/client_server/r0.6.1#m-room-message-feedback - EventType["RoomMessageFeedback"] = "m.room.message.feedback"; - EventType["Reaction"] = "m.reaction"; - EventType["PollStart"] = "org.matrix.msc3381.poll.start"; - // Room ephemeral events - EventType["Typing"] = "m.typing"; - EventType["Receipt"] = "m.receipt"; - EventType["Presence"] = "m.presence"; - // Room account_data events - EventType["FullyRead"] = "m.fully_read"; - EventType["Tag"] = "m.tag"; - EventType["SpaceOrder"] = "org.matrix.msc3230.space_order"; - // User account_data events - EventType["PushRules"] = "m.push_rules"; - EventType["Direct"] = "m.direct"; - EventType["IgnoredUserList"] = "m.ignored_user_list"; - // to_device events - EventType["RoomKey"] = "m.room_key"; - EventType["RoomKeyRequest"] = "m.room_key_request"; - EventType["ForwardedRoomKey"] = "m.forwarded_room_key"; - EventType["Dummy"] = "m.dummy"; - // Group call events - EventType["GroupCallPrefix"] = "org.matrix.msc3401.call"; - EventType["GroupCallMemberPrefix"] = "org.matrix.msc3401.call.member"; -})(EventType = exports.EventType || (exports.EventType = {})); -var RelationType; -(function (RelationType) { - RelationType["Annotation"] = "m.annotation"; - RelationType["Replace"] = "m.replace"; - RelationType["Reference"] = "m.reference"; - RelationType["Thread"] = "m.thread"; -})(RelationType = exports.RelationType || (exports.RelationType = {})); -var MsgType; -(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"; -})(MsgType = exports.MsgType || (exports.MsgType = {})); -exports.RoomCreateTypeField = "type"; -var RoomType; -(function (RoomType) { - RoomType["Space"] = "m.space"; - RoomType["UnstableCall"] = "org.matrix.msc3417.call"; - RoomType["ElementVideo"] = "io.element.video"; -})(RoomType = exports.RoomType || (exports.RoomType = {})); -exports.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. - */ -exports.UNSTABLE_MSC3088_PURPOSE = new NamespacedValue_1.UnstableValue("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. - */ -exports.UNSTABLE_MSC3088_ENABLED = new NamespacedValue_1.UnstableValue("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. - */ -exports.UNSTABLE_MSC3089_TREE_SUBTYPE = new NamespacedValue_1.UnstableValue("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. - */ -exports.UNSTABLE_MSC3089_LEAF = new NamespacedValue_1.UnstableValue("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. - */ -exports.UNSTABLE_MSC3089_BRANCH = new NamespacedValue_1.UnstableValue("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. - */ -exports.UNSTABLE_MSC2716_MARKER = new NamespacedValue_1.UnstableValue("m.room.marker", "org.matrix.msc2716.marker"); -/** - * Name of the "with_relations" request property for relation based redactions. - * {@link https://github.com/matrix-org/matrix-spec-proposals/pull/3912} - */ -exports.MSC3912_RELATION_BASED_REDACTIONS_PROP = new NamespacedValue_1.UnstableValue("with_relations", "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" - * ] - * } - * ``` - */ -exports.UNSTABLE_ELEMENT_FUNCTIONAL_USERS = new NamespacedValue_1.UnstableValue("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 - */ -exports.EVENT_VISIBILITY_CHANGE_TYPE = new NamespacedValue_1.UnstableValue("m.visibility", "org.matrix.msc3531.visibility"); -/** - * https://github.com/matrix-org/matrix-doc/pull/3881 - * - * @experimental - */ -exports.PUSHER_ENABLED = new NamespacedValue_1.UnstableValue("enabled", "org.matrix.msc3881.enabled"); -/** - * https://github.com/matrix-org/matrix-doc/pull/3881 - * - * @experimental - */ -exports.PUSHER_DEVICE_ID = new NamespacedValue_1.UnstableValue("device_id", "org.matrix.msc3881.device_id"); -/** - * https://github.com/matrix-org/matrix-doc/pull/3890 - * - * @experimental - */ -exports.LOCAL_NOTIFICATION_SETTINGS_PREFIX = new NamespacedValue_1.UnstableValue("m.local_notification_settings", "org.matrix.msc3890.local_notification_settings"); - -},{"../NamespacedValue":316}],307:[function(require,module,exports){ -"use strict"; -/* -Copyright 2021 - 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isEventTypeSame = exports.REFERENCE_RELATION = exports.M_HTML = exports.M_TEXT = exports.M_MESSAGE = void 0; -const matrix_events_sdk_1 = require("matrix-events-sdk"); -const utilities_1 = require("../extensible_events_v1/utilities"); -/** - * The namespaced value for m.message - */ -exports.M_MESSAGE = new matrix_events_sdk_1.UnstableValue("m.message", "org.matrix.msc1767.message"); -/** - * The namespaced value for m.text - */ -exports.M_TEXT = new matrix_events_sdk_1.UnstableValue("m.text", "org.matrix.msc1767.text"); -/** - * The namespaced value for m.html - */ -exports.M_HTML = new matrix_events_sdk_1.UnstableValue("m.html", "org.matrix.msc1767.html"); -/** - * The namespaced value for an m.reference relation - */ -exports.REFERENCE_RELATION = new matrix_events_sdk_1.NamespacedValue("m.reference"); -/** - * Determines if two event types are the same, including namespaces. - * @param given - The given event type. This will be compared - * against the expected type. - * @param expected - The expected event type. - * @returns 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 { - const expectedNs = expected; - const givenNs = given; - return (expectedNs.matches(givenNs.name) || - ((0, utilities_1.isProvided)(givenNs.altName) && expectedNs.matches(givenNs.altName))); - } - } -} -exports.isEventTypeSame = isEventTypeSame; - -},{"../extensible_events_v1/utilities":361,"matrix-events-sdk":167}],308:[function(require,module,exports){ -"use strict"; -/* -Copyright 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.M_LOCATION = exports.M_TIMESTAMP = exports.M_ASSET = exports.LocationAssetType = void 0; -const NamespacedValue_1 = require("../NamespacedValue"); -const extensible_events_1 = require("./extensible_events"); -var LocationAssetType; -(function (LocationAssetType) { - LocationAssetType["Self"] = "m.self"; - LocationAssetType["Pin"] = "m.pin"; -})(LocationAssetType = exports.LocationAssetType || (exports.LocationAssetType = {})); -exports.M_ASSET = new NamespacedValue_1.UnstableValue("m.asset", "org.matrix.msc3488.asset"); -exports.M_TIMESTAMP = new NamespacedValue_1.UnstableValue("m.ts", "org.matrix.msc3488.ts"); -exports.M_LOCATION = new NamespacedValue_1.UnstableValue("m.location", "org.matrix.msc3488.location"); - -},{"../NamespacedValue":316,"./extensible_events":307}],309:[function(require,module,exports){ -"use strict"; -/* -Copyright 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.HistoryVisibility = exports.GuestAccess = exports.RestrictedAllowType = exports.JoinRule = exports.Preset = exports.Visibility = void 0; -var Visibility; -(function (Visibility) { - Visibility["Public"] = "public"; - Visibility["Private"] = "private"; -})(Visibility = exports.Visibility || (exports.Visibility = {})); -var Preset; -(function (Preset) { - Preset["PrivateChat"] = "private_chat"; - Preset["TrustedPrivateChat"] = "trusted_private_chat"; - Preset["PublicChat"] = "public_chat"; -})(Preset = exports.Preset || (exports.Preset = {})); -// Knock and private are reserved keywords which are not yet implemented. -var JoinRule; -(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"; -})(JoinRule = exports.JoinRule || (exports.JoinRule = {})); -var RestrictedAllowType; -(function (RestrictedAllowType) { - RestrictedAllowType["RoomMembership"] = "m.room_membership"; -})(RestrictedAllowType = exports.RestrictedAllowType || (exports.RestrictedAllowType = {})); -var GuestAccess; -(function (GuestAccess) { - GuestAccess["CanJoin"] = "can_join"; - GuestAccess["Forbidden"] = "forbidden"; -})(GuestAccess = exports.GuestAccess || (exports.GuestAccess = {})); -var HistoryVisibility; -(function (HistoryVisibility) { - HistoryVisibility["Invited"] = "invited"; - HistoryVisibility["Joined"] = "joined"; - HistoryVisibility["Shared"] = "shared"; - HistoryVisibility["WorldReadable"] = "world_readable"; -})(HistoryVisibility = exports.HistoryVisibility || (exports.HistoryVisibility = {})); - -},{}],310:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 - 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.M_POLL_END = exports.M_POLL_RESPONSE = exports.M_POLL_START = exports.M_POLL_KIND_UNDISCLOSED = exports.M_POLL_KIND_DISCLOSED = void 0; -const matrix_events_sdk_1 = require("matrix-events-sdk"); -/** - * Identifier for a disclosed poll. - */ -exports.M_POLL_KIND_DISCLOSED = new matrix_events_sdk_1.UnstableValue("m.poll.disclosed", "org.matrix.msc3381.poll.disclosed"); -/** - * Identifier for an undisclosed poll. - */ -exports.M_POLL_KIND_UNDISCLOSED = new matrix_events_sdk_1.UnstableValue("m.poll.undisclosed", "org.matrix.msc3381.poll.undisclosed"); -/** - * The namespaced value for m.poll.start - */ -exports.M_POLL_START = new matrix_events_sdk_1.UnstableValue("m.poll.start", "org.matrix.msc3381.poll.start"); -/** - * The namespaced value for m.poll.response - */ -exports.M_POLL_RESPONSE = new matrix_events_sdk_1.UnstableValue("m.poll.response", "org.matrix.msc3381.poll.response"); -/** - * The namespaced value for m.poll.end - */ -exports.M_POLL_END = new matrix_events_sdk_1.UnstableValue("m.poll.end", "org.matrix.msc3381.poll.end"); - -},{"matrix-events-sdk":167}],311:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 Šimon Brandner - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MAIN_ROOM_TIMELINE = exports.ReceiptType = void 0; -var ReceiptType; -(function (ReceiptType) { - ReceiptType["Read"] = "m.read"; - ReceiptType["FullyRead"] = "m.fully_read"; - ReceiptType["ReadPrivate"] = "m.read.private"; -})(ReceiptType = exports.ReceiptType || (exports.ReceiptType = {})); -exports.MAIN_ROOM_TIMELINE = "main"; - -},{}],312:[function(require,module,exports){ -"use strict"; -/* -Copyright 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -/* eslint-enable camelcase */ - -},{}],313:[function(require,module,exports){ -"use strict"; -/* -Copyright 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SearchOrderBy = void 0; -var GroupKey; -(function (GroupKey) { - GroupKey["RoomId"] = "room_id"; - GroupKey["Sender"] = "sender"; -})(GroupKey || (GroupKey = {})); -var SearchOrderBy; -(function (SearchOrderBy) { - SearchOrderBy["Recent"] = "recent"; - SearchOrderBy["Rank"] = "rank"; -})(SearchOrderBy = exports.SearchOrderBy || (exports.SearchOrderBy = {})); -/* eslint-enable camelcase */ - -},{}],314:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.UNREAD_THREAD_NOTIFICATIONS = void 0; -const NamespacedValue_1 = require("../NamespacedValue"); -/** - * https://github.com/matrix-org/matrix-doc/pull/3773 - * - * @experimental - */ -exports.UNREAD_THREAD_NOTIFICATIONS = new NamespacedValue_1.ServerControlledNamespacedValue("unread_thread_notifications", "org.matrix.msc3773.unread_thread_notifications"); - -},{"../NamespacedValue":316}],315:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.M_TOPIC = void 0; -const NamespacedValue_1 = require("../NamespacedValue"); -/** - * 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 pizza", - * "mimetype": "text/html", - * }], - * } - * } - * ``` - */ -/** - * The event type for an m.topic event (in content) - */ -exports.M_TOPIC = new NamespacedValue_1.UnstableValue("m.topic", "org.matrix.msc3765.topic"); - -},{"../NamespacedValue":316}],316:[function(require,module,exports){ -"use strict"; -/* -Copyright 2021 - 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.UnstableValue = exports.ServerControlledNamespacedValue = exports.NamespacedValue = void 0; -/** - * 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. - */ -class NamespacedValue { - 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() { - const names = [this.name]; - const altName = this.altName; - if (altName) - names.push(altName); - return names; - } - matches(val) { - return this.name === val || this.altName === val; - } - // this desperately wants https://github.com/microsoft/TypeScript/pull/26349 at the top level of the class - // so we can instantiate `NamespacedValue` as a default type for that namespace. - findIn(obj) { - let val = undefined; - 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) { - let included = false; - if (this.name) { - included = arr.includes(this.name); - } - if (!included && this.altName) { - included = arr.includes(this.altName); - } - return included; - } -} -exports.NamespacedValue = NamespacedValue; -class ServerControlledNamespacedValue extends NamespacedValue { - constructor() { - super(...arguments); - this.preferUnstable = false; - } - setPreferUnstable(preferUnstable) { - this.preferUnstable = preferUnstable; - } - get name() { - if (this.stable && !this.preferUnstable) { - return this.stable; - } - return this.unstable; - } -} -exports.ServerControlledNamespacedValue = ServerControlledNamespacedValue; -/** - * Represents a namespaced value which prioritizes the unstable value over the stable - * value. - */ -class UnstableValue extends NamespacedValue { - // Note: Constructor difference is that `unstable` is *required*. - 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; - } -} -exports.UnstableValue = UnstableValue; - -},{}],317:[function(require,module,exports){ -"use strict"; -/* -Copyright 2015, 2016 OpenMarket Ltd -Copyright 2017 Vector Creations Ltd -Copyright 2017 New Vector Ltd - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TypedReEmitter = exports.ReEmitter = void 0; -class ReEmitter { - constructor(target) { - this.target = target; - // Map from emitter to event name to re-emitter - this.reEmitters = new Map(); - } - reEmit(source, eventNames) { - let reEmittersByEvent = this.reEmitters.get(source); - if (!reEmittersByEvent) { - reEmittersByEvent = new Map(); - this.reEmitters.set(source, reEmittersByEvent); - } - for (const eventName of eventNames) { - // We include the source as the last argument for event handlers which may need it, - // such as read receipt listeners on the client class which won't have the context - // of the room. - const forSource = (...args) => { - // EventEmitter special cases 'error' to make the emit function throw if no - // handler is attached, which sort of makes sense for making sure that something - // handles an error, but for re-emitting, there could be a listener on the original - // source object so the test doesn't really work. We *could* try to replicate the - // same logic and throw if there is no listener on either the source or the target, - // but this behaviour is fairly undesireable for us anyway: the main place we throw - // 'error' events is for calls, where error events are usually emitted some time - // later by a different part of the code where 'emit' throwing because the app hasn't - // added an error handler isn't terribly helpful. (A better fix in retrospect may - // have been to just avoid using the event name 'error', but backwards compat...) - if (eventName === "error" && this.target.listenerCount("error") === 0) - return; - this.target.emit(eventName, ...args, source); - }; - source.on(eventName, forSource); - reEmittersByEvent.set(eventName, forSource); - } - } - stopReEmitting(source, eventNames) { - const reEmittersByEvent = this.reEmitters.get(source); - if (!reEmittersByEvent) - return; // We were never re-emitting these events in the first place - for (const eventName of eventNames) { - source.off(eventName, reEmittersByEvent.get(eventName)); - reEmittersByEvent.delete(eventName); - } - if (reEmittersByEvent.size === 0) - this.reEmitters.delete(source); - } -} -exports.ReEmitter = ReEmitter; -class TypedReEmitter extends ReEmitter { - constructor(target) { - super(target); - } - reEmit(source, eventNames) { - super.reEmit(source, eventNames); - } - stopReEmitting(source, eventNames) { - super.stopReEmitting(source, eventNames); - } -} -exports.TypedReEmitter = TypedReEmitter; - -},{}],318:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ToDeviceMessageQueue = void 0; -const event_1 = require("./@types/event"); -const logger_1 = require("./logger"); -const client_1 = require("./client"); -const scheduler_1 = require("./scheduler"); -const sync_1 = require("./sync"); -const utils_1 = require("./utils"); -const MAX_BATCH_SIZE = 20; -/** - * Maintains a queue of outgoing to-device messages, sending them - * as soon as the homeserver is reachable. - */ -class ToDeviceMessageQueue { - constructor(client) { - this.client = client; - this.sending = false; - this.running = true; - this.retryTimeout = null; - this.retryAttempts = 0; - this.sendQueue = () => __awaiter(this, void 0, void 0, function* () { - if (this.retryTimeout !== null) - clearTimeout(this.retryTimeout); - this.retryTimeout = null; - if (this.sending || !this.running) - return; - logger_1.logger.debug("Attempting to send queued to-device messages"); - this.sending = true; - let 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; - } - // Make sure we're still running after the async tasks: if not, stop. - if (!this.running) - return; - logger_1.logger.debug("All queued to-device messages sent"); - } - catch (e) { - ++this.retryAttempts; - // eslint-disable-next-line @typescript-eslint/naming-convention - // eslint-disable-next-line new-cap - const retryDelay = scheduler_1.MatrixScheduler.RETRY_BACKOFF_RATELIMIT(null, this.retryAttempts, e); - if (retryDelay === -1) { - // the scheduler function doesn't differentiate between fatal errors and just getting - // bored and giving up for now - if (Math.floor(e.httpStatus / 100) === 4) { - logger_1.logger.error("Fatal error when sending to-device message - dropping to-device batch!", e); - yield this.client.store.removeToDeviceBatch(headBatch.id); - } - else { - logger_1.logger.info("Automatic retry limit reached for to-device messages."); - } - return; - } - logger_1.logger.info(`Failed to send batch of to-device messages. Will retry in ${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 - */ - this.onResumedSync = (state, oldState) => { - if (state === sync_1.SyncState.Syncing && oldState !== sync_1.SyncState.Syncing) { - logger_1.logger.info(`Resuming queue after resumed sync`); - this.sendQueue(); - } - }; - } - start() { - this.running = true; - this.sendQueue(); - this.client.on(client_1.ClientEvent.Sync, this.onResumedSync); - } - stop() { - this.running = false; - if (this.retryTimeout !== null) - clearTimeout(this.retryTimeout); - this.retryTimeout = null; - this.client.removeListener(client_1.ClientEvent.Sync, this.onResumedSync); - } - queueBatch(batch) { - return __awaiter(this, void 0, void 0, function* () { - const batches = []; - for (let i = 0; i < batch.batch.length; i += MAX_BATCH_SIZE) { - const batchWithTxnId = { - eventType: batch.eventType, - batch: batch.batch.slice(i, i + MAX_BATCH_SIZE), - txnId: this.client.makeTxnId(), - }; - batches.push(batchWithTxnId); - const msgmap = batchWithTxnId.batch.map((msg) => `${msg.userId}/${msg.deviceId} (msgid ${msg.payload[event_1.ToDeviceMessageId]})`); - logger_1.logger.info(`Enqueuing batch of to-device messages. type=${batch.eventType} txnid=${batchWithTxnId.txnId}`, msgmap); - } - yield this.client.store.saveToDeviceBatches(batches); - this.sendQueue(); - }); - } - /** - * Attempts to send a batch of to-device messages. - */ - sendBatch(batch) { - return __awaiter(this, void 0, void 0, function* () { - const contentMap = new utils_1.MapWithDefault(() => new Map()); - for (const item of batch.batch) { - contentMap.getOrCreate(item.userId).set(item.deviceId, item.payload); - } - logger_1.logger.info(`Sending batch of ${batch.batch.length} to-device messages with ID ${batch.id} and txnId ${batch.txnId}`); - yield this.client.sendToDevice(batch.eventType, contentMap, batch.txnId); - }); - } -} -exports.ToDeviceMessageQueue = ToDeviceMessageQueue; - -},{"./@types/event":306,"./client":321,"./logger":374,"./scheduler":403,"./sync":414,"./utils":416}],319:[function(require,module,exports){ -(function (global){(function (){ -"use strict"; -/* -Copyright 2018 New Vector Ltd -Copyright 2019 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AutoDiscovery = exports.AutoDiscoveryAction = void 0; -const logger_1 = require("./logger"); -const http_api_1 = require("./http-api"); -// Dev note: Auto discovery is part of the spec. -// See: https://matrix.org/docs/spec/client_server/r0.4.0.html#server-discovery -var AutoDiscoveryAction; -(function (AutoDiscoveryAction) { - AutoDiscoveryAction["SUCCESS"] = "SUCCESS"; - AutoDiscoveryAction["IGNORE"] = "IGNORE"; - AutoDiscoveryAction["PROMPT"] = "PROMPT"; - AutoDiscoveryAction["FAIL_PROMPT"] = "FAIL_PROMPT"; - AutoDiscoveryAction["FAIL_ERROR"] = "FAIL_ERROR"; -})(AutoDiscoveryAction = exports.AutoDiscoveryAction || (exports.AutoDiscoveryAction = {})); -var AutoDiscoveryError; -(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 || (AutoDiscoveryError = {})); -/** - * Utilities for automatically discovery resources, such as homeservers - * for users to log in to. - */ -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 _a; - return __awaiter(this, void 0, void 0, function* () { - // Step 1 is to get the config, which is provided to us here. - // We default to an error state to make the first few checks easier to - // write. We'll update the properties of this object over the duration - // of this function. - const clientConfig = { - "m.homeserver": { - state: AutoDiscovery.FAIL_ERROR, - error: AutoDiscovery.ERROR_INVALID, - base_url: null, - }, - "m.identity_server": { - // Technically, we don't have a problem with the identity server - // config at this point. - state: AutoDiscovery.PROMPT, - error: null, - base_url: null, - }, - }; - if (!wellknown || !wellknown["m.homeserver"]) { - logger_1.logger.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_1.logger.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); - } - // Step 2: Make sure the homeserver URL is valid *looking*. We'll make - // sure it points to a homeserver in Step 3. - const hsUrl = this.sanitizeWellKnownUrl(wellknown["m.homeserver"]["base_url"]); - if (!hsUrl) { - logger_1.logger.error("Invalid base_url for m.homeserver"); - clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL; - return Promise.resolve(clientConfig); - } - // Step 3: Make sure the homeserver URL points to a homeserver. - const hsVersions = yield this.fetchWellKnownObject(`${hsUrl}/_matrix/client/versions`); - if (!hsVersions || !((_a = hsVersions.raw) === null || _a === void 0 ? void 0 : _a["versions"])) { - logger_1.logger.error("Invalid /versions response"); - clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID_HOMESERVER; - // Supply the base_url to the caller because they may be ignoring liveliness - // errors, like this one. - clientConfig["m.homeserver"].base_url = hsUrl; - return Promise.resolve(clientConfig); - } - // Step 4: Now that the homeserver looks valid, update our client config. - clientConfig["m.homeserver"] = { - state: AutoDiscovery.SUCCESS, - error: null, - base_url: hsUrl, - }; - // Step 5: Try to pull out the identity server configuration - let isUrl = ""; - if (wellknown["m.identity_server"]) { - // We prepare a failing identity server response to save lines later - // in this branch. - const failingClientConfig = { - "m.homeserver": clientConfig["m.homeserver"], - "m.identity_server": { - state: AutoDiscovery.FAIL_PROMPT, - error: AutoDiscovery.ERROR_INVALID_IS, - base_url: null, - }, - }; - // Step 5a: Make sure the URL is valid *looking*. We'll make sure it - // points to an identity server in Step 5b. - isUrl = this.sanitizeWellKnownUrl(wellknown["m.identity_server"]["base_url"]); - if (!isUrl) { - logger_1.logger.error("Invalid base_url for m.identity_server"); - failingClientConfig["m.identity_server"].error = AutoDiscovery.ERROR_INVALID_IS_BASE_URL; - return Promise.resolve(failingClientConfig); - } - // Step 5b: Verify there is an identity server listening on the provided - // URL. - const isResponse = yield this.fetchWellKnownObject(`${isUrl}/_matrix/identity/v2`); - if (!(isResponse === null || isResponse === void 0 ? void 0 : isResponse.raw) || isResponse.action !== AutoDiscoveryAction.SUCCESS) { - logger_1.logger.error("Invalid /v2 response"); - failingClientConfig["m.identity_server"].error = AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER; - // Supply the base_url to the caller because they may be ignoring - // liveliness errors, like this one. - failingClientConfig["m.identity_server"].base_url = isUrl; - return Promise.resolve(failingClientConfig); - } - } - // Step 6: Now that the identity server is valid, or never existed, - // populate the IS section. - if (isUrl && isUrl.toString().length > 0) { - clientConfig["m.identity_server"] = { - state: AutoDiscovery.SUCCESS, - error: null, - base_url: isUrl, - }; - } - // Step 7: Copy any other keys directly into the clientConfig. This is for - // things like custom configuration of services. - Object.keys(wellknown).forEach((k) => { - if (k === "m.homeserver" || k === "m.identity_server") { - // Only copy selected parts of the config to avoid overwriting - // properties computed by the validation logic above. - const notProps = ["error", "state", "base_url"]; - for (const prop of Object.keys(wellknown[k])) { - if (notProps.includes(prop)) - continue; - // @ts-ignore - ts gets unhappy as we're mixing types here - clientConfig[k][prop] = wellknown[k][prop]; - } - } - else { - // Just copy the whole thing over otherwise - clientConfig[k] = wellknown[k]; - } - }); - // Step 8: Give the config to the caller (finally) - 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) { - return __awaiter(this, void 0, void 0, function* () { - if (!domain || typeof domain !== "string" || domain.length === 0) { - throw new Error("'domain' must be a string of non-zero length"); - } - // We use a .well-known lookup for all cases. According to the spec, we - // can do other discovery mechanisms if we want such as custom lookups - // however we won't bother with that here (mostly because the spec only - // supports .well-known right now). - // - // By using .well-known, we need to ensure we at least pull out a URL - // for the homeserver. We don't really need an identity server configuration - // but will return one anyways (with state PROMPT) to make development - // easier for clients. If we can't get a homeserver URL, all bets are - // off on the rest of the config and we'll assume it is invalid too. - // We default to an error state to make the first few checks easier to - // write. We'll update the properties of this object over the duration - // of this function. - const clientConfig = { - "m.homeserver": { - state: AutoDiscovery.FAIL_ERROR, - error: AutoDiscovery.ERROR_INVALID, - base_url: null, - }, - "m.identity_server": { - // Technically, we don't have a problem with the identity server - // config at this point. - state: AutoDiscovery.PROMPT, - error: null, - base_url: null, - }, - }; - // Step 1: Actually request the .well-known JSON file and make sure it - // at least has a homeserver definition. - const wellknown = yield this.fetchWellKnownObject(`https://${domain}/.well-known/matrix/client`); - if (!wellknown || wellknown.action !== AutoDiscoveryAction.SUCCESS) { - logger_1.logger.error("No response or error when parsing .well-known"); - if (wellknown.reason) - logger_1.logger.error(wellknown.reason); - if (wellknown.action === AutoDiscoveryAction.IGNORE) { - clientConfig["m.homeserver"] = { - state: AutoDiscovery.PROMPT, - error: null, - base_url: null, - }; - } - else { - // this can only ever be FAIL_PROMPT at this point. - clientConfig["m.homeserver"].state = AutoDiscovery.FAIL_PROMPT; - clientConfig["m.homeserver"].error = AutoDiscovery.ERROR_INVALID; - } - return Promise.resolve(clientConfig); - } - // Step 2: Validate and parse the config - 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) { - return __awaiter(this, void 0, void 0, function* () { - if (!domain || typeof domain !== "string" || domain.length === 0) { - throw new Error("'domain' must be a string of non-zero length"); - } - const response = yield this.fetchWellKnownObject(`https://${domain}/.well-known/matrix/client`); - if (!response) - return {}; - return 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 { - let parsed; - try { - parsed = new URL(url); - } - catch (e) { - logger_1.logger.error("Could not parse url", e); - } - if (!(parsed === null || parsed === void 0 ? void 0 : parsed.hostname)) - return false; - if (parsed.protocol !== "http:" && parsed.protocol !== "https:") - return false; - const port = parsed.port ? `:${parsed.port}` : ""; - const path = parsed.pathname ? parsed.pathname : ""; - let saferUrl = `${parsed.protocol}//${parsed.hostname}${port}${path}`; - if (saferUrl.endsWith("/")) { - saferUrl = saferUrl.substring(0, saferUrl.length - 1); - } - return saferUrl; - } - catch (e) { - logger_1.logger.error(e); - return false; - } - } - static fetch(resource, options) { - if (this.fetchFn) { - return this.fetchFn(resource, options); - } - return global.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 __awaiter(this, void 0, void 0, function* () { - let response; - try { - response = yield AutoDiscovery.fetch(url, { - method: http_api_1.Method.Get, - signal: (0, http_api_1.timeoutSignal)(5000), - }); - if (response.status === 404) { - return { - raw: {}, - action: AutoDiscoveryAction.IGNORE, - reason: AutoDiscovery.ERROR_MISSING_WELLKNOWN, - }; - } - if (!response.ok) { - return { - raw: {}, - action: AutoDiscoveryAction.FAIL_PROMPT, - reason: "General failure", - }; - } - } - catch (err) { - const error = err; - let 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) { - const error = err; - return { - error, - raw: {}, - action: AutoDiscoveryAction.FAIL_PROMPT, - reason: (error === null || error === void 0 ? void 0 : error.name) === "SyntaxError" - ? AutoDiscovery.ERROR_INVALID_JSON - : AutoDiscovery.ERROR_INVALID, - }; - } - }); - } -} -exports.AutoDiscovery = AutoDiscovery; -// Dev note: the constants defined here are related to but not -// exactly the same as those in the spec. This is to hopefully -// translate the meaning of the states in the spec, but also -// support our own if needed. -AutoDiscovery.ERROR_INVALID = AutoDiscoveryError.Invalid; -AutoDiscovery.ERROR_GENERIC_FAILURE = AutoDiscoveryError.GenericFailure; -AutoDiscovery.ERROR_INVALID_HS_BASE_URL = AutoDiscoveryError.InvalidHsBaseUrl; -AutoDiscovery.ERROR_INVALID_HOMESERVER = AutoDiscoveryError.InvalidHomeserver; -AutoDiscovery.ERROR_INVALID_IS_BASE_URL = AutoDiscoveryError.InvalidIsBaseUrl; -AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER = AutoDiscoveryError.InvalidIdentityServer; -AutoDiscovery.ERROR_INVALID_IS = AutoDiscoveryError.InvalidIs; -AutoDiscovery.ERROR_MISSING_WELLKNOWN = AutoDiscoveryError.MissingWellknown; -AutoDiscovery.ERROR_INVALID_JSON = AutoDiscoveryError.InvalidJson; -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. - */ -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. - */ -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. - */ -AutoDiscovery.PROMPT = AutoDiscoveryAction.PROMPT; -/** - * The auto discovery was successful. - */ -AutoDiscovery.SUCCESS = AutoDiscoveryAction.SUCCESS; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"./http-api":367,"./logger":374}],320:[function(require,module,exports){ -(function (global){(function (){ -"use strict"; -/* -Copyright 2019 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const matrixcs = __importStar(require("./matrix")); -if (global.__js_sdk_entrypoint) { - throw new Error("Multiple matrix-js-sdk entrypoints detected!"); -} -global.__js_sdk_entrypoint = true; -// just *accessing* indexedDB throws an exception in firefox with indexeddb disabled. -let indexedDB; -try { - indexedDB = global.indexedDB; -} -catch (e) { } -// if our browser (appears to) support indexeddb, use an indexeddb crypto store. -if (indexedDB) { - matrixcs.setCryptoStoreFactory(() => new matrixcs.IndexedDBCryptoStore(indexedDB, "matrix-js-sdk:crypto")); -} -// We export 3 things to make browserify happy as well as downstream projects. -// It's awkward, but required. -__exportStar(require("./matrix"), exports); -exports.default = matrixcs; // keep export for browserify package deps -global.matrixcs = matrixcs; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"./matrix":375}],321:[function(require,module,exports){ -(function (global){(function (){ -"use strict"; -/* -Copyright 2015-2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __rest = (this && this.__rest) || function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fixNotificationCountOnDecryption = exports.MatrixClient = exports.ClientEvent = exports.M_AUTHENTICATION = exports.RoomVersionStability = exports.PendingEventOrdering = exports.UNSTABLE_MSC3852_LAST_SEEN_UA = exports.CRYPTO_ENABLED = void 0; -const sync_1 = require("./sync"); -const event_1 = require("./models/event"); -const stub_1 = require("./store/stub"); -const call_1 = require("./webrtc/call"); -const filter_1 = require("./filter"); -const callEventHandler_1 = require("./webrtc/callEventHandler"); -const utils = __importStar(require("./utils")); -const utils_1 = require("./utils"); -const event_timeline_1 = require("./models/event-timeline"); -const pushprocessor_1 = require("./pushprocessor"); -const autodiscovery_1 = require("./autodiscovery"); -const olmlib = __importStar(require("./crypto/olmlib")); -const olmlib_1 = require("./crypto/olmlib"); -const ReEmitter_1 = require("./ReEmitter"); -const RoomList_1 = require("./crypto/RoomList"); -const logger_1 = require("./logger"); -const service_types_1 = require("./service-types"); -const http_api_1 = require("./http-api"); -const crypto_1 = require("./crypto"); -const recoverykey_1 = require("./crypto/recoverykey"); -const key_passphrase_1 = require("./crypto/key_passphrase"); -const user_1 = require("./models/user"); -const content_repo_1 = require("./content-repo"); -const search_result_1 = require("./models/search-result"); -const dehydration_1 = require("./crypto/dehydration"); -const api_1 = require("./crypto/api"); -const ContentHelpers = __importStar(require("./content-helpers")); -const room_1 = require("./models/room"); -const room_member_1 = require("./models/room-member"); -const event_2 = require("./@types/event"); -const partials_1 = require("./@types/partials"); -const event_mapper_1 = require("./event-mapper"); -const randomstring_1 = require("./randomstring"); -const backup_1 = require("./crypto/backup"); -const MSC3089TreeSpace_1 = require("./models/MSC3089TreeSpace"); -const search_1 = require("./@types/search"); -const PushRules_1 = require("./@types/PushRules"); -const groupCall_1 = require("./webrtc/groupCall"); -const mediaHandler_1 = require("./webrtc/mediaHandler"); -const groupCallEventHandler_1 = require("./webrtc/groupCallEventHandler"); -const typed_event_emitter_1 = require("./models/typed-event-emitter"); -const read_receipts_1 = require("./@types/read_receipts"); -const sliding_sync_sdk_1 = require("./sliding-sync-sdk"); -const thread_1 = require("./models/thread"); -const beacon_1 = require("./@types/beacon"); -const NamespacedValue_1 = require("./NamespacedValue"); -const ToDeviceMessageQueue_1 = require("./ToDeviceMessageQueue"); -const invites_ignorer_1 = require("./models/invites-ignorer"); -const feature_1 = require("./feature"); -const constants_1 = require("./rust-crypto/constants"); -const SCROLLBACK_DELAY_MS = 3000; -exports.CRYPTO_ENABLED = (0, crypto_1.isCryptoAvailable)(); -const CAPABILITIES_CACHE_MS = 21600000; // 6 hours - an arbitrary value -const TURN_CHECK_INTERVAL = 10 * 60 * 1000; // poll for turn credentials every 10 minutes -exports.UNSTABLE_MSC3852_LAST_SEEN_UA = new NamespacedValue_1.UnstableValue("last_seen_user_agent", "org.matrix.msc3852.last_seen_user_agent"); -var PendingEventOrdering; -(function (PendingEventOrdering) { - PendingEventOrdering["Chronological"] = "chronological"; - PendingEventOrdering["Detached"] = "detached"; -})(PendingEventOrdering = exports.PendingEventOrdering || (exports.PendingEventOrdering = {})); -var RoomVersionStability; -(function (RoomVersionStability) { - RoomVersionStability["Stable"] = "stable"; - RoomVersionStability["Unstable"] = "unstable"; -})(RoomVersionStability = exports.RoomVersionStability || (exports.RoomVersionStability = {})); -var CrossSigningKeyType; -(function (CrossSigningKeyType) { - CrossSigningKeyType["MasterKey"] = "master_key"; - CrossSigningKeyType["SelfSigningKey"] = "self_signing_key"; - CrossSigningKeyType["UserSigningKey"] = "user_signing_key"; -})(CrossSigningKeyType || (CrossSigningKeyType = {})); -exports.M_AUTHENTICATION = new NamespacedValue_1.UnstableValue("m.authentication", "org.matrix.msc2965.authentication"); -/* eslint-enable camelcase */ -// We're using this constant for methods overloading and inspect whether a variable -// contains an eventId or not. This was required to ensure backwards compatibility -// of methods for threads -// Probably not the most graceful solution but does a good enough job for now -const EVENT_ID_PREFIX = "$"; -var ClientEvent; -(function (ClientEvent) { - ClientEvent["Sync"] = "sync"; - ClientEvent["Event"] = "event"; - ClientEvent["ToDeviceEvent"] = "toDeviceEvent"; - ClientEvent["AccountData"] = "accountData"; - ClientEvent["Room"] = "Room"; - ClientEvent["DeleteRoom"] = "deleteRoom"; - ClientEvent["SyncUnexpectedError"] = "sync.unexpectedError"; - ClientEvent["ClientWellKnown"] = "WellKnown.client"; - ClientEvent["ReceivedVoipEvent"] = "received_voip_event"; - ClientEvent["UndecryptableToDeviceEvent"] = "toDeviceEvent.undecryptable"; - ClientEvent["TurnServers"] = "turnServers"; - ClientEvent["TurnServersError"] = "turnServers.error"; -})(ClientEvent = exports.ClientEvent || (exports.ClientEvent = {})); -const SSO_ACTION_PARAM = new NamespacedValue_1.UnstableValue("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. - */ -class MatrixClient extends typed_event_emitter_1.TypedEventEmitter { - constructor(opts) { - var _a; - super(); - this.reEmitter = new ReEmitter_1.TypedReEmitter(this); - this.olmVersion = null; // populated after initCrypto - this.usingExternalCrypto = false; - this.clientRunning = false; - this.timelineSupport = false; - this.urlPreviewCache = {}; - this.supportsCallTransfer = false; // XXX: Intended private, used in code. - this.forceTURN = false; // XXX: Intended private, used in code. - this.iceCandidatePoolSize = 0; // XXX: Intended private, used in code. - // Note: these are all `protected` to let downstream consumers make mistakes if they want to. - // We don't technically support this usage, but have reasons to do this. - this.canSupportVoip = false; - this.peekSync = null; - this.isGuestAccount = false; - this.ongoingScrollbacks = {}; - this.notifTimelineSet = null; - this.fallbackICEServerAllowed = false; - this.syncedLeftRooms = false; - this.canSupport = new Map(); - // The pushprocessor caches useful things, so keep one and re-use it - this.pushProcessor = new pushprocessor_1.PushProcessor(this); - this.turnServers = []; - this.turnServersExpiry = 0; - this.txnCtr = 0; - this.mediaHandler = new mediaHandler_1.MediaHandler(this); - this.pendingEventEncryption = new Map(); - this.useE2eForGroupCall = true; - this.startCallEventHandler = () => { - if (this.isInitialSyncComplete()) { - this.callEventHandler.start(); - this.groupCallEventHandler.start(); - this.off(ClientEvent.Sync, this.startCallEventHandler); - } - }; - /** - * 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. - */ - this.fixupRoomNotifications = () => { - var _a; - if (this.isInitialSyncComplete()) { - const unreadRooms = ((_a = this.getRooms()) !== null && _a !== void 0 ? _a : []).filter((room) => { - return room.getUnreadNotificationCount(room_1.NotificationCountType.Total) > 0; - }); - for (const room of unreadRooms) { - const currentUserId = this.getSafeUserId(); - room.fixupNotifications(currentUserId); - } - this.off(ClientEvent.Sync, this.fixupRoomNotifications); - } - }; - opts.baseUrl = utils.ensureNoTrailingSlash(opts.baseUrl); - opts.idBaseUrl = utils.ensureNoTrailingSlash(opts.idBaseUrl); - this.baseUrl = opts.baseUrl; - this.idBaseUrl = opts.idBaseUrl; - this.identityServer = opts.identityServer; - this.usingExternalCrypto = (_a = opts.usingExternalCrypto) !== null && _a !== void 0 ? _a : false; - this.store = opts.store || new stub_1.StubStore(); - this.deviceId = opts.deviceId || null; - this.sessionId = (0, randomstring_1.randomString)(10); - const userId = opts.userId || null; - this.credentials = { userId }; - this.http = new http_api_1.MatrixHttpApi(this, { - fetchFn: opts.fetchFn, - baseUrl: opts.baseUrl, - idBaseUrl: opts.idBaseUrl, - accessToken: opts.accessToken, - prefix: http_api_1.ClientPrefix.R0, - onlyData: true, - extraParams: opts.queryParams, - localTimeoutMs: opts.localTimeoutMs, - useAuthorizationHeader: opts.useAuthorizationHeader, - }); - if (opts.deviceToImport) { - if (this.deviceId) { - logger_1.logger.warn("not importing device because device ID is provided to " + - "constructor independently of exported data"); - } - else if (this.credentials.userId) { - logger_1.logger.warn("not importing device because user ID is provided to " + - "constructor independently of exported data"); - } - else if (!opts.deviceToImport.deviceId) { - logger_1.logger.warn("not importing device because no device ID in exported data"); - } - else { - this.deviceId = opts.deviceToImport.deviceId; - this.credentials.userId = opts.deviceToImport.userId; - // will be used during async initialization of the crypto - this.exportedOlmDeviceToImport = opts.deviceToImport.olmDevice; - } - } - else if (opts.pickleKey) { - this.pickleKey = opts.pickleKey; - } - this.scheduler = opts.scheduler; - if (this.scheduler) { - this.scheduler.setProcessFunction((eventToSend) => __awaiter(this, void 0, void 0, function* () { - const room = this.getRoom(eventToSend.getRoomId()); - if (eventToSend.status !== event_1.EventStatus.SENDING) { - this.updatePendingEventStatus(room, eventToSend, event_1.EventStatus.SENDING); - } - const res = yield this.sendEventHttpRequest(eventToSend); - if (room) { - // ensure we update pending event before the next scheduler run so that any listeners to event id - // updates on the synchronous event emitter get a chance to run first. - room.updatePendingEvent(eventToSend, event_1.EventStatus.SENT, res.event_id); - } - return res; - })); - } - if ((0, call_1.supportsMatrixCall)()) { - this.callEventHandler = new callEventHandler_1.CallEventHandler(this); - this.groupCallEventHandler = new groupCallEventHandler_1.GroupCallEventHandler(this); - this.canSupportVoip = true; - // Start listening for calls after the initial sync is done - // We do not need to backfill the call event buffer - // with encrypted events that might never get decrypted - this.on(ClientEvent.Sync, this.startCallEventHandler); - } - this.on(ClientEvent.Sync, this.fixupRoomNotifications); - this.timelineSupport = Boolean(opts.timelineSupport); - this.cryptoStore = opts.cryptoStore; - this.verificationMethods = opts.verificationMethods; - this.cryptoCallbacks = opts.cryptoCallbacks || {}; - this.forceTURN = opts.forceTURN || false; - this.iceCandidatePoolSize = opts.iceCandidatePoolSize === undefined ? 0 : opts.iceCandidatePoolSize; - this.supportsCallTransfer = opts.supportsCallTransfer || false; - this.fallbackICEServerAllowed = opts.fallbackICEServerAllowed || false; - this.isVoipWithNoMediaAllowed = opts.isVoipWithNoMediaAllowed || false; - if (opts.useE2eForGroupCall !== undefined) - this.useE2eForGroupCall = opts.useE2eForGroupCall; - // List of which rooms have encryption enabled: separate from crypto because - // we still want to know which rooms are encrypted even if crypto is disabled: - // we don't want to start sending unencrypted events to them. - this.roomList = new RoomList_1.RoomList(this.cryptoStore); - this.roomNameGenerator = opts.roomNameGenerator; - this.toDeviceMessageQueue = new ToDeviceMessageQueue_1.ToDeviceMessageQueue(this); - // The SDK doesn't really provide a clean way for events to recalculate the push - // actions for themselves, so we have to kinda help them out when they are encrypted. - // We do this so that push rules are correctly executed on events in their decrypted - // state, such as highlights when the user's name is mentioned. - this.on(event_1.MatrixEventEvent.Decrypted, (event) => { - fixNotificationCountOnDecryption(this, event); - }); - // Like above, we have to listen for read receipts from ourselves in order to - // correctly handle notification counts on encrypted rooms. - // This fixes https://github.com/vector-im/element-web/issues/9421 - this.on(room_1.RoomEvent.Receipt, (event, room) => { - var _a; - if (room && this.isRoomEncrypted(room.roomId)) { - // Figure out if we've read something or if it's just informational - const content = event.getContent(); - const isSelf = Object.keys(content).filter((eid) => { - for (const [key, value] of Object.entries(content[eid])) { - if (!utils.isSupportedReceiptType(key)) - continue; - if (!value) - continue; - if (Object.keys(value).includes(this.getUserId())) - return true; - } - return false; - }).length > 0; - if (!isSelf) - return; - // Work backwards to determine how many events are unread. We also set - // a limit for how back we'll look to avoid spinning CPU for too long. - // If we hit the limit, we assume the count is unchanged. - const maxHistory = 20; - const events = room.getLiveTimeline().getEvents(); - let highlightCount = 0; - for (let i = events.length - 1; i >= 0; i--) { - if (i === events.length - maxHistory) - return; // limit reached - const event = events[i]; - if (room.hasUserReadEvent(this.getUserId(), event.getId())) { - // If the user has read the event, then the counting is done. - break; - } - const pushActions = this.getPushActionsForEvent(event); - highlightCount += ((_a = pushActions === null || pushActions === void 0 ? void 0 : pushActions.tweaks) === null || _a === void 0 ? void 0 : _a.highlight) ? 1 : 0; - } - // Note: we don't need to handle 'total' notifications because the counts - // will come from the server. - room.setUnreadNotificationCount(room_1.NotificationCountType.Highlight, highlightCount); - } - }); - this.ignoredInvites = new invites_ignorer_1.IgnoredInvites(this); - } - /** - * 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) { - return __awaiter(this, void 0, void 0, function* () { - if (this.clientRunning) { - // client is already running. - return; - } - this.clientRunning = true; - // backwards compat for when 'opts' was 'historyLen'. - if (typeof opts === "number") { - opts = { - initialSyncLimit: opts, - }; - } - // Create our own user object artificially (instead of waiting for sync) - // so it's always available, even if the user is not in any rooms etc. - const userId = this.getUserId(); - if (userId) { - this.store.storeUser(new user_1.User(userId)); - } - // periodically poll for turn servers if we support voip - if (this.canSupportVoip) { - this.checkTurnServersIntervalID = setInterval(() => { - this.checkTurnServers(); - }, TURN_CHECK_INTERVAL); - // noinspection ES6MissingAwait - this.checkTurnServers(); - } - if (this.syncApi) { - // This shouldn't happen since we thought the client was not running - logger_1.logger.error("Still have sync object whilst not running: stopping old one"); - this.syncApi.stop(); - } - try { - yield this.getVersions(); - // This should be done with `canSupport` - // TODO: https://github.com/vector-im/element-web/issues/23643 - const { threads, list, fwdPagination } = yield this.doesServerSupportThread(); - thread_1.Thread.setServerSideSupport(threads); - thread_1.Thread.setServerSideListSupport(list); - thread_1.Thread.setServerSideFwdPaginationSupport(fwdPagination); - } - catch (e) { - logger_1.logger.error("Can't fetch server versions, continuing to initialise sync, this will be retried later", e); - } - this.clientOpts = opts !== null && opts !== void 0 ? opts : {}; - if (this.clientOpts.slidingSync) { - this.syncApi = new sliding_sync_sdk_1.SlidingSyncSdk(this.clientOpts.slidingSync, this, this.clientOpts, this.buildSyncApiOptions()); - } - else { - this.syncApi = new sync_1.SyncApi(this, this.clientOpts, this.buildSyncApiOptions()); - } - if (this.clientOpts.hasOwnProperty("experimentalThreadSupport")) { - logger_1.logger.warn("`experimentalThreadSupport` has been deprecated, use `threadSupport` instead"); - } - // If `threadSupport` is omitted and the deprecated `experimentalThreadSupport` has been passed - // We should fallback to that value for backwards compatibility purposes - if (!this.clientOpts.hasOwnProperty("threadSupport") && - this.clientOpts.hasOwnProperty("experimentalThreadSupport")) { - this.clientOpts.threadSupport = this.clientOpts.experimentalThreadSupport; - } - this.syncApi.sync(); - if (this.clientOpts.clientWellKnownPollPeriod !== undefined) { - this.clientWellKnownIntervalID = setInterval(() => { - this.fetchClientWellKnown(); - }, 1000 * this.clientOpts.clientWellKnownPollPeriod); - this.fetchClientWellKnown(); - } - this.toDeviceMessageQueue.start(); - }); - } - /** - * Construct a SyncApiOptions for this client, suitable for passing into the SyncApi constructor - */ - buildSyncApiOptions() { - return { - crypto: this.crypto, - cryptoCallbacks: this.cryptoBackend, - canResetEntireTimeline: (roomId) => { - if (!this.canResetTimelineCallback) { - return false; - } - return this.canResetTimelineCallback(roomId); - }, - }; - } - /** - * High level helper method to stop the client from polling and allow a - * clean shutdown. - */ - stopClient() { - var _a, _b, _c, _d, _e; - (_a = this.cryptoBackend) === null || _a === void 0 ? void 0 : _a.stop(); // crypto might have been initialised even if the client wasn't fully started - if (!this.clientRunning) - return; // already stopped - logger_1.logger.log("stopping MatrixClient"); - this.clientRunning = false; - (_b = this.syncApi) === null || _b === void 0 ? void 0 : _b.stop(); - this.syncApi = undefined; - (_c = this.peekSync) === null || _c === void 0 ? void 0 : _c.stopPeeking(); - (_d = this.callEventHandler) === null || _d === void 0 ? void 0 : _d.stop(); - (_e = this.groupCallEventHandler) === null || _e === void 0 ? void 0 : _e.stop(); - this.callEventHandler = undefined; - this.groupCallEventHandler = undefined; - global.clearInterval(this.checkTurnServersIntervalID); - this.checkTurnServersIntervalID = undefined; - if (this.clientWellKnownIntervalID !== undefined) { - global.clearInterval(this.clientWellKnownIntervalID); - } - this.toDeviceMessageQueue.stop(); - } - /** - * Try to rehydrate a device if available. The client must have been - * initialized with a `cryptoCallback.getDehydrationKey` option, and this - * function must be called before initCrypto and startClient are called. - * - * @returns Promise which resolves to undefined if a device could not be dehydrated, or - * to the new device ID if the dehydration was successful. - * @returns Rejects: with an error response. - */ - rehydrateDevice() { - return __awaiter(this, void 0, void 0, function* () { - if (this.crypto) { - throw new Error("Cannot rehydrate device after crypto is initialized"); - } - if (!this.cryptoCallbacks.getDehydrationKey) { - return; - } - const getDeviceResult = yield this.getDehydratedDevice(); - if (!getDeviceResult) { - return; - } - if (!getDeviceResult.device_data || !getDeviceResult.device_id) { - logger_1.logger.info("no dehydrated device found"); - return; - } - const account = new global.Olm.Account(); - try { - const deviceData = getDeviceResult.device_data; - if (deviceData.algorithm !== dehydration_1.DEHYDRATION_ALGORITHM) { - logger_1.logger.warn("Wrong algorithm for dehydrated device"); - return; - } - logger_1.logger.log("unpickling dehydrated device"); - const key = yield this.cryptoCallbacks.getDehydrationKey(deviceData, (k) => { - // copy the key so that it doesn't get clobbered - account.unpickle(new Uint8Array(k), deviceData.account); - }); - account.unpickle(key, deviceData.account); - logger_1.logger.log("unpickled device"); - const rehydrateResult = yield this.http.authedRequest(http_api_1.Method.Post, "/dehydrated_device/claim", undefined, { - device_id: getDeviceResult.device_id, - }, { - prefix: "/_matrix/client/unstable/org.matrix.msc2697.v2", - }); - if (rehydrateResult.success) { - this.deviceId = getDeviceResult.device_id; - logger_1.logger.info("using dehydrated device"); - const pickleKey = this.pickleKey || "DEFAULT_KEY"; - this.exportedOlmDeviceToImport = { - pickledAccount: account.pickle(pickleKey), - sessions: [], - pickleKey: pickleKey, - }; - account.free(); - return this.deviceId; - } - else { - account.free(); - logger_1.logger.info("not using dehydrated device"); - return; - } - } - catch (e) { - account.free(); - logger_1.logger.warn("could not unpickle", e); - } - }); - } - /** - * Get the current dehydrated device, if any - * @returns A promise of an object containing the dehydrated device - */ - getDehydratedDevice() { - return __awaiter(this, void 0, void 0, function* () { - try { - return yield this.http.authedRequest(http_api_1.Method.Get, "/dehydrated_device", undefined, undefined, { - prefix: "/_matrix/client/unstable/org.matrix.msc2697.v2", - }); - } - catch (e) { - logger_1.logger.info("could not get dehydrated device", e); - return; - } - }); - } - /** - * Set the dehydration key. This will also periodically dehydrate devices to - * the server. - * - * @param key - the dehydration key - * @param keyInfo - Information about the key. Primarily for - * information about how to generate the key from a passphrase. - * @param deviceDisplayName - The device display name for the - * dehydrated device. - * @returns A promise that resolves when the dehydrated device is stored. - */ - setDehydrationKey(key, keyInfo, deviceDisplayName) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.crypto) { - logger_1.logger.warn("not dehydrating device if crypto is not enabled"); - return; - } - return this.crypto.dehydrationManager.setKeyAndQueueDehydration(key, keyInfo, deviceDisplayName); - }); - } - /** - * Creates a new dehydrated device (without queuing periodic dehydration) - * @param key - the dehydration key - * @param keyInfo - Information about the key. Primarily for - * information about how to generate the key from a passphrase. - * @param deviceDisplayName - The device display name for the - * dehydrated device. - * @returns the device id of the newly created dehydrated device - */ - createDehydratedDevice(key, keyInfo, deviceDisplayName) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.crypto) { - logger_1.logger.warn("not dehydrating device if crypto is not enabled"); - return; - } - yield this.crypto.dehydrationManager.setKey(key, keyInfo, deviceDisplayName); - return this.crypto.dehydrationManager.dehydrateDevice(); - }); - } - exportDevice() { - return __awaiter(this, void 0, void 0, function* () { - if (!this.crypto) { - logger_1.logger.warn("not exporting device if crypto is not enabled"); - return; - } - return { - userId: this.credentials.userId, - deviceId: this.deviceId, - // XXX: Private member access. - olmDevice: yield this.crypto.olmDevice.export(), - }; - }); - } - /** - * Clear any data out of the persistent stores used by the client. - * - * @returns Promise which resolves when the stores have been cleared. - */ - clearStores() { - if (this.clientRunning) { - throw new Error("Cannot clear stores while client is running"); - } - const promises = []; - promises.push(this.store.deleteAllData()); - if (this.cryptoStore) { - promises.push(this.cryptoStore.deleteAllData()); - } - // delete the stores used by the rust matrix-sdk-crypto, in case they were used - const deleteRustSdkStore = () => __awaiter(this, void 0, void 0, function* () { - let indexedDB; - try { - indexedDB = global.indexedDB; - } - catch (e) { - // No indexeddb support - return; - } - for (const dbname of [ - `${constants_1.RUST_SDK_STORE_PREFIX}::matrix-sdk-crypto`, - `${constants_1.RUST_SDK_STORE_PREFIX}::matrix-sdk-crypto-meta`, - ]) { - const prom = new Promise((resolve, reject) => { - logger_1.logger.info(`Removing IndexedDB instance ${dbname}`); - const req = indexedDB.deleteDatabase(dbname); - req.onsuccess = (_) => { - logger_1.logger.info(`Removed IndexedDB instance ${dbname}`); - resolve(0); - }; - req.onerror = (e) => { - // In private browsing, Firefox has a global.indexedDB, but attempts to delete an indexeddb - // (even a non-existent one) fail with "DOMException: A mutation operation was attempted on a - // database that did not allow mutations." - // - // it seems like the only thing we can really do is ignore the error. - logger_1.logger.warn(`Failed to remove IndexedDB instance ${dbname}:`, e); - resolve(0); - }; - req.onblocked = (e) => { - logger_1.logger.info(`cannot yet remove IndexedDB instance ${dbname}`); - }; - }); - yield prom; - } - }); - promises.push(deleteRustSdkStore()); - return Promise.all(promises).then(); // .then to fix types - } - /** - * Get the user-id of the logged-in user - * - * @returns MXID for the logged-in user, or null if not logged in - */ - getUserId() { - if (this.credentials && this.credentials.userId) { - return this.credentials.userId; - } - return null; - } - /** - * Get the user-id of the logged-in user - * - * @returns MXID for the logged-in user - * @throws Error if not logged in - */ - getSafeUserId() { - const 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() { - if (this.credentials && this.credentials.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() { - if (this.credentials && this.credentials.userId) { - return this.credentials.userId.split(":")[0].substring(1); - } - return 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.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 (0, call_1.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) { - return __awaiter(this, void 0, void 0, function* () { - if (this.getGroupCallForRoom(roomId)) { - throw new Error(`${roomId} already has an existing group call`); - } - const room = this.getRoom(roomId); - if (!room) { - throw new Error(`Cannot find room ${roomId}`); - } - // Because without Media section a WebRTC connection is not possible, so need a RTCDataChannel to set up a - // no media WebRTC connection anyway. - return new groupCall_1.GroupCall(this, room, type, isPtt, intent, undefined, dataChannelsEnabled || this.isVoipWithNoMediaAllowed, dataChannelOptions, this.isVoipWithNoMediaAllowed).create(); - }); - } - /** - * 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 _a, _b; - return (_b = (_a = this.syncApi) === null || _a === void 0 ? void 0 : _a.getSyncState()) !== null && _b !== void 0 ? _b : 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() { - const state = this.getSyncState(); - if (!state) { - return false; - } - return state === sync_1.SyncState.Prepared || state === sync_1.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. This method is experimental - * and may change without warning. - * @param guest - True if this is a guest account. - */ - setGuest(guest) { - // 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. - 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 explicitly 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 _a, _b; - // don't await for this promise: we just want to kick it off - this.toDeviceMessageQueue.sendQueue(); - return (_b = (_a = this.syncApi) === null || _a === void 0 ? void 0 : _a.retryImmediately()) !== null && _b !== void 0 ? _b : 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 capabilities of the homeserver. Always returns an object of - * capability keys and their options, which may be empty. - * @param fresh - True to ignore any cached values. - * @returns Promise which resolves to the capabilities of the homeserver - * @returns Rejects: with an error response. - */ - getCapabilities(fresh = false) { - const now = new Date().getTime(); - if (this.cachedCapabilities && !fresh) { - if (now < this.cachedCapabilities.expiration) { - logger_1.logger.log("Returning cached capabilities"); - return Promise.resolve(this.cachedCapabilities.capabilities); - } - } - return this.http - .authedRequest(http_api_1.Method.Get, "/capabilities") - .catch((e) => { - // We swallow errors because we need a default object anyhow - logger_1.logger.error(e); - return {}; - }) - .then((r = {}) => { - const capabilities = r["capabilities"] || {}; - // If the capabilities missed the cache, cache it for a shorter amount - // of time to try and refresh them later. - const cacheMs = Object.keys(capabilities).length ? CAPABILITIES_CACHE_MS : 60000 + Math.random() * 5000; - this.cachedCapabilities = { - capabilities, - expiration: now + cacheMs, - }; - logger_1.logger.log("Caching capabilities: ", capabilities); - return capabilities; - }); - } - /** - * Initialise support for end-to-end encryption in this client, using libolm. - * - * You should call this method after creating the matrixclient, but *before* - * calling `startClient`, if you want to support end-to-end encryption. - * - * It will return a Promise which will resolve when the crypto layer has been - * successfully initialised. - */ - initCrypto() { - return __awaiter(this, void 0, void 0, function* () { - if (!(0, crypto_1.isCryptoAvailable)()) { - throw new Error(`End-to-end encryption not supported in this js-sdk build: did ` + - `you remember to load the olm library?`); - } - if (this.cryptoBackend) { - logger_1.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient"); - return; - } - if (!this.cryptoStore) { - // the cryptostore is provided by sdk.createClient, so this shouldn't happen - throw new Error(`Cannot enable encryption: no cryptoStore provided`); - } - logger_1.logger.log("Crypto: Starting up crypto store..."); - yield this.cryptoStore.startup(); - // initialise the list of encrypted rooms (whether or not crypto is enabled) - logger_1.logger.log("Crypto: initialising roomlist..."); - yield this.roomList.init(); - const userId = this.getUserId(); - if (userId === null) { - throw new Error(`Cannot enable encryption on MatrixClient with unknown userId: ` + - `ensure userId is passed in createClient().`); - } - if (this.deviceId === null) { - throw new Error(`Cannot enable encryption on MatrixClient with unknown deviceId: ` + - `ensure deviceId is passed in createClient().`); - } - const crypto = new crypto_1.Crypto(this, userId, this.deviceId, this.store, this.cryptoStore, this.roomList, this.verificationMethods); - this.reEmitter.reEmit(crypto, [ - crypto_1.CryptoEvent.KeyBackupFailed, - crypto_1.CryptoEvent.KeyBackupSessionsRemaining, - crypto_1.CryptoEvent.RoomKeyRequest, - crypto_1.CryptoEvent.RoomKeyRequestCancellation, - crypto_1.CryptoEvent.Warning, - crypto_1.CryptoEvent.DevicesUpdated, - crypto_1.CryptoEvent.WillUpdateDevices, - crypto_1.CryptoEvent.DeviceVerificationChanged, - crypto_1.CryptoEvent.UserTrustStatusChanged, - crypto_1.CryptoEvent.KeysChanged, - ]); - logger_1.logger.log("Crypto: initialising crypto object..."); - yield crypto.init({ - exportedOlmDevice: this.exportedOlmDeviceToImport, - pickleKey: this.pickleKey, - }); - delete this.exportedOlmDeviceToImport; - this.olmVersion = crypto_1.Crypto.getOlmVersion(); - // if crypto initialisation was successful, tell it to attach its event handlers. - crypto.registerEventHandlers(this); - this.cryptoBackend = this.crypto = crypto; - // upload our keys in the background - this.crypto.uploadDeviceKeys().catch((e) => { - // TODO: throwing away this error is a really bad idea. - logger_1.logger.error("Error uploading device keys", e); - }); - }); - } - /** - * Initialise support for end-to-end encryption in this client, using the rust matrix-sdk-crypto. - * - * An alternative to {@link initCrypto}. - * - * *WARNING*: this API is very experimental, should not be used in production, and may change without notice! - * Eventually it will be deprecated and `initCrypto` will do the same thing. - * - * @experimental - * - * @returns a Promise which will resolve when the crypto layer has been - * successfully initialised. - */ - initRustCrypto() { - return __awaiter(this, void 0, void 0, function* () { - if (this.cryptoBackend) { - logger_1.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient"); - return; - } - const userId = this.getUserId(); - if (userId === null) { - throw new Error(`Cannot enable encryption on MatrixClient with unknown userId: ` + - `ensure userId is passed in createClient().`); - } - const deviceId = this.getDeviceId(); - if (deviceId === null) { - throw new Error(`Cannot enable encryption on MatrixClient with unknown deviceId: ` + - `ensure deviceId is passed in createClient().`); - } - // importing rust-crypto will download the webassembly, so we delay it until we know it will be - // needed. - const RustCrypto = yield Promise.resolve().then(() => __importStar(require("./rust-crypto"))); - const rustCrypto = yield RustCrypto.initRustCrypto(this.http, userId, deviceId); - this.cryptoBackend = rustCrypto; - // attach the event listeners needed by RustCrypto - this.on(room_member_1.RoomMemberEvent.Membership, rustCrypto.onRoomMembership.bind(rustCrypto)); - }); - } - /** - * Access the crypto API for this client. - * - * If end-to-end encryption has been enabled for this client (via {@link initCrypto} or {@link initRustCrypto}), - * returns an object giving access to the crypto API. Otherwise, returns `undefined`. - */ - getCrypto() { - return this.cryptoBackend; - } - /** - * Is end-to-end crypto enabled for this client. - * @returns True if end-to-end is enabled. - * @deprecated prefer {@link getCrypto} - */ - isCryptoEnabled() { - return !!this.cryptoBackend; - } - /** - * Get the Ed25519 key for this device - * - * @returns base64-encoded ed25519 key. Null if crypto is - * disabled. - */ - getDeviceEd25519Key() { - var _a, _b; - return (_b = (_a = this.crypto) === null || _a === void 0 ? void 0 : _a.getDeviceEd25519Key()) !== null && _b !== void 0 ? _b : null; - } - /** - * Get the Curve25519 key for this device - * - * @returns base64-encoded curve25519 key. Null if crypto is - * disabled. - */ - getDeviceCurve25519Key() { - var _a, _b; - return (_b = (_a = this.crypto) === null || _a === void 0 ? void 0 : _a.getDeviceCurve25519Key()) !== null && _b !== void 0 ? _b : null; - } - /** - * @deprecated Does nothing. - */ - uploadKeys() { - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.warn("MatrixClient.uploadKeys is deprecated"); - }); - } - /** - * Download the keys for a list of users and stores the keys in the session - * store. - * @param userIds - The users to fetch. - * @param forceDownload - Always download the keys even if cached. - * - * @returns A promise which resolves to a map userId-\>deviceId-\>{@link DeviceInfo} - */ - downloadKeys(userIds, forceDownload) { - if (!this.crypto) { - return Promise.reject(new Error("End-to-end encryption disabled")); - } - return this.crypto.downloadKeys(userIds, forceDownload); - } - /** - * Get the stored device keys for a user id - * - * @param userId - the user to list keys for. - * - * @returns list of devices - */ - getStoredDevicesForUser(userId) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.getStoredDevicesForUser(userId) || []; - } - /** - * Get the stored device key for a user id and device id - * - * @param userId - the user to list keys for. - * @param deviceId - unique identifier for the device - * - * @returns device or null - */ - getStoredDevice(userId, deviceId) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.getStoredDevice(userId, deviceId) || null; - } - /** - * Mark the given device as verified - * - * @param userId - owner of the device - * @param deviceId - unique identifier for the device or user's - * cross-signing public key ID. - * - * @param verified - whether to mark the device as verified. defaults - * to 'true'. - * - * @returns - * - * @remarks - * Fires {@link CryptoEvent#DeviceVerificationChanged} - */ - setDeviceVerified(userId, deviceId, verified = true) { - const prom = this.setDeviceVerification(userId, deviceId, verified, null, null); - // if one of the user's own devices is being marked as verified / unverified, - // check the key backup status, since whether or not we use this depends on - // whether it has a signature from a verified device - if (userId == this.credentials.userId) { - this.checkKeyBackup(); - } - return prom; - } - /** - * Mark the given device as blocked/unblocked - * - * @param userId - owner of the device - * @param deviceId - unique identifier for the device or user's - * cross-signing public key ID. - * - * @param blocked - whether to mark the device as blocked. defaults - * to 'true'. - * - * @returns - * - * @remarks - * Fires {@link CryptoEvent.DeviceVerificationChanged} - */ - setDeviceBlocked(userId, deviceId, blocked = true) { - return this.setDeviceVerification(userId, deviceId, null, blocked, null); - } - /** - * Mark the given device as known/unknown - * - * @param userId - owner of the device - * @param deviceId - unique identifier for the device or user's - * cross-signing public key ID. - * - * @param known - whether to mark the device as known. defaults - * to 'true'. - * - * @returns - * - * @remarks - * Fires {@link CryptoEvent#DeviceVerificationChanged} - */ - setDeviceKnown(userId, deviceId, known = true) { - return this.setDeviceVerification(userId, deviceId, null, null, known); - } - setDeviceVerification(userId, deviceId, verified, blocked, known) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - yield this.crypto.setDeviceVerification(userId, deviceId, verified, blocked, known); - }); - } - /** - * Request a key verification from another user, using a DM. - * - * @param userId - the user to request verification with - * @param roomId - the room to use for verification - * - * @returns resolves to a VerificationRequest - * when the request has been sent to the other party. - */ - requestVerificationDM(userId, roomId) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.requestVerificationDM(userId, roomId); - } - /** - * Finds a DM verification request that is already in progress for the given room id - * - * @param roomId - the room to use for verification - * - * @returns the VerificationRequest that is in progress, if any - */ - findVerificationRequestDMInProgress(roomId) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.findVerificationRequestDMInProgress(roomId); - } - /** - * Returns all to-device verification requests that are already in progress for the given user id - * - * @param userId - the ID of the user to query - * - * @returns the VerificationRequests that are in progress - */ - getVerificationRequestsToDeviceInProgress(userId) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.getVerificationRequestsToDeviceInProgress(userId); - } - /** - * Request a key verification from another user. - * - * @param userId - the user to request verification with - * @param devices - array of device IDs to send requests to. Defaults to - * all devices owned by the user - * - * @returns resolves to a VerificationRequest - * when the request has been sent to the other party. - */ - requestVerification(userId, devices) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.requestVerification(userId, devices); - } - /** - * Begin a key verification. - * - * @param method - the verification method to use - * @param userId - the user to verify keys with - * @param deviceId - the device to verify - * - * @returns a verification object - * @deprecated Use `requestVerification` instead. - */ - beginKeyVerification(method, userId, deviceId) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.beginKeyVerification(method, userId, deviceId); - } - checkSecretStorageKey(key, info) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.checkSecretStorageKey(key, info); - } - /** - * Set the global override for whether the client should ever send encrypted - * messages to unverified devices. This provides the default for rooms which - * do not specify a value. - * - * @param value - whether to blacklist all unverified devices by default - * - * @deprecated Prefer direct access to {@link CryptoApi.globalBlacklistUnverifiedDevices}: - * - * ```javascript - * client.getCrypto().globalBlacklistUnverifiedDevices = value; - * ``` - */ - setGlobalBlacklistUnverifiedDevices(value) { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - this.cryptoBackend.globalBlacklistUnverifiedDevices = value; - return value; - } - /** - * @returns whether to blacklist all unverified devices by default - * - * @deprecated Prefer direct access to {@link CryptoApi.globalBlacklistUnverifiedDevices}: - * - * ```javascript - * value = client.getCrypto().globalBlacklistUnverifiedDevices; - * ``` - */ - getGlobalBlacklistUnverifiedDevices() { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.globalBlacklistUnverifiedDevices; - } - /** - * Set whether sendMessage in a room with unknown and unverified devices - * should throw an error and not send them message. This has 'Global' for - * symmetry with setGlobalBlacklistUnverifiedDevices but there is currently - * no room-level equivalent for this setting. - * - * This API is currently UNSTABLE and may change or be removed without notice. - * - * @param value - whether error on unknown devices - * - * @deprecated Prefer direct access to {@link CryptoApi.globalBlacklistUnverifiedDevices}: - * - * ```ts - * client.getCrypto().globalBlacklistUnverifiedDevices = value; - * ``` - */ - setGlobalErrorOnUnknownDevices(value) { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - this.cryptoBackend.globalErrorOnUnknownDevices = value; - } - /** - * @returns whether to error on unknown devices - * - * This API is currently UNSTABLE and may change or be removed without notice. - */ - getGlobalErrorOnUnknownDevices() { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.globalErrorOnUnknownDevices; - } - /** - * Get the user's cross-signing key ID. - * - * The cross-signing API is currently UNSTABLE and may change without notice. - * - * @param type - The type of key to get the ID of. One of - * "master", "self_signing", or "user_signing". Defaults to "master". - * - * @returns the key ID - */ - getCrossSigningId(type = api_1.CrossSigningKey.Master) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.getCrossSigningId(type); - } - /** - * Get the cross signing information for a given user. - * - * The cross-signing API is currently UNSTABLE and may change without notice. - * - * @param userId - the user ID to get the cross-signing info for. - * - * @returns the cross signing information for the user. - */ - getStoredCrossSigningForUser(userId) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.getStoredCrossSigningForUser(userId); - } - /** - * Check whether a given user is trusted. - * - * The cross-signing API is currently UNSTABLE and may change without notice. - * - * @param userId - The ID of the user to check. - */ - checkUserTrust(userId) { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.checkUserTrust(userId); - } - /** - * Check whether a given device is trusted. - * - * The cross-signing API is currently UNSTABLE and may change without notice. - * - * @param userId - The ID of the user whose devices is to be checked. - * @param deviceId - The ID of the device to check - */ - checkDeviceTrust(userId, deviceId) { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.checkDeviceTrust(userId, deviceId); - } - /** - * Check whether one of our own devices is cross-signed by our - * user's stored keys, regardless of whether we trust those keys yet. - * - * @param deviceId - The ID of the device to check - * - * @returns true if the device is cross-signed - */ - checkIfOwnDeviceCrossSigned(deviceId) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.checkIfOwnDeviceCrossSigned(deviceId); - } - /** - * Check the copy of our cross-signing key that we have in the device list and - * see if we can get the private key. If so, mark it as trusted. - * @param opts - ICheckOwnCrossSigningTrustOpts object - */ - checkOwnCrossSigningTrust(opts) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.checkOwnCrossSigningTrust(opts); - } - /** - * Checks that a given cross-signing private key matches a given public key. - * This can be used by the getCrossSigningKey callback to verify that the - * private key it is about to supply is the one that was requested. - * @param privateKey - The private key - * @param expectedPublicKey - The public key - * @returns true if the key matches, otherwise false - */ - checkCrossSigningPrivateKey(privateKey, expectedPublicKey) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.checkCrossSigningPrivateKey(privateKey, expectedPublicKey); - } - // deprecated: use requestVerification instead - legacyDeviceVerification(userId, deviceId, method) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.legacyDeviceVerification(userId, deviceId, method); - } - /** - * Perform any background tasks that can be done before a message is ready to - * send, in order to speed up sending of the message. - * @param room - the room the event is in - * - * @deprecated Prefer {@link CryptoApi.prepareToEncrypt | `CryptoApi.prepareToEncrypt`}: - * - * ```javascript - * client.getCrypto().prepareToEncrypt(room); - * ``` - */ - prepareToEncrypt(room) { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - this.cryptoBackend.prepareToEncrypt(room); - } - /** - * Checks if the user has previously published cross-signing keys - * - * This means downloading the devicelist for the user and checking if the list includes - * the cross-signing pseudo-device. - * - * @deprecated Prefer {@link CryptoApi.userHasCrossSigningKeys | `CryptoApi.userHasCrossSigningKeys`}: - * - * ```javascript - * result = client.getCrypto().userHasCrossSigningKeys(); - * ``` - */ - userHasCrossSigningKeys() { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.userHasCrossSigningKeys(); - } - /** - * Checks whether cross signing: - * - is enabled on this account and trusted by this device - * - has private keys either cached locally or stored in secret storage - * - * If this function returns false, bootstrapCrossSigning() can be used - * to fix things such that it returns true. That is to say, after - * bootstrapCrossSigning() completes successfully, this function should - * return true. - * @returns True if cross-signing is ready to be used on this device - */ - isCrossSigningReady() { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.isCrossSigningReady(); - } - /** - * Bootstrap cross-signing by creating keys if needed. If everything is already - * set up, then no changes are made, so this is safe to run to ensure - * cross-signing is ready for use. - * - * This function: - * - creates new cross-signing keys if they are not found locally cached nor in - * secret storage (if it has been setup) - * - * The cross-signing API is currently UNSTABLE and may change without notice. - */ - bootstrapCrossSigning(opts) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.bootstrapCrossSigning(opts); - } - /** - * Whether to trust a others users signatures of their devices. - * If false, devices will only be considered 'verified' if we have - * verified that device individually (effectively disabling cross-signing). - * - * Default: true - * - * @returns True if trusting cross-signed devices - */ - getCryptoTrustCrossSignedDevices() { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.getCryptoTrustCrossSignedDevices(); - } - /** - * See getCryptoTrustCrossSignedDevices - * - * @param val - True to trust cross-signed devices - */ - setCryptoTrustCrossSignedDevices(val) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - this.crypto.setCryptoTrustCrossSignedDevices(val); - } - /** - * Counts the number of end to end session keys that are waiting to be backed up - * @returns Promise which resolves to the number of sessions requiring backup - */ - countSessionsNeedingBackup() { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.countSessionsNeedingBackup(); - } - /** - * Get information about the encryption of an event - * - * @param event - event to be checked - * @returns The event information. - */ - getEventEncryptionInfo(event) { - if (!this.cryptoBackend) { - throw new Error("End-to-end encryption disabled"); - } - return this.cryptoBackend.getEventEncryptionInfo(event); - } - /** - * Create a recovery key from a user-supplied passphrase. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @param password - Passphrase string that can be entered by the user - * when restoring the backup as an alternative to entering the recovery key. - * Optional. - * @returns Object with public key metadata, encoded private - * recovery key which should be disposed of after displaying to the user, - * and raw private key to avoid round tripping if needed. - */ - createRecoveryKeyFromPassphrase(password) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.createRecoveryKeyFromPassphrase(password); - } - /** - * Checks whether secret storage: - * - is enabled on this account - * - is storing cross-signing private keys - * - is storing session backup key (if enabled) - * - * If this function returns false, bootstrapSecretStorage() can be used - * to fix things such that it returns true. That is to say, after - * bootstrapSecretStorage() completes successfully, this function should - * return true. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @returns True if secret storage is ready to be used on this device - */ - isSecretStorageReady() { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.isSecretStorageReady(); - } - /** - * Bootstrap Secure Secret Storage if needed by creating a default key. If everything is - * already set up, then no changes are made, so this is safe to run to ensure secret - * storage is ready for use. - * - * This function - * - creates a new Secure Secret Storage key if no default key exists - * - if a key backup exists, it is migrated to store the key in the Secret - * Storage - * - creates a backup if none exists, and one is requested - * - migrates Secure Secret Storage to use the latest algorithm, if an outdated - * algorithm is found - * - */ - bootstrapSecretStorage(opts) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.bootstrapSecretStorage(opts); - } - /** - * Add a key for encrypting secrets. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @param algorithm - the algorithm used by the key - * @param opts - the options for the algorithm. The properties used - * depend on the algorithm given. - * @param keyName - the name of the key. If not given, a random name will be generated. - * - * @returns An object with: - * keyId: the ID of the key - * keyInfo: details about the key (iv, mac, passphrase) - */ - addSecretStorageKey(algorithm, opts, keyName) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.addSecretStorageKey(algorithm, opts, keyName); - } - /** - * Check whether we have a key with a given ID. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @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. - */ - hasSecretStorageKey(keyId) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.hasSecretStorageKey(keyId); - } - /** - * Store an encrypted secret on the server. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @param name - The name of the secret - * @param secret - The secret contents. - * @param keys - The IDs of the keys to use to encrypt the secret or null/undefined - * to use the default (will throw if no default key is set). - */ - storeSecret(name, secret, keys) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.storeSecret(name, secret, keys); - } - /** - * Get a secret from storage. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @param name - the name of the secret - * - * @returns the contents of the secret - */ - getSecret(name) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.getSecret(name); - } - /** - * Check if a secret is stored on the server. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @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 - */ - isSecretStored(name) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.isSecretStored(name); - } - /** - * Request a secret from another device. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @param name - the name of the secret to request - * @param devices - the devices to request the secret from - * - * @returns the secret request object - */ - requestSecret(name, devices) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.requestSecret(name, devices); - } - /** - * Get the current default key ID for encrypting secrets. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @returns The default key ID or null if no default key ID is set - */ - getDefaultSecretStorageKeyId() { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.getDefaultSecretStorageKeyId(); - } - /** - * Set the current default key ID for encrypting secrets. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @param keyId - The new default key ID - */ - setDefaultSecretStorageKeyId(keyId) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.setDefaultSecretStorageKeyId(keyId); - } - /** - * Checks that a given secret storage private key matches a given public key. - * This can be used by the getSecretStorageKey callback to verify that the - * private key it is about to supply is the one that was requested. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @param privateKey - The private key - * @param expectedPublicKey - The public key - * @returns true if the key matches, otherwise false - */ - checkSecretStoragePrivateKey(privateKey, expectedPublicKey) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.checkSecretStoragePrivateKey(privateKey, expectedPublicKey); - } - /** - * Get e2e information on the device that sent an event - * - * @param event - event to be checked - */ - getEventSenderDeviceInfo(event) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.crypto) { - return null; - } - return this.crypto.getEventSenderDeviceInfo(event); - }); - } - /** - * Check if the sender of an event is verified - * - * @param event - event to be checked - * - * @returns true if the sender of this event has been verified using - * {@link MatrixClient#setDeviceVerified}. - */ - isEventSenderVerified(event) { - return __awaiter(this, void 0, void 0, function* () { - const device = yield this.getEventSenderDeviceInfo(event); - if (!device) { - return false; - } - return device.isVerified(); - }); - } - /** - * Get outgoing room key request for this event if there is one. - * @param event - The event to check for - * - * @returns A room key request, or null if there is none - */ - getOutgoingRoomKeyRequest(event) { - if (!this.crypto) { - throw new Error("End-to-End encryption disabled"); - } - const wireContent = event.getWireContent(); - const requestBody = { - session_id: wireContent.session_id, - sender_key: wireContent.sender_key, - algorithm: wireContent.algorithm, - room_id: event.getRoomId(), - }; - if (!requestBody.session_id || !requestBody.sender_key || !requestBody.algorithm || !requestBody.room_id) { - return Promise.resolve(null); - } - return this.crypto.cryptoStore.getOutgoingRoomKeyRequest(requestBody); - } - /** - * Cancel a room key request for this event if one is ongoing and resend the - * request. - * @param event - event of which to cancel and resend the room - * key request. - * @returns A promise that will resolve when the key request is queued - */ - cancelAndResendEventRoomKeyRequest(event) { - if (!this.crypto) { - throw new Error("End-to-End encryption disabled"); - } - return event.cancelAndResendKeyRequest(this.crypto, this.getUserId()); - } - /** - * Enable end-to-end encryption for a room. This does not modify room state. - * Any messages sent before the returned promise resolves will be sent unencrypted. - * @param roomId - The room ID to enable encryption in. - * @param config - The encryption config for the room. - * @returns A promise that will resolve when encryption is set up. - */ - setRoomEncryption(roomId, config) { - if (!this.crypto) { - throw new Error("End-to-End encryption disabled"); - } - return this.crypto.setRoomEncryption(roomId, config); - } - /** - * Whether encryption is enabled for a room. - * @param roomId - the room id to query. - * @returns whether encryption is enabled. - */ - isRoomEncrypted(roomId) { - const room = this.getRoom(roomId); - if (!room) { - // we don't know about this room, so can't determine if it should be - // encrypted. Let's assume not. - return false; - } - // if there is an 'm.room.encryption' event in this room, it should be - // encrypted (independently of whether we actually support encryption) - const ev = room.currentState.getStateEvents(event_2.EventType.RoomEncryption, ""); - if (ev) { - return true; - } - // we don't have an m.room.encrypted event, but that might be because - // the server is hiding it from us. Check the store to see if it was - // previously encrypted. - return this.roomList.isRoomEncrypted(roomId); - } - /** - * Encrypts and sends a given object via Olm to-device messages to a given - * set of devices. - * - * @param userDeviceMap - mapping from userId to deviceInfo - * - * @param payload - fields to include in the encrypted payload - * - * @returns Promise which - * resolves once the message has been encrypted and sent to the given - * userDeviceMap, and returns the `{ contentMap, deviceInfoByDeviceId }` - * of the successfully sent messages. - */ - encryptAndSendToDevices(userDeviceInfoArr, payload) { - if (!this.crypto) { - throw new Error("End-to-End encryption disabled"); - } - return this.crypto.encryptAndSendToDevices(userDeviceInfoArr, payload); - } - /** - * Forces the current outbound group session to be discarded such - * that another one will be created next time an event is sent. - * - * @param roomId - The ID of the room to discard the session for - * - * @deprecated Prefer {@link CryptoApi.forceDiscardSession | `CryptoApi.forceDiscardSession`}: - * - */ - forceDiscardSession(roomId) { - if (!this.cryptoBackend) { - throw new Error("End-to-End encryption disabled"); - } - this.cryptoBackend.forceDiscardSession(roomId); - } - /** - * Get a list containing all of the room keys - * - * This should be encrypted before returning it to the user. - * - * @returns a promise which resolves to a list of session export objects - * - * @deprecated Prefer {@link CryptoApi.exportRoomKeys | `CryptoApi.exportRoomKeys`}: - * - * ```javascript - * sessionData = await client.getCrypto().exportRoomKeys(); - * ``` - */ - exportRoomKeys() { - if (!this.cryptoBackend) { - return Promise.reject(new Error("End-to-end encryption disabled")); - } - return this.cryptoBackend.exportRoomKeys(); - } - /** - * Import a list of room keys previously exported by exportRoomKeys - * - * @param keys - a list of session export objects - * - * @returns a promise which resolves when the keys have been imported - */ - importRoomKeys(keys, opts) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.importRoomKeys(keys, opts); - } - /** - * Force a re-check of the local key backup status against - * what's on the server. - * - * @returns Object with backup info (as returned by - * getKeyBackupVersion) in backupInfo and - * trust information (as returned by isKeyBackupTrusted) - * in trustInfo. - */ - checkKeyBackup() { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.backupManager.checkKeyBackup(); - } - /** - * Get information about the current key backup. - * @returns Information object from API or null - */ - getKeyBackupVersion() { - return __awaiter(this, void 0, void 0, function* () { - let res; - try { - res = yield this.http.authedRequest(http_api_1.Method.Get, "/room_keys/version", undefined, undefined, { prefix: http_api_1.ClientPrefix.V3 }); - } - catch (e) { - if (e.errcode === "M_NOT_FOUND") { - return null; - } - else { - throw e; - } - } - backup_1.BackupManager.checkBackupVersion(res); - return res; - }); - } - /** - * @param info - key backup info dict from getKeyBackupVersion() - */ - isKeyBackupTrusted(info) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.backupManager.isKeyBackupTrusted(info); - } - /** - * @returns true if the client is configured to back up keys to - * the server, otherwise false. If we haven't completed a successful check - * of key backup status yet, returns null. - */ - getKeyBackupEnabled() { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.backupManager.getKeyBackupEnabled(); - } - /** - * Enable backing up of keys, using data previously returned from - * getKeyBackupVersion. - * - * @param info - Backup information object as returned by getKeyBackupVersion - * @returns Promise which resolves when complete. - */ - enableKeyBackup(info) { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.backupManager.enableKeyBackup(info); - } - /** - * Disable backing up of keys. - */ - disableKeyBackup() { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - this.crypto.backupManager.disableKeyBackup(); - } - /** - * Set up the data required to create a new backup version. The backup version - * will not be created and enabled until createKeyBackupVersion is called. - * - * @param password - Passphrase string that can be entered by the user - * when restoring the backup as an alternative to entering the recovery key. - * Optional. - * - * @returns Object that can be passed to createKeyBackupVersion and - * additionally has a 'recovery_key' member with the user-facing recovery key string. - */ - prepareKeyBackupVersion(password, opts = { secureSecretStorage: false }) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - // eslint-disable-next-line camelcase - const { algorithm, auth_data, recovery_key, privateKey } = yield this.crypto.backupManager.prepareKeyBackupVersion(password); - if (opts.secureSecretStorage) { - yield this.storeSecret("m.megolm_backup.v1", (0, olmlib_1.encodeBase64)(privateKey)); - logger_1.logger.info("Key backup private key stored in secret storage"); - } - return { - algorithm, - /* eslint-disable camelcase */ - auth_data, - recovery_key, - /* eslint-enable camelcase */ - }; - }); - } - /** - * 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.isSecretStored("m.megolm_backup.v1")); - } - /** - * Create a new key backup version and enable it, using the information return - * from prepareKeyBackupVersion. - * - * @param info - Info object from prepareKeyBackupVersion - * @returns Object with 'version' param indicating the version created - */ - createKeyBackupVersion(info) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - yield this.crypto.backupManager.createKeyBackupVersion(info); - const data = { - algorithm: info.algorithm, - auth_data: info.auth_data, - }; - // Sign the backup auth data with the device key for backwards compat with - // older devices with cross-signing. This can probably go away very soon in - // favour of just signing with the cross-singing master key. - // XXX: Private member access - yield this.crypto.signObject(data.auth_data); - if (this.cryptoCallbacks.getCrossSigningKey && - // XXX: Private member access - this.crypto.crossSigningInfo.getId()) { - // now also sign the auth data with the cross-signing master key - // we check for the callback explicitly here because we still want to be able - // to create an un-cross-signed key backup if there is a cross-signing key but - // no callback supplied. - // XXX: Private member access - yield this.crypto.crossSigningInfo.signObject(data.auth_data, "master"); - } - const res = yield this.http.authedRequest(http_api_1.Method.Post, "/room_keys/version", undefined, data, { - prefix: http_api_1.ClientPrefix.V3, - }); - // We could assume everything's okay and enable directly, but this ensures - // we run the same signature verification that will be used for future - // sessions. - yield this.checkKeyBackup(); - if (!this.getKeyBackupEnabled()) { - logger_1.logger.error("Key backup not usable even though we just created it"); - } - return res; - }); - } - deleteKeyBackupVersion(version) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - // If we're currently backing up to this backup... stop. - // (We start using it automatically in createKeyBackupVersion - // so this is symmetrical). - if (this.crypto.backupManager.version) { - this.crypto.backupManager.disableKeyBackup(); - } - const path = utils.encodeUri("/room_keys/version/$version", { - $version: version, - }); - yield this.http.authedRequest(http_api_1.Method.Delete, path, undefined, undefined, { prefix: http_api_1.ClientPrefix.V3 }); - }); - } - makeKeyBackupPath(roomId, sessionId, version) { - let path; - if (sessionId !== undefined) { - path = utils.encodeUri("/room_keys/keys/$roomId/$sessionId", { - $roomId: roomId, - $sessionId: sessionId, - }); - } - else if (roomId !== undefined) { - path = utils.encodeUri("/room_keys/keys/$roomId", { - $roomId: roomId, - }); - } - else { - path = "/room_keys/keys"; - } - const queryData = version === undefined ? undefined : { version }; - return { path, queryData }; - } - sendKeyBackup(roomId, sessionId, version, data) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - const path = this.makeKeyBackupPath(roomId, sessionId, version); - yield this.http.authedRequest(http_api_1.Method.Put, path.path, path.queryData, data, { prefix: http_api_1.ClientPrefix.V3 }); - }); - } - /** - * Marks all group sessions as needing to be backed up and schedules them to - * upload in the background as soon as possible. - */ - scheduleAllGroupSessionsForBackup() { - return __awaiter(this, void 0, void 0, function* () { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - yield this.crypto.backupManager.scheduleAllGroupSessionsForBackup(); - }); - } - /** - * Marks all group sessions as needing to be backed up without scheduling - * them to upload in the background. - * @returns Promise which resolves to the number of sessions requiring a backup. - */ - flagAllGroupSessionsForBackup() { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - return this.crypto.backupManager.flagAllGroupSessionsForBackup(); - } - isValidRecoveryKey(recoveryKey) { - try { - (0, recoverykey_1.decodeRecoveryKey)(recoveryKey); - return true; - } - catch (e) { - return false; - } - } - /** - * Get the raw key for a key backup from the password - * Used when migrating key backups into SSSS - * - * The cross-signing API is currently UNSTABLE and may change without notice. - * - * @param password - Passphrase - * @param backupInfo - Backup metadata from `checkKeyBackup` - * @returns key backup key - */ - keyBackupKeyFromPassword(password, backupInfo) { - return (0, key_passphrase_1.keyFromAuthData)(backupInfo.auth_data, password); - } - /** - * Get the raw key for a key backup from the recovery key - * Used when migrating key backups into SSSS - * - * The cross-signing API is currently UNSTABLE and may change without notice. - * - * @param recoveryKey - The recovery key - * @returns key backup key - */ - keyBackupKeyFromRecoveryKey(recoveryKey) { - return (0, recoverykey_1.decodeRecoveryKey)(recoveryKey); - } - restoreKeyBackupWithPassword(password, targetRoomId, targetSessionId, backupInfo, opts) { - return __awaiter(this, void 0, void 0, function* () { - const privKey = yield (0, key_passphrase_1.keyFromAuthData)(backupInfo.auth_data, password); - return this.restoreKeyBackup(privKey, targetRoomId, targetSessionId, backupInfo, opts); - }); - } - /** - * Restore from an existing key backup via a private key stored in secret - * storage. - * - * @param backupInfo - Backup metadata from `checkKeyBackup` - * @param targetRoomId - Room ID to target a specific room. - * Restores all rooms if omitted. - * @param targetSessionId - Session ID to target a specific session. - * Restores all sessions if omitted. - * @param opts - Optional params such as callbacks - * @returns Status of restoration with `total` and `imported` - * key counts. - */ - restoreKeyBackupWithSecretStorage(backupInfo, targetRoomId, targetSessionId, opts) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - const storedKey = yield this.getSecret("m.megolm_backup.v1"); - // ensure that the key is in the right format. If not, fix the key and - // store the fixed version - const fixedKey = (0, crypto_1.fixBackupKey)(storedKey); - if (fixedKey) { - const keys = yield this.crypto.getSecretStorageKey(); - yield this.storeSecret("m.megolm_backup.v1", fixedKey, [keys[0]]); - } - const privKey = (0, olmlib_1.decodeBase64)(fixedKey || storedKey); - return this.restoreKeyBackup(privKey, targetRoomId, targetSessionId, backupInfo, opts); - }); - } - restoreKeyBackupWithRecoveryKey(recoveryKey, targetRoomId, targetSessionId, backupInfo, opts) { - const privKey = (0, recoverykey_1.decodeRecoveryKey)(recoveryKey); - return this.restoreKeyBackup(privKey, targetRoomId, targetSessionId, backupInfo, opts); - } - restoreKeyBackupWithCache(targetRoomId, targetSessionId, backupInfo, opts) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - const privKey = yield this.crypto.getSessionBackupPrivateKey(); - if (!privKey) { - throw new Error("Couldn't get key"); - } - return this.restoreKeyBackup(privKey, targetRoomId, targetSessionId, backupInfo, opts); - }); - } - restoreKeyBackup(privKey, targetRoomId, targetSessionId, backupInfo, opts) { - return __awaiter(this, void 0, void 0, function* () { - const cacheCompleteCallback = opts === null || opts === void 0 ? void 0 : opts.cacheCompleteCallback; - const progressCallback = opts === null || opts === void 0 ? void 0 : opts.progressCallback; - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - let totalKeyCount = 0; - let keys = []; - const path = this.makeKeyBackupPath(targetRoomId, targetSessionId, backupInfo.version); - const algorithm = yield backup_1.BackupManager.makeAlgorithm(backupInfo, () => __awaiter(this, void 0, void 0, function* () { - return privKey; - })); - const untrusted = algorithm.untrusted; - try { - // If the pubkey computed from the private data we've been given - // doesn't match the one in the auth_data, the user has entered - // a different recovery key / the wrong passphrase. - if (!(yield algorithm.keyMatches(privKey))) { - return Promise.reject(new http_api_1.MatrixError({ errcode: MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY })); - } - // Cache the key, if possible. - // This is async. - this.crypto - .storeSessionBackupPrivateKey(privKey) - .catch((e) => { - logger_1.logger.warn("Error caching session backup key:", e); - }) - .then(cacheCompleteCallback); - if (progressCallback) { - progressCallback({ - stage: "fetch", - }); - } - const res = yield this.http.authedRequest(http_api_1.Method.Get, path.path, path.queryData, undefined, { prefix: http_api_1.ClientPrefix.V3 }); - if (res.rooms) { - const rooms = res.rooms; - for (const [roomId, roomData] of Object.entries(rooms)) { - if (!roomData.sessions) - continue; - totalKeyCount += Object.keys(roomData.sessions).length; - const roomKeys = yield algorithm.decryptSessions(roomData.sessions); - for (const k of roomKeys) { - k.room_id = roomId; - keys.push(k); - } - } - } - else if (res.sessions) { - const sessions = res.sessions; - totalKeyCount = Object.keys(sessions).length; - keys = yield algorithm.decryptSessions(sessions); - for (const k of keys) { - k.room_id = targetRoomId; - } - } - else { - totalKeyCount = 1; - try { - const [key] = yield algorithm.decryptSessions({ - [targetSessionId]: res, - }); - key.room_id = targetRoomId; - key.session_id = targetSessionId; - keys.push(key); - } - catch (e) { - logger_1.logger.log("Failed to decrypt megolm session from backup", e); - } - } - } - finally { - algorithm.free(); - } - yield this.importRoomKeys(keys, { - progressCallback, - untrusted, - source: "backup", - }); - yield this.checkKeyBackup(); - return { total: totalKeyCount, imported: keys.length }; - }); - } - deleteKeysFromBackup(roomId, sessionId, version) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - const path = this.makeKeyBackupPath(roomId, sessionId, version); - yield this.http.authedRequest(http_api_1.Method.Delete, path.path, path.queryData, undefined, { prefix: http_api_1.ClientPrefix.V3 }); - }); - } - /** - * Share shared-history decryption keys with the given users. - * - * @param roomId - the room for which keys should be shared. - * @param userIds - a list of users to share with. The keys will be sent to - * all of the user's current devices. - */ - sendSharedHistoryKeys(roomId, userIds) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.crypto) { - throw new Error("End-to-end encryption disabled"); - } - const roomEncryption = this.roomList.getRoomEncryption(roomId); - if (!roomEncryption) { - // unknown room, or unencrypted room - logger_1.logger.error("Unknown room. Not sharing decryption keys"); - return; - } - const deviceInfos = yield this.crypto.downloadKeys(userIds); - const devicesByUser = new Map(); - for (const [userId, devices] of deviceInfos) { - devicesByUser.set(userId, Array.from(devices.values())); - } - // XXX: Private member access - const alg = this.crypto.getRoomDecryptor(roomId, roomEncryption.algorithm); - if (alg.sendSharedHistoryInboundSessions) { - yield alg.sendSharedHistoryInboundSessions(devicesByUser); - } - else { - logger_1.logger.warn("Algorithm does not support sharing previous keys", roomEncryption.algorithm); - } - }); - } - /** - * Get the config for the media repository. - * @returns Promise which resolves with an object containing the config. - */ - getMediaConfig() { - return this.http.authedRequest(http_api_1.Method.Get, "/config", undefined, undefined, { - prefix: http_api_1.MediaPrefix.R0, - }); - } - /** - * 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(msc3946ProcessDynamicPredecessor = false) { - var _a; - const allRooms = this.store.getRooms(); - const replacedRooms = new Set(); - for (const r of allRooms) { - const predecessor = (_a = r.findPredecessor(msc3946ProcessDynamicPredecessor)) === null || _a === void 0 ? void 0 : _a.roomId; - if (predecessor) { - replacedRooms.add(predecessor); - } - } - return allRooms.filter((r) => { - const tombstone = r.currentState.getStateEvents(event_2.EventType.RoomTombstone, ""); - if (tombstone && replacedRooms.has(r.roomId)) { - return false; - } - return true; - }); - } - /** - * 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. - * It will retry the request up to 5 times. - * @param eventType - The event type - * @param content - the contents object for the event - * @returns Promise which resolves: an empty object - * @returns Rejects: with an error response. - */ - setAccountData(eventType, content) { - const path = utils.encodeUri("/user/$userId/account_data/$type", { - $userId: this.credentials.userId, - $type: eventType, - }); - return (0, http_api_1.retryNetworkOperation)(5, () => { - return this.http.authedRequest(http_api_1.Method.Put, path, undefined, 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 _a; - return __awaiter(this, void 0, void 0, function* () { - if (this.isInitialSyncComplete()) { - const event = this.store.getAccountData(eventType); - if (!event) { - return null; - } - // The network version below returns just the content, so this branch - // does the same to match. - return event.getContent(); - } - const path = utils.encodeUri("/user/$userId/account_data/$type", { - $userId: this.credentials.userId, - $type: eventType, - }); - try { - return yield this.http.authedRequest(http_api_1.Method.Get, path); - } - catch (e) { - if (((_a = e.data) === null || _a === void 0 ? void 0 : _a.errcode) === "M_NOT_FOUND") { - return null; - } - throw e; - } - }); - } - deleteAccountData(eventType) { - return __awaiter(this, void 0, void 0, function* () { - const msc3391DeleteAccountDataServerSupport = this.canSupport.get(feature_1.Feature.AccountDataDeletion); - // if deletion is not supported overwrite with empty content - if (msc3391DeleteAccountDataServerSupport === feature_1.ServerSupport.Unsupported) { - yield this.setAccountData(eventType, {}); - return; - } - const path = utils.encodeUri("/user/$userId/account_data/$type", { - $userId: this.getSafeUserId(), - $type: eventType, - }); - const options = msc3391DeleteAccountDataServerSupport === feature_1.ServerSupport.Unstable - ? { prefix: "/_matrix/client/unstable/org.matrix.msc3391" } - : undefined; - return yield this.http.authedRequest(http_api_1.Method.Delete, path, undefined, undefined, options); - }); - } - /** - * Gets the users that are ignored by this client - * @returns The array of users that are ignored (empty if none) - */ - getIgnoredUsers() { - const event = this.getAccountData("m.ignored_user_list"); - if (!event || !event.getContent() || !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) { - const content = { ignored_users: {} }; - userIds.forEach((u) => { - content.ignored_users[u] = {}; - }); - return this.setAccountData("m.ignored_user_list", 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, opts = {}) { - return __awaiter(this, void 0, void 0, function* () { - if (opts.syncRoom === undefined) { - opts.syncRoom = true; - } - const room = this.getRoom(roomIdOrAlias); - if (room === null || room === void 0 ? void 0 : room.hasMembershipState(this.credentials.userId, "join")) { - return Promise.resolve(room); - } - let signPromise = Promise.resolve(); - if (opts.inviteSignUrl) { - const url = new URL(opts.inviteSignUrl); - url.searchParams.set("mxid", this.credentials.userId); - signPromise = this.http.requestOtherUrl(http_api_1.Method.Post, url); - } - const queryString = {}; - if (opts.viaServers) { - queryString["server_name"] = opts.viaServers; - } - try { - const data = {}; - const signedInviteObj = yield signPromise; - if (signedInviteObj) { - data.third_party_signed = signedInviteObj; - } - const path = utils.encodeUri("/join/$roomid", { $roomid: roomIdOrAlias }); - const res = yield this.http.authedRequest(http_api_1.Method.Post, path, queryString, data); - const roomId = res.room_id; - const syncApi = new sync_1.SyncApi(this, this.clientOpts, this.buildSyncApiOptions()); - const room = syncApi.createRoom(roomId); - if (opts.syncRoom) { - // v2 will do this for us - // return syncApi.syncRoom(room); - } - return room; - } - catch (e) { - throw e; // rethrow for reject - } - }); - } - /** - * 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. - * @returns Promise which resolves: to an ISendEventResponse object - * @returns Rejects: with an error response. - */ - resendEvent(event, room) { - // also kick the to-device queue to retry - this.toDeviceMessageQueue.sendQueue(); - this.updatePendingEventStatus(room, event, event_1.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 (![event_1.EventStatus.QUEUED, event_1.EventStatus.NOT_SENT, event_1.EventStatus.ENCRYPTING].includes(event.status)) { - throw new Error("cannot cancel an event with status " + event.status); - } - // if the event is currently being encrypted then - if (event.status === event_1.EventStatus.ENCRYPTING) { - this.pendingEventEncryption.delete(event.getId()); - } - else if (this.scheduler && event.status === event_1.EventStatus.QUEUED) { - // tell the scheduler to forget about it, if it's queued - this.scheduler.removeEventFromQueue(event); - } - // then tell the room about the change of state, which will remove it - // from the room's list of pending events. - const room = this.getRoom(event.getRoomId()); - this.updatePendingEventStatus(room, event, event_1.EventStatus.CANCELLED); - } - /** - * @returns Promise which resolves: TODO - * @returns Rejects: with an error response. - */ - setRoomName(roomId, name) { - return this.sendStateEvent(roomId, event_2.EventType.RoomName, { name: name }); - } - /** - * @param htmlTopic - Optional. - * @returns Promise which resolves: TODO - * @returns Rejects: with an error response. - */ - setRoomTopic(roomId, topic, htmlTopic) { - const content = ContentHelpers.makeTopicContent(topic, htmlTopic); - return this.sendStateEvent(roomId, event_2.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) { - const path = utils.encodeUri("/user/$userId/rooms/$roomId/tags", { - $userId: this.credentials.userId, - $roomId: roomId, - }); - return this.http.authedRequest(http_api_1.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, metadata) { - const path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/$tag", { - $userId: this.credentials.userId, - $roomId: roomId, - $tag: tagName, - }); - return this.http.authedRequest(http_api_1.Method.Put, path, undefined, 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) { - const path = utils.encodeUri("/user/$userId/rooms/$roomId/tags/$tag", { - $userId: this.credentials.userId, - $roomId: roomId, - $tag: tagName, - }); - return this.http.authedRequest(http_api_1.Method.Delete, path); - } - /** - * @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) { - const path = utils.encodeUri("/user/$userId/rooms/$roomId/account_data/$type", { - $userId: this.credentials.userId, - $roomId: roomId, - $type: eventType, - }); - return this.http.authedRequest(http_api_1.Method.Put, path, undefined, content); - } - /** - * Set a power level to one or multiple users. - * @returns Promise which resolves: to an ISendEventResponse object - * @returns Rejects: with an error response. - */ - setPowerLevel(roomId, userId, powerLevel, event) { - let content = { - users: {}, - }; - if ((event === null || event === void 0 ? void 0 : event.getType()) === event_2.EventType.RoomPowerLevels) { - // take a copy of the content to ensure we don't corrupt - // existing client state with a failed power level change - content = utils.deepCopy(event.getContent()); - } - const users = Array.isArray(userId) ? userId : [userId]; - for (const user of users) { - if (powerLevel == null) { - delete content.users[user]; - } - else { - content.users[user] = powerLevel; - } - } - const path = utils.encodeUri("/rooms/$roomId/state/m.room.power_levels", { - $roomId: roomId, - }); - return this.http.authedRequest(http_api_1.Method.Put, path, undefined, content); - } - /** - * Create an m.beacon_info event - * @returns - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - unstable_createLiveBeacon(roomId, beaconInfoContent) { - return __awaiter(this, void 0, void 0, function* () { - return this.unstable_setLiveBeacon(roomId, beaconInfoContent); - }); - } - /** - * Upsert a live beacon event - * using a specific m.beacon_info.* event variable type - * @param roomId - string - * @returns - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - unstable_setLiveBeacon(roomId, beaconInfoContent) { - return __awaiter(this, void 0, void 0, function* () { - return this.sendStateEvent(roomId, beacon_1.M_BEACON_INFO.name, beaconInfoContent, this.getUserId()); - }); - } - sendEvent(roomId, threadIdOrEventType, eventTypeOrContent, contentOrTxnId, txnIdOrVoid) { - var _a, _b, _c, _d, _e; - let threadId; - let eventType; - let content; - let txnId; - if (!(threadIdOrEventType === null || threadIdOrEventType === void 0 ? 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; - } - // 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 - if (threadId && !((_a = content["m.relates_to"]) === null || _a === void 0 ? void 0 : _a.rel_type)) { - const isReply = !!((_b = content["m.relates_to"]) === null || _b === void 0 ? void 0 : _b["m.in_reply_to"]); - content["m.relates_to"] = Object.assign(Object.assign({}, content["m.relates_to"]), { rel_type: thread_1.THREAD_RELATION_TYPE.name, event_id: threadId, - // Set is_falling_back to true unless this is actually intended to be a reply - is_falling_back: !isReply }); - const thread = (_c = this.getRoom(roomId)) === null || _c === void 0 ? void 0 : _c.getThread(threadId); - if (thread && !isReply) { - content["m.relates_to"]["m.in_reply_to"] = { - event_id: (_e = (_d = thread - .lastReply((ev) => { - return ev.isRelation(thread_1.THREAD_RELATION_TYPE.name) && !ev.status; - })) === null || _d === void 0 ? void 0 : _d.getId()) !== null && _e !== void 0 ? _e : threadId, - }; - } - } - return this.sendCompleteEvent(roomId, threadId, { type: eventType, content }, txnId); - } - /** - * @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. - */ - sendCompleteEvent(roomId, threadId, eventObject, txnId) { - if (!txnId) { - txnId = this.makeTxnId(); - } - // We always construct a MatrixEvent when sending because the store and scheduler use them. - // We'll extract the params back out if it turns out the client has no scheduler or store. - const localEvent = new event_1.MatrixEvent(Object.assign(eventObject, { - event_id: "~" + roomId + ":" + txnId, - user_id: this.credentials.userId, - sender: this.credentials.userId, - room_id: roomId, - origin_server_ts: new Date().getTime(), - })); - const room = this.getRoom(roomId); - const thread = threadId ? room === null || room === void 0 ? void 0 : room.getThread(threadId) : undefined; - if (thread) { - localEvent.setThread(thread); - } - // set up re-emitter for this new event - this is normally the job of EventMapper but we don't use it here - this.reEmitter.reEmit(localEvent, [event_1.MatrixEventEvent.Replaced, event_1.MatrixEventEvent.VisibilityChange]); - room === null || room === void 0 ? void 0 : room.reEmitter.reEmit(localEvent, [event_1.MatrixEventEvent.BeforeRedaction]); - // if this is a relation or redaction of an event - // that hasn't been sent yet (e.g. with a local id starting with a ~) - // then listen for the remote echo of that event so that by the time - // this event does get sent, we have the correct event_id - const targetId = localEvent.getAssociatedId(); - if (targetId === null || targetId === void 0 ? void 0 : targetId.startsWith("~")) { - const target = room === null || room === void 0 ? void 0 : room.getPendingEvents().find((e) => e.getId() === targetId); - target === null || target === void 0 ? void 0 : target.once(event_1.MatrixEventEvent.LocalEventIdReplaced, () => { - localEvent.updateAssociatedId(target.getId()); - }); - } - const type = localEvent.getType(); - logger_1.logger.log(`sendEvent of type ${type} in ${roomId} with txnId ${txnId}`); - localEvent.setTxnId(txnId); - localEvent.setStatus(event_1.EventStatus.SENDING); - // add this event immediately to the local store as 'sending'. - room === null || room === void 0 ? void 0 : room.addPendingEvent(localEvent, txnId); - // addPendingEvent can change the state to NOT_SENT if it believes - // that there's other events that have failed. We won't bother to - // try sending the event if the state has changed as such. - if (localEvent.status === event_1.EventStatus.NOT_SENT) { - return Promise.reject(new Error("Event blocked by other events not yet sent")); - } - return this.encryptAndSendEvent(room, localEvent); - } - /** - * 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 - */ - encryptAndSendEvent(room, event) { - let cancelled = false; - // Add an extra Promise.resolve() to turn synchronous exceptions into promise rejections, - // so that we can handle synchronous and asynchronous exceptions with the - // same code path. - return Promise.resolve() - .then(() => { - const encryptionPromise = this.encryptEventIfNeeded(event, room !== null && room !== void 0 ? room : undefined); - if (!encryptionPromise) - return null; // doesn't need encryption - this.pendingEventEncryption.set(event.getId(), encryptionPromise); - this.updatePendingEventStatus(room, event, event_1.EventStatus.ENCRYPTING); - return encryptionPromise.then(() => { - if (!this.pendingEventEncryption.has(event.getId())) { - // cancelled via MatrixClient::cancelPendingEvent - cancelled = true; - return; - } - this.updatePendingEventStatus(room, event, event_1.EventStatus.SENDING); - }); - }) - .then(() => { - if (cancelled) - return {}; - let promise = null; - if (this.scheduler) { - // if this returns a promise then the scheduler has control now and will - // resolve/reject when it is done. Internally, the scheduler will invoke - // processFn which is set to this._sendEventHttpRequest so the same code - // path is executed regardless. - promise = this.scheduler.queueEvent(event); - if (promise && this.scheduler.getQueueForEvent(event).length > 1) { - // event is processed FIFO so if the length is 2 or more we know - // this event is stuck behind an earlier event. - this.updatePendingEventStatus(room, event, event_1.EventStatus.QUEUED); - } - } - if (!promise) { - promise = this.sendEventHttpRequest(event); - if (room) { - promise = promise.then((res) => { - room.updatePendingEvent(event, event_1.EventStatus.SENT, res["event_id"]); - return res; - }); - } - } - return promise; - }) - .catch((err) => { - logger_1.logger.error("Error sending event", err.stack || err); - try { - // set the error on the event before we update the status: - // updating the status emits the event, so the state should be - // consistent at that point. - event.error = err; - this.updatePendingEventStatus(room, event, event_1.EventStatus.NOT_SENT); - } - catch (e) { - logger_1.logger.error("Exception in error handler!", e.stack || err); - } - if (err instanceof http_api_1.MatrixError) { - err.event = event; - } - throw err; - }); - } - encryptEventIfNeeded(event, room) { - if (event.isEncrypted()) { - // this event has already been encrypted; this happens if the - // encryption step succeeded, but the send step failed on the first - // attempt. - return null; - } - if (event.isRedaction()) { - // Redactions do not support encryption in the spec at this time, - // whilst it mostly worked in some clients, it wasn't compliant. - return null; - } - if (!room || !this.isRoomEncrypted(event.getRoomId())) { - return null; - } - if (!this.cryptoBackend && this.usingExternalCrypto) { - // The client has opted to allow sending messages to encrypted - // rooms even if the room is encrypted, and we haven't setup - // crypto. This is useful for users of matrix-org/pantalaimon - return null; - } - if (event.getType() === event_2.EventType.Reaction) { - // For reactions, there is a very little gained by encrypting the entire - // event, as relation data is already kept in the clear. Event - // encryption for a reaction effectively only obscures the event type, - // but the purpose is still obvious from the relation data, so nothing - // is really gained. It also causes quite a few problems, such as: - // * triggers notifications via default push rules - // * prevents server-side bundling for reactions - // The reaction key / content / emoji value does warrant encrypting, but - // this will be handled separately by encrypting just this value. - // See https://github.com/matrix-org/matrix-doc/pull/1849#pullrequestreview-248763642 - return null; - } - if (!this.cryptoBackend) { - throw new Error("This room is configured to use encryption, but your client does not support encryption."); - } - return this.cryptoBackend.encryptEvent(event, room); - } - /** - * 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) { - if (eventType === event_2.EventType.Reaction) - return eventType; - return this.isRoomEncrypted(roomId) ? event_2.EventType.RoomMessageEncrypted : eventType; - } - updatePendingEventStatus(room, event, newStatus) { - if (room) { - room.updatePendingEvent(event, newStatus); - } - else { - event.setStatus(newStatus); - } - } - sendEventHttpRequest(event) { - let txnId = event.getTxnId(); - if (!txnId) { - txnId = this.makeTxnId(); - event.setTxnId(txnId); - } - const pathParams = { - $roomId: event.getRoomId(), - $eventType: event.getWireType(), - $stateKey: event.getStateKey(), - $txnId: txnId, - }; - let path; - if (event.isState()) { - let pathTemplate = "/rooms/$roomId/state/$eventType"; - if (event.getStateKey() && event.getStateKey().length > 0) { - pathTemplate = "/rooms/$roomId/state/$eventType/$stateKey"; - } - path = utils.encodeUri(pathTemplate, pathParams); - } - else if (event.isRedaction()) { - const pathTemplate = `/rooms/$roomId/redact/$redactsEventId/$txnId`; - path = utils.encodeUri(pathTemplate, Object.assign({ $redactsEventId: event.event.redacts }, pathParams)); - } - else { - path = utils.encodeUri("/rooms/$roomId/send/$eventType/$txnId", pathParams); - } - return this.http - .authedRequest(http_api_1.Method.Put, path, undefined, event.getWireContent()) - .then((res) => { - logger_1.logger.log(`Event sent to ${event.getRoomId()} with event id ${res.event_id}`); - return res; - }); - } - redactEvent(roomId, threadId, eventId, txnId, opts) { - if (!(eventId === null || eventId === void 0 ? void 0 : eventId.startsWith(EVENT_ID_PREFIX))) { - opts = txnId; - txnId = eventId; - eventId = threadId; - threadId = null; - } - const reason = opts === null || opts === void 0 ? void 0 : opts.reason; - if ((opts === null || opts === void 0 ? void 0 : opts.with_relations) && - this.canSupport.get(feature_1.Feature.RelationBasedRedactions) === feature_1.ServerSupport.Unsupported) { - throw new Error("Server does not support relation based redactions " + - `roomId ${roomId} eventId ${eventId} txnId: ${txnId} threadId ${threadId}`); - } - const withRelations = (opts === null || opts === void 0 ? void 0 : opts.with_relations) - ? { - [this.canSupport.get(feature_1.Feature.RelationBasedRedactions) === feature_1.ServerSupport.Stable - ? event_2.MSC3912_RELATION_BASED_REDACTIONS_PROP.stable - : event_2.MSC3912_RELATION_BASED_REDACTIONS_PROP.unstable]: opts === null || opts === void 0 ? void 0 : opts.with_relations, - } - : {}; - return this.sendCompleteEvent(roomId, threadId, { - type: event_2.EventType.RoomRedaction, - content: Object.assign(Object.assign({}, withRelations), { reason }), - redacts: eventId, - }, txnId); - } - sendMessage(roomId, threadId, content, txnId) { - if (typeof threadId !== "string" && threadId !== null) { - txnId = content; - content = threadId; - threadId = null; - } - const eventType = event_2.EventType.RoomMessage; - const sendContent = content; - return this.sendEvent(roomId, threadId, eventType, sendContent, txnId); - } - sendTextMessage(roomId, threadId, body, txnId) { - if (!(threadId === null || threadId === void 0 ? void 0 : threadId.startsWith(EVENT_ID_PREFIX)) && threadId !== null) { - txnId = body; - body = threadId; - threadId = null; - } - const content = ContentHelpers.makeTextMessage(body); - return this.sendMessage(roomId, threadId, content, txnId); - } - sendNotice(roomId, threadId, body, txnId) { - if (!(threadId === null || threadId === void 0 ? void 0 : threadId.startsWith(EVENT_ID_PREFIX)) && threadId !== null) { - txnId = body; - body = threadId; - threadId = null; - } - const content = ContentHelpers.makeNotice(body); - return this.sendMessage(roomId, threadId, content, txnId); - } - sendEmoteMessage(roomId, threadId, body, txnId) { - if (!(threadId === null || threadId === void 0 ? void 0 : threadId.startsWith(EVENT_ID_PREFIX)) && threadId !== null) { - txnId = body; - body = threadId; - threadId = null; - } - const content = ContentHelpers.makeEmoteMessage(body); - return this.sendMessage(roomId, threadId, content, txnId); - } - sendImageMessage(roomId, threadId, url, info, text = "Image") { - if (!(threadId === null || threadId === void 0 ? void 0 : threadId.startsWith(EVENT_ID_PREFIX)) && threadId !== null) { - text = info || "Image"; - info = url; - url = threadId; - threadId = null; - } - const content = { - msgtype: event_2.MsgType.Image, - url: url, - info: info, - body: text, - }; - return this.sendMessage(roomId, threadId, content); - } - sendStickerMessage(roomId, threadId, url, info, text = "Sticker") { - if (!(threadId === null || threadId === void 0 ? void 0 : threadId.startsWith(EVENT_ID_PREFIX)) && threadId !== null) { - text = info || "Sticker"; - info = url; - url = threadId; - threadId = null; - } - const content = { - url: url, - info: info, - body: text, - }; - return this.sendEvent(roomId, threadId, event_2.EventType.Sticker, content); - } - sendHtmlMessage(roomId, threadId, body, htmlBody) { - if (!(threadId === null || threadId === void 0 ? void 0 : threadId.startsWith(EVENT_ID_PREFIX)) && threadId !== null) { - htmlBody = body; - body = threadId; - threadId = null; - } - const content = ContentHelpers.makeHtmlMessage(body, htmlBody); - return this.sendMessage(roomId, threadId, content); - } - sendHtmlNotice(roomId, threadId, body, htmlBody) { - if (!(threadId === null || threadId === void 0 ? void 0 : threadId.startsWith(EVENT_ID_PREFIX)) && threadId !== null) { - htmlBody = body; - body = threadId; - threadId = null; - } - const content = ContentHelpers.makeHtmlNotice(body, htmlBody); - return this.sendMessage(roomId, threadId, content); - } - sendHtmlEmote(roomId, threadId, body, htmlBody) { - if (!(threadId === null || threadId === void 0 ? void 0 : threadId.startsWith(EVENT_ID_PREFIX)) && threadId !== null) { - htmlBody = body; - body = threadId; - threadId = null; - } - const content = ContentHelpers.makeHtmlEmote(body, htmlBody); - return this.sendMessage(roomId, threadId, content); - } - /** - * 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, unthreaded = false) { - return __awaiter(this, void 0, void 0, function* () { - if (this.isGuest()) { - return Promise.resolve({}); // guests cannot send receipts so don't bother. - } - const path = utils.encodeUri("/rooms/$roomId/receipt/$receiptType/$eventId", { - $roomId: event.getRoomId(), - $receiptType: receiptType, - $eventId: event.getId(), - }); - if (!unthreaded) { - const isThread = !!event.threadRootId; - body = Object.assign(Object.assign({}, body), { thread_id: isThread ? event.threadRootId : read_receipts_1.MAIN_ROOM_TIMELINE }); - } - const promise = this.http.authedRequest(http_api_1.Method.Post, path, undefined, body || {}); - const room = this.getRoom(event.getRoomId()); - if (room && this.credentials.userId) { - room.addLocalEchoReceipt(this.credentials.userId, event, receiptType); - } - 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, receiptType = read_receipts_1.ReceiptType.Read, unthreaded = false) { - return __awaiter(this, void 0, void 0, function* () { - if (!event) - return; - const eventId = event.getId(); - const room = this.getRoom(event.getRoomId()); - if (room === null || room === void 0 ? void 0 : room.hasPendingEvent(eventId)) { - throw new Error(`Cannot set read receipt to a pending event (${eventId})`); - } - return this.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) { - return __awaiter(this, void 0, void 0, function* () { - const room = this.getRoom(roomId); - if (room && room.hasPendingEvent(rmEventId)) { - throw new Error(`Cannot set read marker to a pending event (${rmEventId})`); - } - // Add the optional RR update, do local echo like `sendReceipt` - let rrEventId; - if (rrEvent) { - rrEventId = rrEvent.getId(); - if (room === null || room === void 0 ? void 0 : room.hasPendingEvent(rrEventId)) { - throw new Error(`Cannot set read receipt to a pending event (${rrEventId})`); - } - room === null || room === void 0 ? void 0 : room.addLocalEchoReceipt(this.credentials.userId, rrEvent, read_receipts_1.ReceiptType.Read); - } - // Add the optional private RR update, do local echo like `sendReceipt` - let rpEventId; - if (rpEvent) { - rpEventId = rpEvent.getId(); - if (room === null || room === void 0 ? void 0 : room.hasPendingEvent(rpEventId)) { - throw new Error(`Cannot set read receipt to a pending event (${rpEventId})`); - } - room === null || room === void 0 ? void 0 : room.addLocalEchoReceipt(this.credentials.userId, rpEvent, read_receipts_1.ReceiptType.ReadPrivate); - } - return yield this.setRoomReadMarkersHttpRequest(roomId, rmEventId, rrEventId, rpEventId); - }); - } - /** - * 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) { - // bucket the timestamp to the nearest minute to prevent excessive spam to the server - // Surely 60-second accuracy is enough for anyone. - ts = Math.floor(ts / 60000) * 60000; - const parsed = new URL(url); - parsed.hash = ""; // strip the hash as it won't affect the preview - url = parsed.toString(); - const key = ts + "_" + url; - // If there's already a request in flight (or we've handled it), return that instead. - const cachedPreview = this.urlPreviewCache[key]; - if (cachedPreview) { - return cachedPreview; - } - const resp = this.http.authedRequest(http_api_1.Method.Get, "/preview_url", { - url, - ts: ts.toString(), - }, undefined, { - prefix: http_api_1.MediaPrefix.R0, - }); - // TODO: Expire the URL preview cache sometimes - this.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({}); // guests cannot send typing notifications so don't bother. - } - const path = utils.encodeUri("/rooms/$roomId/typing/$userId", { - $roomId: roomId, - $userId: this.getUserId(), - }); - const data = { - typing: isTyping, - }; - if (isTyping) { - data.timeout = timeoutMs ? timeoutMs : 20000; - } - return this.http.authedRequest(http_api_1.Method.Put, path, undefined, 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, verifyLinks = false, msc3946ProcessDynamicPredecessor = false) { - const currentRoom = this.getRoom(roomId); - if (!currentRoom) - return []; - const before = this.findPredecessorRooms(currentRoom, verifyLinks, msc3946ProcessDynamicPredecessor); - const after = this.findSuccessorRooms(currentRoom, verifyLinks, msc3946ProcessDynamicPredecessor); - return [...before, currentRoom, ...after]; - } - findPredecessorRooms(room, verifyLinks, msc3946ProcessDynamicPredecessor) { - var _a, _b; - const ret = []; - // Work backwards from newer to older rooms - let predecessorRoomId = (_a = room.findPredecessor(msc3946ProcessDynamicPredecessor)) === null || _a === void 0 ? void 0 : _a.roomId; - while (predecessorRoomId !== null) { - const predecessorRoom = this.getRoom(predecessorRoomId); - if (predecessorRoom === null) { - break; - } - if (verifyLinks) { - const tombstone = predecessorRoom.currentState.getStateEvents(event_2.EventType.RoomTombstone, ""); - if (!tombstone || tombstone.getContent()["replacement_room"] !== room.roomId) { - break; - } - } - // Insert at the front because we're working backwards from the currentRoom - ret.splice(0, 0, predecessorRoom); - room = predecessorRoom; - predecessorRoomId = (_b = room.findPredecessor(msc3946ProcessDynamicPredecessor)) === null || _b === void 0 ? void 0 : _b.roomId; - } - return ret; - } - findSuccessorRooms(room, verifyLinks, msc3946ProcessDynamicPredecessor) { - var _a; - const ret = []; - // Work forwards, looking at tombstone events - let tombstoneEvent = room.currentState.getStateEvents(event_2.EventType.RoomTombstone, ""); - while (tombstoneEvent) { - const successorRoom = this.getRoom(tombstoneEvent.getContent()["replacement_room"]); - if (!successorRoom) - break; // end of the chain - if (successorRoom.roomId === room.roomId) - break; // Tombstone is referencing its own room - if (verifyLinks) { - const predecessorRoomId = (_a = successorRoom.findPredecessor(msc3946ProcessDynamicPredecessor)) === null || _a === void 0 ? void 0 : _a.roomId; - if (!predecessorRoomId || predecessorRoomId !== room.roomId) { - break; - } - } - // Push to the end because we're looking forwards - ret.push(successorRoom); - const roomIds = new Set(ret.map((ref) => ref.roomId)); - if (roomIds.size < ret.length) { - // The last room added to the list introduced a previous roomId - // To avoid recursion, return the last rooms - 1 - return ret.slice(0, ret.length - 1); - } - // Set the current room to the reference room so we know where we're at - room = successorRoom; - tombstoneEvent = room.currentState.getStateEvents(event_2.EventType.RoomTombstone, ""); - } - return ret; - } - /** - * @param reason - Optional. - * @returns Promise which resolves: `{}` an empty object. - * @returns Rejects: with an error response. - */ - invite(roomId, userId, reason) { - return this.membershipChange(roomId, userId, "invite", 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. - */ - 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. - */ - inviteByThreePid(roomId, medium, address) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const path = utils.encodeUri("/rooms/$roomId/invite", { $roomId: roomId }); - const identityServerUrl = this.getIdentityServerUrl(true); - if (!identityServerUrl) { - return Promise.reject(new http_api_1.MatrixError({ - error: "No supplied identity server URL", - errcode: "ORG.MATRIX.JSSDK_MISSING_PARAM", - })); - } - const params = { - id_server: identityServerUrl, - medium: medium, - address: address, - }; - if (((_a = this.identityServer) === null || _a === void 0 ? void 0 : _a.getAccessToken) && (yield this.doesServerAcceptIdentityAccessToken())) { - const identityAccessToken = yield this.identityServer.getAccessToken(); - if (identityAccessToken) { - params["id_access_token"] = identityAccessToken; - } - } - return this.http.authedRequest(http_api_1.Method.Post, path, undefined, params); - }); - } - /** - * @returns Promise which resolves: `{}` an empty object. - * @returns Rejects: with an error response. - */ - leave(roomId) { - return this.membershipChange(roomId, undefined, "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, includeFuture = true) { - const upgradeHistory = this.getRoomUpgradeHistory(roomId); - let eligibleToLeave = upgradeHistory; - if (!includeFuture) { - eligibleToLeave = []; - for (const room of upgradeHistory) { - eligibleToLeave.push(room); - if (room.roomId === roomId) { - break; - } - } - } - const populationResults = {}; - const promises = []; - const doLeave = (roomId) => { - return this.leave(roomId) - .then(() => { - delete populationResults[roomId]; - }) - .catch((err) => { - // suppress error - populationResults[roomId] = err; - }); - }; - for (const room of eligibleToLeave) { - promises.push(doLeave(room.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, "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, deleteRoom = true) { - const promise = this.membershipChange(roomId, undefined, "forget"); - if (!deleteRoom) { - return promise; - } - return promise.then((response) => { - this.store.removeRoom(roomId); - this.emit(ClientEvent.DeleteRoom, roomId); - return response; - }); - } - /** - * @returns Promise which resolves: Object (currently empty) - * @returns Rejects: with an error response. - */ - unban(roomId, userId) { - // unbanning != set their state to leave: this used to be - // the case, but was then changed so that leaving was always - // a revoking of privilege, otherwise two people racing to - // kick / ban someone could end up banning and then un-banning - // them. - const path = utils.encodeUri("/rooms/$roomId/unban", { - $roomId: roomId, - }); - const data = { - user_id: userId, - }; - return this.http.authedRequest(http_api_1.Method.Post, path, undefined, data); - } - /** - * @param reason - Optional. - * @returns Promise which resolves: `{}` an empty object. - * @returns Rejects: with an error response. - */ - kick(roomId, userId, reason) { - const path = utils.encodeUri("/rooms/$roomId/kick", { - $roomId: roomId, - }); - const data = { - user_id: userId, - reason: reason, - }; - return this.http.authedRequest(http_api_1.Method.Post, path, undefined, data); - } - membershipChange(roomId, userId, membership, reason) { - // API returns an empty object - const path = utils.encodeUri("/rooms/$room_id/$membership", { - $room_id: roomId, - $membership: membership, - }); - return this.http.authedRequest(http_api_1.Method.Post, path, undefined, { - user_id: userId, - reason: 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, forceRecalculate = false) { - if (!event.getPushActions() || forceRecalculate) { - event.setPushActions(this.pushProcessor.actionsForEvent(event)); - } - return event.getPushActions(); - } - setProfileInfo(info, data) { - const path = utils.encodeUri("/profile/$userId/$info", { - $userId: this.credentials.userId, - $info: info, - }); - return this.http.authedRequest(http_api_1.Method.Put, path, undefined, data); - } - /** - * @returns Promise which resolves: `{}` an empty object. - * @returns Rejects: with an error response. - */ - setDisplayName(name) { - return __awaiter(this, void 0, void 0, function* () { - const prom = yield this.setProfileInfo("displayname", { displayname: name }); - // XXX: synthesise a profile update for ourselves because Synapse is broken and won't - const user = this.getUser(this.getUserId()); - if (user) { - user.displayName = name; - user.emit(user_1.UserEvent.DisplayName, user.events.presence, user); - } - return prom; - }); - } - /** - * @returns Promise which resolves: `{}` an empty object. - * @returns Rejects: with an error response. - */ - setAvatarUrl(url) { - return __awaiter(this, void 0, void 0, function* () { - const prom = yield this.setProfileInfo("avatar_url", { avatar_url: url }); - // XXX: synthesise a profile update for ourselves because Synapse is broken and won't - const user = this.getUser(this.getUserId()); - if (user) { - user.avatarUrl = url; - user.emit(user_1.UserEvent.AvatarUrl, user.events.presence, user); - } - return prom; - }); - } - /** - * Turn an MXC URL into an HTTP one. This method is experimental and - * may change. - * @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. - * @returns the avatar URL or null. - */ - mxcUrlToHttp(mxcUrl, width, height, resizeMethod, allowDirectLinks) { - return (0, content_repo_1.getHttpUriForMxc)(this.baseUrl, mxcUrl, width, height, resizeMethod, allowDirectLinks); - } - /** - * @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) { - return __awaiter(this, void 0, void 0, function* () { - const path = utils.encodeUri("/presence/$userId/status", { - $userId: this.credentials.userId, - }); - const validStates = ["offline", "online", "unavailable"]; - if (validStates.indexOf(opts.presence) === -1) { - throw new Error("Bad presence value: " + opts.presence); - } - yield this.http.authedRequest(http_api_1.Method.Put, path, undefined, 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) { - const path = utils.encodeUri("/presence/$userId/status", { - $userId: userId, - }); - return this.http.authedRequest(http_api_1.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 same - * 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, limit = 30) { - let timeToWaitMs = 0; - let info = this.ongoingScrollbacks[room.roomId] || {}; - if (info.promise) { - return info.promise; - } - else if (info.errorTs) { - const timeWaitedMs = Date.now() - info.errorTs; - timeToWaitMs = Math.max(SCROLLBACK_DELAY_MS - timeWaitedMs, 0); - } - if (room.oldState.paginationToken === null) { - return Promise.resolve(room); // already at the start. - } - // attempt to grab more events from the store first - const numAdded = this.store.scrollback(room, limit).length; - if (numAdded === limit) { - // store contained everything we needed. - return Promise.resolve(room); - } - // reduce the required number of events appropriately - limit = limit - numAdded; - const promise = new Promise((resolve, reject) => { - // wait for a time before doing this request - // (which may be 0 in order not to special case the code paths) - (0, utils_1.sleep)(timeToWaitMs) - .then(() => { - return this.createMessagesRequest(room.roomId, room.oldState.paginationToken, limit, event_timeline_1.Direction.Backward); - }) - .then((res) => { - var _a, _b; - const matrixEvents = res.chunk.map(this.getEventMapper()); - if (res.state) { - const stateEvents = res.state.map(this.getEventMapper()); - room.currentState.setUnknownStateEvents(stateEvents); - } - const [timelineEvents, threadedEvents] = room.partitionThreadedEvents(matrixEvents); - this.processAggregatedTimelineEvents(room, timelineEvents); - room.addEventsToTimeline(timelineEvents, true, room.getLiveTimeline()); - this.processThreadEvents(room, threadedEvents, true); - room.oldState.paginationToken = (_a = res.end) !== null && _a !== void 0 ? _a : null; - if (res.chunk.length === 0) { - room.oldState.paginationToken = null; - } - this.store.storeEvents(room, matrixEvents, (_b = res.end) !== null && _b !== void 0 ? _b : 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 (0, event_mapper_1.eventMapperFor)(this, options || {}); - } - /** - * Get an EventTimeline for the given event - * - *

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 _a, _b, _c, _d; - return __awaiter(this, void 0, void 0, function* () { - // don't allow any timeline support unless it's been enabled. - if (!this.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 ? void 0 : timelineSet.room)) { - throw new Error("getEventTimeline only supports room timelines"); - } - if (timelineSet.getTimelineForEvent(eventId)) { - return timelineSet.getTimelineForEvent(eventId); - } - if (timelineSet.thread && this.supportsThreads()) { - return this.getThreadTimeline(timelineSet, eventId); - } - const path = utils.encodeUri("/rooms/$roomId/context/$eventId", { - $roomId: timelineSet.room.roomId, - $eventId: eventId, - }); - let params = undefined; - if ((_a = this.clientOpts) === null || _a === void 0 ? void 0 : _a.lazyLoadMembers) { - params = { filter: JSON.stringify(filter_1.Filter.LAZY_LOADING_MESSAGES_FILTER) }; - } - // TODO: we should implement a backoff (as per scrollback()) to deal more nicely with HTTP errors. - const res = yield this.http.authedRequest(http_api_1.Method.Get, path, params); - if (!res.event) { - throw new Error("'event' not in '/context' result - homeserver too old?"); - } - // by the time the request completes, the event might have ended up in the timeline. - if (timelineSet.getTimelineForEvent(eventId)) { - return timelineSet.getTimelineForEvent(eventId); - } - const mapper = this.getEventMapper(); - const event = mapper(res.event); - if (event.isRelation(thread_1.THREAD_RELATION_TYPE.name)) { - logger_1.logger.warn("Tried loading a regular timeline at the position of a thread event"); - return undefined; - } - const events = [ - // Order events from most recent to oldest (reverse-chronological). - // We start with the last event, since that's the point at which we have known state. - // events_after is already backwards; events_before is forwards. - ...res.events_after.reverse().map(mapper), - event, - ...res.events_before.map(mapper), - ]; - // Here we handle non-thread timelines only, but still process any thread events to populate thread summaries. - let timeline = timelineSet.getTimelineForEvent(events[0].getId()); - if (timeline) { - timeline.getState(event_timeline_1.EventTimeline.BACKWARDS).setUnknownStateEvents(res.state.map(mapper)); - } - else { - timeline = timelineSet.addTimeline(); - timeline.initialiseState(res.state.map(mapper)); - timeline.getState(event_timeline_1.EventTimeline.FORWARDS).paginationToken = res.end; - } - const [timelineEvents, threadedEvents] = timelineSet.room.partitionThreadedEvents(events); - timelineSet.addEventsToTimeline(timelineEvents, true, timeline, res.start); - // The target event is not in a thread but process the contextual events, so we can show any threads around it. - this.processThreadEvents(timelineSet.room, threadedEvents, true); - this.processAggregatedTimelineEvents(timelineSet.room, timelineEvents); - // There is no guarantee that the event ended up in "timeline" (we might have switched to a neighbouring - // timeline) - so check the room's index again. On the other hand, there's no guarantee the event ended up - // anywhere, if it was later redacted, so we just return the timeline we first thought of. - return ((_d = (_b = timelineSet.getTimelineForEvent(eventId)) !== null && _b !== void 0 ? _b : (_c = timelineSet.room.findThreadForEvent(event)) === null || _c === void 0 ? void 0 : _c.liveTimeline) !== null && _d !== void 0 ? _d : timeline); - }); - } - getThreadTimeline(timelineSet, eventId) { - var _a, _b, _c, _d, _e, _f, _g, _h; - return __awaiter(this, void 0, void 0, function* () { - if (!this.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"); - } - const path = utils.encodeUri("/rooms/$roomId/context/$eventId", { - $roomId: timelineSet.room.roomId, - $eventId: eventId, - }); - const params = { - limit: "0", - }; - if ((_a = this.clientOpts) === null || _a === void 0 ? void 0 : _a.lazyLoadMembers) { - params.filter = JSON.stringify(filter_1.Filter.LAZY_LOADING_MESSAGES_FILTER); - } - // TODO: we should implement a backoff (as per scrollback()) to deal more nicely with HTTP errors. - const res = yield this.http.authedRequest(http_api_1.Method.Get, path, params); - const mapper = this.getEventMapper(); - const event = mapper(res.event); - if (!timelineSet.canContain(event)) { - return undefined; - } - if (thread_1.Thread.hasServerSideSupport) { - if (thread_1.Thread.hasServerSideFwdPaginationSupport) { - if (!timelineSet.thread) { - throw new Error("could not get thread timeline: not a thread timeline"); - } - const thread = timelineSet.thread; - const resOlder = yield this.fetchRelations(timelineSet.room.roomId, thread.id, thread_1.THREAD_RELATION_TYPE.name, null, { dir: event_timeline_1.Direction.Backward, from: res.start }); - const resNewer = yield this.fetchRelations(timelineSet.room.roomId, thread.id, thread_1.THREAD_RELATION_TYPE.name, null, { dir: event_timeline_1.Direction.Forward, from: res.end }); - const events = [ - // Order events from most recent to oldest (reverse-chronological). - // We start with the last event, since that's the point at which we have known state. - // events_after is already backwards; events_before is forwards. - ...resNewer.chunk.reverse().map(mapper), - event, - ...resOlder.chunk.map(mapper), - ]; - for (const event of events) { - yield ((_b = timelineSet.thread) === null || _b === void 0 ? void 0 : _b.processEvent(event)); - } - // Here we handle non-thread timelines only, but still process any thread events to populate thread summaries. - let timeline = timelineSet.getTimelineForEvent(event.getId()); - if (timeline) { - timeline.getState(event_timeline_1.EventTimeline.BACKWARDS).setUnknownStateEvents(res.state.map(mapper)); - } - else { - timeline = timelineSet.addTimeline(); - timeline.initialiseState(res.state.map(mapper)); - } - timelineSet.addEventsToTimeline(events, true, timeline, resNewer.next_batch); - if (!resOlder.next_batch) { - const originalEvent = yield this.fetchRoomEvent(timelineSet.room.roomId, thread.id); - timelineSet.addEventsToTimeline([mapper(originalEvent)], true, timeline, null); - } - timeline.setPaginationToken((_c = resOlder.next_batch) !== null && _c !== void 0 ? _c : null, event_timeline_1.Direction.Backward); - timeline.setPaginationToken((_d = resNewer.next_batch) !== null && _d !== void 0 ? _d : null, event_timeline_1.Direction.Forward); - this.processAggregatedTimelineEvents(timelineSet.room, events); - // There is no guarantee that the event ended up in "timeline" (we might have switched to a neighbouring - // timeline) - so check the room's index again. On the other hand, there's no guarantee the event ended up - // anywhere, if it was later redacted, so we just return the timeline we first thought of. - return (_e = timelineSet.getTimelineForEvent(eventId)) !== null && _e !== void 0 ? _e : timeline; - } - else { - // Where the event is a thread reply (not a root) and running in MSC-enabled mode the Thread timeline only - // functions contiguously, so we have to jump through some hoops to get our target event in it. - // XXX: workaround for https://github.com/vector-im/element-meta/issues/150 - const thread = timelineSet.thread; - const resOlder = yield this.fetchRelations(timelineSet.room.roomId, thread.id, thread_1.THREAD_RELATION_TYPE.name, null, { dir: event_timeline_1.Direction.Backward, from: res.start }); - const eventsNewer = []; - let nextBatch = res.end; - while (nextBatch) { - const resNewer = yield this.fetchRelations(timelineSet.room.roomId, thread.id, thread_1.THREAD_RELATION_TYPE.name, null, { dir: event_timeline_1.Direction.Forward, from: nextBatch }); - nextBatch = (_f = resNewer.next_batch) !== null && _f !== void 0 ? _f : null; - eventsNewer.push(...resNewer.chunk); - } - const events = [ - // Order events from most recent to oldest (reverse-chronological). - // We start with the last event, since that's the point at which we have known state. - // events_after is already backwards; events_before is forwards. - ...eventsNewer.reverse().map(mapper), - event, - ...resOlder.chunk.map(mapper), - ]; - for (const event of events) { - yield ((_g = timelineSet.thread) === null || _g === void 0 ? void 0 : _g.processEvent(event)); - } - // Here we handle non-thread timelines only, but still process any thread events to populate thread - // summaries. - const timeline = timelineSet.getLiveTimeline(); - timeline.getState(event_timeline_1.EventTimeline.BACKWARDS).setUnknownStateEvents(res.state.map(mapper)); - timelineSet.addEventsToTimeline(events, true, timeline, null); - if (!resOlder.next_batch) { - const originalEvent = yield this.fetchRoomEvent(timelineSet.room.roomId, thread.id); - timelineSet.addEventsToTimeline([mapper(originalEvent)], true, timeline, null); - } - timeline.setPaginationToken((_h = resOlder.next_batch) !== null && _h !== void 0 ? _h : null, event_timeline_1.Direction.Backward); - timeline.setPaginationToken(null, event_timeline_1.Direction.Forward); - this.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 _a, _b, _c, _d; - return __awaiter(this, void 0, void 0, function* () { - // don't allow any timeline support unless it's been enabled. - if (!this.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"); - } - let event; - if (timelineSet.threadListType !== null) { - const res = yield this.createThreadListMessagesRequest(timelineSet.room.roomId, null, 1, event_timeline_1.Direction.Backward, timelineSet.threadListType, timelineSet.getFilter()); - event = (_a = res.chunk) === null || _a === void 0 ? void 0 : _a[0]; - } - else if (timelineSet.thread && thread_1.Thread.hasServerSideSupport) { - const res = yield this.fetchRelations(timelineSet.room.roomId, timelineSet.thread.id, thread_1.THREAD_RELATION_TYPE.name, null, { dir: event_timeline_1.Direction.Backward, limit: 1 }); - event = (_b = res.chunk) === null || _b === void 0 ? void 0 : _b[0]; - } - else { - const messagesPath = utils.encodeUri("/rooms/$roomId/messages", { - $roomId: timelineSet.room.roomId, - }); - const params = { - dir: "b", - }; - if ((_c = this.clientOpts) === null || _c === void 0 ? void 0 : _c.lazyLoadMembers) { - params.filter = JSON.stringify(filter_1.Filter.LAZY_LOADING_MESSAGES_FILTER); - } - const res = yield this.http.authedRequest(http_api_1.Method.Get, messagesPath, params); - event = (_d = res.chunk) === null || _d === void 0 ? void 0 : _d[0]; - } - if (!event) { - throw new Error("No message returned when trying to construct getLatestTimeline"); - } - return this.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 - */ - // XXX: Intended private, used in code. - createMessagesRequest(roomId, fromToken, limit = 30, dir, timelineFilter) { - var _a, _b; - const path = utils.encodeUri("/rooms/$roomId/messages", { $roomId: roomId }); - const params = { - limit: limit.toString(), - dir: dir, - }; - if (fromToken) { - params.from = fromToken; - } - let filter = null; - if ((_a = this.clientOpts) === null || _a === void 0 ? void 0 : _a.lazyLoadMembers) { - // create a shallow copy of LAZY_LOADING_MESSAGES_FILTER, - // so the timelineFilter doesn't get written into it below - filter = Object.assign({}, filter_1.Filter.LAZY_LOADING_MESSAGES_FILTER); - } - if (timelineFilter) { - // XXX: it's horrific that /messages' filter parameter doesn't match - // /sync's one - see https://matrix.org/jira/browse/SPEC-451 - filter = filter || {}; - Object.assign(filter, (_b = timelineFilter.getRoomTimelineFilterComponent()) === null || _b === void 0 ? void 0 : _b.toJSON()); - } - if (filter) { - params.filter = JSON.stringify(filter); - } - return this.http.authedRequest(http_api_1.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 - */ - // XXX: Intended private, used by room.fetchRoomThreads - createThreadListMessagesRequest(roomId, fromToken, limit = 30, dir = event_timeline_1.Direction.Backward, threadListType = thread_1.ThreadFilterType.All, timelineFilter) { - var _a, _b; - const path = utils.encodeUri("/rooms/$roomId/threads", { $roomId: roomId }); - const params = { - limit: limit.toString(), - dir: dir, - include: (0, thread_1.threadFilterTypeToFilter)(threadListType), - }; - if (fromToken) { - params.from = fromToken; - } - let filter = {}; - if ((_a = this.clientOpts) === null || _a === void 0 ? void 0 : _a.lazyLoadMembers) { - // create a shallow copy of LAZY_LOADING_MESSAGES_FILTER, - // so the timelineFilter doesn't get written into it below - filter = Object.assign({}, filter_1.Filter.LAZY_LOADING_MESSAGES_FILTER); - } - if (timelineFilter) { - // XXX: it's horrific that /messages' filter parameter doesn't match - // /sync's one - see https://matrix.org/jira/browse/SPEC-451 - filter = Object.assign(Object.assign({}, filter), (_b = timelineFilter.getRoomTimelineFilterComponent()) === null || _b === void 0 ? void 0 : _b.toJSON()); - } - if (Object.keys(filter).length) { - params.filter = JSON.stringify(filter); - } - const opts = { - prefix: thread_1.Thread.hasServerSideListSupport === thread_1.FeatureSupport.Stable - ? "/_matrix/client/v1" - : "/_matrix/client/unstable/org.matrix.msc3856", - }; - return this.http - .authedRequest(http_api_1.Method.Get, path, params, undefined, opts) - .then((res) => { - var _a; - return (Object.assign(Object.assign({}, res), { chunk: (_a = res.chunk) === null || _a === void 0 ? void 0 : _a.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 _a, _b, _c; - const isNotifTimeline = eventTimeline.getTimelineSet() === this.notifTimelineSet; - const room = this.getRoom(eventTimeline.getRoomId()); - const threadListType = eventTimeline.getTimelineSet().threadListType; - const thread = eventTimeline.getTimelineSet().thread; - // TODO: we should implement a backoff (as per scrollback()) to deal more - // nicely with HTTP errors. - opts = opts || {}; - const backwards = opts.backwards || false; - if (isNotifTimeline) { - if (!backwards) { - throw new Error("paginateNotifTimeline can only paginate backwards"); - } - } - const dir = backwards ? event_timeline_1.EventTimeline.BACKWARDS : event_timeline_1.EventTimeline.FORWARDS; - const token = eventTimeline.getPaginationToken(dir); - const pendingRequest = eventTimeline.paginationRequests[dir]; - if (pendingRequest) { - // already a request in progress - return the existing promise - return pendingRequest; - } - let path; - let params; - let promise; - if (isNotifTimeline) { - path = "/notifications"; - params = { - limit: ((_a = opts.limit) !== null && _a !== void 0 ? _a : 30).toString(), - only: "highlight", - }; - if (token && token !== "end") { - params.from = token; - } - promise = this.http - .authedRequest(http_api_1.Method.Get, path, params) - .then((res) => __awaiter(this, void 0, void 0, function* () { - const token = res.next_token; - const matrixEvents = []; - res.notifications = res.notifications.filter(utils_1.noUnsafeEventProps); - for (let i = 0; i < res.notifications.length; i++) { - const notification = res.notifications[i]; - const event = this.getEventMapper()(notification.event); - event.setPushActions(pushprocessor_1.PushProcessor.actionListToActionsObject(notification.actions)); - event.event.room_id = notification.room_id; // XXX: gutwrenching - matrixEvents[i] = event; - } - // No need to partition events for threads here, everything lives - // in the notification timeline set - const timelineSet = eventTimeline.getTimelineSet(); - timelineSet.addEventsToTimeline(matrixEvents, backwards, eventTimeline, token); - this.processAggregatedTimelineEvents(timelineSet.room, matrixEvents); - // if we've hit the end of the timeline, we need to stop trying to - // paginate. We need to keep the 'forwards' token though, to make sure - // we can recover from gappy syncs. - if (backwards && !res.next_token) { - eventTimeline.setPaginationToken(null, dir); - } - return Boolean(res.next_token); - })) - .finally(() => { - eventTimeline.paginationRequests[dir] = null; - }); - eventTimeline.paginationRequests[dir] = promise; - } - else if (threadListType !== null) { - if (!room) { - throw new Error("Unknown room " + eventTimeline.getRoomId()); - } - if (!thread_1.Thread.hasServerSideFwdPaginationSupport && dir === event_timeline_1.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) { - const roomState = eventTimeline.getState(dir); - const stateEvents = res.state.filter(utils_1.noUnsafeEventProps).map(this.getEventMapper()); - roomState.setUnknownStateEvents(stateEvents); - } - const token = res.end; - const matrixEvents = res.chunk.filter(utils_1.noUnsafeEventProps).map(this.getEventMapper()); - const timelineSet = eventTimeline.getTimelineSet(); - timelineSet.addEventsToTimeline(matrixEvents, backwards, eventTimeline, token); - this.processAggregatedTimelineEvents(room, matrixEvents); - this.processThreadRoots(room, matrixEvents, backwards); - // if we've hit the end of the timeline, we need to stop trying to - // paginate. We need to keep the 'forwards' token though, to make sure - // we can recover from gappy syncs. - 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) { - const room = this.getRoom((_b = eventTimeline.getRoomId()) !== null && _b !== void 0 ? _b : undefined); - if (!room) { - throw new Error("Unknown room " + eventTimeline.getRoomId()); - } - promise = this.fetchRelations((_c = eventTimeline.getRoomId()) !== null && _c !== void 0 ? _c : "", thread.id, thread_1.THREAD_RELATION_TYPE.name, null, { - dir, - limit: opts.limit, - from: token !== null && token !== void 0 ? token : undefined, - }) - .then((res) => __awaiter(this, void 0, void 0, function* () { - var _d; - const mapper = this.getEventMapper(); - const matrixEvents = res.chunk.filter(utils_1.noUnsafeEventProps).map(mapper); - // Process latest events first - for (const event of matrixEvents.slice().reverse()) { - yield (thread === null || thread === void 0 ? void 0 : thread.processEvent(event)); - const sender = event.getSender(); - if (!backwards || (thread === null || thread === void 0 ? void 0 : thread.getEventReadUpTo(sender)) === null) { - room.addLocalEchoReceipt(sender, event, read_receipts_1.ReceiptType.Read); - } - } - const newToken = res.next_batch; - const timelineSet = eventTimeline.getTimelineSet(); - timelineSet.addEventsToTimeline(matrixEvents, backwards, eventTimeline, newToken !== null && newToken !== void 0 ? newToken : null); - if (!newToken && backwards) { - const originalEvent = yield this.fetchRoomEvent((_d = eventTimeline.getRoomId()) !== null && _d !== void 0 ? _d : "", thread.id); - timelineSet.addEventsToTimeline([mapper(originalEvent)], true, eventTimeline, null); - } - this.processAggregatedTimelineEvents(timelineSet.room, matrixEvents); - // if we've hit the end of the timeline, we need to stop trying to - // paginate. We need to keep the 'forwards' token though, to make sure - // we can recover from gappy syncs. - if (backwards && !newToken) { - eventTimeline.setPaginationToken(null, dir); - } - return Boolean(newToken); - })) - .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) { - const roomState = eventTimeline.getState(dir); - const stateEvents = res.state.filter(utils_1.noUnsafeEventProps).map(this.getEventMapper()); - roomState.setUnknownStateEvents(stateEvents); - } - const token = res.end; - const matrixEvents = res.chunk.filter(utils_1.noUnsafeEventProps).map(this.getEventMapper()); - const timelineSet = eventTimeline.getTimelineSet(); - const [timelineEvents] = room.partitionThreadedEvents(matrixEvents); - timelineSet.addEventsToTimeline(timelineEvents, backwards, eventTimeline, token); - this.processAggregatedTimelineEvents(room, timelineEvents); - this.processThreadRoots(room, timelineEvents.filter((it) => it.getServerAggregatedRelation(thread_1.THREAD_RELATION_TYPE.name)), false); - const atEnd = res.end === undefined || res.end === res.start; - // if we've hit the end of the timeline, we need to stop trying to - // paginate. We need to keep the 'forwards' token though, to make sure - // we can recover from gappy syncs. - 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; - } - // FIXME: This thing is a total hack, and results in duplicate events being - // added to the timeline both from /sync and /notifications, and lots of - // slow and wasteful processing and pagination. The correct solution is to - // extend /messages or /search or something to filter on notifications. - // use the fictitious token 'end'. in practice we would ideally give it - // the oldest backwards pagination token from /sync, but /sync doesn't - // know about /notifications, so we have no choice but to start paginating - // from the current point in time. This may well overlap with historical - // notifs which are then inserted into the timeline by /sync responses. - this.notifTimelineSet.resetLiveTimeline("end"); - // we could try to paginate a single event at this point in order to get - // a more valid pagination token, but it just ends up with an out of order - // timeline. given what a mess this is and given we're going to have duplicate - // events anyway, just leave it with the dummy token for now. - /* - this.paginateNotifTimeline(this._notifTimelineSet.getLiveTimeline(), { - backwards: true, - limit: 1 - }); - */ - } - /** - * 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. - * @returns Promise which resolves: Room object - * @returns Rejects: with an error response. - */ - peekInRoom(roomId) { - var _a; - (_a = this.peekSync) === null || _a === void 0 ? void 0 : _a.stopPeeking(); - this.peekSync = new sync_1.SyncApi(this, this.clientOpts, this.buildSyncApiOptions()); - return this.peekSync.peek(roomId); - } - /** - * 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) { - const writePromise = this.sendStateEvent(roomId, event_2.EventType.RoomGuestAccess, { - guest_access: opts.allowJoin ? "can_join" : "forbidden", - }, ""); - let readPromise = Promise.resolve(undefined); - if (opts.allowRead) { - readPromise = this.sendStateEvent(roomId, event_2.EventType.RoomHistoryVisibility, { - history_visibility: "world_readable", - }, ""); - } - return Promise.all([readPromise, writePromise]).then(); // .then() to hide results for contract - } - /** - * 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: 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: 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: 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 _a; - return __awaiter(this, void 0, void 0, function* () { - const postParams = Object.assign({}, params); - // If the HS supports separate add and bind, then requestToken endpoints - // don't need an IS as they are all validated by the HS directly. - if (!(yield this.doesServerSupportSeparateAddAndBind()) && this.idBaseUrl) { - const idServerUrl = new URL(this.idBaseUrl); - postParams.id_server = idServerUrl.host; - if (((_a = this.identityServer) === null || _a === void 0 ? void 0 : _a.getAccessToken) && (yield this.doesServerAcceptIdentityAccessToken())) { - const identityAccessToken = yield this.identityServer.getAccessToken(); - if (identityAccessToken) { - postParams.id_access_token = identityAccessToken; - } - } - } - return this.http.request(http_api_1.Method.Post, endpoint, undefined, 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) { - var _a, _b; - // There can be only room-kind push rule per room - // and its id is the room id. - if (this.pushRules) { - return (_b = (_a = this.pushRules[scope]) === null || _a === void 0 ? void 0 : _a.room) === null || _b === void 0 ? void 0 : _b.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) { - let promise; - let hasDontNotifyRule = false; - // Get the existing room-kind push rule if any - const roomPushRule = this.getRoomPushRule(scope, roomId); - if (roomPushRule === null || roomPushRule === void 0 ? void 0 : roomPushRule.actions.includes(PushRules_1.PushRuleActionName.DontNotify)) { - hasDontNotifyRule = true; - } - if (!mute) { - // Remove the rule only if it is a muting rule - if (hasDontNotifyRule) { - promise = this.deletePushRule(scope, PushRules_1.PushRuleKind.RoomSpecific, roomPushRule.rule_id); - } - } - else { - if (!roomPushRule) { - promise = this.addPushRule(scope, PushRules_1.PushRuleKind.RoomSpecific, roomId, { - actions: [PushRules_1.PushRuleActionName.DontNotify], - }); - } - else if (!hasDontNotifyRule) { - // Remove the existing one before setting the mute push rule - // This is a workaround to SYN-590 (Push rule update fails) - const deferred = utils.defer(); - this.deletePushRule(scope, PushRules_1.PushRuleKind.RoomSpecific, roomPushRule.rule_id) - .then(() => { - this.addPushRule(scope, PushRules_1.PushRuleKind.RoomSpecific, roomId, { - actions: [PushRules_1.PushRuleActionName.DontNotify], - }) - .then(() => { - deferred.resolve(); - }) - .catch((err) => { - deferred.reject(err); - }); - }) - .catch((err) => { - deferred.reject(err); - }); - promise = deferred.promise; - } - } - if (promise) { - return new Promise((resolve, reject) => { - // Update this.pushRules when the operation completes - promise - .then(() => { - this.getPushRules() - .then((result) => { - this.pushRules = result; - resolve(); - }) - .catch((err) => { - reject(err); - }); - }) - .catch((err) => { - // Update it even if the previous operation fails. This can help the - // app to recover when push settings has been modified from another client - this.getPushRules() - .then((result) => { - this.pushRules = result; - reject(err); - }) - .catch((err2) => { - reject(err); - }); - }); - }); - } - } - searchMessageText(opts) { - const 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) { - // TODO: support search groups - const body = { - search_categories: { - room_events: { - search_term: opts.term, - filter: opts.filter, - order_by: search_1.SearchOrderBy.Recent, - event_context: { - before_limit: 1, - after_limit: 1, - include_profile: true, - }, - }, - }, - }; - const searchResults = { - _query: body, - results: [], - highlights: [], - }; - return this.search({ body: 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) { - // TODO: we should implement a backoff (as per scrollback()) to deal more - // nicely with HTTP errors. - if (!searchResults.next_batch) { - return Promise.reject(new Error("Cannot backpaginate event search any further")); - } - if (searchResults.pendingRequest) { - // already a request in progress - return the existing promise - return searchResults.pendingRequest; - } - const searchOpts = { - body: searchResults._query, - next_batch: searchResults.next_batch, - }; - const promise = this.search(searchOpts, searchResults.abortSignal) - .then((res) => this.processRoomEventsSearch(searchResults, res)) - .finally(() => { - searchResults.pendingRequest = undefined; - }); - searchResults.pendingRequest = promise; - return promise; - } - /** - * helper for searchRoomEvents and backPaginateRoomEventsSearch. Processes the - * response from the API call and updates the searchResults - * - * @returns searchResults - * @internal - */ - // XXX: Intended private, used in code - processRoomEventsSearch(searchResults, response) { - var _a, _b; - const roomEvents = response.search_categories.room_events; - searchResults.count = roomEvents.count; - searchResults.next_batch = roomEvents.next_batch; - // combine the highlight list with our existing list; - const highlights = new Set(roomEvents.highlights); - searchResults.highlights.forEach((hl) => { - highlights.add(hl); - }); - // turn it back into a list. - searchResults.highlights = Array.from(highlights); - const mapper = this.getEventMapper(); - // append the new results to our existing results - const resultsLength = (_b = (_a = roomEvents.results) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0; - for (let i = 0; i < resultsLength; i++) { - const sr = search_result_1.SearchResult.fromJson(roomEvents.results[i], mapper); - const room = this.getRoom(sr.context.getEvent().getRoomId()); - if (room) { - // Copy over a known event sender if we can - for (const ev of sr.context.getTimeline()) { - const sender = room.getMember(ev.getSender()); - if (!ev.sender && sender) - ev.sender = sender; - } - } - 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() { - // Guard against multiple calls whilst ongoing and multiple calls post success - if (this.syncedLeftRooms) { - return Promise.resolve([]); // don't call syncRooms again if it succeeded. - } - if (this.syncLeftRoomsPromise) { - return this.syncLeftRoomsPromise; // return the ongoing request - } - const syncApi = new sync_1.SyncApi(this, this.clientOpts, this.buildSyncApiOptions()); - this.syncLeftRoomsPromise = syncApi.syncLeftRooms(); - // cleanup locks - this.syncLeftRoomsPromise - .then(() => { - logger_1.logger.log("Marking success of sync left room request"); - this.syncedLeftRooms = true; // flip the bit on success - }) - .finally(() => { - this.syncLeftRoomsPromise = undefined; // cleanup ongoing request state - }); - 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) { - const path = utils.encodeUri("/user/$userId/filter", { - $userId: this.credentials.userId, - }); - return this.http.authedRequest(http_api_1.Method.Post, path, undefined, content).then((response) => { - // persist the filter - const filter = filter_1.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) { - const filter = this.store.getFilter(userId, filterId); - if (filter) { - return Promise.resolve(filter); - } - } - const path = utils.encodeUri("/user/$userId/filter/$filterId", { - $userId: userId, - $filterId: filterId, - }); - return this.http.authedRequest(http_api_1.Method.Get, path).then((response) => { - // persist the filter - const filter = filter_1.Filter.fromJson(userId, filterId, response); - this.store.storeFilter(filter); - return filter; - }); - } - /** - * @returns Filter ID - */ - getOrCreateFilter(filterName, filter) { - return __awaiter(this, void 0, void 0, function* () { - const filterId = this.store.getFilterIdByName(filterName); - let existingId; - if (filterId) { - // check that the existing filter matches our expectations - try { - const existingFilter = yield this.getFilter(this.credentials.userId, filterId, true); - if (existingFilter) { - const oldDef = existingFilter.getDefinition(); - const newDef = filter.getDefinition(); - if (utils.deepCompare(oldDef, newDef)) { - // super, just use that. - // debuglog("Using existing filter ID %s: %s", filterId, - // JSON.stringify(oldDef)); - existingId = filterId; - } - } - } - catch (error) { - // Synapse currently returns the following when the filter cannot be found: - // { - // errcode: "M_UNKNOWN", - // name: "M_UNKNOWN", - // message: "No row found", - // } - if (error.errcode !== "M_UNKNOWN" && error.errcode !== "M_NOT_FOUND") { - throw error; - } - } - // if the filter doesn't exist anymore on the server, remove from store - if (!existingId) { - this.store.setFilterIdByName(filterName, undefined); - } - } - if (existingId) { - return existingId; - } - // create a new filter - const createdFilter = yield this.createFilter(filter.getDefinition()); - this.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() { - const path = utils.encodeUri("/user/$userId/openid/request_token", { - $userId: this.credentials.userId, - }); - return this.http.authedRequest(http_api_1.Method.Post, path, undefined, {}); - } - /** - * @returns Promise which resolves: ITurnServerResponse object - * @returns Rejects: with an error response. - */ - turnServer() { - return this.http.authedRequest(http_api_1.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 !== undefined; - } - // XXX: Intended private, used in code. - checkTurnServers() { - return __awaiter(this, void 0, void 0, function* () { - if (!this.canSupportVoip) { - return; - } - let credentialsGood = false; - const remainingTime = this.turnServersExpiry - Date.now(); - if (remainingTime > TURN_CHECK_INTERVAL) { - logger_1.logger.debug("TURN creds are valid for another " + remainingTime + " ms: not fetching new ones."); - credentialsGood = true; - } - else { - logger_1.logger.debug("Fetching new TURN credentials"); - try { - const res = yield this.turnServer(); - if (res.uris) { - logger_1.logger.log("Got TURN URIs: " + res.uris + " refresh in " + res.ttl + " secs"); - // map the response to a format that can be fed to RTCPeerConnection - const servers = { - urls: res.uris, - username: res.username, - credential: res.password, - }; - this.turnServers = [servers]; - // The TTL is in seconds but we work in ms - this.turnServersExpiry = Date.now() + res.ttl * 1000; - credentialsGood = true; - this.emit(ClientEvent.TurnServers, this.turnServers); - } - } - catch (err) { - logger_1.logger.error("Failed to get TURN URIs", err); - if (err.httpStatus === 403) { - // We got a 403, so there's no point in looping forever. - logger_1.logger.info("TURN access unavailable for this account: stopping credentials checks"); - if (this.checkTurnServersIntervalID !== null) - global.clearInterval(this.checkTurnServersIntervalID); - this.checkTurnServersIntervalID = undefined; - this.emit(ClientEvent.TurnServersError, err, true); // fatal - } - else { - // otherwise, if we failed for whatever reason, try again the next time we're called. - this.emit(ClientEvent.TurnServersError, err, false); // non-fatal - } - } - } - 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. This function is implementation specific and may change - * as a result. - * @returns true if the user appears to be a Synapse administrator. - */ - isSynapseAdministrator() { - const path = utils.encodeUri("/_synapse/admin/v1/users/$userId/admin", { $userId: this.getUserId() }); - return this.http - .authedRequest(http_api_1.Method.Get, path, undefined, undefined, { prefix: "" }) - .then((r) => r.admin); // pull out the specific boolean we want - } - /** - * Performs a whois lookup on a user using Synapse's administrator API. - * This function is implementation specific and may change as a - * result. - * @param userId - the User ID to look up. - * @returns the whois response - see Synapse docs for information. - */ - whoisSynapseUser(userId) { - const path = utils.encodeUri("/_synapse/admin/v1/whois/$userId", { $userId: userId }); - return this.http.authedRequest(http_api_1.Method.Get, path, undefined, undefined, { prefix: "" }); - } - /** - * Deactivates a user using Synapse's administrator API. This - * function is implementation specific and may change as a result. - * @param userId - the User ID to deactivate. - * @returns the deactivate response - see Synapse docs for information. - */ - deactivateSynapseUser(userId) { - const path = utils.encodeUri("/_synapse/admin/v1/deactivate/$userId", { $userId: userId }); - return this.http.authedRequest(http_api_1.Method.Post, path, undefined, undefined, { prefix: "" }); - } - fetchClientWellKnown() { - var _a; - return __awaiter(this, void 0, void 0, function* () { - // `getRawClientConfig` does not throw or reject on network errors, instead - // it absorbs errors and returns `{}`. - this.clientWellKnownPromise = autodiscovery_1.AutoDiscovery.getRawClientConfig((_a = this.getDomain()) !== null && _a !== void 0 ? _a : undefined); - this.clientWellKnown = yield this.clientWellKnownPromise; - this.emit(ClientEvent.ClientWellKnown, this.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) - * @param opts - the complete set of client options - * @returns for store operation - */ - storeClientOptions() { - // XXX: Intended private, used in code - const primTypes = ["boolean", "string", "number"]; - const serializableOpts = Object.entries(this.clientOpts) - .filter(([key, value]) => { - return primTypes.includes(typeof value); - }) - .reduce((obj, [key, value]) => { - obj[key] = value; - return obj; - }, {}); - return this.store.storeClientOptions(serializableOpts); - } - /** - * Gets a set of room IDs in common with another user - * @param userId - The userId to check. - * @returns Promise which resolves to a set of rooms - * @returns Rejects: with an error response. - */ - // eslint-disable-next-line - _unstable_getSharedRooms(userId) { - return __awaiter(this, void 0, void 0, function* () { - const sharedRoomsSupport = yield this.doesServerSupportUnstableFeature("uk.half-shot.msc2666"); - const mutualRoomsSupport = yield this.doesServerSupportUnstableFeature("uk.half-shot.msc2666.mutual_rooms"); - if (!sharedRoomsSupport && !mutualRoomsSupport) { - throw Error("Server does not support mutual_rooms API"); - } - const path = utils.encodeUri(`/uk.half-shot.msc2666/user/${mutualRoomsSupport ? "mutual_rooms" : "shared_rooms"}/$userId`, { $userId: userId }); - const res = yield this.http.authedRequest(http_api_1.Method.Get, path, undefined, undefined, { - prefix: http_api_1.ClientPrefix.Unstable, - }); - return res.joined; - }); - } - /** - * Get the API versions supported by the server, along with any - * unstable APIs it supports - * @returns The server /versions response - */ - getVersions() { - return __awaiter(this, void 0, void 0, function* () { - if (this.serverVersionsPromise) { - return this.serverVersionsPromise; - } - this.serverVersionsPromise = this.http - .request(http_api_1.Method.Get, "/_matrix/client/versions", undefined, // queryParams - undefined, // data - { - prefix: "", - }) - .catch((e) => { - // Need to unset this if it fails, otherwise we'll never retry - this.serverVersionsPromise = undefined; - // but rethrow the exception to anything that was waiting - throw e; - }); - const serverVersions = yield this.serverVersionsPromise; - this.canSupport = yield (0, feature_1.buildFeatureSupportMap)(serverVersions); - return this.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) { - return __awaiter(this, void 0, void 0, function* () { - const { versions } = yield this.getVersions(); - return versions && versions.includes(version); - }); - } - /** - * Query the server to see if it supports members lazy loading - * @returns true if server supports lazy loading - */ - doesServerSupportLazyLoading() { - return __awaiter(this, void 0, void 0, function* () { - const response = yield this.getVersions(); - if (!response) - return false; - const versions = response["versions"]; - const unstableFeatures = response["unstable_features"]; - return ((versions && versions.includes("r0.5.0")) || (unstableFeatures && unstableFeatures["m.lazy_load_members"])); - }); - } - /** - * Query the server to see if the `id_server` parameter is required - * when registering with an 3pid, adding a 3pid or resetting password. - * @returns true if id_server parameter is required - */ - doesServerRequireIdServerParam() { - return __awaiter(this, void 0, void 0, function* () { - const response = yield this.getVersions(); - if (!response) - return true; - const versions = response["versions"]; - // Supporting r0.6.0 is the same as having the flag set to false - if (versions && versions.includes("r0.6.0")) { - return false; - } - const unstableFeatures = response["unstable_features"]; - if (!unstableFeatures) - return true; - if (unstableFeatures["m.require_identity_server"] === undefined) { - return true; - } - else { - return unstableFeatures["m.require_identity_server"]; - } - }); - } - /** - * Query the server to see if the `id_access_token` parameter can be safely - * passed to the homeserver. Some homeservers may trigger errors if they are not - * prepared for the new parameter. - * @returns true if id_access_token can be sent - */ - doesServerAcceptIdentityAccessToken() { - return __awaiter(this, void 0, void 0, function* () { - const response = yield this.getVersions(); - if (!response) - return false; - const versions = response["versions"]; - const unstableFeatures = response["unstable_features"]; - return (versions && versions.includes("r0.6.0")) || (unstableFeatures && unstableFeatures["m.id_access_token"]); - }); - } - /** - * Query the server to see if it supports separate 3PID add and bind functions. - * This affects the sequence of API calls clients should use for these operations, - * so it's helpful to be able to check for support. - * @returns true if separate functions are supported - */ - doesServerSupportSeparateAddAndBind() { - return __awaiter(this, void 0, void 0, function* () { - const response = yield this.getVersions(); - if (!response) - return false; - const versions = response["versions"]; - const unstableFeatures = response["unstable_features"]; - return (versions === null || versions === void 0 ? void 0 : versions.includes("r0.6.0")) || (unstableFeatures === null || unstableFeatures === void 0 ? void 0 : unstableFeatures["m.separate_add_and_bind"]); - }); - } - /** - * 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) { - return __awaiter(this, void 0, void 0, function* () { - const response = yield this.getVersions(); - if (!response) - return false; - const 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) { - return __awaiter(this, void 0, void 0, function* () { - const response = yield this.getVersions(); - if (!response) - return false; - const unstableFeatures = response["unstable_features"]; - // The preset name in the versions response will be without the _chat suffix. - const versionsPresetName = presetName.includes("_chat") - ? presetName.substring(0, presetName.indexOf("_chat")) - : presetName; - return unstableFeatures && !!unstableFeatures[`io.element.e2ee_forced.${versionsPresetName}`]; - }); - } - doesServerSupportThread() { - return __awaiter(this, void 0, void 0, function* () { - if (yield this.isVersionSupported("v1.4")) { - return { - threads: thread_1.FeatureSupport.Stable, - list: thread_1.FeatureSupport.Stable, - fwdPagination: thread_1.FeatureSupport.Stable, - }; - } - try { - const [threadUnstable, threadStable, listUnstable, listStable, fwdPaginationUnstable, fwdPaginationStable] = yield Promise.all([ - this.doesServerSupportUnstableFeature("org.matrix.msc3440"), - this.doesServerSupportUnstableFeature("org.matrix.msc3440.stable"), - this.doesServerSupportUnstableFeature("org.matrix.msc3856"), - this.doesServerSupportUnstableFeature("org.matrix.msc3856.stable"), - this.doesServerSupportUnstableFeature("org.matrix.msc3715"), - this.doesServerSupportUnstableFeature("org.matrix.msc3715.stable"), - ]); - return { - threads: (0, thread_1.determineFeatureSupport)(threadStable, threadUnstable), - list: (0, thread_1.determineFeatureSupport)(listStable, listUnstable), - fwdPagination: (0, thread_1.determineFeatureSupport)(fwdPaginationStable, fwdPaginationUnstable), - }; - } - catch (e) { - return { - threads: thread_1.FeatureSupport.None, - list: thread_1.FeatureSupport.None, - fwdPagination: thread_1.FeatureSupport.None, - }; - } - }); - } - /** - * Query the server to see if it supports the MSC2457 `logout_devices` parameter when setting password - * @returns true if server supports the `logout_devices` parameter - */ - doesServerSupportLogoutDevices() { - return this.isVersionSupported("r0.6.1"); - } - /** - * Get if lazy loading members is being used. - * @returns Whether or not members are lazy loaded by this client - */ - hasLazyLoadMembersEnabled() { - var _a; - return !!((_a = this.clientOpts) === null || _a === void 0 ? void 0 : _a.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, opts = { dir: event_timeline_1.Direction.Backward }) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - const fetchedEventType = eventType ? this.getEncryptedIfNeededEventType(roomId, eventType) : null; - const [eventResult, result] = yield Promise.all([ - this.fetchRoomEvent(roomId, eventId), - this.fetchRelations(roomId, eventId, relationType, fetchedEventType, opts), - ]); - const mapper = this.getEventMapper(); - const originalEvent = eventResult ? mapper(eventResult) : undefined; - let events = result.chunk.map(mapper); - if (fetchedEventType === event_2.EventType.RoomMessageEncrypted) { - const allEvents = originalEvent ? events.concat(originalEvent) : events; - yield Promise.all(allEvents.map((e) => this.decryptEventIfNeeded(e))); - if (eventType !== null) { - events = events.filter((e) => e.getType() === eventType); - } - } - if (originalEvent && relationType === event_2.RelationType.Replace) { - events = events.filter((e) => e.getSender() === originalEvent.getSender()); - } - return { - originalEvent: originalEvent !== null && originalEvent !== void 0 ? originalEvent : null, - events, - nextBatch: (_a = result.next_batch) !== null && _a !== void 0 ? _a : null, - prevBatch: (_b = result.prev_batch) !== null && _b !== void 0 ? _b : null, - }; - }); - } - /** - * The app may wish to see if we have a key cached without - * triggering a user interaction. - */ - getCrossSigningCacheCallbacks() { - var _a; - // XXX: Private member access - return (_a = this.crypto) === null || _a === void 0 ? void 0 : _a.crossSigningInfo.getCacheCallbacks(); - } - /** - * Generates a random string suitable for use as a client secret. This - * method is experimental and may change. - * @returns A new client secret - */ - generateClientSecret() { - return (0, randomstring_1.randomString)(32); - } - /** - * Attempts to decrypt an event - * @param event - The event to decrypt - * @returns A decryption promise - */ - decryptEventIfNeeded(event, options) { - if (event.shouldAttemptDecryption() && this.isCryptoEnabled()) { - event.attemptDecryption(this.cryptoBackend, options); - } - if (event.isBeingDecrypted()) { - return event.getDecryptionPromise(); - } - else { - return Promise.resolve(); - } - } - termsUrlForService(serviceType, baseUrl) { - switch (serviceType) { - case service_types_1.SERVICE_TYPES.IS: - return this.http.getUrl("/terms", undefined, http_api_1.IdentityPrefix.V2, baseUrl); - case service_types_1.SERVICE_TYPES.IM: - return this.http.getUrl("/terms", undefined, "/_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(stripProto = false) { - var _a, _b; - if (stripProto && (((_a = this.idBaseUrl) === null || _a === void 0 ? void 0 : _a.startsWith("http://")) || ((_b = this.idBaseUrl) === null || _b === void 0 ? void 0 : _b.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 = utils.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; - } - /** - * Set the access token associated with this account. - * @param token - The new access token. - */ - setAccessToken(token) { - this.http.opts.accessToken = token; - } - /** - * @returns true if there is a valid access_token for this client. - */ - isLoggedIn() { - return this.http.opts.accessToken !== undefined; - } - /** - * Make up a new transaction id - * - * @returns a new, unique, transaction id - */ - makeTxnId() { - return "m" + 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(http_api_1.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: TODO - * @returns Rejects: with an error response. - */ - register(username, password, sessionId, auth, bindThreepids, guestAccessToken, inhibitLogin) { - // backwards compat - if (bindThreepids === true) { - bindThreepids = { email: true }; - } - else if (bindThreepids === null || bindThreepids === undefined || bindThreepids === false) { - bindThreepids = {}; - } - if (sessionId) { - auth.session = sessionId; - } - const params = { - auth: auth, - refresh_token: true, // always ask for a refresh token - does nothing if unsupported - }; - if (username !== undefined && username !== null) { - params.username = username; - } - if (password !== undefined && password !== null) { - params.password = password; - } - if (bindThreepids.email) { - params.bind_email = true; - } - if (bindThreepids.msisdn) { - params.bind_msisdn = true; - } - if (guestAccessToken !== undefined && guestAccessToken !== null) { - params.guest_access_token = guestAccessToken; - } - if (inhibitLogin !== undefined && inhibitLogin !== null) { - params.inhibit_login = inhibitLogin; - } - // Temporary parameter added to make the register endpoint advertise - // msisdn flows. This exists because there are clients that break - // when given stages they don't recognise. This parameter will cease - // to be necessary once these old clients are gone. - // Only send it if we send any params at all (the password param is - // mandatory, so if we send any params, we'll send the password param) - if (password !== undefined && password !== null) { - params.x_show_msisdn = true; - } - 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({ body } = {}) { - // TODO: Types - 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) { - const params = {}; - if (kind) { - params.kind = kind; - } - return this.http.request(http_api_1.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) { - return this.http.authedRequest(http_api_1.Method.Post, "/refresh", undefined, { refresh_token: refreshToken }, { - prefix: http_api_1.ClientPrefix.V1, - inhibitLogoutEmit: true, // we don't want to cause logout loops - }); - } - /** - * @returns Promise which resolves to the available login flows - * @returns Rejects: with an error response. - */ - loginFlows() { - return this.http.request(http_api_1.Method.Get, "/login"); - } - /** - * @returns Promise which resolves: TODO - * @returns Rejects: with an error response. - */ - login(loginType, data) { - // TODO: Types - const loginData = { - type: loginType, - }; - // merge data into loginData - Object.assign(loginData, data); - return this.http - .authedRequest(http_api_1.Method.Post, "/login", undefined, loginData) - .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: TODO - * @returns Rejects: with an error response. - */ - loginWithPassword(user, password) { - // TODO: Types - return this.login("m.login.password", { - user: user, - password: password, - }); - } - /** - * @param relayState - URL Callback after SAML2 Authentication - * @returns Promise which resolves: TODO - * @returns Rejects: with an error response. - */ - loginWithSAML2(relayState) { - // TODO: Types - return this.login("m.login.saml2", { - relay_state: relayState, - }); - } - /** - * @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, loginType = "sso", idpId, action) { - let url = "/login/" + loginType + "/redirect"; - if (idpId) { - url += "/" + idpId; - } - const params = { - redirectUrl, - [SSO_ACTION_PARAM.unstable]: action, - }; - return this.http.getUrl(url, params, http_api_1.ClientPrefix.R0).href; - } - /** - * @param token - Login token previously received from homeserver - * @returns Promise which resolves: TODO - * @returns Rejects: with an error response. - */ - loginWithToken(token) { - // TODO: Types - return this.login("m.login.token", { - token: token, - }); - } - /** - * 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(stopClient = false) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - if ((_b = (_a = this.crypto) === null || _a === void 0 ? void 0 : _a.backupManager) === null || _b === void 0 ? void 0 : _b.getKeyBackupEnabled()) { - try { - while ((yield this.crypto.backupManager.backupPendingKeys(200)) > 0) - ; - } - catch (err) { - logger_1.logger.error("Key backup request failed when logging out. Some keys may be missing from backup", err); - } - } - if (stopClient) { - this.stopClient(); - this.http.abort(); - } - return this.http.authedRequest(http_api_1.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) { - const body = {}; - if (auth) { - body.auth = auth; - } - if (erase !== undefined) { - body.erase = erase; - } - return this.http.authedRequest(http_api_1.Method.Post, "/account/deactivate", undefined, body); - } - /** - * Make a request for an `m.login.token` to be issued as per - * [MSC3882](https://github.com/matrix-org/matrix-spec-proposals/pull/3882). - * The server may require User-Interactive auth. - * Note that this is UNSTABLE and subject to breaking changes without notice. - * @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) { - const body = { auth }; - return this.http.authedRequest(http_api_1.Method.Post, "/org.matrix.msc3882/login/token", undefined, // no query params - body, { prefix: http_api_1.ClientPrefix.Unstable }); - } - /** - * 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) { - const path = utils.encodeUri("/auth/$loginType/fallback/web", { - $loginType: loginType, - }); - return this.http.getUrl(path, { - session: authSessionId, - }, http_api_1.ClientPrefix.R0).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 _a; - return __awaiter(this, void 0, void 0, function* () { - // eslint-disable-line camelcase - // some valid options include: room_alias_name, visibility, invite - // inject the id_access_token if inviting 3rd party addresses - const invitesNeedingToken = (options.invite_3pid || []).filter((i) => !i.id_access_token); - if (invitesNeedingToken.length > 0 && - ((_a = this.identityServer) === null || _a === void 0 ? void 0 : _a.getAccessToken) && - (yield this.doesServerAcceptIdentityAccessToken())) { - const identityAccessToken = yield this.identityServer.getAccessToken(); - if (identityAccessToken) { - for (const invite of invitesNeedingToken) { - invite.id_access_token = identityAccessToken; - } - } - } - return this.http.authedRequest(http_api_1.Method.Post, "/createRoom", undefined, 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, opts = { dir: event_timeline_1.Direction.Backward }) { - let params = opts; - if (thread_1.Thread.hasServerSideFwdPaginationSupport === thread_1.FeatureSupport.Experimental) { - params = (0, utils_1.replaceParam)("dir", "org.matrix.msc3715.dir", params); - } - const queryString = utils.encodeParams(params); - let templatedUrl = "/rooms/$roomId/relations/$eventId"; - if (relationType !== null) { - templatedUrl += "/$relationType"; - if (eventType !== null) { - templatedUrl += "/$eventType"; - } - } - else if (eventType !== null) { - logger_1.logger.warn(`eventType: ${eventType} ignored when fetching - relations as relationType is null`); - eventType = null; - } - const path = utils.encodeUri(templatedUrl + "?" + queryString, { - $roomId: roomId, - $eventId: eventId, - $relationType: relationType, - $eventType: eventType, - }); - return this.http.authedRequest(http_api_1.Method.Get, path, undefined, undefined, { - prefix: http_api_1.ClientPrefix.V1, - }); - } - /** - * @returns Promise which resolves: TODO - * @returns Rejects: with an error response. - */ - roomState(roomId) { - const path = utils.encodeUri("/rooms/$roomId/state", { $roomId: roomId }); - return this.http.authedRequest(http_api_1.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) { - const path = utils.encodeUri("/rooms/$roomId/event/$eventId", { - $roomId: roomId, - $eventId: eventId, - }); - return this.http.authedRequest(http_api_1.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) { - const queryParams = {}; - if (includeMembership) { - queryParams.membership = includeMembership; - } - if (excludeMembership) { - queryParams.not_membership = excludeMembership; - } - if (atEventId) { - queryParams.at = atEventId; - } - const queryString = utils.encodeParams(queryParams); - const path = utils.encodeUri("/rooms/$roomId/members?" + queryString, { $roomId: roomId }); - return this.http.authedRequest(http_api_1.Method.Get, path); - } - /** - * Upgrades a room to a new protocol version - * @param newVersion - The target version to upgrade to - * @returns Promise which resolves: Object with key 'replacement_room' - * @returns Rejects: with an error response. - */ - upgradeRoom(roomId, newVersion) { - // eslint-disable-line camelcase - const path = utils.encodeUri("/rooms/$roomId/upgrade", { $roomId: roomId }); - return this.http.authedRequest(http_api_1.Method.Post, path, undefined, { new_version: newVersion }); - } - /** - * Retrieve a state event. - * @returns Promise which resolves: TODO - * @returns Rejects: with an error response. - */ - getStateEvent(roomId, eventType, stateKey) { - const pathParams = { - $roomId: roomId, - $eventType: eventType, - $stateKey: stateKey, - }; - let path = utils.encodeUri("/rooms/$roomId/state/$eventType", pathParams); - if (stateKey !== undefined) { - path = utils.encodeUri(path + "/$stateKey", pathParams); - } - return this.http.authedRequest(http_api_1.Method.Get, path); - } - /** - * @param opts - Options for the request function. - * @returns Promise which resolves: TODO - * @returns Rejects: with an error response. - */ - sendStateEvent(roomId, eventType, content, stateKey = "", opts = {}) { - const pathParams = { - $roomId: roomId, - $eventType: eventType, - $stateKey: stateKey, - }; - let path = utils.encodeUri("/rooms/$roomId/state/$eventType", pathParams); - if (stateKey !== undefined) { - path = utils.encodeUri(path + "/$stateKey", pathParams); - } - return this.http.authedRequest(http_api_1.Method.Put, path, undefined, content, opts); - } - /** - * @returns Promise which resolves: TODO - * @returns Rejects: with an error response. - */ - roomInitialSync(roomId, limit) { - var _a; - const path = utils.encodeUri("/rooms/$roomId/initialSync", { $roomId: roomId }); - return this.http.authedRequest(http_api_1.Method.Get, path, { limit: (_a = limit === null || limit === void 0 ? void 0 : limit.toString()) !== null && _a !== void 0 ? _a : "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) { - return __awaiter(this, void 0, void 0, function* () { - const path = utils.encodeUri("/rooms/$roomId/read_markers", { - $roomId: roomId, - }); - const content = { - [read_receipts_1.ReceiptType.FullyRead]: rmEventId, - [read_receipts_1.ReceiptType.Read]: rrEventId, - }; - if ((yield this.doesServerSupportUnstableFeature("org.matrix.msc2285.stable")) || - (yield this.isVersionSupported("v1.4"))) { - content[read_receipts_1.ReceiptType.ReadPrivate] = rpEventId; - } - return this.http.authedRequest(http_api_1.Method.Post, path, undefined, content); - }); - } - /** - * @returns Promise which resolves: A list of the user's current rooms - * @returns Rejects: with an error response. - */ - getJoinedRooms() { - const path = utils.encodeUri("/joined_rooms", {}); - return this.http.authedRequest(http_api_1.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) { - const path = utils.encodeUri("/rooms/$roomId/joined_members", { - $roomId: roomId, - }); - return this.http.authedRequest(http_api_1.Method.Get, path); - } - /** - * @param options - Options for this request - * @param server - The remote server to query for the room list. - * Optional. If unspecified, get the local home - * server's public room list. - * @param limit - Maximum number of entries to return - * @param since - Token to paginate from - * @returns Promise which resolves: IPublicRoomsResponse - * @returns Rejects: with an error response. - */ - publicRooms(_a = {}) { - var { server, limit, since } = _a, options = __rest(_a, ["server", "limit", "since"]); - const queryParams = { server, limit, since }; - if (Object.keys(options).length === 0) { - return this.http.authedRequest(http_api_1.Method.Get, "/publicRooms", queryParams); - } - else { - return this.http.authedRequest(http_api_1.Method.Post, "/publicRooms", queryParams, options); - } - } - /** - * 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) { - const path = utils.encodeUri("/directory/room/$alias", { - $alias: alias, - }); - const data = { - room_id: roomId, - }; - return this.http.authedRequest(http_api_1.Method.Put, path, undefined, 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) { - const path = utils.encodeUri("/directory/room/$alias", { - $alias: alias, - }); - return this.http.authedRequest(http_api_1.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) { - const path = utils.encodeUri("/rooms/$roomId/aliases", { $roomId: roomId }); - const prefix = http_api_1.ClientPrefix.V3; - return this.http.authedRequest(http_api_1.Method.Get, path, undefined, undefined, { 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) { - // eslint-disable-line camelcase - // TODO: deprecate this or resolveRoomAlias - const path = utils.encodeUri("/directory/room/$alias", { - $alias: alias, - }); - return this.http.authedRequest(http_api_1.Method.Get, path); - } - /** - * @returns Promise which resolves: Object with room_id and servers. - * @returns Rejects: with an error response. - */ - // eslint-disable-next-line camelcase - resolveRoomAlias(roomAlias) { - // TODO: deprecate this or getRoomIdForAlias - const path = utils.encodeUri("/directory/room/$alias", { $alias: roomAlias }); - return this.http.request(http_api_1.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) { - const path = utils.encodeUri("/directory/list/room/$roomId", { - $roomId: roomId, - }); - return this.http.authedRequest(http_api_1.Method.Get, path); - } - /** - * Set the visbility 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) { - const path = utils.encodeUri("/directory/list/room/$roomId", { - $roomId: roomId, - }); - return this.http.authedRequest(http_api_1.Method.Put, path, undefined, { visibility }); - } - /** - * Set the visbility of a room bridged to a 3rd party network in - * the current HS's room directory. - * @param networkId - the network ID of the 3rd party - * instance under which this room is published under. - * @param visibility - "public" to make the room visible - * in the public directory, or "private" to make - * it invisible. - * @returns Promise which resolves: result object - * @returns Rejects: with an error response. - */ - setRoomDirectoryVisibilityAppService(networkId, roomId, visibility) { - // TODO: Types - const path = utils.encodeUri("/directory/list/appservice/$networkId/$roomId", { - $networkId: networkId, - $roomId: roomId, - }); - return this.http.authedRequest(http_api_1.Method.Put, path, undefined, { visibility: visibility }); - } - /** - * Query the user directory with a term matching user IDs, display names and domains. - * @param term - the term with which to search. - * @param 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({ term, limit }) { - const body = { - search_term: term, - }; - if (limit !== undefined) { - body.limit = limit; - } - return this.http.authedRequest(http_api_1.Method.Post, "/user_directory/search", undefined, 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, as - * determined by this.opts.onlyData, opts.rawResponse, and - * opts.onlyContentUri. 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) { - const path = info - ? utils.encodeUri("/profile/$userId/$info", { $userId: userId, $info: info }) - : utils.encodeUri("/profile/$userId", { $userId: userId }); - return this.http.authedRequest(http_api_1.Method.Get, path); - } - /** - * @returns Promise which resolves to a list of the user's threepids. - * @returns Rejects: with an error response. - */ - getThreePids() { - return this.http.authedRequest(http_api_1.Method.Get, "/account/3pid"); - } - /** - * Add a 3PID to your homeserver account and optionally bind it to an identity - * server as well. An identity server is required as part of the `creds` object. - * - * This API is deprecated, and you should instead use `addThreePidOnly` - * for homeservers that support it. - * - * @returns Promise which resolves: on success - * @returns Rejects: with an error response. - */ - addThreePid(creds, bind) { - // TODO: Types - const path = "/account/3pid"; - const data = { - threePidCreds: creds, - bind: bind, - }; - return this.http.authedRequest(http_api_1.Method.Post, path, undefined, data); - } - /** - * 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. - * - * You can check whether a homeserver supports this API via - * `doesServerSupportSeparateAddAndBind`. - * - * @param data - A object with 3PID validation data from having called - * `account/3pid//requestToken` on the homeserver. - * @returns Promise which resolves: to an empty object `{}` - * @returns Rejects: with an error response. - */ - addThreePidOnly(data) { - return __awaiter(this, void 0, void 0, function* () { - const path = "/account/3pid/add"; - const prefix = (yield this.isVersionSupported("r0.6.0")) ? http_api_1.ClientPrefix.R0 : http_api_1.ClientPrefix.Unstable; - return this.http.authedRequest(http_api_1.Method.Post, path, undefined, data, { prefix }); - }); - } - /** - * 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. - * - * You can check whether a homeserver supports this API via - * `doesServerSupportSeparateAddAndBind`. - * - * @param data - A object with 3PID validation data from having called - * `validate//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) { - return __awaiter(this, void 0, void 0, function* () { - const path = "/account/3pid/bind"; - const prefix = (yield this.isVersionSupported("r0.6.0")) ? http_api_1.ClientPrefix.R0 : http_api_1.ClientPrefix.Unstable; - return this.http.authedRequest(http_api_1.Method.Post, path, undefined, data, { prefix }); - }); - } - /** - * 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) { - return __awaiter(this, void 0, void 0, function* () { - const path = "/account/3pid/unbind"; - const data = { - medium, - address, - id_server: this.getIdentityServerUrl(true), - }; - const prefix = (yield this.isVersionSupported("r0.6.0")) ? http_api_1.ClientPrefix.R0 : http_api_1.ClientPrefix.Unstable; - return this.http.authedRequest(http_api_1.Method.Post, path, undefined, data, { prefix }); - }); - } - /** - * @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) { - const path = "/account/3pid/delete"; - return this.http.authedRequest(http_api_1.Method.Post, path, undefined, { 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) { - const path = "/account/password"; - const data = { - auth: authDict, - new_password: newPassword, - logout_devices: logoutDevices, - }; - return this.http.authedRequest(http_api_1.Method.Post, path, undefined, 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(http_api_1.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) { - const path = utils.encodeUri("/devices/$device_id", { - $device_id: deviceId, - }); - return this.http.authedRequest(http_api_1.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. - */ - // eslint-disable-next-line camelcase - setDeviceDetails(deviceId, body) { - const path = utils.encodeUri("/devices/$device_id", { - $device_id: deviceId, - }); - return this.http.authedRequest(http_api_1.Method.Put, path, undefined, 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) { - const path = utils.encodeUri("/devices/$device_id", { - $device_id: deviceId, - }); - const body = {}; - if (auth) { - body.auth = auth; - } - return this.http.authedRequest(http_api_1.Method.Delete, path, undefined, 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) { - const body = { devices }; - if (auth) { - body.auth = auth; - } - const path = "/delete_devices"; - return this.http.authedRequest(http_api_1.Method.Post, path, undefined, 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() { - return __awaiter(this, void 0, void 0, function* () { - const response = yield this.http.authedRequest(http_api_1.Method.Get, "/pushers"); - // Migration path for clients that connect to a homeserver that does not support - // MSC3881 yet, see https://github.com/matrix-org/matrix-spec-proposals/blob/kerry/remote-push-toggle/proposals/3881-remote-push-notification-toggling.md#migration - if (!(yield this.doesServerSupportUnstableFeature("org.matrix.msc3881"))) { - response.pushers = response.pushers.map((pusher) => { - if (!pusher.hasOwnProperty(event_2.PUSHER_ENABLED.name)) { - pusher[event_2.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) { - const path = "/pushers/set"; - return this.http.authedRequest(http_api_1.Method.Post, path, undefined, pusher); - } - /** - * Persists local notification settings - * @returns Promise which resolves: an empty object - * @returns Rejects: with an error response. - */ - setLocalNotificationSettings(deviceId, notificationSettings) { - const key = `${event_2.LOCAL_NOTIFICATION_SETTINGS_PREFIX.name}.${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(http_api_1.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) { - // Fix-up defaults, if applicable. - this.pushRules = pushprocessor_1.PushProcessor.rewriteDefaultRules(rules, this.getUserId()); - // Pre-calculate any necessary caches. - this.pushProcessor.updateCachedPushRuleKeys(this.pushRules); - } - /** - * @returns Promise which resolves: an empty object `{}` - * @returns Rejects: with an error response. - */ - addPushRule(scope, kind, ruleId, body) { - // NB. Scope not uri encoded because devices need the '/' - const path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId", { - $kind: kind, - $ruleId: ruleId, - }); - return this.http.authedRequest(http_api_1.Method.Put, path, undefined, body); - } - /** - * @returns Promise which resolves: an empty object `{}` - * @returns Rejects: with an error response. - */ - deletePushRule(scope, kind, ruleId) { - // NB. Scope not uri encoded because devices need the '/' - const path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId", { - $kind: kind, - $ruleId: ruleId, - }); - return this.http.authedRequest(http_api_1.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) { - const path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId/enabled", { - $kind: kind, - $ruleId: ruleId, - }); - return this.http.authedRequest(http_api_1.Method.Put, path, undefined, { enabled: 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) { - const path = utils.encodeUri("/pushrules/" + scope + "/$kind/$ruleId/actions", { - $kind: kind, - $ruleId: ruleId, - }); - return this.http.authedRequest(http_api_1.Method.Put, path, undefined, { actions: actions }); - } - /** - * Perform a server-side search. - * @param next_batch - the batch token to pass in the query string - * @param 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({ body, next_batch: nextBatch }, abortSignal) { - const queryParams = {}; - if (nextBatch) { - queryParams.next_batch = nextBatch; - } - return this.http.authedRequest(http_api_1.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(http_api_1.Method.Post, "/keys/upload", undefined, content); - } - uploadKeySignatures(content) { - return this.http.authedRequest(http_api_1.Method.Post, "/keys/signatures/upload", undefined, content, { - prefix: http_api_1.ClientPrefix.V3, - }); - } - /** - * 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, { token } = {}) { - const content = { - device_keys: {}, - }; - if (token !== undefined) { - content.token = token; - } - userIds.forEach((u) => { - content.device_keys[u] = []; - }); - return this.http.authedRequest(http_api_1.Method.Post, "/keys/query", undefined, 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, keyAlgorithm = "signed_curve25519", timeout) { - const queries = {}; - if (keyAlgorithm === undefined) { - keyAlgorithm = "signed_curve25519"; - } - for (const [userId, deviceId] of devices) { - const query = queries[userId] || {}; - queries[userId] = query; - query[deviceId] = keyAlgorithm; - } - const content = { one_time_keys: queries }; - if (timeout) { - content.timeout = timeout; - } - const path = "/keys/claim"; - return this.http.authedRequest(http_api_1.Method.Post, path, undefined, 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) { - const qps = { - from: oldToken, - to: newToken, - }; - return this.http.authedRequest(http_api_1.Method.Get, "/keys/changes", qps); - } - uploadDeviceSigningKeys(auth, keys) { - // API returns empty object - const data = Object.assign({}, keys); - if (auth) - Object.assign(data, { auth }); - return this.http.authedRequest(http_api_1.Method.Post, "/keys/device_signing/upload", undefined, data, { - prefix: http_api_1.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"); - } - const uri = this.http.getUrl("/account/register", undefined, http_api_1.IdentityPrefix.V2, this.idBaseUrl); - return this.http.requestOtherUrl(http_api_1.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) { - const params = { - client_secret: clientSecret, - email: email, - send_attempt: sendAttempt === null || sendAttempt === void 0 ? void 0 : sendAttempt.toString(), - }; - if (nextLink) { - params.next_link = nextLink; - } - return this.http.idServerRequest(http_api_1.Method.Post, "/validate/email/requestToken", params, http_api_1.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) { - const 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(http_api_1.Method.Post, "/validate/msisdn/requestToken", params, http_api_1.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 enetered by the user. - * @param identityAccessToken - The `access_token` field of the Identity - * Server `/account/register` response (see {@link registerWithIdentityServer}). - * - * @returns Promise which resolves: Object, currently with no parameters. - * @returns Rejects: with an error response. - * @throws Error if No identity server is set - */ - submitMsisdnToken(sid, clientSecret, msisdnToken, identityAccessToken) { - // TODO: Types - const params = { - sid: sid, - client_secret: clientSecret, - token: msisdnToken, - }; - return this.http.idServerRequest(http_api_1.Method.Post, "/validate/msisdn/submitToken", params, http_api_1.IdentityPrefix.V2, identityAccessToken); - } - /** - * 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 enetered by the user. - * - * @returns Promise which resolves: Object, currently with no parameters. - * @returns Rejects: with an error response. - */ - submitMsisdnTokenOtherUrl(url, sid, clientSecret, msisdnToken) { - // TODO: Types - const params = { - sid: sid, - client_secret: clientSecret, - token: msisdnToken, - }; - return this.http.requestOtherUrl(http_api_1.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) { - // TODO: Types - return this.http.idServerRequest(http_api_1.Method.Get, "/hash_details", undefined, http_api_1.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) { - return __awaiter(this, void 0, void 0, function* () { - const params = { - // addresses: ["email@example.org", "10005550000"], - // algorithm: "sha256", - // pepper: "abc123" - }; - // Get hash information first before trying to do a lookup - const hashes = yield this.getIdentityHashDetails(identityAccessToken); - if (!hashes || !hashes["lookup_pepper"] || !hashes["algorithms"]) { - throw new Error("Unsupported identity server: bad response"); - } - params["pepper"] = hashes["lookup_pepper"]; - const localMapping = { - // hashed identifier => plain text address - // For use in this function's return format - }; - // When picking an algorithm, we pick the hashed over no hashes - if (hashes["algorithms"].includes("sha256")) { - // Abuse the olm hashing - const olmutil = new global.Olm.Utility(); - params["addresses"] = addressPairs.map((p) => { - const addr = p[0].toLowerCase(); // lowercase to get consistent hashes - const med = p[1].toLowerCase(); - const hashed = olmutil - .sha256(`${addr} ${med} ${params["pepper"]}`) - .replace(/\+/g, "-") - .replace(/\//g, "_"); // URL-safe base64 - // Map the hash to a known (case-sensitive) address. We use the case - // sensitive version because the caller might be expecting that. - localMapping[hashed] = p[0]; - return hashed; - }); - params["algorithm"] = "sha256"; - } - else if (hashes["algorithms"].includes("none")) { - params["addresses"] = addressPairs.map((p) => { - const addr = p[0].toLowerCase(); // lowercase to get consistent hashes - const med = p[1].toLowerCase(); - const unhashed = `${addr} ${med}`; - // Map the unhashed values to a known (case-sensitive) address. We use - // the case-sensitive version because the caller might be expecting that. - localMapping[unhashed] = p[0]; - return unhashed; - }); - params["algorithm"] = "none"; - } - else { - throw new Error("Unsupported identity server: unknown hash algorithm"); - } - const response = yield this.http.idServerRequest(http_api_1.Method.Post, "/lookup", params, http_api_1.IdentityPrefix.V2, identityAccessToken); - if (!(response === null || response === void 0 ? void 0 : response["mappings"])) - return []; // no results - const foundAddresses = []; - for (const hashed of Object.keys(response["mappings"])) { - const mxid = response["mappings"][hashed]; - const 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) { - return __awaiter(this, void 0, void 0, function* () { - // TODO: Types - // Note: we're using the V2 API by calling this function, but our - // function contract requires a V1 response. We therefore have to - // convert it manually. - const response = yield this.identityHashedLookup([[address, medium]], identityAccessToken); - const result = response.find((p) => p.address === address); - if (!result) { - return {}; - } - const mapping = { - address, - medium, - mxid: result.mxid, - // We can't reasonably fill these parameters: - // not_before - // not_after - // ts - // signatures - }; - return mapping; - }); - } - /** - * 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) { - return __awaiter(this, void 0, void 0, function* () { - // TODO: Types - // Note: we're using the V2 API by calling this function, but our - // function contract requires a V1 response. We therefore have to - // convert it manually. - const response = yield this.identityHashedLookup( - // We have to reverse the query order to get [address, medium] pairs - query.map((p) => [p[1], p[0]]), identityAccessToken); - const v1results = []; - for (const mapping of response) { - const 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, - ]); - } - 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) { - // TODO: Types - return this.http.idServerRequest(http_api_1.Method.Get, "/account", undefined, http_api_1.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) { - const path = utils.encodeUri("/sendToDevice/$eventType/$txnId", { - $eventType: eventType, - $txnId: txnId ? txnId : this.makeTxnId(), - }); - const body = { - messages: utils.recursiveMapToObject(contentMap), - }; - const targets = new Map(); - for (const [userId, deviceMessages] of contentMap) { - targets.set(userId, Array.from(deviceMessages.keys())); - } - logger_1.logger.log(`PUT ${path}`, targets); - return this.http.authedRequest(http_api_1.Method.Put, path, undefined, body); - } - /** - * 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(http_api_1.Method.Get, "/thirdparty/protocols") - .then((response) => { - // sanity check - if (!response || typeof response !== "object") { - throw new Error(`/thirdparty/protocols did not return an object: ${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) { - const path = utils.encodeUri("/thirdparty/location/$protocol", { - $protocol: protocol, - }); - return this.http.authedRequest(http_api_1.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) { - // TODO: Types - const path = utils.encodeUri("/thirdparty/user/$protocol", { - $protocol: protocol, - }); - return this.http.authedRequest(http_api_1.Method.Get, path, params); - } - getTerms(serviceType, baseUrl) { - // TODO: Types - const url = this.termsUrlForService(serviceType, baseUrl); - return this.http.requestOtherUrl(http_api_1.Method.Get, url); - } - agreeToTerms(serviceType, baseUrl, accessToken, termsUrls) { - const url = this.termsUrlForService(serviceType, baseUrl); - const headers = { - Authorization: "Bearer " + accessToken, - }; - return this.http.requestOtherUrl(http_api_1.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) { - const path = utils.encodeUri("/rooms/$roomId/report/$eventId", { - $roomId: roomId, - $eventId: eventId, - }); - return this.http.authedRequest(http_api_1.Method.Post, path, undefined, { score, reason }); - } - /** - * Fetches or paginates a room hierarchy as 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, suggestedOnly = false, fromToken) { - const path = utils.encodeUri("/rooms/$roomId/hierarchy", { - $roomId: roomId, - }); - const 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(http_api_1.Method.Get, path, queryParams, undefined, { - prefix: http_api_1.ClientPrefix.V1, - }) - .catch((e) => { - if (e.errcode === "M_UNRECOGNIZED") { - // fall back to the prefixed hierarchy API. - return this.http.authedRequest(http_api_1.Method.Get, path, queryParams, undefined, { - 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) { - return __awaiter(this, void 0, void 0, function* () { - const { room_id: roomId } = yield this.createRoom({ - name: name, - preset: partials_1.Preset.PrivateChat, - power_level_content_override: Object.assign(Object.assign({}, MSC3089TreeSpace_1.DEFAULT_TREE_POWER_LEVELS_TEMPLATE), { users: { - [this.getUserId()]: 100, - } }), - creation_content: { - [event_2.RoomCreateTypeField]: event_2.RoomType.Space, - }, - initial_state: [ - { - type: event_2.UNSTABLE_MSC3088_PURPOSE.name, - state_key: event_2.UNSTABLE_MSC3089_TREE_SUBTYPE.name, - content: { - [event_2.UNSTABLE_MSC3088_ENABLED.name]: true, - }, - }, - { - type: event_2.EventType.RoomEncryption, - state_key: "", - content: { - algorithm: olmlib.MEGOLM_ALGORITHM, - }, - }, - ], - }); - return new MSC3089TreeSpace_1.MSC3089TreeSpace(this, 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 _a, _b; - const room = this.getRoom(roomId); - if ((room === null || room === void 0 ? void 0 : room.getMyMembership()) !== "join") - return null; - const createEvent = room.currentState.getStateEvents(event_2.EventType.RoomCreate, ""); - const purposeEvent = room.currentState.getStateEvents(event_2.UNSTABLE_MSC3088_PURPOSE.name, event_2.UNSTABLE_MSC3089_TREE_SUBTYPE.name); - if (!createEvent) - throw new Error("Expected single room create event"); - if (!((_a = purposeEvent === null || purposeEvent === void 0 ? void 0 : purposeEvent.getContent()) === null || _a === void 0 ? void 0 : _a[event_2.UNSTABLE_MSC3088_ENABLED.name])) - return null; - if (((_b = createEvent.getContent()) === null || _b === void 0 ? void 0 : _b[event_2.RoomCreateTypeField]) !== event_2.RoomType.Space) - return null; - return new MSC3089TreeSpace_1.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) { - const qps = {}; - if (req.pos) { - qps.pos = req.pos; - delete req.pos; - } - if (req.timeout) { - qps.timeout = req.timeout; - delete req.timeout; - } - const clientTimeout = req.clientTimeout; - delete req.clientTimeout; - return this.http.authedRequest(http_api_1.Method.Post, "/sync", qps, req, { - prefix: "/_matrix/client/unstable/org.matrix.msc3575", - baseUrl: proxyBaseUrl, - localTimeoutMs: clientTimeout, - abortSignal, - }); - } - /** - * @deprecated use supportsThreads() instead - */ - supportsExperimentalThreads() { - var _a; - logger_1.logger.warn(`supportsExperimentalThreads() is deprecated, use supportThreads() instead`); - return ((_a = this.clientOpts) === null || _a === void 0 ? void 0 : _a.experimentalThreadSupport) || false; - } - /** - * A helper to determine thread support - * @returns a boolean to determine if threads are enabled - */ - supportsThreads() { - var _a; - return ((_a = this.clientOpts) === null || _a === void 0 ? void 0 : _a.threadSupport) || false; - } - /** - * A helper to determine intentional mentions support - * @returns a boolean to determine if intentional mentions are enabled - * @experimental - */ - supportsIntentionalMentions() { - var _a; - return ((_a = this.clientOpts) === null || _a === void 0 ? void 0 : _a.intentionalMentions) || false; - } - /** - * 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) { - return __awaiter(this, void 0, void 0, function* () { - const path = utils.encodeUri("/rooms/$roomid/summary", { $roomid: roomIdOrAlias }); - return this.http.authedRequest(http_api_1.Method.Get, path, { via }, undefined, { - prefix: "/_matrix/client/unstable/im.nheko.summary", - }); - }); - } - /** - * 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) { - 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 ? 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() { - return __awaiter(this, void 0, void 0, function* () { - return this.http.authedRequest(http_api_1.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) { - return __awaiter(this, void 0, void 0, function* () { - const path = utils.encodeUri("/rooms/$roomId/timestamp_to_event", { - $roomId: roomId, - }); - const queryParams = { - ts: timestamp.toString(), - dir: dir, - }; - try { - return yield this.http.authedRequest(http_api_1.Method.Get, path, queryParams, undefined, { - prefix: http_api_1.ClientPrefix.V1, - }); - } - catch (err) { - // Fallback to the prefixed unstable endpoint. Since the stable endpoint is - // new, we should also try the unstable endpoint before giving up. We can - // remove this fallback request in a year (remove after 2023-11-28). - if (err.errcode === "M_UNRECOGNIZED" && - // XXX: The 400 status code check should be removed in the future - // when Synapse is compliant with MSC3743. - (err.httpStatus === 400 || - // This the correct standard status code for an unsupported - // endpoint according to MSC3743. Not Found and Method Not Allowed - // both indicate that this endpoint+verb combination is - // not supported. - err.httpStatus === 404 || - err.httpStatus === 405)) { - return yield this.http.authedRequest(http_api_1.Method.Get, path, queryParams, undefined, { - prefix: "/_matrix/client/unstable/org.matrix.msc3030", - }); - } - throw err; - } - }); - } -} -exports.MatrixClient = MatrixClient; -MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY = "RESTORE_BACKUP_ERROR_BAD_KEY"; -/** - * 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 _a, _b; - const ourUserId = cli.getUserId(); - const eventId = event.getId(); - const room = cli.getRoom(event.getRoomId()); - if (!room || !ourUserId || !eventId) - return; - const oldActions = event.getPushActions(); - const actions = cli.getPushActionsForEvent(event, true); - const isThreadEvent = !!event.threadRootId && !event.isThreadRoot; - const currentHighlightCount = room.getUnreadCountForEventContext(room_1.NotificationCountType.Highlight, event); - // Ensure the unread counts are kept up to date if the event is encrypted - // We also want to make sure that the notification count goes up if we already - // have encrypted events to avoid other code from resetting 'highlight' to zero. - const oldHighlight = !!((_a = oldActions === null || oldActions === void 0 ? void 0 : oldActions.tweaks) === null || _a === void 0 ? void 0 : _a.highlight); - const newHighlight = !!((_b = actions === null || actions === void 0 ? void 0 : actions.tweaks) === null || _b === void 0 ? void 0 : _b.highlight); - let hasReadEvent; - if (isThreadEvent) { - const thread = room.getThread(event.threadRootId); - hasReadEvent = thread - ? thread.hasUserReadEvent(ourUserId, eventId) - : // If the thread object does not exist in the room yet, we don't - // want to calculate notification for this event yet. We have not - // restored the read receipts yet and can't accurately calculate - // notifications at this stage. - // - // This issue can likely go away when MSC3874 is implemented - true; - } - else { - hasReadEvent = room.hasUserReadEvent(ourUserId, eventId); - } - if (hasReadEvent) { - // If the event has been read, ignore it. - return; - } - if (oldHighlight !== newHighlight || currentHighlightCount > 0) { - // TODO: Handle mentions received while the client is offline - // See also https://github.com/vector-im/element-web/issues/9069 - let newCount = currentHighlightCount; - if (newHighlight && !oldHighlight) - newCount++; - if (!newHighlight && oldHighlight) - newCount--; - if (isThreadEvent) { - room.setThreadUnreadNotificationCount(event.threadRootId, room_1.NotificationCountType.Highlight, newCount); - } - else { - room.setUnreadNotificationCount(room_1.NotificationCountType.Highlight, newCount); - } - } - // Total count is used to typically increment a room notification counter, but not loudly highlight it. - const currentTotalCount = room.getUnreadCountForEventContext(room_1.NotificationCountType.Total, event); - // `notify` is used in practice for incrementing the total count - const newNotify = !!(actions === null || actions === void 0 ? void 0 : actions.notify); - // The room total count is NEVER incremented by the server for encrypted rooms. We basically ignore - // the server here as it's always going to tell us to increment for encrypted events. - if (newNotify) { - if (isThreadEvent) { - room.setThreadUnreadNotificationCount(event.threadRootId, room_1.NotificationCountType.Total, currentTotalCount + 1); - } - else { - room.setUnreadNotificationCount(room_1.NotificationCountType.Total, currentTotalCount + 1); - } - } -} -exports.fixNotificationCountOnDecryption = fixNotificationCountOnDecryption; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"./@types/PushRules":304,"./@types/beacon":305,"./@types/event":306,"./@types/partials":309,"./@types/read_receipts":311,"./@types/search":313,"./NamespacedValue":316,"./ReEmitter":317,"./ToDeviceMessageQueue":318,"./autodiscovery":319,"./content-helpers":322,"./content-repo":323,"./crypto":341,"./crypto/RoomList":329,"./crypto/api":336,"./crypto/backup":337,"./crypto/dehydration":339,"./crypto/key_passphrase":342,"./crypto/olmlib":343,"./crypto/recoverykey":344,"./event-mapper":360,"./feature":362,"./filter":364,"./http-api":367,"./logger":374,"./models/MSC3089TreeSpace":377,"./models/event":383,"./models/event-timeline":382,"./models/invites-ignorer":384,"./models/room":392,"./models/room-member":389,"./models/search-result":393,"./models/thread":394,"./models/typed-event-emitter":395,"./models/user":396,"./pushprocessor":397,"./randomstring":398,"./rust-crypto":402,"./rust-crypto/constants":401,"./service-types":405,"./sliding-sync-sdk":406,"./store/stub":412,"./sync":414,"./utils":416,"./webrtc/call":418,"./webrtc/callEventHandler":419,"./webrtc/groupCall":422,"./webrtc/groupCallEventHandler":423,"./webrtc/mediaHandler":424}],322:[function(require,module,exports){ -"use strict"; -/* -Copyright 2018 - 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.parseBeaconContent = exports.makeBeaconContent = exports.parseBeaconInfoContent = exports.makeBeaconInfoContent = exports.parseTopicContent = exports.makeTopicContent = exports.parseLocationEvent = exports.makeLocationContent = exports.getTextForLocationEvent = exports.makeEmoteMessage = exports.makeNotice = exports.makeTextMessage = exports.makeHtmlEmote = exports.makeHtmlNotice = exports.makeHtmlMessage = void 0; -const event_1 = require("./@types/event"); -const extensible_events_1 = require("./@types/extensible_events"); -const utilities_1 = require("./extensible_events_v1/utilities"); -const location_1 = require("./@types/location"); -const topic_1 = require("./@types/topic"); -/** - * 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: event_1.MsgType.Text, - format: "org.matrix.custom.html", - body: body, - formatted_body: htmlBody, - }; -} -exports.makeHtmlMessage = makeHtmlMessage; -/** - * 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: event_1.MsgType.Notice, - format: "org.matrix.custom.html", - body: body, - formatted_body: htmlBody, - }; -} -exports.makeHtmlNotice = makeHtmlNotice; -/** - * 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: event_1.MsgType.Emote, - format: "org.matrix.custom.html", - body: body, - formatted_body: htmlBody, - }; -} -exports.makeHtmlEmote = makeHtmlEmote; -/** - * Generates the content for a Plaintext Message event - * @param body - the plaintext body of the emote - * @returns - */ -function makeTextMessage(body) { - return { - msgtype: event_1.MsgType.Text, - body: body, - }; -} -exports.makeTextMessage = makeTextMessage; -/** - * Generates the content for a Plaintext Notice event - * @param body - the plaintext body of the notice - * @returns - */ -function makeNotice(body) { - return { - msgtype: event_1.MsgType.Notice, - body: body, - }; -} -exports.makeNotice = makeNotice; -/** - * Generates the content for a Plaintext Emote event - * @param body - the plaintext body of the emote - * @returns - */ -function makeEmoteMessage(body) { - return { - msgtype: event_1.MsgType.Emote, - body: body, - }; -} -exports.makeEmoteMessage = makeEmoteMessage; -/** Location content helpers */ -const getTextForLocationEvent = (uri, assetType, timestamp, description) => { - const date = `at ${new Date(timestamp).toISOString()}`; - const assetName = assetType === location_1.LocationAssetType.Self ? "User" : undefined; - const quotedDescription = description ? `"${description}"` : undefined; - return [assetName, "Location", quotedDescription, uri, date].filter(Boolean).join(" "); -}; -exports.getTextForLocationEvent = getTextForLocationEvent; -/** - * Generates the content for a Location event - * @param uri - a geo:// uri for the location - * @param timestamp - the timestamp when the location was correct (milliseconds since the UNIX epoch) - * @param description - the (optional) label for this location on the map - * @param assetType - the (optional) asset type of this location e.g. "m.self" - * @param text - optional. A text for the location - */ -const makeLocationContent = ( -// this is first but optional -// to avoid a breaking change -text, uri, timestamp, description, assetType) => { - const defaultedText = text !== null && text !== void 0 ? text : (0, exports.getTextForLocationEvent)(uri, assetType || location_1.LocationAssetType.Self, timestamp, description); - const timestampEvent = timestamp ? { [location_1.M_TIMESTAMP.name]: timestamp } : {}; - return Object.assign({ msgtype: event_1.MsgType.Location, body: defaultedText, geo_uri: uri, [location_1.M_LOCATION.name]: { - description, - uri, - }, [location_1.M_ASSET.name]: { - type: assetType || location_1.LocationAssetType.Self, - }, [extensible_events_1.M_TEXT.name]: defaultedText }, timestampEvent); -}; -exports.makeLocationContent = makeLocationContent; -/** - * Parse location event content and transform to - * a backwards compatible modern m.location event format - */ -const parseLocationEvent = (wireEventContent) => { - var _a, _b; - const location = location_1.M_LOCATION.findIn(wireEventContent); - const asset = location_1.M_ASSET.findIn(wireEventContent); - const timestamp = location_1.M_TIMESTAMP.findIn(wireEventContent); - const text = extensible_events_1.M_TEXT.findIn(wireEventContent); - const geoUri = (_a = location === null || location === void 0 ? void 0 : location.uri) !== null && _a !== void 0 ? _a : wireEventContent === null || wireEventContent === void 0 ? void 0 : wireEventContent.geo_uri; - const description = location === null || location === void 0 ? void 0 : location.description; - const assetType = (_b = asset === null || asset === void 0 ? void 0 : asset.type) !== null && _b !== void 0 ? _b : location_1.LocationAssetType.Self; - const fallbackText = text !== null && text !== void 0 ? text : wireEventContent.body; - return (0, exports.makeLocationContent)(fallbackText, geoUri, timestamp !== null && timestamp !== void 0 ? timestamp : undefined, description, assetType); -}; -exports.parseLocationEvent = parseLocationEvent; -const makeTopicContent = (topic, htmlTopic) => { - const renderings = [{ body: topic, mimetype: "text/plain" }]; - if ((0, utilities_1.isProvided)(htmlTopic)) { - renderings.push({ body: htmlTopic, mimetype: "text/html" }); - } - return { topic, [topic_1.M_TOPIC.name]: renderings }; -}; -exports.makeTopicContent = makeTopicContent; -const parseTopicContent = (content) => { - var _a, _b, _c; - const mtopic = topic_1.M_TOPIC.findIn(content); - if (!Array.isArray(mtopic)) { - return { text: content.topic }; - } - const text = (_b = (_a = mtopic === null || mtopic === void 0 ? void 0 : mtopic.find((r) => !(0, utilities_1.isProvided)(r.mimetype) || r.mimetype === "text/plain")) === null || _a === void 0 ? void 0 : _a.body) !== null && _b !== void 0 ? _b : content.topic; - const html = (_c = mtopic === null || mtopic === void 0 ? void 0 : mtopic.find((r) => r.mimetype === "text/html")) === null || _c === void 0 ? void 0 : _c.body; - return { text, html }; -}; -exports.parseTopicContent = parseTopicContent; -const makeBeaconInfoContent = (timeout, isLive, description, assetType, timestamp) => ({ - description, - timeout, - live: isLive, - [location_1.M_TIMESTAMP.name]: timestamp || Date.now(), - [location_1.M_ASSET.name]: { - type: assetType !== null && assetType !== void 0 ? assetType : location_1.LocationAssetType.Self, - }, -}); -exports.makeBeaconInfoContent = makeBeaconInfoContent; -/** - * Flatten beacon info event content - */ -const parseBeaconInfoContent = (content) => { - var _a; - const { description, timeout, live } = content; - const timestamp = (_a = location_1.M_TIMESTAMP.findIn(content)) !== null && _a !== void 0 ? _a : undefined; - const asset = location_1.M_ASSET.findIn(content); - return { - description, - timeout, - live, - assetType: asset === null || asset === void 0 ? void 0 : asset.type, - timestamp, - }; -}; -exports.parseBeaconInfoContent = parseBeaconInfoContent; -const makeBeaconContent = (uri, timestamp, beaconInfoEventId, description) => ({ - [location_1.M_LOCATION.name]: { - description, - uri, - }, - [location_1.M_TIMESTAMP.name]: timestamp, - "m.relates_to": { - rel_type: extensible_events_1.REFERENCE_RELATION.name, - event_id: beaconInfoEventId, - }, -}); -exports.makeBeaconContent = makeBeaconContent; -const parseBeaconContent = (content) => { - var _a; - const location = location_1.M_LOCATION.findIn(content); - const timestamp = (_a = location_1.M_TIMESTAMP.findIn(content)) !== null && _a !== void 0 ? _a : undefined; - return { - description: location === null || location === void 0 ? void 0 : location.description, - uri: location === null || location === void 0 ? void 0 : location.uri, - timestamp, - }; -}; -exports.parseBeaconContent = parseBeaconContent; - -},{"./@types/event":306,"./@types/extensible_events":307,"./@types/location":308,"./@types/topic":315,"./extensible_events_v1/utilities":361}],323:[function(require,module,exports){ -"use strict"; -/* -Copyright 2015 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getHttpUriForMxc = void 0; -const utils = __importStar(require("./utils")); -/** - * 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. - * @returns The complete URL to the content. - */ -function getHttpUriForMxc(baseUrl, mxc, width, height, resizeMethod, allowDirectLinks = false) { - if (typeof mxc !== "string" || !mxc) { - return ""; - } - if (mxc.indexOf("mxc://") !== 0) { - if (allowDirectLinks) { - return mxc; - } - else { - return ""; - } - } - let serverAndMediaId = mxc.slice(6); // strips mxc:// - let prefix = "/_matrix/media/r0/download/"; - const params = {}; - if (width) { - params["width"] = Math.round(width).toString(); - } - if (height) { - params["height"] = Math.round(height).toString(); - } - if (resizeMethod) { - params["method"] = resizeMethod; - } - if (Object.keys(params).length > 0) { - // these are thumbnailing params so they probably want the - // thumbnailing API... - prefix = "/_matrix/media/r0/thumbnail/"; - } - const fragmentOffset = serverAndMediaId.indexOf("#"); - let fragment = ""; - if (fragmentOffset >= 0) { - fragment = serverAndMediaId.slice(fragmentOffset); - serverAndMediaId = serverAndMediaId.slice(0, fragmentOffset); - } - const urlParams = Object.keys(params).length === 0 ? "" : "?" + utils.encodeParams(params); - return baseUrl + prefix + serverAndMediaId + urlParams + fragment; -} -exports.getHttpUriForMxc = getHttpUriForMxc; - -},{"./utils":416}],324:[function(require,module,exports){ -(function (global,Buffer){(function (){ -"use strict"; -/* -Copyright 2019 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.requestKeysDuringVerification = exports.createCryptoStoreCacheCallbacks = exports.DeviceTrustLevel = exports.UserTrustLevel = exports.CrossSigningLevel = exports.CrossSigningInfo = void 0; -const olmlib_1 = require("./olmlib"); -const logger_1 = require("../logger"); -const indexeddb_crypto_store_1 = require("../crypto/store/indexeddb-crypto-store"); -const aes_1 = require("./aes"); -const KEY_REQUEST_TIMEOUT_MS = 1000 * 60; -function publicKeyFromKeyInfo(keyInfo) { - // `keys` is an object with { [`ed25519:${pubKey}`]: pubKey } - // We assume only a single key, and we want the bare form without type - // prefix, so we select the values. - return Object.values(keyInfo.keys)[0]; -} -class CrossSigningInfo { - /** - * Information about a user's cross-signing keys - * - * @param userId - the user that the information is about - * @param callbacks - Callbacks used to interact with the app - * Requires getCrossSigningKey and saveCrossSigningKeys - * @param cacheCallbacks - Callbacks used to interact with the cache - */ - constructor(userId, callbacks = {}, cacheCallbacks = {}) { - this.userId = userId; - this.callbacks = callbacks; - this.cacheCallbacks = cacheCallbacks; - this.keys = {}; - this.firstUse = true; - // This tracks whether we've ever verified this user with any identity. - // When you verify a user, any devices online at the time that receive - // the verifying signature via the homeserver will latch this to true - // and can use it in the future to detect cases where the user has - // become unverified later for any reason. - this.crossSigningVerifiedBefore = false; - } - static fromStorage(obj, userId) { - const res = new CrossSigningInfo(userId); - for (const prop in obj) { - if (obj.hasOwnProperty(prop)) { - // @ts-ignore - ts doesn't like this and nor should we - res[prop] = obj[prop]; - } - } - return res; - } - toStorage() { - return { - keys: this.keys, - firstUse: this.firstUse, - crossSigningVerifiedBefore: this.crossSigningVerifiedBefore, - }; - } - /** - * Calls the app callback to ask for a private key - * - * @param type - The key type ("master", "self_signing", or "user_signing") - * @param expectedPubkey - The matching public key or undefined to use - * the stored public key for the given key type. - * @returns An array with [ public key, Olm.PkSigning ] - */ - getCrossSigningKey(type, expectedPubkey) { - return __awaiter(this, void 0, void 0, function* () { - const shouldCache = ["master", "self_signing", "user_signing"].indexOf(type) >= 0; - if (!this.callbacks.getCrossSigningKey) { - throw new Error("No getCrossSigningKey callback supplied"); - } - if (expectedPubkey === undefined) { - expectedPubkey = this.getId(type); - } - function validateKey(key) { - if (!key) - return; - const signing = new global.Olm.PkSigning(); - const gotPubkey = signing.init_with_seed(key); - if (gotPubkey === expectedPubkey) { - return [gotPubkey, signing]; - } - signing.free(); - } - let privkey = null; - if (this.cacheCallbacks.getCrossSigningKeyCache && shouldCache) { - privkey = yield this.cacheCallbacks.getCrossSigningKeyCache(type, expectedPubkey); - } - const cacheresult = validateKey(privkey); - if (cacheresult) { - return cacheresult; - } - privkey = yield this.callbacks.getCrossSigningKey(type, expectedPubkey); - const result = validateKey(privkey); - if (result) { - if (this.cacheCallbacks.storeCrossSigningKeyCache && shouldCache) { - yield this.cacheCallbacks.storeCrossSigningKeyCache(type, privkey); - } - return result; - } - /* No keysource even returned a key */ - if (!privkey) { - throw new Error("getCrossSigningKey callback for " + type + " returned falsey"); - } - /* We got some keys from the keysource, but none of them were valid */ - throw new Error("Key type " + type + " from getCrossSigningKey callback did not match"); - }); - } - /** - * Check whether the private keys exist in secret storage. - * XXX: This could be static, be we often seem to have an instance when we - * want to know this anyway... - * - * @param secretStorage - The secret store using account data - * @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 - */ - isStoredInSecretStorage(secretStorage) { - return __awaiter(this, void 0, void 0, function* () { - // check what SSSS keys have encrypted the master key (if any) - const stored = (yield secretStorage.isStored("m.cross_signing.master")) || {}; - // then check which of those SSSS keys have also encrypted the SSK and USK - function intersect(s) { - for (const k of Object.keys(stored)) { - if (!s[k]) { - delete stored[k]; - } - } - } - for (const type of ["self_signing", "user_signing"]) { - intersect((yield secretStorage.isStored(`m.cross_signing.${type}`)) || {}); - } - return Object.keys(stored).length ? stored : null; - }); - } - /** - * Store private keys in secret storage for use by other devices. This is - * typically called in conjunction with the creation of new cross-signing - * keys. - * - * @param keys - The keys to store - * @param secretStorage - The secret store using account data - */ - static storeInSecretStorage(keys, secretStorage) { - return __awaiter(this, void 0, void 0, function* () { - for (const [type, privateKey] of keys) { - const encodedKey = (0, olmlib_1.encodeBase64)(privateKey); - yield secretStorage.store(`m.cross_signing.${type}`, encodedKey); - } - }); - } - /** - * Get private keys from secret storage created by some other device. This - * also passes the private keys to the app-specific callback. - * - * @param type - The type of key to get. One of "master", - * "self_signing", or "user_signing". - * @param secretStorage - The secret store using account data - * @returns The private key - */ - static getFromSecretStorage(type, secretStorage) { - return __awaiter(this, void 0, void 0, function* () { - const encodedKey = yield secretStorage.get(`m.cross_signing.${type}`); - if (!encodedKey) { - return null; - } - return (0, olmlib_1.decodeBase64)(encodedKey); - }); - } - /** - * Check whether the private keys exist in the local key cache. - * - * @param type - The type of key to get. One of "master", - * "self_signing", or "user_signing". Optional, will check all by default. - * @returns True if all keys are stored in the local cache. - */ - isStoredInKeyCache(type) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const cacheCallbacks = this.cacheCallbacks; - if (!cacheCallbacks) - return false; - const types = type ? [type] : ["master", "self_signing", "user_signing"]; - for (const t of types) { - if (!(yield ((_a = cacheCallbacks.getCrossSigningKeyCache) === null || _a === void 0 ? void 0 : _a.call(cacheCallbacks, t)))) { - return false; - } - } - return true; - }); - } - /** - * Get cross-signing private keys from the local cache. - * - * @returns A map from key type (string) to private key (Uint8Array) - */ - getCrossSigningKeysFromCache() { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const keys = new Map(); - const cacheCallbacks = this.cacheCallbacks; - if (!cacheCallbacks) - return keys; - for (const type of ["master", "self_signing", "user_signing"]) { - const privKey = yield ((_a = cacheCallbacks.getCrossSigningKeyCache) === null || _a === void 0 ? void 0 : _a.call(cacheCallbacks, type)); - if (!privKey) { - continue; - } - keys.set(type, privKey); - } - return keys; - }); - } - /** - * Get the ID used to identify the user. This can also be used to test for - * the existence of a given key type. - * - * @param type - The type of key to get the ID of. One of "master", - * "self_signing", or "user_signing". Defaults to "master". - * - * @returns the ID - */ - getId(type = "master") { - if (!this.keys[type]) - return null; - const keyInfo = this.keys[type]; - return publicKeyFromKeyInfo(keyInfo); - } - /** - * Create new cross-signing keys for the given key types. The public keys - * will be held in this class, while the private keys are passed off to the - * `saveCrossSigningKeys` application callback. - * - * @param level - The key types to reset - */ - resetKeys(level) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.callbacks.saveCrossSigningKeys) { - throw new Error("No saveCrossSigningKeys callback supplied"); - } - // If we're resetting the master key, we reset all keys - if (level === undefined || level & CrossSigningLevel.MASTER || !this.keys.master) { - level = CrossSigningLevel.MASTER | CrossSigningLevel.USER_SIGNING | CrossSigningLevel.SELF_SIGNING; - } - else if (level === 0) { - return; - } - const privateKeys = {}; - const keys = {}; - let masterSigning; - let masterPub; - try { - if (level & CrossSigningLevel.MASTER) { - masterSigning = new global.Olm.PkSigning(); - privateKeys.master = masterSigning.generate_seed(); - masterPub = masterSigning.init_with_seed(privateKeys.master); - keys.master = { - user_id: this.userId, - usage: ["master"], - keys: { - ["ed25519:" + masterPub]: masterPub, - }, - }; - } - else { - [masterPub, masterSigning] = yield this.getCrossSigningKey("master"); - } - if (level & CrossSigningLevel.SELF_SIGNING) { - const sskSigning = new global.Olm.PkSigning(); - try { - privateKeys.self_signing = sskSigning.generate_seed(); - const sskPub = sskSigning.init_with_seed(privateKeys.self_signing); - keys.self_signing = { - user_id: this.userId, - usage: ["self_signing"], - keys: { - ["ed25519:" + sskPub]: sskPub, - }, - }; - (0, olmlib_1.pkSign)(keys.self_signing, masterSigning, this.userId, masterPub); - } - finally { - sskSigning.free(); - } - } - if (level & CrossSigningLevel.USER_SIGNING) { - const uskSigning = new global.Olm.PkSigning(); - try { - privateKeys.user_signing = uskSigning.generate_seed(); - const uskPub = uskSigning.init_with_seed(privateKeys.user_signing); - keys.user_signing = { - user_id: this.userId, - usage: ["user_signing"], - keys: { - ["ed25519:" + uskPub]: uskPub, - }, - }; - (0, olmlib_1.pkSign)(keys.user_signing, masterSigning, this.userId, masterPub); - } - finally { - uskSigning.free(); - } - } - Object.assign(this.keys, keys); - this.callbacks.saveCrossSigningKeys(privateKeys); - } - finally { - if (masterSigning) { - masterSigning.free(); - } - } - }); - } - /** - * unsets the keys, used when another session has reset the keys, to disable cross-signing - */ - clearKeys() { - this.keys = {}; - } - setKeys(keys) { - const signingKeys = {}; - if (keys.master) { - if (keys.master.user_id !== this.userId) { - const error = "Mismatched user ID " + keys.master.user_id + " in master key from " + this.userId; - logger_1.logger.error(error); - throw new Error(error); - } - if (!this.keys.master) { - // this is the first key we've seen, so first-use is true - this.firstUse = true; - } - else if (publicKeyFromKeyInfo(keys.master) !== this.getId()) { - // this is a different key, so first-use is false - this.firstUse = false; - } // otherwise, same key, so no change - signingKeys.master = keys.master; - } - else if (this.keys.master) { - signingKeys.master = this.keys.master; - } - else { - throw new Error("Tried to set cross-signing keys without a master key"); - } - const masterKey = publicKeyFromKeyInfo(signingKeys.master); - // verify signatures - if (keys.user_signing) { - if (keys.user_signing.user_id !== this.userId) { - const error = "Mismatched user ID " + keys.master.user_id + " in user_signing key from " + this.userId; - logger_1.logger.error(error); - throw new Error(error); - } - try { - (0, olmlib_1.pkVerify)(keys.user_signing, masterKey, this.userId); - } - catch (e) { - logger_1.logger.error("invalid signature on user-signing key"); - // FIXME: what do we want to do here? - throw e; - } - } - if (keys.self_signing) { - if (keys.self_signing.user_id !== this.userId) { - const error = "Mismatched user ID " + keys.master.user_id + " in self_signing key from " + this.userId; - logger_1.logger.error(error); - throw new Error(error); - } - try { - (0, olmlib_1.pkVerify)(keys.self_signing, masterKey, this.userId); - } - catch (e) { - logger_1.logger.error("invalid signature on self-signing key"); - // FIXME: what do we want to do here? - throw e; - } - } - // if everything checks out, then save the keys - if (keys.master) { - this.keys.master = keys.master; - // if the master key is set, then the old self-signing and user-signing keys are obsolete - delete this.keys["self_signing"]; - delete this.keys["user_signing"]; - } - if (keys.self_signing) { - this.keys.self_signing = keys.self_signing; - } - if (keys.user_signing) { - this.keys.user_signing = keys.user_signing; - } - } - updateCrossSigningVerifiedBefore(isCrossSigningVerified) { - // It is critical that this value latches forward from false to true but - // never back to false to avoid a downgrade attack. - if (!this.crossSigningVerifiedBefore && isCrossSigningVerified) { - this.crossSigningVerifiedBefore = true; - } - } - signObject(data, type) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.keys[type]) { - throw new Error("Attempted to sign with " + type + " key but no such key present"); - } - const [pubkey, signing] = yield this.getCrossSigningKey(type); - try { - (0, olmlib_1.pkSign)(data, signing, this.userId, pubkey); - return data; - } - finally { - signing.free(); - } - }); - } - signUser(key) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.keys.user_signing) { - logger_1.logger.info("No user signing key: not signing user"); - return; - } - return this.signObject(key.keys.master, "user_signing"); - }); - } - signDevice(userId, device) { - return __awaiter(this, void 0, void 0, function* () { - if (userId !== this.userId) { - throw new Error(`Trying to sign ${userId}'s device; can only sign our own device`); - } - if (!this.keys.self_signing) { - logger_1.logger.info("No self signing key: not signing device"); - return; - } - return this.signObject({ - algorithms: device.algorithms, - keys: device.keys, - device_id: device.deviceId, - user_id: userId, - }, "self_signing"); - }); - } - /** - * Check whether a given user is trusted. - * - * @param userCrossSigning - Cross signing info for user - * - * @returns - */ - checkUserTrust(userCrossSigning) { - // if we're checking our own key, then it's trusted if the master key - // and self-signing key match - if (this.userId === userCrossSigning.userId && - this.getId() && - this.getId() === userCrossSigning.getId() && - this.getId("self_signing") && - this.getId("self_signing") === userCrossSigning.getId("self_signing")) { - return new UserTrustLevel(true, true, this.firstUse); - } - if (!this.keys.user_signing) { - // If there's no user signing key, they can't possibly be verified. - // They may be TOFU trusted though. - return new UserTrustLevel(false, false, userCrossSigning.firstUse); - } - let userTrusted; - const userMaster = userCrossSigning.keys.master; - const uskId = this.getId("user_signing"); - try { - (0, olmlib_1.pkVerify)(userMaster, uskId, this.userId); - userTrusted = true; - } - catch (e) { - userTrusted = false; - } - return new UserTrustLevel(userTrusted, userCrossSigning.crossSigningVerifiedBefore, userCrossSigning.firstUse); - } - /** - * Check whether a given device is trusted. - * - * @param userCrossSigning - Cross signing info for user - * @param device - The device to check - * @param localTrust - Whether the device is trusted locally - * @param trustCrossSignedDevices - Whether we trust cross signed devices - * - * @returns - */ - checkDeviceTrust(userCrossSigning, device, localTrust, trustCrossSignedDevices) { - const userTrust = this.checkUserTrust(userCrossSigning); - const userSSK = userCrossSigning.keys.self_signing; - if (!userSSK) { - // if the user has no self-signing key then we cannot make any - // trust assertions about this device from cross-signing - return new DeviceTrustLevel(false, false, localTrust, trustCrossSignedDevices); - } - const deviceObj = deviceToObject(device, userCrossSigning.userId); - try { - // if we can verify the user's SSK from their master key... - (0, olmlib_1.pkVerify)(userSSK, userCrossSigning.getId(), userCrossSigning.userId); - // ...and this device's key from their SSK... - (0, olmlib_1.pkVerify)(deviceObj, publicKeyFromKeyInfo(userSSK), userCrossSigning.userId); - // ...then we trust this device as much as far as we trust the user - return DeviceTrustLevel.fromUserTrustLevel(userTrust, localTrust, trustCrossSignedDevices); - } - catch (e) { - return new DeviceTrustLevel(false, false, localTrust, trustCrossSignedDevices); - } - } - /** - * @returns Cache callbacks - */ - getCacheCallbacks() { - return this.cacheCallbacks; - } -} -exports.CrossSigningInfo = CrossSigningInfo; -function deviceToObject(device, userId) { - return { - algorithms: device.algorithms, - keys: device.keys, - device_id: device.deviceId, - user_id: userId, - signatures: device.signatures, - }; -} -var CrossSigningLevel; -(function (CrossSigningLevel) { - CrossSigningLevel[CrossSigningLevel["MASTER"] = 4] = "MASTER"; - CrossSigningLevel[CrossSigningLevel["USER_SIGNING"] = 2] = "USER_SIGNING"; - CrossSigningLevel[CrossSigningLevel["SELF_SIGNING"] = 1] = "SELF_SIGNING"; -})(CrossSigningLevel = exports.CrossSigningLevel || (exports.CrossSigningLevel = {})); -/** - * Represents the ways in which we trust a user - */ -class UserTrustLevel { - constructor(crossSigningVerified, crossSigningVerifiedBefore, tofu) { - this.crossSigningVerified = crossSigningVerified; - this.crossSigningVerifiedBefore = crossSigningVerifiedBefore; - this.tofu = tofu; - } - /** - * @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 - */ - isTofu() { - return this.tofu; - } -} -exports.UserTrustLevel = UserTrustLevel; -/** - * Represents the ways in which we trust a device - */ -class DeviceTrustLevel { - constructor(crossSigningVerified, tofu, localVerified, trustCrossSignedDevices) { - this.crossSigningVerified = crossSigningVerified; - this.tofu = tofu; - this.localVerified = localVerified; - this.trustCrossSignedDevices = trustCrossSignedDevices; - } - static fromUserTrustLevel(userTrustLevel, localVerified, trustCrossSignedDevices) { - return new DeviceTrustLevel(userTrustLevel.isCrossSigningVerified(), userTrustLevel.isTofu(), localVerified, trustCrossSignedDevices); - } - /** - * @returns true if this device is verified via any means - */ - isVerified() { - return Boolean(this.isLocallyVerified() || (this.trustCrossSignedDevices && this.isCrossSigningVerified())); - } - /** - * @returns true if this device is verified via cross signing - */ - isCrossSigningVerified() { - return this.crossSigningVerified; - } - /** - * @returns true if this device is verified locally - */ - isLocallyVerified() { - return this.localVerified; - } - /** - * @returns true if this device is trusted from a user's key - * that is trusted on first use - */ - isTofu() { - return this.tofu; - } -} -exports.DeviceTrustLevel = DeviceTrustLevel; -function createCryptoStoreCacheCallbacks(store, olmDevice) { - return { - getCrossSigningKeyCache: function (type, _expectedPublicKey) { - return __awaiter(this, void 0, void 0, function* () { - const key = yield new Promise((resolve) => { - return store.doTxn("readonly", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { - store.getSecretStorePrivateKey(txn, resolve, type); - }); - }); - if (key && key.ciphertext) { - const pickleKey = Buffer.from(olmDevice.pickleKey); - const decrypted = yield (0, aes_1.decryptAES)(key, pickleKey, type); - return (0, olmlib_1.decodeBase64)(decrypted); - } - else { - return key; - } - }); - }, - storeCrossSigningKeyCache: function (type, key) { - return __awaiter(this, void 0, void 0, function* () { - if (!(key instanceof Uint8Array)) { - throw new Error(`storeCrossSigningKeyCache expects Uint8Array, got ${key}`); - } - const pickleKey = Buffer.from(olmDevice.pickleKey); - const encryptedKey = yield (0, aes_1.encryptAES)((0, olmlib_1.encodeBase64)(key), pickleKey, type); - return store.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { - store.storeSecretStorePrivateKey(txn, type, encryptedKey); - }); - }); - }, - }; -} -exports.createCryptoStoreCacheCallbacks = createCryptoStoreCacheCallbacks; -/** - * Request cross-signing keys from another device during verification. - * - * @param baseApis - base Matrix API interface - * @param userId - The user ID being verified - * @param deviceId - The device ID being verified - */ -function requestKeysDuringVerification(baseApis, userId, deviceId) { - return __awaiter(this, void 0, void 0, function* () { - // If this is a self-verification, ask the other party for keys - if (baseApis.getUserId() !== userId) { - return; - } - logger_1.logger.log("Cross-signing: Self-verification done; requesting keys"); - // This happens asynchronously, and we're not concerned about waiting for - // it. We return here in order to test. - return new Promise((resolve, reject) => { - const client = baseApis; - const original = client.crypto.crossSigningInfo; - // We already have all of the infrastructure we need to validate and - // cache cross-signing keys, so instead of replicating that, here we set - // up callbacks that request them from the other device and call - // CrossSigningInfo.getCrossSigningKey() to validate/cache - const crossSigning = new CrossSigningInfo(original.userId, { - getCrossSigningKey: (type) => __awaiter(this, void 0, void 0, function* () { - logger_1.logger.debug("Cross-signing: requesting secret", type, deviceId); - const { promise } = client.requestSecret(`m.cross_signing.${type}`, [deviceId]); - const result = yield promise; - const decoded = (0, olmlib_1.decodeBase64)(result); - return Uint8Array.from(decoded); - }), - }, original.getCacheCallbacks()); - crossSigning.keys = original.keys; - // XXX: get all keys out if we get one key out - // https://github.com/vector-im/element-web/issues/12604 - // then change here to reject on the timeout - // Requests can be ignored, so don't wait around forever - const timeout = new Promise((resolve) => { - setTimeout(resolve, KEY_REQUEST_TIMEOUT_MS, new Error("Timeout")); - }); - // also request and cache the key backup key - const backupKeyPromise = (() => __awaiter(this, void 0, void 0, function* () { - const cachedKey = yield client.crypto.getSessionBackupPrivateKey(); - if (!cachedKey) { - logger_1.logger.info("No cached backup key found. Requesting..."); - const secretReq = client.requestSecret("m.megolm_backup.v1", [deviceId]); - const base64Key = yield secretReq.promise; - logger_1.logger.info("Got key backup key, decoding..."); - const decodedKey = (0, olmlib_1.decodeBase64)(base64Key); - logger_1.logger.info("Decoded backup key, storing..."); - yield client.crypto.storeSessionBackupPrivateKey(Uint8Array.from(decodedKey)); - logger_1.logger.info("Backup key stored. Starting backup restore..."); - const backupInfo = yield client.getKeyBackupVersion(); - // no need to await for this - just let it go in the bg - client.restoreKeyBackupWithCache(undefined, undefined, backupInfo).then(() => { - logger_1.logger.info("Backup restored."); - }); - } - }))(); - // We call getCrossSigningKey() for its side-effects - return Promise.race([ - Promise.all([ - crossSigning.getCrossSigningKey("master"), - crossSigning.getCrossSigningKey("self_signing"), - crossSigning.getCrossSigningKey("user_signing"), - backupKeyPromise, - ]), - timeout, - ]).then(resolve, reject); - }).catch((e) => { - logger_1.logger.warn("Cross-signing: failure while requesting keys:", e); - }); - }); -} -exports.requestKeysDuringVerification = requestKeysDuringVerification; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) - -},{"../crypto/store/indexeddb-crypto-store":346,"../logger":374,"./aes":331,"./olmlib":343,"buffer":68}],325:[function(require,module,exports){ -"use strict"; -/* -Copyright 2017 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DeviceList = exports.TrackingStatus = void 0; -/** - * Manages the list of other users' devices - */ -const logger_1 = require("../logger"); -const deviceinfo_1 = require("./deviceinfo"); -const CrossSigning_1 = require("./CrossSigning"); -const olmlib = __importStar(require("./olmlib")); -const indexeddb_crypto_store_1 = require("./store/indexeddb-crypto-store"); -const utils_1 = require("../utils"); -const typed_event_emitter_1 = require("../models/typed-event-emitter"); -const index_1 = require("./index"); -/* State transition diagram for DeviceList.deviceTrackingStatus - * - * | - * stopTrackingDeviceList V - * +---------------------> NOT_TRACKED - * | | - * +<--------------------+ | startTrackingDeviceList - * | | V - * | +-------------> PENDING_DOWNLOAD <--------------------+-+ - * | | ^ | | | - * | | restart download | | start download | | invalidateUserDeviceList - * | | client failed | | | | - * | | | V | | - * | +------------ DOWNLOAD_IN_PROGRESS -------------------+ | - * | | | | - * +<-------------------+ | download successful | - * ^ V | - * +----------------------- UP_TO_DATE ------------------------+ - */ -// constants for DeviceList.deviceTrackingStatus -var TrackingStatus; -(function (TrackingStatus) { - TrackingStatus[TrackingStatus["NotTracked"] = 0] = "NotTracked"; - TrackingStatus[TrackingStatus["PendingDownload"] = 1] = "PendingDownload"; - TrackingStatus[TrackingStatus["DownloadInProgress"] = 2] = "DownloadInProgress"; - TrackingStatus[TrackingStatus["UpToDate"] = 3] = "UpToDate"; -})(TrackingStatus = exports.TrackingStatus || (exports.TrackingStatus = {})); -class DeviceList extends typed_event_emitter_1.TypedEventEmitter { - constructor(baseApis, cryptoStore, olmDevice, - // Maximum number of user IDs per request to prevent server overload (#1619) - keyDownloadChunkSize = 250) { - super(); - this.cryptoStore = cryptoStore; - this.keyDownloadChunkSize = keyDownloadChunkSize; - this.devices = {}; - this.crossSigningInfo = {}; - // map of identity keys to the user who owns it - this.userByIdentityKey = {}; - // which users we are tracking device status for. - this.deviceTrackingStatus = {}; // loaded from storage in load() - // The 'next_batch' sync token at the point the data was written, - // ie. a token representing the point immediately after the - // moment represented by the snapshot in the db. - this.syncToken = null; - this.keyDownloadsInProgressByUser = new Map(); - // Set whenever changes are made other than setting the sync token - this.dirty = false; - // Promise resolved when device data is saved - this.savePromise = null; - // Function that resolves the save promise - this.resolveSavePromise = null; - // The time the save is scheduled for - this.savePromiseTime = null; - // The timer used to delay the save - this.saveTimer = null; - // True if we have fetched data from the server or loaded a non-empty - // set of device data from the store - this.hasFetched = null; - this.serialiser = new DeviceListUpdateSerialiser(baseApis, olmDevice, this); - } - /** - * Load the device tracking state from storage - */ - load() { - return __awaiter(this, void 0, void 0, function* () { - yield this.cryptoStore.doTxn("readonly", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_DEVICE_DATA], (txn) => { - this.cryptoStore.getEndToEndDeviceData(txn, (deviceData) => { - var _a; - this.hasFetched = Boolean(deviceData && deviceData.devices); - this.devices = deviceData ? deviceData.devices : {}; - this.crossSigningInfo = deviceData ? deviceData.crossSigningInfo || {} : {}; - this.deviceTrackingStatus = deviceData ? deviceData.trackingStatus : {}; - this.syncToken = (_a = deviceData === null || deviceData === void 0 ? void 0 : deviceData.syncToken) !== null && _a !== void 0 ? _a : null; - this.userByIdentityKey = {}; - for (const user of Object.keys(this.devices)) { - const userDevices = this.devices[user]; - for (const device of Object.keys(userDevices)) { - const idKey = userDevices[device].keys["curve25519:" + device]; - if (idKey !== undefined) { - this.userByIdentityKey[idKey] = user; - } - } - } - }); - }); - for (const u of Object.keys(this.deviceTrackingStatus)) { - // if a download was in progress when we got shut down, it isn't any more. - if (this.deviceTrackingStatus[u] == TrackingStatus.DownloadInProgress) { - this.deviceTrackingStatus[u] = TrackingStatus.PendingDownload; - } - } - }); - } - stop() { - if (this.saveTimer !== null) { - clearTimeout(this.saveTimer); - } - } - /** - * Save the device tracking state to storage, if any changes are - * pending other than updating the sync token - * - * The actual save will be delayed by a short amount of time to - * aggregate multiple writes to the database. - * - * @param delay - Time in ms before which the save actually happens. - * By default, the save is delayed for a short period in order to batch - * multiple writes, but this behaviour can be disabled by passing 0. - * - * @returns true if the data was saved, false if - * it was not (eg. because no changes were pending). The promise - * will only resolve once the data is saved, so may take some time - * to resolve. - */ - saveIfDirty(delay = 500) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.dirty) - return Promise.resolve(false); - // Delay saves for a bit so we can aggregate multiple saves that happen - // in quick succession (eg. when a whole room's devices are marked as known) - const targetTime = Date.now() + delay; - if (this.savePromiseTime && targetTime < this.savePromiseTime) { - // There's a save scheduled but for after we would like: cancel - // it & schedule one for the time we want - clearTimeout(this.saveTimer); - this.saveTimer = null; - this.savePromiseTime = null; - // (but keep the save promise since whatever called save before - // will still want to know when the save is done) - } - let savePromise = this.savePromise; - if (savePromise === null) { - savePromise = new Promise((resolve) => { - this.resolveSavePromise = resolve; - }); - this.savePromise = savePromise; - } - if (this.saveTimer === null) { - const resolveSavePromise = this.resolveSavePromise; - this.savePromiseTime = targetTime; - this.saveTimer = setTimeout(() => { - logger_1.logger.log("Saving device tracking data", this.syncToken); - // null out savePromise now (after the delay but before the write), - // otherwise we could return the existing promise when the save has - // actually already happened. - this.savePromiseTime = null; - this.saveTimer = null; - this.savePromise = null; - this.resolveSavePromise = null; - this.cryptoStore - .doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_DEVICE_DATA], (txn) => { - var _a; - this.cryptoStore.storeEndToEndDeviceData({ - devices: this.devices, - crossSigningInfo: this.crossSigningInfo, - trackingStatus: this.deviceTrackingStatus, - syncToken: (_a = this.syncToken) !== null && _a !== void 0 ? _a : undefined, - }, txn); - }) - .then(() => { - // The device list is considered dirty until the write completes. - this.dirty = false; - resolveSavePromise === null || resolveSavePromise === void 0 ? void 0 : resolveSavePromise(true); - }, (err) => { - logger_1.logger.error("Failed to save device tracking data", this.syncToken); - logger_1.logger.error(err); - }); - }, delay); - } - return savePromise; - }); - } - /** - * Gets the sync token last set with setSyncToken - * - * @returns The sync token - */ - getSyncToken() { - return this.syncToken; - } - /** - * Sets the sync token that the app will pass as the 'since' to the /sync - * endpoint next time it syncs. - * The sync token must always be set after any changes made as a result of - * data in that sync since setting the sync token to a newer one will mean - * those changed will not be synced from the server if a new client starts - * up with that data. - * - * @param st - The sync token - */ - setSyncToken(st) { - this.syncToken = st; - } - /** - * Ensures up to date keys for a list of users are stored in the session store, - * downloading and storing them if they're not (or if forceDownload is - * true). - * @param userIds - The users to fetch. - * @param forceDownload - Always download the keys even if cached. - * - * @returns A promise which resolves to a map userId-\>deviceId-\>{@link DeviceInfo}. - */ - downloadKeys(userIds, forceDownload) { - const usersToDownload = []; - const promises = []; - userIds.forEach((u) => { - const trackingStatus = this.deviceTrackingStatus[u]; - if (this.keyDownloadsInProgressByUser.has(u)) { - // already a key download in progress/queued for this user; its results - // will be good enough for us. - logger_1.logger.log(`downloadKeys: already have a download in progress for ` + `${u}: awaiting its result`); - promises.push(this.keyDownloadsInProgressByUser.get(u)); - } - else if (forceDownload || trackingStatus != TrackingStatus.UpToDate) { - usersToDownload.push(u); - } - }); - if (usersToDownload.length != 0) { - logger_1.logger.log("downloadKeys: downloading for", usersToDownload); - const downloadPromise = this.doKeyDownload(usersToDownload); - promises.push(downloadPromise); - } - if (promises.length === 0) { - logger_1.logger.log("downloadKeys: already have all necessary keys"); - } - return Promise.all(promises).then(() => { - return this.getDevicesFromStore(userIds); - }); - } - /** - * Get the stored device keys for a list of user ids - * - * @param userIds - the list of users to list keys for. - * - * @returns userId-\>deviceId-\>{@link DeviceInfo}. - */ - getDevicesFromStore(userIds) { - const stored = new Map(); - userIds.forEach((userId) => { - var _a; - const deviceMap = new Map(); - (_a = this.getStoredDevicesForUser(userId)) === null || _a === void 0 ? void 0 : _a.forEach(function (device) { - deviceMap.set(device.deviceId, device); - }); - stored.set(userId, deviceMap); - }); - return stored; - } - /** - * Returns a list of all user IDs the DeviceList knows about - * - * @returns All known user IDs - */ - getKnownUserIds() { - return Object.keys(this.devices); - } - /** - * Get the stored device keys for a user id - * - * @param userId - the user to list keys for. - * - * @returns list of devices, or null if we haven't - * managed to get a list of devices for this user yet. - */ - getStoredDevicesForUser(userId) { - const devs = this.devices[userId]; - if (!devs) { - return null; - } - const res = []; - for (const deviceId in devs) { - if (devs.hasOwnProperty(deviceId)) { - res.push(deviceinfo_1.DeviceInfo.fromStorage(devs[deviceId], deviceId)); - } - } - return res; - } - /** - * Get the stored device data for a user, in raw object form - * - * @param userId - the user to get data for - * - * @returns `deviceId->{object}` devices, or undefined if - * there is no data for this user. - */ - getRawStoredDevicesForUser(userId) { - return this.devices[userId]; - } - getStoredCrossSigningForUser(userId) { - if (!this.crossSigningInfo[userId]) - return null; - return CrossSigning_1.CrossSigningInfo.fromStorage(this.crossSigningInfo[userId], userId); - } - storeCrossSigningForUser(userId, info) { - this.crossSigningInfo[userId] = info; - this.dirty = true; - } - /** - * Get the stored keys for a single device - * - * - * @returns device, or undefined - * if we don't know about this device - */ - getStoredDevice(userId, deviceId) { - const devs = this.devices[userId]; - if (!(devs === null || devs === void 0 ? void 0 : devs[deviceId])) { - return undefined; - } - return deviceinfo_1.DeviceInfo.fromStorage(devs[deviceId], deviceId); - } - /** - * Get a user ID by one of their device's curve25519 identity key - * - * @param algorithm - encryption algorithm - * @param senderKey - curve25519 key to match - * - * @returns user ID - */ - getUserByIdentityKey(algorithm, senderKey) { - if (algorithm !== olmlib.OLM_ALGORITHM && algorithm !== olmlib.MEGOLM_ALGORITHM) { - // we only deal in olm keys - return null; - } - return this.userByIdentityKey[senderKey]; - } - /** - * Find a device by curve25519 identity key - * - * @param algorithm - encryption algorithm - * @param senderKey - curve25519 key to match - */ - getDeviceByIdentityKey(algorithm, senderKey) { - const userId = this.getUserByIdentityKey(algorithm, senderKey); - if (!userId) { - return null; - } - const devices = this.devices[userId]; - if (!devices) { - return null; - } - for (const deviceId in devices) { - if (!devices.hasOwnProperty(deviceId)) { - continue; - } - const device = devices[deviceId]; - for (const keyId in device.keys) { - if (!device.keys.hasOwnProperty(keyId)) { - continue; - } - if (keyId.indexOf("curve25519:") !== 0) { - continue; - } - const deviceKey = device.keys[keyId]; - if (deviceKey == senderKey) { - return deviceinfo_1.DeviceInfo.fromStorage(device, deviceId); - } - } - } - // doesn't match a known device - return null; - } - /** - * Replaces the list of devices for a user with the given device list - * - * @param userId - The user ID - * @param devices - New device info for user - */ - storeDevicesForUser(userId, devices) { - this.setRawStoredDevicesForUser(userId, devices); - this.dirty = true; - } - /** - * flag the given user for device-list tracking, if they are not already. - * - * This will mean that a subsequent call to refreshOutdatedDeviceLists() - * will download the device list for the user, and that subsequent calls to - * invalidateUserDeviceList will trigger more updates. - * - */ - startTrackingDeviceList(userId) { - // sanity-check the userId. This is mostly paranoia, but if synapse - // can't parse the userId we give it as an mxid, it 500s the whole - // request and we can never update the device lists again (because - // the broken userId is always 'invalid' and always included in any - // refresh request). - // By checking it is at least a string, we can eliminate a class of - // silly errors. - if (typeof userId !== "string") { - throw new Error("userId must be a string; was " + userId); - } - if (!this.deviceTrackingStatus[userId]) { - logger_1.logger.log("Now tracking device list for " + userId); - this.deviceTrackingStatus[userId] = TrackingStatus.PendingDownload; - // we don't yet persist the tracking status, since there may be a lot - // of calls; we save all data together once the sync is done - this.dirty = true; - } - } - /** - * Mark the given user as no longer being tracked for device-list updates. - * - * This won't affect any in-progress downloads, which will still go on to - * complete; it will just mean that we don't think that we have an up-to-date - * list for future calls to downloadKeys. - * - */ - stopTrackingDeviceList(userId) { - if (this.deviceTrackingStatus[userId]) { - logger_1.logger.log("No longer tracking device list for " + userId); - this.deviceTrackingStatus[userId] = TrackingStatus.NotTracked; - // we don't yet persist the tracking status, since there may be a lot - // of calls; we save all data together once the sync is done - this.dirty = true; - } - } - /** - * Set all users we're currently tracking to untracked - * - * This will flag each user whose devices we are tracking as in need of an - * update. - */ - stopTrackingAllDeviceLists() { - for (const userId of Object.keys(this.deviceTrackingStatus)) { - this.deviceTrackingStatus[userId] = TrackingStatus.NotTracked; - } - this.dirty = true; - } - /** - * Mark the cached device list for the given user outdated. - * - * If we are not tracking this user's devices, we'll do nothing. Otherwise - * we flag the user as needing an update. - * - * This doesn't actually set off an update, so that several users can be - * batched together. Call refreshOutdatedDeviceLists() for that. - * - */ - invalidateUserDeviceList(userId) { - if (this.deviceTrackingStatus[userId]) { - logger_1.logger.log("Marking device list outdated for", userId); - this.deviceTrackingStatus[userId] = TrackingStatus.PendingDownload; - // we don't yet persist the tracking status, since there may be a lot - // of calls; we save all data together once the sync is done - this.dirty = true; - } - } - /** - * If we have users who have outdated device lists, start key downloads for them - * - * @returns which completes when the download completes; normally there - * is no need to wait for this (it's mostly for the unit tests). - */ - refreshOutdatedDeviceLists() { - this.saveIfDirty(); - const usersToDownload = []; - for (const userId of Object.keys(this.deviceTrackingStatus)) { - const stat = this.deviceTrackingStatus[userId]; - if (stat == TrackingStatus.PendingDownload) { - usersToDownload.push(userId); - } - } - return this.doKeyDownload(usersToDownload); - } - /** - * Set the stored device data for a user, in raw object form - * Used only by internal class DeviceListUpdateSerialiser - * - * @param userId - the user to get data for - * - * @param devices - `deviceId->{object}` the new devices - */ - setRawStoredDevicesForUser(userId, devices) { - // remove old devices from userByIdentityKey - if (this.devices[userId] !== undefined) { - for (const [deviceId, dev] of Object.entries(this.devices[userId])) { - const identityKey = dev.keys["curve25519:" + deviceId]; - delete this.userByIdentityKey[identityKey]; - } - } - this.devices[userId] = devices; - // add new devices into userByIdentityKey - for (const [deviceId, dev] of Object.entries(devices)) { - const identityKey = dev.keys["curve25519:" + deviceId]; - this.userByIdentityKey[identityKey] = userId; - } - } - setRawStoredCrossSigningForUser(userId, info) { - this.crossSigningInfo[userId] = info; - } - /** - * Fire off download update requests for the given users, and update the - * device list tracking status for them, and the - * keyDownloadsInProgressByUser map for them. - * - * @param users - list of userIds - * - * @returns resolves when all the users listed have - * been updated. rejects if there was a problem updating any of the - * users. - */ - doKeyDownload(users) { - if (users.length === 0) { - // nothing to do - return Promise.resolve(); - } - const prom = this.serialiser.updateDevicesForUsers(users, this.syncToken).then(() => { - finished(true); - }, (e) => { - logger_1.logger.error("Error downloading keys for " + users + ":", e); - finished(false); - throw e; - }); - users.forEach((u) => { - this.keyDownloadsInProgressByUser.set(u, prom); - const stat = this.deviceTrackingStatus[u]; - if (stat == TrackingStatus.PendingDownload) { - this.deviceTrackingStatus[u] = TrackingStatus.DownloadInProgress; - } - }); - const finished = (success) => { - this.emit(index_1.CryptoEvent.WillUpdateDevices, users, !this.hasFetched); - users.forEach((u) => { - this.dirty = true; - // we may have queued up another download request for this user - // since we started this request. If that happens, we should - // ignore the completion of the first one. - if (this.keyDownloadsInProgressByUser.get(u) !== prom) { - logger_1.logger.log("Another update in the queue for", u, "- not marking up-to-date"); - return; - } - this.keyDownloadsInProgressByUser.delete(u); - const stat = this.deviceTrackingStatus[u]; - if (stat == TrackingStatus.DownloadInProgress) { - if (success) { - // we didn't get any new invalidations since this download started: - // this user's device list is now up to date. - this.deviceTrackingStatus[u] = TrackingStatus.UpToDate; - logger_1.logger.log("Device list for", u, "now up to date"); - } - else { - this.deviceTrackingStatus[u] = TrackingStatus.PendingDownload; - } - } - }); - this.saveIfDirty(); - this.emit(index_1.CryptoEvent.DevicesUpdated, users, !this.hasFetched); - this.hasFetched = true; - }; - return prom; - } -} -exports.DeviceList = DeviceList; -/** - * Serialises updates to device lists - * - * Ensures that results from /keys/query are not overwritten if a second call - * completes *before* an earlier one. - * - * It currently does this by ensuring only one call to /keys/query happens at a - * time (and queuing other requests up). - */ -class DeviceListUpdateSerialiser { - /* - * @param baseApis - Base API object - * @param olmDevice - The Olm Device - * @param deviceList - The device list object, the device list to be updated - */ - constructor(baseApis, olmDevice, deviceList) { - this.baseApis = baseApis; - this.olmDevice = olmDevice; - this.deviceList = deviceList; - this.downloadInProgress = false; - // users which are queued for download - // userId -> true - this.keyDownloadsQueuedByUser = {}; - } - /** - * Make a key query request for the given users - * - * @param users - list of user ids - * - * @param syncToken - sync token to pass in the query request, to - * help the HS give the most recent results - * - * @returns resolves when all the users listed have - * been updated. rejects if there was a problem updating any of the - * users. - */ - updateDevicesForUsers(users, syncToken) { - users.forEach((u) => { - this.keyDownloadsQueuedByUser[u] = true; - }); - if (!this.queuedQueryDeferred) { - this.queuedQueryDeferred = (0, utils_1.defer)(); - } - // We always take the new sync token and just use the latest one we've - // been given, since it just needs to be at least as recent as the - // sync response the device invalidation message arrived in - this.syncToken = syncToken; - if (this.downloadInProgress) { - // just queue up these users - logger_1.logger.log("Queued key download for", users); - return this.queuedQueryDeferred.promise; - } - // start a new download. - return this.doQueuedQueries(); - } - doQueuedQueries() { - if (this.downloadInProgress) { - throw new Error("DeviceListUpdateSerialiser.doQueuedQueries called with request active"); - } - const downloadUsers = Object.keys(this.keyDownloadsQueuedByUser); - this.keyDownloadsQueuedByUser = {}; - const deferred = this.queuedQueryDeferred; - this.queuedQueryDeferred = undefined; - logger_1.logger.log("Starting key download for", downloadUsers); - this.downloadInProgress = true; - const opts = {}; - if (this.syncToken) { - opts.token = this.syncToken; - } - const factories = []; - for (let i = 0; i < downloadUsers.length; i += this.deviceList.keyDownloadChunkSize) { - const userSlice = downloadUsers.slice(i, i + this.deviceList.keyDownloadChunkSize); - factories.push(() => this.baseApis.downloadKeysForUsers(userSlice, opts)); - } - (0, utils_1.chunkPromises)(factories, 3) - .then((responses) => __awaiter(this, void 0, void 0, function* () { - const dk = Object.assign({}, ...responses.map((res) => res.device_keys || {})); - const masterKeys = Object.assign({}, ...responses.map((res) => res.master_keys || {})); - const ssks = Object.assign({}, ...responses.map((res) => res.self_signing_keys || {})); - const usks = Object.assign({}, ...responses.map((res) => res.user_signing_keys || {})); - // yield to other things that want to execute in between users, to - // avoid wedging the CPU - // (https://github.com/vector-im/element-web/issues/3158) - // - // of course we ought to do this in a web worker or similar, but - // this serves as an easy solution for now. - for (const userId of downloadUsers) { - yield (0, utils_1.sleep)(5); - try { - yield this.processQueryResponseForUser(userId, dk[userId], { - master: masterKeys === null || masterKeys === void 0 ? void 0 : masterKeys[userId], - self_signing: ssks === null || ssks === void 0 ? void 0 : ssks[userId], - user_signing: usks === null || usks === void 0 ? void 0 : usks[userId], - }); - } - catch (e) { - // log the error but continue, so that one bad key - // doesn't kill the whole process - logger_1.logger.error(`Error processing keys for ${userId}:`, e); - } - } - })) - .then(() => { - logger_1.logger.log("Completed key download for " + downloadUsers); - this.downloadInProgress = false; - deferred === null || deferred === void 0 ? void 0 : deferred.resolve(); - // if we have queued users, fire off another request. - if (this.queuedQueryDeferred) { - this.doQueuedQueries(); - } - }, (e) => { - logger_1.logger.warn("Error downloading keys for " + downloadUsers + ":", e); - this.downloadInProgress = false; - deferred === null || deferred === void 0 ? void 0 : deferred.reject(e); - }); - return deferred.promise; - } - processQueryResponseForUser(userId, dkResponse, crossSigningResponse) { - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.log("got device keys for " + userId + ":", dkResponse); - logger_1.logger.log("got cross-signing keys for " + userId + ":", crossSigningResponse); - { - // map from deviceid -> deviceinfo for this user - const userStore = {}; - const devs = this.deviceList.getRawStoredDevicesForUser(userId); - if (devs) { - Object.keys(devs).forEach((deviceId) => { - const d = deviceinfo_1.DeviceInfo.fromStorage(devs[deviceId], deviceId); - userStore[deviceId] = d; - }); - } - yield updateStoredDeviceKeysForUser(this.olmDevice, userId, userStore, dkResponse || {}, this.baseApis.getUserId(), this.baseApis.deviceId); - // put the updates into the object that will be returned as our results - const storage = {}; - Object.keys(userStore).forEach((deviceId) => { - storage[deviceId] = userStore[deviceId].toStorage(); - }); - this.deviceList.setRawStoredDevicesForUser(userId, storage); - } - // now do the same for the cross-signing keys - { - // FIXME: should we be ignoring empty cross-signing responses, or - // should we be dropping the keys? - if (crossSigningResponse && - (crossSigningResponse.master || crossSigningResponse.self_signing || crossSigningResponse.user_signing)) { - const crossSigning = this.deviceList.getStoredCrossSigningForUser(userId) || new CrossSigning_1.CrossSigningInfo(userId); - crossSigning.setKeys(crossSigningResponse); - this.deviceList.setRawStoredCrossSigningForUser(userId, crossSigning.toStorage()); - // NB. Unlike most events in the js-sdk, this one is internal to the - // js-sdk and is not re-emitted - this.deviceList.emit(index_1.CryptoEvent.UserCrossSigningUpdated, userId); - } - } - }); - } -} -function updateStoredDeviceKeysForUser(olmDevice, userId, userStore, userResult, localUserId, localDeviceId) { - return __awaiter(this, void 0, void 0, function* () { - let updated = false; - // remove any devices in the store which aren't in the response - for (const deviceId in userStore) { - if (!userStore.hasOwnProperty(deviceId)) { - continue; - } - if (!(deviceId in userResult)) { - if (userId === localUserId && deviceId === localDeviceId) { - logger_1.logger.warn(`Local device ${deviceId} missing from sync, skipping removal`); - continue; - } - logger_1.logger.log("Device " + userId + ":" + deviceId + " has been removed"); - delete userStore[deviceId]; - updated = true; - } - } - for (const deviceId in userResult) { - if (!userResult.hasOwnProperty(deviceId)) { - continue; - } - const deviceResult = userResult[deviceId]; - // check that the user_id and device_id in the response object are - // correct - if (deviceResult.user_id !== userId) { - logger_1.logger.warn("Mismatched user_id " + deviceResult.user_id + " in keys from " + userId + ":" + deviceId); - continue; - } - if (deviceResult.device_id !== deviceId) { - logger_1.logger.warn("Mismatched device_id " + deviceResult.device_id + " in keys from " + userId + ":" + deviceId); - continue; - } - if (yield storeDeviceKeys(olmDevice, userStore, deviceResult)) { - updated = true; - } - } - return updated; - }); -} -/* - * Process a device in a /query response, and add it to the userStore - * - * returns (a promise for) true if a change was made, else false - */ -function storeDeviceKeys(olmDevice, userStore, deviceResult) { - return __awaiter(this, void 0, void 0, function* () { - if (!deviceResult.keys) { - // no keys? - return false; - } - const deviceId = deviceResult.device_id; - const userId = deviceResult.user_id; - const signKeyId = "ed25519:" + deviceId; - const signKey = deviceResult.keys[signKeyId]; - if (!signKey) { - logger_1.logger.warn("Device " + userId + ":" + deviceId + " has no ed25519 key"); - return false; - } - const unsigned = deviceResult.unsigned || {}; - const signatures = deviceResult.signatures || {}; - try { - yield olmlib.verifySignature(olmDevice, deviceResult, userId, deviceId, signKey); - } - catch (e) { - logger_1.logger.warn("Unable to verify signature on device " + userId + ":" + deviceId + ":" + e); - return false; - } - // DeviceInfo - let deviceStore; - if (deviceId in userStore) { - // already have this device. - deviceStore = userStore[deviceId]; - if (deviceStore.getFingerprint() != signKey) { - // this should only happen if the list has been MITMed; we are - // best off sticking with the original keys. - // - // Should we warn the user about it somehow? - logger_1.logger.warn("Ed25519 key for device " + userId + ":" + deviceId + " has changed"); - return false; - } - } - else { - userStore[deviceId] = deviceStore = new deviceinfo_1.DeviceInfo(deviceId); - } - deviceStore.keys = deviceResult.keys || {}; - deviceStore.algorithms = deviceResult.algorithms || []; - deviceStore.unsigned = unsigned; - deviceStore.signatures = signatures; - return true; - }); -} - -},{"../logger":374,"../models/typed-event-emitter":395,"../utils":416,"./CrossSigning":324,"./deviceinfo":340,"./index":341,"./olmlib":343,"./store/indexeddb-crypto-store":346}],326:[function(require,module,exports){ -"use strict"; -/* -Copyright 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.EncryptionSetupOperation = exports.EncryptionSetupBuilder = void 0; -const logger_1 = require("../logger"); -const event_1 = require("../models/event"); -const CrossSigning_1 = require("./CrossSigning"); -const indexeddb_crypto_store_1 = require("./store/indexeddb-crypto-store"); -const http_api_1 = require("../http-api"); -const client_1 = require("../client"); -const typed_event_emitter_1 = require("../models/typed-event-emitter"); -/** - * Builds an EncryptionSetupOperation by calling any of the add.. methods. - * Once done, `buildOperation()` can be called which allows to apply to operation. - * - * This is used as a helper by Crypto to keep track of all the network requests - * and other side-effects of bootstrapping, so it can be applied in one go (and retried in the future) - * Also keeps track of all the private keys created during bootstrapping, so we don't need to prompt for them - * more than once. - */ -class EncryptionSetupBuilder { - /** - * @param accountData - pre-existing account data, will only be read, not written. - * @param delegateCryptoCallbacks - crypto callbacks to delegate to if the key isn't in cache yet - */ - constructor(accountData, delegateCryptoCallbacks) { - this.accountDataClientAdapter = new AccountDataClientAdapter(accountData); - this.crossSigningCallbacks = new CrossSigningCallbacks(); - this.ssssCryptoCallbacks = new SSSSCryptoCallbacks(delegateCryptoCallbacks); - } - /** - * Adds new cross-signing public keys - * - * @param authUpload - Function called to await an interactive auth - * flow when uploading device signing keys. - * Args: - * A function that makes the request requiring auth. Receives - * the auth data as an object. Can be called multiple times, first with - * an empty authDict, to obtain the flows. - * @param keys - the new keys - */ - addCrossSigningKeys(authUpload, keys) { - this.crossSigningKeys = { authUpload, keys }; - } - /** - * Adds the key backup info to be updated on the server - * - * Used either to create a new key backup, or add signatures - * from the new MSK. - * - * @param keyBackupInfo - as received from/sent to the server - */ - addSessionBackup(keyBackupInfo) { - this.keyBackupInfo = keyBackupInfo; - } - /** - * Adds the session backup private key to be updated in the local cache - * - * Used after fixing the format of the key - * - */ - addSessionBackupPrivateKeyToCache(privateKey) { - this.sessionBackupPrivateKey = privateKey; - } - /** - * Add signatures from a given user and device/x-sign key - * Used to sign the new cross-signing key with the device key - * - */ - addKeySignature(userId, deviceId, signature) { - if (!this.keySignatures) { - this.keySignatures = {}; - } - const userSignatures = this.keySignatures[userId] || {}; - this.keySignatures[userId] = userSignatures; - userSignatures[deviceId] = signature; - } - setAccountData(type, content) { - return __awaiter(this, void 0, void 0, function* () { - yield this.accountDataClientAdapter.setAccountData(type, content); - }); - } - /** - * builds the operation containing all the parts that have been added to the builder - */ - buildOperation() { - const accountData = this.accountDataClientAdapter.values; - return new EncryptionSetupOperation(accountData, this.crossSigningKeys, this.keyBackupInfo, this.keySignatures); - } - /** - * Stores the created keys locally. - * - * This does not yet store the operation in a way that it can be restored, - * but that is the idea in the future. - */ - persist(crypto) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - // store private keys in cache - if (this.crossSigningKeys) { - const cacheCallbacks = (0, CrossSigning_1.createCryptoStoreCacheCallbacks)(crypto.cryptoStore, crypto.olmDevice); - for (const type of ["master", "self_signing", "user_signing"]) { - logger_1.logger.log(`Cache ${type} cross-signing private key locally`); - const privateKey = this.crossSigningCallbacks.privateKeys.get(type); - yield ((_a = cacheCallbacks.storeCrossSigningKeyCache) === null || _a === void 0 ? void 0 : _a.call(cacheCallbacks, type, privateKey)); - } - // store own cross-sign pubkeys as trusted - yield crypto.cryptoStore.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { - crypto.cryptoStore.storeCrossSigningKeys(txn, this.crossSigningKeys.keys); - }); - } - // store session backup key in cache - if (this.sessionBackupPrivateKey) { - yield crypto.storeSessionBackupPrivateKey(this.sessionBackupPrivateKey); - } - }); - } -} -exports.EncryptionSetupBuilder = EncryptionSetupBuilder; -/** - * Can be created from EncryptionSetupBuilder, or - * (in a follow-up PR, not implemented yet) restored from storage, to retry. - * - * It does not have knowledge of any private keys, unlike the builder. - */ -class EncryptionSetupOperation { - /** - */ - constructor(accountData, crossSigningKeys, keyBackupInfo, keySignatures) { - this.accountData = accountData; - this.crossSigningKeys = crossSigningKeys; - this.keyBackupInfo = keyBackupInfo; - this.keySignatures = keySignatures; - } - /** - * Runs the (remaining part of, in the future) operation by sending requests to the server. - */ - apply(crypto) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - const baseApis = crypto.baseApis; - // upload cross-signing keys - if (this.crossSigningKeys) { - const keys = {}; - for (const [name, key] of Object.entries(this.crossSigningKeys.keys)) { - keys[(name + "_key")] = key; - } - // We must only call `uploadDeviceSigningKeys` from inside this auth - // helper to ensure we properly handle auth errors. - yield ((_b = (_a = this.crossSigningKeys).authUpload) === null || _b === void 0 ? void 0 : _b.call(_a, (authDict) => { - return baseApis.uploadDeviceSigningKeys(authDict, keys); - })); - // pass the new keys to the main instance of our own CrossSigningInfo. - crypto.crossSigningInfo.setKeys(this.crossSigningKeys.keys); - } - // set account data - if (this.accountData) { - for (const [type, content] of this.accountData) { - yield baseApis.setAccountData(type, content); - } - } - // upload first cross-signing signatures with the new key - // (e.g. signing our own device) - if (this.keySignatures) { - yield baseApis.uploadKeySignatures(this.keySignatures); - } - // need to create/update key backup info - if (this.keyBackupInfo) { - if (this.keyBackupInfo.version) { - // session backup signature - // The backup is trusted because the user provided the private key. - // Sign the backup with the cross signing key so the key backup can - // be trusted via cross-signing. - yield baseApis.http.authedRequest(http_api_1.Method.Put, "/room_keys/version/" + this.keyBackupInfo.version, undefined, { - algorithm: this.keyBackupInfo.algorithm, - auth_data: this.keyBackupInfo.auth_data, - }, { prefix: http_api_1.ClientPrefix.V3 }); - } - else { - // add new key backup - yield baseApis.http.authedRequest(http_api_1.Method.Post, "/room_keys/version", undefined, this.keyBackupInfo, { - prefix: http_api_1.ClientPrefix.V3, - }); - } - } - }); - } -} -exports.EncryptionSetupOperation = EncryptionSetupOperation; -/** - * Catches account data set by SecretStorage during bootstrapping by - * implementing the methods related to account data in MatrixClient - */ -class AccountDataClientAdapter extends typed_event_emitter_1.TypedEventEmitter { - /** - * @param existingValues - existing account data - */ - constructor(existingValues) { - super(); - this.existingValues = existingValues; - // - this.values = new Map(); - } - /** - * @returns the content of the account data - */ - getAccountDataFromServer(type) { - return Promise.resolve(this.getAccountData(type)); - } - /** - * @returns the content of the account data - */ - getAccountData(type) { - const modifiedValue = this.values.get(type); - if (modifiedValue) { - return modifiedValue; - } - const existingValue = this.existingValues.get(type); - if (existingValue) { - return existingValue.getContent(); - } - return null; - } - setAccountData(type, content) { - const lastEvent = this.values.get(type); - this.values.set(type, content); - // ensure accountData is emitted on the next tick, - // as SecretStorage listens for it while calling this method - // and it seems to rely on this. - return Promise.resolve().then(() => { - const event = new event_1.MatrixEvent({ type, content }); - this.emit(client_1.ClientEvent.AccountData, event, lastEvent); - return {}; - }); - } -} -/** - * Catches the private cross-signing keys set during bootstrapping - * by both cache callbacks (see createCryptoStoreCacheCallbacks) as non-cache callbacks. - * See CrossSigningInfo constructor - */ -class CrossSigningCallbacks { - constructor() { - this.privateKeys = new Map(); - } - // cache callbacks - getCrossSigningKeyCache(type, expectedPublicKey) { - return this.getCrossSigningKey(type, expectedPublicKey); - } - storeCrossSigningKeyCache(type, key) { - this.privateKeys.set(type, key); - return Promise.resolve(); - } - // non-cache callbacks - getCrossSigningKey(type, expectedPubkey) { - var _a; - return Promise.resolve((_a = this.privateKeys.get(type)) !== null && _a !== void 0 ? _a : null); - } - saveCrossSigningKeys(privateKeys) { - for (const [type, privateKey] of Object.entries(privateKeys)) { - this.privateKeys.set(type, privateKey); - } - } -} -/** - * Catches the 4S private key set during bootstrapping by implementing - * the SecretStorage crypto callbacks - */ -class SSSSCryptoCallbacks { - constructor(delegateCryptoCallbacks) { - this.delegateCryptoCallbacks = delegateCryptoCallbacks; - this.privateKeys = new Map(); - } - getSecretStorageKey({ keys }, name) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - for (const keyId of Object.keys(keys)) { - const privateKey = this.privateKeys.get(keyId); - if (privateKey) { - return [keyId, privateKey]; - } - } - // if we don't have the key cached yet, ask - // for it to the general crypto callbacks and cache it - if ((_a = this === null || this === void 0 ? void 0 : this.delegateCryptoCallbacks) === null || _a === void 0 ? void 0 : _a.getSecretStorageKey) { - const result = yield this.delegateCryptoCallbacks.getSecretStorageKey({ keys }, name); - if (result) { - const [keyId, privateKey] = result; - this.privateKeys.set(keyId, privateKey); - } - return result; - } - return null; - }); - } - addPrivateKey(keyId, keyInfo, privKey) { - var _a, _b; - this.privateKeys.set(keyId, privKey); - // Also pass along to application to cache if it wishes - (_b = (_a = this.delegateCryptoCallbacks) === null || _a === void 0 ? void 0 : _a.cacheSecretStorageKey) === null || _b === void 0 ? void 0 : _b.call(_a, keyId, keyInfo, privKey); - } -} - -},{"../client":321,"../http-api":367,"../logger":374,"../models/event":383,"../models/typed-event-emitter":395,"./CrossSigning":324,"./store/indexeddb-crypto-store":346}],327:[function(require,module,exports){ -(function (global){(function (){ -"use strict"; -/* -Copyright 2016 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.WITHHELD_MESSAGES = exports.OlmDevice = exports.PayloadTooLargeError = void 0; -const logger_1 = require("../logger"); -const indexeddb_crypto_store_1 = require("./store/indexeddb-crypto-store"); -const algorithms = __importStar(require("./algorithms")); -// The maximum size of an event is 65K, and we base64 the content, so this is a -// reasonable approximation to the biggest plaintext we can encrypt. -const MAX_PLAINTEXT_LENGTH = (65536 * 3) / 4; -class PayloadTooLargeError extends Error { - constructor() { - super(...arguments); - this.data = { - errcode: "M_TOO_LARGE", - error: "Payload too large for encrypted message", - }; - } -} -exports.PayloadTooLargeError = PayloadTooLargeError; -function checkPayloadLength(payloadString) { - if (payloadString === undefined) { - throw new Error("payloadString undefined"); - } - if (payloadString.length > MAX_PLAINTEXT_LENGTH) { - // might as well fail early here rather than letting the olm library throw - // a cryptic memory allocation error. - // - // Note that even if we manage to do the encryption, the message send may fail, - // because by the time we've wrapped the ciphertext in the event object, it may - // exceed 65K. But at least we won't just fail with "abort()" in that case. - throw new PayloadTooLargeError(`Message too long (${payloadString.length} bytes). ` + - `The maximum for an encrypted message is ${MAX_PLAINTEXT_LENGTH} bytes.`); - } -} -/** - * Manages the olm cryptography functions. Each OlmDevice has a single - * OlmAccount and a number of OlmSessions. - * - * Accounts and sessions are kept pickled in the cryptoStore. - */ -class OlmDevice { - constructor(cryptoStore) { - this.cryptoStore = cryptoStore; - this.pickleKey = "DEFAULT_KEY"; // set by consumers - /** Curve25519 key for the account, unknown until we load the account from storage in init() */ - this.deviceCurve25519Key = null; - /** Ed25519 key for the account, unknown until we load the account from storage in init() */ - this.deviceEd25519Key = null; - this.maxOneTimeKeys = null; - // we don't bother stashing outboundgroupsessions in the cryptoStore - - // instead we keep them here. - this.outboundGroupSessionStore = {}; - // Store a set of decrypted message indexes for each group session. - // This partially mitigates a replay attack where a MITM resends a group - // message into the room. - // - // When we decrypt a message and the message index matches a previously - // decrypted message, one possible cause of that is that we are decrypting - // the same event, and may not indicate an actual replay attack. For - // example, this could happen if we receive events, forget about them, and - // then re-fetch them when we backfill. So we store the event ID and - // timestamp corresponding to each message index when we first decrypt it, - // and compare these against the event ID and timestamp every time we use - // that same index. If they match, then we're probably decrypting the same - // event and we don't consider it a replay attack. - // - // Keys are strings of form "||" - // Values are objects of the form "{id: , timestamp: }" - this.inboundGroupSessionMessageIndexes = {}; - // Keep track of sessions that we're starting, so that we don't start - // multiple sessions for the same device at the same time. - this.sessionsInProgress = {}; // set by consumers - // Used by olm to serialise prekey message decryptions - this.olmPrekeyPromise = Promise.resolve(); // set by consumers - } - /** - * @returns The version of Olm. - */ - static getOlmVersion() { - return global.Olm.get_library_version(); - } - /** - * Initialise the OlmAccount. This must be called before any other operations - * on the OlmDevice. - * - * Data from an exported Olm device can be provided - * in order to re-create this device. - * - * Attempts to load the OlmAccount from the crypto store, or creates one if none is - * found. - * - * Reads the device keys from the OlmAccount object. - * - * @param fromExportedDevice - (Optional) data from exported device - * that must be re-created. - * If present, opts.pickleKey is ignored - * (exported data already provides a pickle key) - * @param pickleKey - (Optional) pickle key to set instead of default one - */ - init({ pickleKey, fromExportedDevice } = {}) { - return __awaiter(this, void 0, void 0, function* () { - let e2eKeys; - const account = new global.Olm.Account(); - try { - if (fromExportedDevice) { - if (pickleKey) { - logger_1.logger.warn("ignoring opts.pickleKey" + " because opts.fromExportedDevice is present."); - } - this.pickleKey = fromExportedDevice.pickleKey; - yield this.initialiseFromExportedDevice(fromExportedDevice, account); - } - else { - if (pickleKey) { - this.pickleKey = pickleKey; - } - yield this.initialiseAccount(account); - } - e2eKeys = JSON.parse(account.identity_keys()); - this.maxOneTimeKeys = account.max_number_of_one_time_keys(); - } - finally { - account.free(); - } - this.deviceCurve25519Key = e2eKeys.curve25519; - this.deviceEd25519Key = e2eKeys.ed25519; - }); - } - /** - * Populates the crypto store using data that was exported from an existing device. - * Note that for now only the “account” and “sessions” stores are populated; - * Other stores will be as with a new device. - * - * @param exportedData - Data exported from another device - * through the “export” method. - * @param account - an olm account to initialize - */ - initialiseFromExportedDevice(exportedData, account) { - return __awaiter(this, void 0, void 0, function* () { - yield this.cryptoStore.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT, indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_SESSIONS], (txn) => { - this.cryptoStore.storeAccount(txn, exportedData.pickledAccount); - exportedData.sessions.forEach((session) => { - const { deviceKey, sessionId } = session; - const sessionInfo = { - session: session.session, - lastReceivedMessageTs: session.lastReceivedMessageTs, - }; - this.cryptoStore.storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn); - }); - }); - account.unpickle(this.pickleKey, exportedData.pickledAccount); - }); - } - initialiseAccount(account) { - return __awaiter(this, void 0, void 0, function* () { - yield this.cryptoStore.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { - this.cryptoStore.getAccount(txn, (pickledAccount) => { - if (pickledAccount !== null) { - account.unpickle(this.pickleKey, pickledAccount); - } - else { - account.create(); - pickledAccount = account.pickle(this.pickleKey); - this.cryptoStore.storeAccount(txn, pickledAccount); - } - }); - }); - }); - } - /** - * extract our OlmAccount from the crypto store and call the given function - * with the account object - * The `account` object is usable only within the callback passed to this - * function and will be freed as soon the callback returns. It is *not* - * usable for the rest of the lifetime of the transaction. - * This function requires a live transaction object from cryptoStore.doTxn() - * and therefore may only be called in a doTxn() callback. - * - * @param txn - Opaque transaction object from cryptoStore.doTxn() - * @internal - */ - getAccount(txn, func) { - this.cryptoStore.getAccount(txn, (pickledAccount) => { - const account = new global.Olm.Account(); - try { - account.unpickle(this.pickleKey, pickledAccount); - func(account); - } - finally { - account.free(); - } - }); - } - /* - * Saves an account to the crypto store. - * This function requires a live transaction object from cryptoStore.doTxn() - * and therefore may only be called in a doTxn() callback. - * - * @param txn - Opaque transaction object from cryptoStore.doTxn() - * @param Olm.Account object - * @internal - */ - storeAccount(txn, account) { - this.cryptoStore.storeAccount(txn, account.pickle(this.pickleKey)); - } - /** - * Export data for re-creating the Olm device later. - * TODO export data other than just account and (P2P) sessions. - * - * @returns The exported data - */ - export() { - return __awaiter(this, void 0, void 0, function* () { - const result = { - pickleKey: this.pickleKey, - }; - yield this.cryptoStore.doTxn("readonly", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT, indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_SESSIONS], (txn) => { - this.cryptoStore.getAccount(txn, (pickledAccount) => { - result.pickledAccount = pickledAccount; - }); - result.sessions = []; - // Note that the pickledSession object we get in the callback - // is not exactly the same thing you get in method _getSession - // see documentation of IndexedDBCryptoStore.getAllEndToEndSessions - this.cryptoStore.getAllEndToEndSessions(txn, (pickledSession) => { - result.sessions.push(pickledSession); - }); - }); - return result; - }); - } - /** - * extract an OlmSession from the session store and call the given function - * The session is usable only within the callback passed to this - * function and will be freed as soon the callback returns. It is *not* - * usable for the rest of the lifetime of the transaction. - * - * @param txn - Opaque transaction object from cryptoStore.doTxn() - * @internal - */ - getSession(deviceKey, sessionId, txn, func) { - this.cryptoStore.getEndToEndSession(deviceKey, sessionId, txn, (sessionInfo) => { - this.unpickleSession(sessionInfo, func); - }); - } - /** - * Creates a session object from a session pickle and executes the given - * function with it. The session object is destroyed once the function - * returns. - * - * @internal - */ - unpickleSession(sessionInfo, func) { - const session = new global.Olm.Session(); - try { - session.unpickle(this.pickleKey, sessionInfo.session); - const unpickledSessInfo = Object.assign({}, sessionInfo, { session }); - func(unpickledSessInfo); - } - finally { - session.free(); - } - } - /** - * store our OlmSession in the session store - * - * @param sessionInfo - `{session: OlmSession, lastReceivedMessageTs: int}` - * @param txn - Opaque transaction object from cryptoStore.doTxn() - * @internal - */ - saveSession(deviceKey, sessionInfo, txn) { - const sessionId = sessionInfo.session.session_id(); - logger_1.logger.debug(`Saving Olm session ${sessionId} with device ${deviceKey}: ${sessionInfo.session.describe()}`); - // Why do we re-use the input object for this, overwriting the same key with a different - // type? Is it because we want to erase the unpickled session to enforce that it's no longer - // used? A comment would be great. - const pickledSessionInfo = Object.assign(sessionInfo, { - session: sessionInfo.session.pickle(this.pickleKey), - }); - this.cryptoStore.storeEndToEndSession(deviceKey, sessionId, pickledSessionInfo, txn); - } - /** - * get an OlmUtility and call the given function - * - * @returns result of func - * @internal - */ - getUtility(func) { - const utility = new global.Olm.Utility(); - try { - return func(utility); - } - finally { - utility.free(); - } - } - /** - * Signs a message with the ed25519 key for this account. - * - * @param message - message to be signed - * @returns base64-encoded signature - */ - sign(message) { - return __awaiter(this, void 0, void 0, function* () { - let result; - yield this.cryptoStore.doTxn("readonly", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { - this.getAccount(txn, (account) => { - result = account.sign(message); - }); - }); - return result; - }); - } - /** - * Get the current (unused, unpublished) one-time keys for this account. - * - * @returns one time keys; an object with the single property - * curve25519, which is itself an object mapping key id to Curve25519 - * key. - */ - getOneTimeKeys() { - return __awaiter(this, void 0, void 0, function* () { - let result; - yield this.cryptoStore.doTxn("readonly", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { - this.getAccount(txn, (account) => { - result = JSON.parse(account.one_time_keys()); - }); - }); - return result; - }); - } - /** - * Get the maximum number of one-time keys we can store. - * - * @returns number of keys - */ - maxNumberOfOneTimeKeys() { - var _a; - return (_a = this.maxOneTimeKeys) !== null && _a !== void 0 ? _a : -1; - } - /** - * Marks all of the one-time keys as published. - */ - markKeysAsPublished() { - return __awaiter(this, void 0, void 0, function* () { - yield this.cryptoStore.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { - this.getAccount(txn, (account) => { - account.mark_keys_as_published(); - this.storeAccount(txn, account); - }); - }); - }); - } - /** - * Generate some new one-time keys - * - * @param numKeys - number of keys to generate - * @returns Resolved once the account is saved back having generated the keys - */ - generateOneTimeKeys(numKeys) { - return this.cryptoStore.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { - this.getAccount(txn, (account) => { - account.generate_one_time_keys(numKeys); - this.storeAccount(txn, account); - }); - }); - } - /** - * Generate a new fallback keys - * - * @returns Resolved once the account is saved back having generated the key - */ - generateFallbackKey() { - return __awaiter(this, void 0, void 0, function* () { - yield this.cryptoStore.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { - this.getAccount(txn, (account) => { - account.generate_fallback_key(); - this.storeAccount(txn, account); - }); - }); - }); - } - getFallbackKey() { - return __awaiter(this, void 0, void 0, function* () { - let result; - yield this.cryptoStore.doTxn("readonly", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { - this.getAccount(txn, (account) => { - result = JSON.parse(account.unpublished_fallback_key()); - }); - }); - return result; - }); - } - forgetOldFallbackKey() { - return __awaiter(this, void 0, void 0, function* () { - yield this.cryptoStore.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { - this.getAccount(txn, (account) => { - account.forget_old_fallback_key(); - this.storeAccount(txn, account); - }); - }); - }); - } - /** - * Generate a new outbound session - * - * The new session will be stored in the cryptoStore. - * - * @param theirIdentityKey - remote user's Curve25519 identity key - * @param theirOneTimeKey - remote user's one-time Curve25519 key - * @returns sessionId for the outbound session. - */ - createOutboundSession(theirIdentityKey, theirOneTimeKey) { - return __awaiter(this, void 0, void 0, function* () { - let newSessionId; - yield this.cryptoStore.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT, indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_SESSIONS], (txn) => { - this.getAccount(txn, (account) => { - const session = new global.Olm.Session(); - try { - session.create_outbound(account, theirIdentityKey, theirOneTimeKey); - newSessionId = session.session_id(); - this.storeAccount(txn, account); - const sessionInfo = { - session, - // Pretend we've received a message at this point, otherwise - // if we try to send a message to the device, it won't use - // this session - lastReceivedMessageTs: Date.now(), - }; - this.saveSession(theirIdentityKey, sessionInfo, txn); - } - finally { - session.free(); - } - }); - }, logger_1.logger.withPrefix("[createOutboundSession]")); - return newSessionId; - }); - } - /** - * Generate a new inbound session, given an incoming message - * - * @param theirDeviceIdentityKey - remote user's Curve25519 identity key - * @param messageType - messageType field from the received message (must be 0) - * @param ciphertext - base64-encoded body from the received message - * - * @returns decrypted payload, and - * session id of new session - * - * @throws Error if the received message was not valid (for instance, it didn't use a valid one-time key). - */ - createInboundSession(theirDeviceIdentityKey, messageType, ciphertext) { - return __awaiter(this, void 0, void 0, function* () { - if (messageType !== 0) { - throw new Error("Need messageType == 0 to create inbound session"); - } - let result; // eslint-disable-line camelcase - yield this.cryptoStore.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT, indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_SESSIONS], (txn) => { - this.getAccount(txn, (account) => { - const session = new global.Olm.Session(); - try { - session.create_inbound_from(account, theirDeviceIdentityKey, ciphertext); - account.remove_one_time_keys(session); - this.storeAccount(txn, account); - const payloadString = session.decrypt(messageType, ciphertext); - const sessionInfo = { - session, - // this counts as a received message: set last received message time - // to now - lastReceivedMessageTs: Date.now(), - }; - this.saveSession(theirDeviceIdentityKey, sessionInfo, txn); - result = { - payload: payloadString, - session_id: session.session_id(), - }; - } - finally { - session.free(); - } - }); - }, logger_1.logger.withPrefix("[createInboundSession]")); - return result; - }); - } - /** - * Get a list of known session IDs for the given device - * - * @param theirDeviceIdentityKey - Curve25519 identity key for the - * remote device - * @returns a list of known session ids for the device - */ - getSessionIdsForDevice(theirDeviceIdentityKey) { - return __awaiter(this, void 0, void 0, function* () { - const log = logger_1.logger.withPrefix("[getSessionIdsForDevice]"); - if (theirDeviceIdentityKey in this.sessionsInProgress) { - log.debug(`Waiting for Olm session for ${theirDeviceIdentityKey} to be created`); - try { - yield this.sessionsInProgress[theirDeviceIdentityKey]; - } - catch (e) { - // if the session failed to be created, just fall through and - // return an empty result - } - } - let sessionIds; - yield this.cryptoStore.doTxn("readonly", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_SESSIONS], (txn) => { - this.cryptoStore.getEndToEndSessions(theirDeviceIdentityKey, txn, (sessions) => { - sessionIds = Object.keys(sessions); - }); - }, log); - return sessionIds; - }); - } - /** - * Get the right olm session id for encrypting messages to the given identity key - * - * @param theirDeviceIdentityKey - Curve25519 identity key for the - * remote device - * @param nowait - Don't wait for an in-progress session to complete. - * This should only be set to true of the calling function is the function - * that marked the session as being in-progress. - * @param log - A possibly customised log - * @returns session id, or null if no established session - */ - getSessionIdForDevice(theirDeviceIdentityKey, nowait = false, log) { - return __awaiter(this, void 0, void 0, function* () { - const sessionInfos = yield this.getSessionInfoForDevice(theirDeviceIdentityKey, nowait, log); - if (sessionInfos.length === 0) { - return null; - } - // Use the session that has most recently received a message - let idxOfBest = 0; - for (let i = 1; i < sessionInfos.length; i++) { - const thisSessInfo = sessionInfos[i]; - const thisLastReceived = thisSessInfo.lastReceivedMessageTs === undefined ? 0 : thisSessInfo.lastReceivedMessageTs; - const bestSessInfo = sessionInfos[idxOfBest]; - const bestLastReceived = bestSessInfo.lastReceivedMessageTs === undefined ? 0 : bestSessInfo.lastReceivedMessageTs; - if (thisLastReceived > bestLastReceived || - (thisLastReceived === bestLastReceived && thisSessInfo.sessionId < bestSessInfo.sessionId)) { - idxOfBest = i; - } - } - return sessionInfos[idxOfBest].sessionId; - }); - } - /** - * Get information on the active Olm sessions for a device. - *

- * Returns an array, with an entry for each active session. The first entry in - * the result will be the one used for outgoing messages. Each entry contains - * the keys 'hasReceivedMessage' (true if the session has received an incoming - * message and is therefore past the pre-key stage), and 'sessionId'. - * - * @param deviceIdentityKey - Curve25519 identity key for the device - * @param nowait - Don't wait for an in-progress session to complete. - * This should only be set to true of the calling function is the function - * that marked the session as being in-progress. - * @param log - A possibly customised log - */ - getSessionInfoForDevice(deviceIdentityKey, nowait = false, log = logger_1.logger) { - return __awaiter(this, void 0, void 0, function* () { - log = log.withPrefix("[getSessionInfoForDevice]"); - if (deviceIdentityKey in this.sessionsInProgress && !nowait) { - log.debug(`Waiting for Olm session for ${deviceIdentityKey} to be created`); - try { - yield this.sessionsInProgress[deviceIdentityKey]; - } - catch (e) { - // if the session failed to be created, then just fall through and - // return an empty result - } - } - const info = []; - yield this.cryptoStore.doTxn("readonly", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_SESSIONS], (txn) => { - this.cryptoStore.getEndToEndSessions(deviceIdentityKey, txn, (sessions) => { - const sessionIds = Object.keys(sessions).sort(); - for (const sessionId of sessionIds) { - this.unpickleSession(sessions[sessionId], (sessInfo) => { - info.push({ - lastReceivedMessageTs: sessInfo.lastReceivedMessageTs, - hasReceivedMessage: sessInfo.session.has_received_message(), - sessionId, - }); - }); - } - }); - }, log); - return info; - }); - } - /** - * Encrypt an outgoing message using an existing session - * - * @param theirDeviceIdentityKey - Curve25519 identity key for the - * remote device - * @param sessionId - the id of the active session - * @param payloadString - payload to be encrypted and sent - * - * @returns ciphertext - */ - encryptMessage(theirDeviceIdentityKey, sessionId, payloadString) { - return __awaiter(this, void 0, void 0, function* () { - checkPayloadLength(payloadString); - let res; - yield this.cryptoStore.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_SESSIONS], (txn) => { - this.getSession(theirDeviceIdentityKey, sessionId, txn, (sessionInfo) => { - const sessionDesc = sessionInfo.session.describe(); - logger_1.logger.log("encryptMessage: Olm Session ID " + - sessionId + - " to " + - theirDeviceIdentityKey + - ": " + - sessionDesc); - res = sessionInfo.session.encrypt(payloadString); - this.saveSession(theirDeviceIdentityKey, sessionInfo, txn); - }); - }, logger_1.logger.withPrefix("[encryptMessage]")); - return res; - }); - } - /** - * Decrypt an incoming message using an existing session - * - * @param theirDeviceIdentityKey - Curve25519 identity key for the - * remote device - * @param sessionId - the id of the active session - * @param messageType - messageType field from the received message - * @param ciphertext - base64-encoded body from the received message - * - * @returns decrypted payload. - */ - decryptMessage(theirDeviceIdentityKey, sessionId, messageType, ciphertext) { - return __awaiter(this, void 0, void 0, function* () { - let payloadString; - yield this.cryptoStore.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_SESSIONS], (txn) => { - this.getSession(theirDeviceIdentityKey, sessionId, txn, (sessionInfo) => { - const sessionDesc = sessionInfo.session.describe(); - logger_1.logger.log("decryptMessage: Olm Session ID " + - sessionId + - " from " + - theirDeviceIdentityKey + - ": " + - sessionDesc); - payloadString = sessionInfo.session.decrypt(messageType, ciphertext); - sessionInfo.lastReceivedMessageTs = Date.now(); - this.saveSession(theirDeviceIdentityKey, sessionInfo, txn); - }); - }, logger_1.logger.withPrefix("[decryptMessage]")); - return payloadString; - }); - } - /** - * Determine if an incoming messages is a prekey message matching an existing session - * - * @param theirDeviceIdentityKey - Curve25519 identity key for the - * remote device - * @param sessionId - the id of the active session - * @param messageType - messageType field from the received message - * @param ciphertext - base64-encoded body from the received message - * - * @returns true if the received message is a prekey message which matches - * the given session. - */ - matchesSession(theirDeviceIdentityKey, sessionId, messageType, ciphertext) { - return __awaiter(this, void 0, void 0, function* () { - if (messageType !== 0) { - return false; - } - let matches; - yield this.cryptoStore.doTxn("readonly", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_SESSIONS], (txn) => { - this.getSession(theirDeviceIdentityKey, sessionId, txn, (sessionInfo) => { - matches = sessionInfo.session.matches_inbound(ciphertext); - }); - }, logger_1.logger.withPrefix("[matchesSession]")); - return matches; - }); - } - recordSessionProblem(deviceKey, type, fixed) { - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.info(`Recording problem on olm session with ${deviceKey} of type ${type}. Recreating: ${fixed}`); - yield this.cryptoStore.storeEndToEndSessionProblem(deviceKey, type, fixed); - }); - } - sessionMayHaveProblems(deviceKey, timestamp) { - return this.cryptoStore.getEndToEndSessionProblem(deviceKey, timestamp); - } - filterOutNotifiedErrorDevices(devices) { - return this.cryptoStore.filterOutNotifiedErrorDevices(devices); - } - // Outbound group session - // ====================== - /** - * store an OutboundGroupSession in outboundGroupSessionStore - * - * @internal - */ - saveOutboundGroupSession(session) { - this.outboundGroupSessionStore[session.session_id()] = session.pickle(this.pickleKey); - } - /** - * extract an OutboundGroupSession from outboundGroupSessionStore and call the - * given function - * - * @returns result of func - * @internal - */ - getOutboundGroupSession(sessionId, func) { - const pickled = this.outboundGroupSessionStore[sessionId]; - if (pickled === undefined) { - throw new Error("Unknown outbound group session " + sessionId); - } - const session = new global.Olm.OutboundGroupSession(); - try { - session.unpickle(this.pickleKey, pickled); - return func(session); - } - finally { - session.free(); - } - } - /** - * Generate a new outbound group session - * - * @returns sessionId for the outbound session. - */ - createOutboundGroupSession() { - const session = new global.Olm.OutboundGroupSession(); - try { - session.create(); - this.saveOutboundGroupSession(session); - return session.session_id(); - } - finally { - session.free(); - } - } - /** - * Encrypt an outgoing message with an outbound group session - * - * @param sessionId - the id of the outboundgroupsession - * @param payloadString - payload to be encrypted and sent - * - * @returns ciphertext - */ - encryptGroupMessage(sessionId, payloadString) { - logger_1.logger.log(`encrypting msg with megolm session ${sessionId}`); - checkPayloadLength(payloadString); - return this.getOutboundGroupSession(sessionId, (session) => { - const res = session.encrypt(payloadString); - this.saveOutboundGroupSession(session); - return res; - }); - } - /** - * Get the session keys for an outbound group session - * - * @param sessionId - the id of the outbound group session - * - * @returns current chain index, and - * base64-encoded secret key. - */ - getOutboundGroupSessionKey(sessionId) { - return this.getOutboundGroupSession(sessionId, function (session) { - return { - chain_index: session.message_index(), - key: session.session_key(), - }; - }); - } - // Inbound group session - // ===================== - /** - * Unpickle a session from a sessionData object and invoke the given function. - * The session is valid only until func returns. - * - * @param sessionData - Object describing the session. - * @param func - Invoked with the unpickled session - * @returns result of func - */ - unpickleInboundGroupSession(sessionData, func) { - const session = new global.Olm.InboundGroupSession(); - try { - session.unpickle(this.pickleKey, sessionData.session); - return func(session); - } - finally { - session.free(); - } - } - /** - * extract an InboundGroupSession from the crypto store and call the given function - * - * @param roomId - The room ID to extract the session for, or null to fetch - * sessions for any room. - * @param txn - Opaque transaction object from cryptoStore.doTxn() - * @param func - function to call. - * - * @internal - */ - getInboundGroupSession(roomId, senderKey, sessionId, txn, func) { - this.cryptoStore.getEndToEndInboundGroupSession(senderKey, sessionId, txn, (sessionData, withheld) => { - if (sessionData === null) { - func(null, null, withheld); - return; - } - // if we were given a room ID, check that the it matches the original one for the session. This stops - // the HS pretending a message was targeting a different room. - if (roomId !== null && roomId !== sessionData.room_id) { - throw new Error("Mismatched room_id for inbound group session (expected " + - sessionData.room_id + - ", was " + - roomId + - ")"); - } - this.unpickleInboundGroupSession(sessionData, (session) => { - func(session, sessionData, withheld); - }); - }); - } - /** - * Add an inbound group session to the session store - * - * @param roomId - room in which this session will be used - * @param senderKey - base64-encoded curve25519 key of the sender - * @param forwardingCurve25519KeyChain - Devices involved in forwarding - * this session to us. - * @param sessionId - session identifier - * @param sessionKey - base64-encoded secret key - * @param keysClaimed - Other keys the sender claims. - * @param exportFormat - true if the megolm keys are in export format - * (ie, they lack an ed25519 signature) - * @param extraSessionData - any other data to be include with the session - */ - addInboundGroupSession(roomId, senderKey, forwardingCurve25519KeyChain, sessionId, sessionKey, keysClaimed, exportFormat, extraSessionData = {}) { - return __awaiter(this, void 0, void 0, function* () { - yield this.cryptoStore.doTxn("readwrite", [ - indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, - indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD, - indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS, - ], (txn) => { - /* if we already have this session, consider updating it */ - this.getInboundGroupSession(roomId, senderKey, sessionId, txn, (existingSession, existingSessionData) => { - // new session. - const session = new global.Olm.InboundGroupSession(); - try { - if (exportFormat) { - session.import_session(sessionKey); - } - else { - session.create(sessionKey); - } - if (sessionId != session.session_id()) { - throw new Error("Mismatched group session ID from senderKey: " + senderKey); - } - if (existingSession) { - logger_1.logger.log(`Update for megolm session ${senderKey}|${sessionId}`); - if (existingSession.first_known_index() <= session.first_known_index()) { - if (!existingSessionData.untrusted || extraSessionData.untrusted) { - // existing session has less-than-or-equal index - // (i.e. can decrypt at least as much), and the - // new session's trust does not win over the old - // session's trust, so keep it - logger_1.logger.log(`Keeping existing megolm session ${senderKey}|${sessionId}`); - return; - } - if (existingSession.first_known_index() < session.first_known_index()) { - // We want to upgrade the existing session's trust, - // but we can't just use the new session because we'll - // lose the lower index. Check that the sessions connect - // properly, and then manually set the existing session - // as trusted. - if (existingSession.export_session(session.first_known_index()) === - session.export_session(session.first_known_index())) { - logger_1.logger.info("Upgrading trust of existing megolm session " + - `${senderKey}|${sessionId} based on newly-received trusted session`); - existingSessionData.untrusted = false; - this.cryptoStore.storeEndToEndInboundGroupSession(senderKey, sessionId, existingSessionData, txn); - } - else { - logger_1.logger.warn(`Newly-received megolm session ${senderKey}|$sessionId}` + - " does not match existing session! Keeping existing session"); - } - return; - } - // If the sessions have the same index, go ahead and store the new trusted one. - } - } - logger_1.logger.info(`Storing megolm session ${senderKey}|${sessionId} with first index ` + - session.first_known_index()); - const sessionData = Object.assign({}, extraSessionData, { - room_id: roomId, - session: session.pickle(this.pickleKey), - keysClaimed: keysClaimed, - forwardingCurve25519KeyChain: forwardingCurve25519KeyChain, - }); - this.cryptoStore.storeEndToEndInboundGroupSession(senderKey, sessionId, sessionData, txn); - if (!existingSession && extraSessionData.sharedHistory) { - this.cryptoStore.addSharedHistoryInboundGroupSession(roomId, senderKey, sessionId, txn); - } - } - finally { - session.free(); - } - }); - }, logger_1.logger.withPrefix("[addInboundGroupSession]")); - }); - } - /** - * Record in the data store why an inbound group session was withheld. - * - * @param roomId - room that the session belongs to - * @param senderKey - base64-encoded curve25519 key of the sender - * @param sessionId - session identifier - * @param code - reason code - * @param reason - human-readable version of `code` - */ - addInboundGroupSessionWithheld(roomId, senderKey, sessionId, code, reason) { - return __awaiter(this, void 0, void 0, function* () { - yield this.cryptoStore.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD], (txn) => { - this.cryptoStore.storeEndToEndInboundGroupSessionWithheld(senderKey, sessionId, { - room_id: roomId, - code: code, - reason: reason, - }, txn); - }); - }); - } - /** - * Decrypt a received message with an inbound group session - * - * @param roomId - room in which the message was received - * @param senderKey - base64-encoded curve25519 key of the sender - * @param sessionId - session identifier - * @param body - base64-encoded body of the encrypted message - * @param eventId - ID of the event being decrypted - * @param timestamp - timestamp of the event being decrypted - * - * @returns null if the sessionId is unknown - */ - decryptGroupMessage(roomId, senderKey, sessionId, body, eventId, timestamp) { - return __awaiter(this, void 0, void 0, function* () { - let result = null; - // when the localstorage crypto store is used as an indexeddb backend, - // exceptions thrown from within the inner function are not passed through - // to the top level, so we store exceptions in a variable and raise them at - // the end - let error; - yield this.cryptoStore.doTxn("readwrite", [ - indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, - indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD, - ], (txn) => { - this.getInboundGroupSession(roomId, senderKey, sessionId, txn, (session, sessionData, withheld) => { - if (session === null || sessionData === null) { - if (withheld) { - error = new algorithms.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID", calculateWithheldMessage(withheld), { - session: senderKey + "|" + sessionId, - }); - } - result = null; - return; - } - let res; - try { - res = session.decrypt(body); - } - catch (e) { - if ((e === null || e === void 0 ? void 0 : e.message) === "OLM.UNKNOWN_MESSAGE_INDEX" && withheld) { - error = new algorithms.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID", calculateWithheldMessage(withheld), { - session: senderKey + "|" + sessionId, - }); - } - else { - error = e; - } - return; - } - let plaintext = res.plaintext; - if (plaintext === undefined) { - // @ts-ignore - Compatibility for older olm versions. - plaintext = res; - } - else { - // Check if we have seen this message index before to detect replay attacks. - // If the event ID and timestamp are specified, and the match the event ID - // and timestamp from the last time we used this message index, then we - // don't consider it a replay attack. - const messageIndexKey = senderKey + "|" + sessionId + "|" + res.message_index; - if (messageIndexKey in this.inboundGroupSessionMessageIndexes) { - const msgInfo = this.inboundGroupSessionMessageIndexes[messageIndexKey]; - if (msgInfo.id !== eventId || msgInfo.timestamp !== timestamp) { - error = new Error("Duplicate message index, possible replay attack: " + messageIndexKey); - return; - } - } - this.inboundGroupSessionMessageIndexes[messageIndexKey] = { - id: eventId, - timestamp: timestamp, - }; - } - sessionData.session = session.pickle(this.pickleKey); - this.cryptoStore.storeEndToEndInboundGroupSession(senderKey, sessionId, sessionData, txn); - result = { - result: plaintext, - keysClaimed: sessionData.keysClaimed || {}, - senderKey: senderKey, - forwardingCurve25519KeyChain: sessionData.forwardingCurve25519KeyChain || [], - untrusted: !!sessionData.untrusted, - }; - }); - }, logger_1.logger.withPrefix("[decryptGroupMessage]")); - if (error) { - throw error; - } - return result; - }); - } - /** - * Determine if we have the keys for a given megolm session - * - * @param roomId - room in which the message was received - * @param senderKey - base64-encoded curve25519 key of the sender - * @param sessionId - session identifier - * - * @returns true if we have the keys to this session - */ - hasInboundSessionKeys(roomId, senderKey, sessionId) { - return __awaiter(this, void 0, void 0, function* () { - let result; - yield this.cryptoStore.doTxn("readonly", [ - indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, - indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD, - ], (txn) => { - this.cryptoStore.getEndToEndInboundGroupSession(senderKey, sessionId, txn, (sessionData) => { - if (sessionData === null) { - result = false; - return; - } - if (roomId !== sessionData.room_id) { - logger_1.logger.warn(`requested keys for inbound group session ${senderKey}|` + - `${sessionId}, with incorrect room_id ` + - `(expected ${sessionData.room_id}, ` + - `was ${roomId})`); - result = false; - } - else { - result = true; - } - }); - }, logger_1.logger.withPrefix("[hasInboundSessionKeys]")); - return result; - }); - } - /** - * Extract the keys to a given megolm session, for sharing - * - * @param roomId - room in which the message was received - * @param senderKey - base64-encoded curve25519 key of the sender - * @param sessionId - session identifier - * @param chainIndex - The chain index at which to export the session. - * If omitted, export at the first index we know about. - * - * @returns - * details of the session key. The key is a base64-encoded megolm key in - * export format. - * - * @throws Error If the given chain index could not be obtained from the known - * index (ie. the given chain index is before the first we have). - */ - getInboundGroupSessionKey(roomId, senderKey, sessionId, chainIndex) { - return __awaiter(this, void 0, void 0, function* () { - let result = null; - yield this.cryptoStore.doTxn("readonly", [ - indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, - indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD, - ], (txn) => { - this.getInboundGroupSession(roomId, senderKey, sessionId, txn, (session, sessionData) => { - if (session === null || sessionData === null) { - result = null; - return; - } - if (chainIndex === undefined) { - chainIndex = session.first_known_index(); - } - const exportedSession = session.export_session(chainIndex); - const claimedKeys = sessionData.keysClaimed || {}; - const senderEd25519Key = claimedKeys.ed25519 || null; - const forwardingKeyChain = sessionData.forwardingCurve25519KeyChain || []; - // older forwarded keys didn't set the "untrusted" - // property, but can be identified by having a - // non-empty forwarding key chain. These keys should - // be marked as untrusted since we don't know that they - // can be trusted - const untrusted = "untrusted" in sessionData ? sessionData.untrusted : forwardingKeyChain.length > 0; - result = { - chain_index: chainIndex, - key: exportedSession, - forwarding_curve25519_key_chain: forwardingKeyChain, - sender_claimed_ed25519_key: senderEd25519Key, - shared_history: sessionData.sharedHistory || false, - untrusted: untrusted, - }; - }); - }, logger_1.logger.withPrefix("[getInboundGroupSessionKey]")); - return result; - }); - } - /** - * Export an inbound group session - * - * @param senderKey - base64-encoded curve25519 key of the sender - * @param sessionId - session identifier - * @param sessionData - The session object from the store - * @returns exported session data - */ - exportInboundGroupSession(senderKey, sessionId, sessionData) { - return this.unpickleInboundGroupSession(sessionData, (session) => { - const messageIndex = session.first_known_index(); - return { - "sender_key": senderKey, - "sender_claimed_keys": sessionData.keysClaimed, - "room_id": sessionData.room_id, - "session_id": sessionId, - "session_key": session.export_session(messageIndex), - "forwarding_curve25519_key_chain": sessionData.forwardingCurve25519KeyChain || [], - "first_known_index": session.first_known_index(), - "org.matrix.msc3061.shared_history": sessionData.sharedHistory || false, - }; - }); - } - getSharedHistoryInboundGroupSessions(roomId) { - return __awaiter(this, void 0, void 0, function* () { - let result; - yield this.cryptoStore.doTxn("readonly", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS], (txn) => { - result = this.cryptoStore.getSharedHistoryInboundGroupSessions(roomId, txn); - }, logger_1.logger.withPrefix("[getSharedHistoryInboundGroupSessionsForRoom]")); - return result; - }); - } - // Utilities - // ========= - /** - * Verify an ed25519 signature. - * - * @param key - ed25519 key - * @param message - message which was signed - * @param signature - base64-encoded signature to be checked - * - * @throws Error if there is a problem with the verification. If the key was - * too small then the message will be "OLM.INVALID_BASE64". If the signature - * was invalid then the message will be "OLM.BAD_MESSAGE_MAC". - */ - verifySignature(key, message, signature) { - this.getUtility(function (util) { - util.ed25519_verify(key, message, signature); - }); - } -} -exports.OlmDevice = OlmDevice; -exports.WITHHELD_MESSAGES = { - "m.unverified": "The sender has disabled encrypting to unverified devices.", - "m.blacklisted": "The sender has blocked you.", - "m.unauthorised": "You are not authorised to read the message.", - "m.no_olm": "Unable to establish a secure channel.", -}; -/** - * Calculate the message to use for the exception when a session key is withheld. - * - * @param withheld - An object that describes why the key was withheld. - * - * @returns the message - * - * @internal - */ -function calculateWithheldMessage(withheld) { - if (withheld.code && withheld.code in exports.WITHHELD_MESSAGES) { - return exports.WITHHELD_MESSAGES[withheld.code]; - } - else if (withheld.reason) { - return withheld.reason; - } - else { - return "decryption key withheld"; - } -} - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"../logger":374,"./algorithms":333,"./store/indexeddb-crypto-store":346}],328:[function(require,module,exports){ -"use strict"; -/* -Copyright 2017 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OutgoingRoomKeyRequestManager = exports.RoomKeyRequestState = void 0; -const uuid_1 = require("uuid"); -const logger_1 = require("../logger"); -const event_1 = require("../@types/event"); -const utils_1 = require("../utils"); -/** - * Internal module. Management of outgoing room key requests. - * - * See https://docs.google.com/document/d/1m4gQkcnJkxNuBmb5NoFCIadIY-DyqqNAS3lloE73BlQ - * for draft documentation on what we're supposed to be implementing here. - */ -// delay between deciding we want some keys, and sending out the request, to -// allow for (a) it turning up anyway, (b) grouping requests together -const SEND_KEY_REQUESTS_DELAY_MS = 500; -/** - * possible states for a room key request - * - * The state machine looks like: - * ``` - * - * | (cancellation sent) - * | .-------------------------------------------------. - * | | | - * V V (cancellation requested) | - * UNSENT -----------------------------+ | - * | | | - * | | | - * | (send successful) | CANCELLATION_PENDING_AND_WILL_RESEND - * V | Λ - * SENT | | - * |-------------------------------- | --------------' - * | | (cancellation requested with intent - * | | to resend the original request) - * | | - * | (cancellation requested) | - * V | - * CANCELLATION_PENDING | - * | | - * | (cancellation sent) | - * V | - * (deleted) <---------------------------+ - * ``` - */ -var RoomKeyRequestState; -(function (RoomKeyRequestState) { - /** request not yet sent */ - RoomKeyRequestState[RoomKeyRequestState["Unsent"] = 0] = "Unsent"; - /** request sent, awaiting reply */ - RoomKeyRequestState[RoomKeyRequestState["Sent"] = 1] = "Sent"; - /** reply received, cancellation not yet sent */ - RoomKeyRequestState[RoomKeyRequestState["CancellationPending"] = 2] = "CancellationPending"; - /** - * Cancellation not yet sent and will transition to UNSENT instead of - * being deleted once the cancellation has been sent. - */ - RoomKeyRequestState[RoomKeyRequestState["CancellationPendingAndWillResend"] = 3] = "CancellationPendingAndWillResend"; -})(RoomKeyRequestState = exports.RoomKeyRequestState || (exports.RoomKeyRequestState = {})); -class OutgoingRoomKeyRequestManager { - constructor(baseApis, deviceId, cryptoStore) { - this.baseApis = baseApis; - this.deviceId = deviceId; - this.cryptoStore = cryptoStore; - // sanity check to ensure that we don't end up with two concurrent runs - // of sendOutgoingRoomKeyRequests - this.sendOutgoingRoomKeyRequestsRunning = false; - this.clientRunning = true; - } - /** - * Called when the client is stopped. Stops any running background processes. - */ - stop() { - logger_1.logger.log("stopping OutgoingRoomKeyRequestManager"); - // stop the timer on the next run - this.clientRunning = false; - } - /** - * Send any requests that have been queued - */ - sendQueuedRequests() { - this.startTimer(); - } - /** - * Queue up a room key request, if we haven't already queued or sent one. - * - * The `requestBody` is compared (with a deep-equality check) against - * previous queued or sent requests and if it matches, no change is made. - * Otherwise, a request is added to the pending list, and a job is started - * in the background to send it. - * - * @param resend - whether to resend the key request if there is - * already one - * - * @returns resolves when the request has been added to the - * pending list (or we have established that a similar request already - * exists) - */ - queueRoomKeyRequest(requestBody, recipients, resend = false) { - return __awaiter(this, void 0, void 0, function* () { - const req = yield this.cryptoStore.getOutgoingRoomKeyRequest(requestBody); - if (!req) { - yield this.cryptoStore.getOrAddOutgoingRoomKeyRequest({ - requestBody: requestBody, - recipients: recipients, - requestId: this.baseApis.makeTxnId(), - state: RoomKeyRequestState.Unsent, - }); - } - else { - switch (req.state) { - case RoomKeyRequestState.CancellationPendingAndWillResend: - case RoomKeyRequestState.Unsent: - // nothing to do here, since we're going to send a request anyways - return; - case RoomKeyRequestState.CancellationPending: { - // existing request is about to be cancelled. If we want to - // resend, then change the state so that it resends after - // cancelling. Otherwise, just cancel the cancellation. - const state = resend - ? RoomKeyRequestState.CancellationPendingAndWillResend - : RoomKeyRequestState.Sent; - yield this.cryptoStore.updateOutgoingRoomKeyRequest(req.requestId, RoomKeyRequestState.CancellationPending, { - state, - cancellationTxnId: this.baseApis.makeTxnId(), - }); - break; - } - case RoomKeyRequestState.Sent: { - // a request has already been sent. If we don't want to - // resend, then do nothing. If we do want to, then cancel the - // existing request and send a new one. - if (resend) { - const state = RoomKeyRequestState.CancellationPendingAndWillResend; - const updatedReq = yield this.cryptoStore.updateOutgoingRoomKeyRequest(req.requestId, RoomKeyRequestState.Sent, { - state, - cancellationTxnId: this.baseApis.makeTxnId(), - // need to use a new transaction ID so that - // the request gets sent - requestTxnId: this.baseApis.makeTxnId(), - }); - if (!updatedReq) { - // updateOutgoingRoomKeyRequest couldn't find the request - // in state ROOM_KEY_REQUEST_STATES.SENT, so we must have - // raced with another tab to mark the request cancelled. - // Try again, to make sure the request is resent. - return this.queueRoomKeyRequest(requestBody, recipients, resend); - } - // We don't want to wait for the timer, so we send it - // immediately. (We might actually end up racing with the timer, - // but that's ok: even if we make the request twice, we'll do it - // with the same transaction_id, so only one message will get - // sent). - // - // (We also don't want to wait for the response from the server - // here, as it will slow down processing of received keys if we - // do.) - try { - yield this.sendOutgoingRoomKeyRequestCancellation(updatedReq, true); - } - catch (e) { - logger_1.logger.error("Error sending room key request cancellation;" + " will retry later.", e); - } - // The request has transitioned from - // CANCELLATION_PENDING_AND_WILL_RESEND to UNSENT. We - // still need to resend the request which is now UNSENT, so - // start the timer if it isn't already started. - } - break; - } - default: - throw new Error("unhandled state: " + req.state); - } - } - }); - } - /** - * Cancel room key requests, if any match the given requestBody - * - * - * @returns resolves when the request has been updated in our - * pending list. - */ - cancelRoomKeyRequest(requestBody) { - return this.cryptoStore.getOutgoingRoomKeyRequest(requestBody).then((req) => { - if (!req) { - // no request was made for this key - return; - } - switch (req.state) { - case RoomKeyRequestState.CancellationPending: - case RoomKeyRequestState.CancellationPendingAndWillResend: - // nothing to do here - return; - case RoomKeyRequestState.Unsent: - // just delete it - // FIXME: ghahah we may have attempted to send it, and - // not yet got a successful response. So the server - // may have seen it, so we still need to send a cancellation - // in that case :/ - logger_1.logger.log("deleting unnecessary room key request for " + stringifyRequestBody(requestBody)); - return this.cryptoStore.deleteOutgoingRoomKeyRequest(req.requestId, RoomKeyRequestState.Unsent); - case RoomKeyRequestState.Sent: { - // send a cancellation. - return this.cryptoStore - .updateOutgoingRoomKeyRequest(req.requestId, RoomKeyRequestState.Sent, { - state: RoomKeyRequestState.CancellationPending, - cancellationTxnId: this.baseApis.makeTxnId(), - }) - .then((updatedReq) => { - if (!updatedReq) { - // updateOutgoingRoomKeyRequest couldn't find the - // request in state ROOM_KEY_REQUEST_STATES.SENT, - // so we must have raced with another tab to mark - // the request cancelled. There is no point in - // sending another cancellation since the other tab - // will do it. - logger_1.logger.log("Tried to cancel room key request for " + - stringifyRequestBody(requestBody) + - " but it was already cancelled in another tab"); - return; - } - // We don't want to wait for the timer, so we send it - // immediately. (We might actually end up racing with the timer, - // but that's ok: even if we make the request twice, we'll do it - // with the same transaction_id, so only one message will get - // sent). - // - // (We also don't want to wait for the response from the server - // here, as it will slow down processing of received keys if we - // do.) - this.sendOutgoingRoomKeyRequestCancellation(updatedReq).catch((e) => { - logger_1.logger.error("Error sending room key request cancellation;" + " will retry later.", e); - this.startTimer(); - }); - }); - } - default: - throw new Error("unhandled state: " + req.state); - } - }); - } - /** - * Look for room key requests by target device and state - * - * @param userId - Target user ID - * @param deviceId - Target device ID - * - * @returns resolves to a list of all the {@link OutgoingRoomKeyRequest} - */ - getOutgoingSentRoomKeyRequest(userId, deviceId) { - return this.cryptoStore.getOutgoingRoomKeyRequestsByTarget(userId, deviceId, [RoomKeyRequestState.Sent]); - } - /** - * Find anything in `sent` state, and kick it around the loop again. - * This is intended for situations where something substantial has changed, and we - * don't really expect the other end to even care about the cancellation. - * For example, after initialization or self-verification. - * @returns An array of `queueRoomKeyRequest` outputs. - */ - cancelAndResendAllOutgoingRequests() { - return __awaiter(this, void 0, void 0, function* () { - const outgoings = yield this.cryptoStore.getAllOutgoingRoomKeyRequestsByState(RoomKeyRequestState.Sent); - return Promise.all(outgoings.map(({ requestBody, recipients }) => this.queueRoomKeyRequest(requestBody, recipients, true))); - }); - } - // start the background timer to send queued requests, if the timer isn't - // already running - startTimer() { - if (this.sendOutgoingRoomKeyRequestsTimer) { - return; - } - const startSendingOutgoingRoomKeyRequests = () => { - if (this.sendOutgoingRoomKeyRequestsRunning) { - throw new Error("RoomKeyRequestSend already in progress!"); - } - this.sendOutgoingRoomKeyRequestsRunning = true; - this.sendOutgoingRoomKeyRequests() - .finally(() => { - this.sendOutgoingRoomKeyRequestsRunning = false; - }) - .catch((e) => { - // this should only happen if there is an indexeddb error, - // in which case we're a bit stuffed anyway. - logger_1.logger.warn(`error in OutgoingRoomKeyRequestManager: ${e}`); - }); - }; - this.sendOutgoingRoomKeyRequestsTimer = setTimeout(startSendingOutgoingRoomKeyRequests, SEND_KEY_REQUESTS_DELAY_MS); - } - // look for and send any queued requests. Runs itself recursively until - // there are no more requests, or there is an error (in which case, the - // timer will be restarted before the promise resolves). - sendOutgoingRoomKeyRequests() { - return __awaiter(this, void 0, void 0, function* () { - if (!this.clientRunning) { - this.sendOutgoingRoomKeyRequestsTimer = undefined; - return; - } - const req = yield this.cryptoStore.getOutgoingRoomKeyRequestByState([ - RoomKeyRequestState.CancellationPending, - RoomKeyRequestState.CancellationPendingAndWillResend, - RoomKeyRequestState.Unsent, - ]); - if (!req) { - this.sendOutgoingRoomKeyRequestsTimer = undefined; - return; - } - try { - switch (req.state) { - case RoomKeyRequestState.Unsent: - yield this.sendOutgoingRoomKeyRequest(req); - break; - case RoomKeyRequestState.CancellationPending: - yield this.sendOutgoingRoomKeyRequestCancellation(req); - break; - case RoomKeyRequestState.CancellationPendingAndWillResend: - yield this.sendOutgoingRoomKeyRequestCancellation(req, true); - break; - } - // go around the loop again - return this.sendOutgoingRoomKeyRequests(); - } - catch (e) { - logger_1.logger.error("Error sending room key request; will retry later.", e); - this.sendOutgoingRoomKeyRequestsTimer = undefined; - } - }); - } - // given a RoomKeyRequest, send it and update the request record - sendOutgoingRoomKeyRequest(req) { - logger_1.logger.log(`Requesting keys for ${stringifyRequestBody(req.requestBody)}` + - ` from ${stringifyRecipientList(req.recipients)}` + - `(id ${req.requestId})`); - const requestMessage = { - action: "request", - requesting_device_id: this.deviceId, - request_id: req.requestId, - body: req.requestBody, - }; - return this.sendMessageToDevices(requestMessage, req.recipients, req.requestTxnId || req.requestId).then(() => { - return this.cryptoStore.updateOutgoingRoomKeyRequest(req.requestId, RoomKeyRequestState.Unsent, { - state: RoomKeyRequestState.Sent, - }); - }); - } - // Given a RoomKeyRequest, cancel it and delete the request record unless - // andResend is set, in which case transition to UNSENT. - sendOutgoingRoomKeyRequestCancellation(req, andResend = false) { - logger_1.logger.log(`Sending cancellation for key request for ` + - `${stringifyRequestBody(req.requestBody)} to ` + - `${stringifyRecipientList(req.recipients)} ` + - `(cancellation id ${req.cancellationTxnId})`); - const requestMessage = { - action: "request_cancellation", - requesting_device_id: this.deviceId, - request_id: req.requestId, - }; - return this.sendMessageToDevices(requestMessage, req.recipients, req.cancellationTxnId).then(() => { - if (andResend) { - // We want to resend, so transition to UNSENT - return this.cryptoStore.updateOutgoingRoomKeyRequest(req.requestId, RoomKeyRequestState.CancellationPendingAndWillResend, { state: RoomKeyRequestState.Unsent }); - } - return this.cryptoStore.deleteOutgoingRoomKeyRequest(req.requestId, RoomKeyRequestState.CancellationPending); - }); - } - // send a RoomKeyRequest to a list of recipients - sendMessageToDevices(message, recipients, txnId) { - const contentMap = new utils_1.MapWithDefault(() => new Map()); - for (const recip of recipients) { - const userDeviceMap = contentMap.getOrCreate(recip.userId); - userDeviceMap.set(recip.deviceId, Object.assign(Object.assign({}, message), { [event_1.ToDeviceMessageId]: (0, uuid_1.v4)() })); - } - return this.baseApis.sendToDevice(event_1.EventType.RoomKeyRequest, contentMap, txnId); - } -} -exports.OutgoingRoomKeyRequestManager = OutgoingRoomKeyRequestManager; -function stringifyRequestBody(requestBody) { - // we assume that the request is for megolm keys, which are identified by - // room id and session id - return requestBody.room_id + " / " + requestBody.session_id; -} -function stringifyRecipientList(recipients) { - return `[${recipients.map((r) => `${r.userId}:${r.deviceId}`).join(",")}]`; -} - -},{"../@types/event":306,"../logger":374,"../utils":416,"uuid":287}],329:[function(require,module,exports){ -"use strict"; -/* -Copyright 2018 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RoomList = void 0; -const indexeddb_crypto_store_1 = require("./store/indexeddb-crypto-store"); -/* eslint-enable camelcase */ -class RoomList { - constructor(cryptoStore) { - this.cryptoStore = cryptoStore; - // Object of roomId -> room e2e info object (body of the m.room.encryption event) - this.roomEncryption = {}; - } - init() { - return __awaiter(this, void 0, void 0, function* () { - yield this.cryptoStore.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ROOMS], (txn) => { - this.cryptoStore.getEndToEndRooms(txn, (result) => { - this.roomEncryption = result; - }); - }); - }); - } - getRoomEncryption(roomId) { - return this.roomEncryption[roomId] || null; - } - isRoomEncrypted(roomId) { - return Boolean(this.getRoomEncryption(roomId)); - } - setRoomEncryption(roomId, roomInfo) { - return __awaiter(this, void 0, void 0, function* () { - // important that this happens before calling into the store - // as it prevents the Crypto::setRoomEncryption from calling - // this twice for consecutive m.room.encryption events - this.roomEncryption[roomId] = roomInfo; - yield this.cryptoStore.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ROOMS], (txn) => { - this.cryptoStore.storeEndToEndRoom(roomId, roomInfo, txn); - }); - }); - } -} -exports.RoomList = RoomList; - -},{"./store/indexeddb-crypto-store":346}],330:[function(require,module,exports){ -"use strict"; -/* -Copyright 2019 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SecretStorage = exports.SECRET_STORAGE_ALGORITHM_V1_AES = void 0; -const uuid_1 = require("uuid"); -const logger_1 = require("../logger"); -const olmlib = __importStar(require("./olmlib")); -const randomstring_1 = require("../randomstring"); -const aes_1 = require("./aes"); -const client_1 = require("../client"); -const utils_1 = require("../utils"); -const event_1 = require("../@types/event"); -exports.SECRET_STORAGE_ALGORITHM_V1_AES = "m.secret_storage.v1.aes-hmac-sha2"; -/** - * Implements Secure Secret Storage and Sharing (MSC1946) - */ -class SecretStorage { - // In it's pure javascript days, this was relying on some proper Javascript-style - // type-abuse where sometimes we'd pass in a fake client object with just the account - // data methods implemented, which is all this class needs unless you use the secret - // sharing code, so it was fine. As a low-touch TypeScript migration, this now has - // an extra, optional param for a real matrix client, so you can not pass it as long - // as you don't request any secrets. - // A better solution would probably be to split this class up into secret storage and - // secret sharing which are really two separate things, even though they share an MSC. - constructor(accountDataAdapter, cryptoCallbacks, baseApis) { - this.accountDataAdapter = accountDataAdapter; - this.cryptoCallbacks = cryptoCallbacks; - this.baseApis = baseApis; - this.requests = new Map(); - } - getDefaultKeyId() { - return __awaiter(this, void 0, void 0, function* () { - const defaultKey = yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.default_key"); - if (!defaultKey) - return null; - return defaultKey.key; - }); - } - setDefaultKeyId(keyId) { - return new Promise((resolve, reject) => { - const listener = (ev) => { - if (ev.getType() === "m.secret_storage.default_key" && ev.getContent().key === keyId) { - this.accountDataAdapter.removeListener(client_1.ClientEvent.AccountData, listener); - resolve(); - } - }; - this.accountDataAdapter.on(client_1.ClientEvent.AccountData, listener); - this.accountDataAdapter.setAccountData("m.secret_storage.default_key", { key: keyId }).catch((e) => { - this.accountDataAdapter.removeListener(client_1.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) { - return __awaiter(this, void 0, void 0, function* () { - if (algorithm !== exports.SECRET_STORAGE_ALGORITHM_V1_AES) { - throw new Error(`Unknown key algorithm ${algorithm}`); - } - const keyInfo = { algorithm }; - if (opts.name) { - keyInfo.name = opts.name; - } - if (opts.passphrase) { - keyInfo.passphrase = opts.passphrase; - } - if (opts.key) { - const { iv, mac } = yield (0, aes_1.calculateKeyCheck)(opts.key); - keyInfo.iv = iv; - keyInfo.mac = mac; - } - if (!keyId) { - do { - keyId = (0, randomstring_1.randomString)(32); - } while (yield this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${keyId}`)); - } - yield this.accountDataAdapter.setAccountData(`m.secret_storage.key.${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) { - return __awaiter(this, void 0, void 0, function* () { - if (!keyId) { - keyId = yield this.getDefaultKeyId(); - } - if (!keyId) { - return null; - } - const keyInfo = yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key." + 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) { - return __awaiter(this, void 0, void 0, function* () { - return Boolean(yield this.getKey(keyId)); - }); - } - /** - * 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 __awaiter(this, void 0, void 0, function* () { - if (info.algorithm === exports.SECRET_STORAGE_ALGORITHM_V1_AES) { - if (info.mac) { - const { mac } = yield (0, aes_1.calculateKeyCheck)(key, info.iv); - return info.mac.replace(/=+$/g, "") === mac.replace(/=+$/g, ""); - } - else { - // if we have no information, we have to assume the key is right - return true; - } - } - else { - throw new Error("Unknown algorithm"); - } - }); - } - /** - * Store an encrypted secret on the server - * - * @param name - The name of the secret - * @param secret - The secret contents. - * @param keys - The IDs of the keys to use to encrypt the secret - * or null/undefined to use the default key. - */ - store(name, secret, keys) { - return __awaiter(this, void 0, void 0, function* () { - const encrypted = {}; - if (!keys) { - const defaultKeyId = yield this.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 (const keyId of keys) { - // get key information from key storage - const keyInfo = yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key." + keyId); - if (!keyInfo) { - throw new Error("Unknown key: " + keyId); - } - // encrypt secret, based on the algorithm - if (keyInfo.algorithm === exports.SECRET_STORAGE_ALGORITHM_V1_AES) { - const keys = { [keyId]: keyInfo }; - const [, encryption] = yield this.getSecretStorageKey(keys, name); - encrypted[keyId] = yield encryption.encrypt(secret); - } - else { - logger_1.logger.warn("unknown algorithm for secret storage key " + keyId + ": " + keyInfo.algorithm); - // do nothing if we don't understand the encryption algorithm - } - } - // save encrypted secret - yield this.accountDataAdapter.setAccountData(name, { encrypted }); - }); - } - /** - * Get a secret from storage. - * - * @param name - the name of the secret - * - * @returns the contents of the secret - */ - get(name) { - return __awaiter(this, void 0, void 0, function* () { - const secretInfo = yield this.accountDataAdapter.getAccountDataFromServer(name); - if (!secretInfo) { - return; - } - if (!secretInfo.encrypted) { - throw new Error("Content is not encrypted!"); - } - // get possible keys to decrypt - const keys = {}; - for (const keyId of Object.keys(secretInfo.encrypted)) { - // get key information from key storage - const keyInfo = yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key." + keyId); - const encInfo = secretInfo.encrypted[keyId]; - // only use keys we understand the encryption algorithm of - if (keyInfo.algorithm === exports.SECRET_STORAGE_ALGORITHM_V1_AES) { - if (encInfo.iv && encInfo.ciphertext && encInfo.mac) { - keys[keyId] = keyInfo; - } - } - } - if (Object.keys(keys).length === 0) { - throw new Error(`Could not decrypt ${name} because none of ` + - `the keys it is encrypted with are for a supported algorithm`); - } - // fetch private key from app - const [keyId, decryption] = yield this.getSecretStorageKey(keys, name); - const 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) { - return __awaiter(this, void 0, void 0, function* () { - // check if secret exists - const secretInfo = yield this.accountDataAdapter.getAccountDataFromServer(name); - if (!(secretInfo === null || secretInfo === void 0 ? void 0 : secretInfo.encrypted)) - return null; - const ret = {}; - // filter secret encryption keys with supported algorithm - for (const keyId of Object.keys(secretInfo.encrypted)) { - // get key information from key storage - const keyInfo = yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key." + keyId); - if (!keyInfo) - continue; - const encInfo = secretInfo.encrypted[keyId]; - // only use keys we understand the encryption algorithm of - if (keyInfo.algorithm === exports.SECRET_STORAGE_ALGORITHM_V1_AES) { - if (encInfo.iv && encInfo.ciphertext && encInfo.mac) { - ret[keyId] = keyInfo; - } - } - } - return Object.keys(ret).length ? ret : null; - }); - } - /** - * Request a secret from another device - * - * @param name - the name of the secret to request - * @param devices - the devices to request the secret from - */ - request(name, devices) { - const requestId = this.baseApis.makeTxnId(); - const deferred = (0, utils_1.defer)(); - this.requests.set(requestId, { name, devices, deferred }); - const cancel = (reason) => { - // send cancellation event - const cancelData = { - action: "request_cancellation", - requesting_device_id: this.baseApis.deviceId, - request_id: requestId, - }; - const toDevice = new Map(); - for (const device of devices) { - toDevice.set(device, cancelData); - } - this.baseApis.sendToDevice("m.secret.request", new Map([[this.baseApis.getUserId(), toDevice]])); - // and reject the promise so that anyone waiting on it will be - // notified - deferred.reject(new Error(reason || "Cancelled")); - }; - // send request to devices - const requestData = { - name, - action: "request", - requesting_device_id: this.baseApis.deviceId, - request_id: requestId, - [event_1.ToDeviceMessageId]: (0, uuid_1.v4)(), - }; - const toDevice = new Map(); - for (const device of devices) { - toDevice.set(device, requestData); - } - logger_1.logger.info(`Request secret ${name} from ${devices}, id ${requestId}`); - this.baseApis.sendToDevice("m.secret.request", new Map([[this.baseApis.getUserId(), toDevice]])); - return { - requestId, - promise: deferred.promise, - cancel, - }; - } - onRequestReceived(event) { - return __awaiter(this, void 0, void 0, function* () { - const sender = event.getSender(); - const content = event.getContent(); - if (sender !== this.baseApis.getUserId() || - !(content.name && content.action && content.requesting_device_id && content.request_id)) { - // ignore requests from anyone else, for now - return; - } - const deviceId = content.requesting_device_id; - // check if it's a cancel - if (content.action === "request_cancellation") { - /* - Looks like we intended to emit events when we got cancelations, but - we never put anything in the _incomingRequests object, and the request - itself doesn't use events anyway so if we were to wire up cancellations, - they probably ought to use the same callback interface. I'm leaving them - disabled for now while converting this file to typescript. - if (this._incomingRequests[deviceId] - && this._incomingRequests[deviceId][content.request_id]) { - logger.info( - "received request cancellation for secret (" + sender + - ", " + deviceId + ", " + content.request_id + ")", - ); - this.baseApis.emit("crypto.secrets.requestCancelled", { - user_id: sender, - device_id: deviceId, - request_id: content.request_id, - }); - } - */ - } - else if (content.action === "request") { - if (deviceId === this.baseApis.deviceId) { - // no point in trying to send ourself the secret - return; - } - // check if we have the secret - logger_1.logger.info("received request for secret (" + sender + ", " + deviceId + ", " + content.request_id + ")"); - if (!this.cryptoCallbacks.onSecretRequested) { - return; - } - const secret = yield this.cryptoCallbacks.onSecretRequested(sender, deviceId, content.request_id, content.name, this.baseApis.checkDeviceTrust(sender, deviceId)); - if (secret) { - logger_1.logger.info(`Preparing ${content.name} secret for ${deviceId}`); - const payload = { - type: "m.secret.send", - content: { - request_id: content.request_id, - secret: secret, - }, - }; - const encryptedContent = { - algorithm: olmlib.OLM_ALGORITHM, - sender_key: this.baseApis.crypto.olmDevice.deviceCurve25519Key, - ciphertext: {}, - [event_1.ToDeviceMessageId]: (0, uuid_1.v4)(), - }; - yield olmlib.ensureOlmSessionsForDevices(this.baseApis.crypto.olmDevice, this.baseApis, new Map([[sender, [this.baseApis.getStoredDevice(sender, deviceId)]]])); - yield olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this.baseApis.getUserId(), this.baseApis.deviceId, this.baseApis.crypto.olmDevice, sender, this.baseApis.getStoredDevice(sender, deviceId), payload); - const contentMap = new Map([[sender, new Map([[deviceId, encryptedContent]])]]); - logger_1.logger.info(`Sending ${content.name} secret for ${deviceId}`); - this.baseApis.sendToDevice("m.room.encrypted", contentMap); - } - else { - logger_1.logger.info(`Request denied for ${content.name} secret for ${deviceId}`); - } - } - }); - } - onSecretReceived(event) { - if (event.getSender() !== this.baseApis.getUserId()) { - // we shouldn't be receiving secrets from anyone else, so ignore - // because someone could be trying to send us bogus data - return; - } - if (!olmlib.isOlmEncrypted(event)) { - logger_1.logger.error("secret event not properly encrypted"); - return; - } - const content = event.getContent(); - const senderKeyUser = this.baseApis.crypto.deviceList.getUserByIdentityKey(olmlib.OLM_ALGORITHM, event.getSenderKey() || ""); - if (senderKeyUser !== event.getSender()) { - logger_1.logger.error("sending device does not belong to the user it claims to be from"); - return; - } - logger_1.logger.log("got secret share for request", content.request_id); - const requestControl = this.requests.get(content.request_id); - if (requestControl) { - // make sure that the device that sent it is one of the devices that - // we requested from - const deviceInfo = this.baseApis.crypto.deviceList.getDeviceByIdentityKey(olmlib.OLM_ALGORITHM, event.getSenderKey()); - if (!deviceInfo) { - logger_1.logger.log("secret share from unknown device with key", event.getSenderKey()); - return; - } - if (!requestControl.devices.includes(deviceInfo.deviceId)) { - logger_1.logger.log("unsolicited secret share from device", deviceInfo.deviceId); - return; - } - // unsure that the sender is trusted. In theory, this check is - // unnecessary since we only accept secret shares from devices that - // we requested from, but it doesn't hurt. - const deviceTrust = this.baseApis.crypto.checkDeviceInfoTrust(event.getSender(), deviceInfo); - if (!deviceTrust.isVerified()) { - logger_1.logger.log("secret share from unverified device"); - return; - } - logger_1.logger.log(`Successfully received secret ${requestControl.name} ` + `from ${deviceInfo.deviceId}`); - requestControl.deferred.resolve(content.secret); - } - } - getSecretStorageKey(keys, name) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.cryptoCallbacks.getSecretStorageKey) { - throw new Error("No getSecretStorageKey callback supplied"); - } - const returned = yield this.cryptoCallbacks.getSecretStorageKey({ keys }, name); - if (!returned) { - throw new Error("getSecretStorageKey callback returned falsey"); - } - if (returned.length < 2) { - throw new Error("getSecretStorageKey callback returned invalid data"); - } - const [keyId, privateKey] = returned; - if (!keys[keyId]) { - throw new Error("App returned unknown key from getSecretStorageKey!"); - } - if (keys[keyId].algorithm === exports.SECRET_STORAGE_ALGORITHM_V1_AES) { - const decryption = { - encrypt: function (secret) { - return (0, aes_1.encryptAES)(secret, privateKey, name); - }, - decrypt: function (encInfo) { - return (0, aes_1.decryptAES)(encInfo, privateKey, name); - }, - }; - return [keyId, decryption]; - } - else { - throw new Error("Unknown key type: " + keys[keyId].algorithm); - } - }); - } -} -exports.SecretStorage = SecretStorage; - -},{"../@types/event":306,"../client":321,"../logger":374,"../randomstring":398,"../utils":416,"./aes":331,"./olmlib":343,"uuid":287}],331:[function(require,module,exports){ -"use strict"; -/* -Copyright 2020 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.calculateKeyCheck = exports.decryptAES = exports.encryptAES = void 0; -const olmlib_1 = require("./olmlib"); -const crypto_1 = require("./crypto"); -// salt for HKDF, with 8 bytes of zeros -const zeroSalt = new Uint8Array(8); -/** - * encrypt a string - * - * @param data - the plaintext to encrypt - * @param key - the encryption key to use - * @param name - the name of the secret - * @param ivStr - the initialization vector to use - */ -function encryptAES(data, key, name, ivStr) { - return __awaiter(this, void 0, void 0, function* () { - let iv; - if (ivStr) { - iv = (0, olmlib_1.decodeBase64)(ivStr); - } - else { - iv = new Uint8Array(16); - crypto_1.crypto.getRandomValues(iv); - // clear bit 63 of the IV to stop us hitting the 64-bit counter boundary - // (which would mean we wouldn't be able to decrypt on Android). The loss - // of a single bit of iv is a price we have to pay. - iv[8] &= 0x7f; - } - const [aesKey, hmacKey] = yield deriveKeys(key, name); - const encodedData = new crypto_1.TextEncoder().encode(data); - const ciphertext = yield crypto_1.subtleCrypto.encrypt({ - name: "AES-CTR", - counter: iv, - length: 64, - }, aesKey, encodedData); - const hmac = yield crypto_1.subtleCrypto.sign({ name: "HMAC" }, hmacKey, ciphertext); - return { - iv: (0, olmlib_1.encodeBase64)(iv), - ciphertext: (0, olmlib_1.encodeBase64)(ciphertext), - mac: (0, olmlib_1.encodeBase64)(hmac), - }; - }); -} -exports.encryptAES = encryptAES; -/** - * decrypt a string - * - * @param data - the encrypted data - * @param key - the encryption key to use - * @param name - the name of the secret - */ -function decryptAES(data, key, name) { - return __awaiter(this, void 0, void 0, function* () { - const [aesKey, hmacKey] = yield deriveKeys(key, name); - const ciphertext = (0, olmlib_1.decodeBase64)(data.ciphertext); - if (!(yield crypto_1.subtleCrypto.verify({ name: "HMAC" }, hmacKey, (0, olmlib_1.decodeBase64)(data.mac), ciphertext))) { - throw new Error(`Error decrypting secret ${name}: bad MAC`); - } - const plaintext = yield crypto_1.subtleCrypto.decrypt({ - name: "AES-CTR", - counter: (0, olmlib_1.decodeBase64)(data.iv), - length: 64, - }, aesKey, ciphertext); - return new TextDecoder().decode(new Uint8Array(plaintext)); - }); -} -exports.decryptAES = decryptAES; -function deriveKeys(key, name) { - return __awaiter(this, void 0, void 0, function* () { - const hkdfkey = yield crypto_1.subtleCrypto.importKey("raw", key, { name: "HKDF" }, false, ["deriveBits"]); - const keybits = yield crypto_1.subtleCrypto.deriveBits({ - name: "HKDF", - salt: zeroSalt, - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore: https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/879 - info: new crypto_1.TextEncoder().encode(name), - hash: "SHA-256", - }, hkdfkey, 512); - const aesKey = keybits.slice(0, 32); - const hmacKey = keybits.slice(32); - const aesProm = crypto_1.subtleCrypto.importKey("raw", aesKey, { name: "AES-CTR" }, false, ["encrypt", "decrypt"]); - const hmacProm = crypto_1.subtleCrypto.importKey("raw", hmacKey, { - name: "HMAC", - hash: { name: "SHA-256" }, - }, false, ["sign", "verify"]); - return Promise.all([aesProm, hmacProm]); - }); -} -// string of zeroes, for calculating the key check -const 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. - * - * @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 encryptAES(ZERO_STR, key, "", iv); -} -exports.calculateKeyCheck = calculateKeyCheck; - -},{"./crypto":338,"./olmlib":343}],332:[function(require,module,exports){ -"use strict"; -/* -Copyright 2016 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.registerAlgorithm = exports.UnknownDeviceError = exports.DecryptionError = exports.DecryptionAlgorithm = exports.EncryptionAlgorithm = exports.DECRYPTION_CLASSES = exports.ENCRYPTION_CLASSES = void 0; -/** - * Map of registered encryption algorithm classes. A map from string to {@link EncryptionAlgorithm} class - */ -exports.ENCRYPTION_CLASSES = new Map(); -/** - * map of registered encryption algorithm classes. Map from string to {@link DecryptionAlgorithm} class - */ -exports.DECRYPTION_CLASSES = new Map(); -/** - * base type for encryption implementations - */ -class EncryptionAlgorithm { - /** - * @param params - parameters - */ - constructor(params) { - this.userId = params.userId; - this.deviceId = params.deviceId; - this.crypto = params.crypto; - this.olmDevice = params.olmDevice; - this.baseApis = params.baseApis; - this.roomId = params.roomId; - } - /** - * Perform any background tasks that can be done before a message is ready to - * send, in order to speed up sending of the message. - * - * @param room - the room the event is in - */ - prepareToEncrypt(room) { } - /** - * Called when the membership of a member of the room changes. - * - * @param event - event causing the change - * @param member - user whose membership changed - * @param oldMembership - previous membership - * @public - */ - onRoomMembership(event, member, oldMembership) { } -} -exports.EncryptionAlgorithm = EncryptionAlgorithm; -/** - * base type for decryption implementations - */ -class DecryptionAlgorithm { - constructor(params) { - this.userId = params.userId; - this.crypto = params.crypto; - this.olmDevice = params.olmDevice; - this.baseApis = params.baseApis; - this.roomId = params.roomId; - } - /** - * Handle a key event - * - * @param params - event key event - */ - onRoomKeyEvent(params) { - return __awaiter(this, void 0, void 0, function* () { - // ignore by default - }); - } - /** - * Import a room key - * - * @param opts - object - */ - importRoomKey(session, opts) { - return __awaiter(this, void 0, void 0, function* () { - // ignore by default - }); - } - /** - * Determine if we have the keys necessary to respond to a room key request - * - * @returns true if we have the keys and could (theoretically) share - * them; else false. - */ - hasKeysForKeyRequest(keyRequest) { - return Promise.resolve(false); - } - /** - * Send the response to a room key request - * - */ - shareKeysWithDevice(keyRequest) { - throw new Error("shareKeysWithDevice not supported for this DecryptionAlgorithm"); - } - /** - * Retry decrypting all the events from a sender that haven't been - * decrypted yet. - * - * @param senderKey - the sender's key - */ - retryDecryptionFromSender(senderKey) { - return __awaiter(this, void 0, void 0, function* () { - // ignore by default - return false; - }); - } -} -exports.DecryptionAlgorithm = DecryptionAlgorithm; -/** - * Exception thrown when decryption fails - * - * @param msg - user-visible message describing the problem - * - * @param details - key/value pairs reported in the logs but not shown - * to the user. - */ -class DecryptionError extends Error { - constructor(code, msg, details) { - super(msg); - this.code = code; - this.code = code; - this.name = "DecryptionError"; - this.detailedString = detailedStringForDecryptionError(this, details); - } -} -exports.DecryptionError = DecryptionError; -function detailedStringForDecryptionError(err, details) { - let result = err.name + "[msg: " + err.message; - if (details) { - result += - ", " + - Object.keys(details) - .map((k) => k + ": " + details[k]) - .join(", "); - } - result += "]"; - return result; -} -class UnknownDeviceError extends Error { - /** - * Exception thrown specifically when we want to warn the user to consider - * the security of their conversation before continuing - * - * @param msg - message describing the problem - * @param devices - set of unknown devices per user we're warning about - */ - constructor(msg, devices, event) { - super(msg); - this.devices = devices; - this.event = event; - this.name = "UnknownDeviceError"; - this.devices = devices; - } -} -exports.UnknownDeviceError = UnknownDeviceError; -/** - * Registers an encryption/decryption class for a particular algorithm - * - * @param algorithm - algorithm tag to register for - * - * @param encryptor - {@link EncryptionAlgorithm} implementation - * - * @param decryptor - {@link DecryptionAlgorithm} implementation - */ -function registerAlgorithm(algorithm, encryptor, decryptor) { - exports.ENCRYPTION_CLASSES.set(algorithm, encryptor); - exports.DECRYPTION_CLASSES.set(algorithm, decryptor); -} -exports.registerAlgorithm = registerAlgorithm; - -},{}],333:[function(require,module,exports){ -"use strict"; -/* -Copyright 2016 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -require("./olm"); -require("./megolm"); -__exportStar(require("./base"), exports); - -},{"./base":332,"./megolm":334,"./olm":335}],334:[function(require,module,exports){ -"use strict"; -/* -Copyright 2015 - 2021, 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MegolmDecryption = exports.MegolmEncryption = exports.isRoomSharedHistory = void 0; -/** - * Defines m.olm encryption/decryption - */ -const uuid_1 = require("uuid"); -const logger_1 = require("../../logger"); -const olmlib = __importStar(require("../olmlib")); -const base_1 = require("./base"); -const OlmDevice_1 = require("../OlmDevice"); -const event_1 = require("../../@types/event"); -const OutgoingRoomKeyRequestManager_1 = require("../OutgoingRoomKeyRequestManager"); -const utils_1 = require("../../utils"); -// determine whether the key can be shared with invitees -function isRoomSharedHistory(room) { - var _a, _b; - const visibilityEvent = (_a = room === null || room === void 0 ? void 0 : room.currentState) === null || _a === void 0 ? void 0 : _a.getStateEvents("m.room.history_visibility", ""); - // NOTE: if the room visibility is unset, it would normally default to - // "world_readable". - // (https://spec.matrix.org/unstable/client-server-api/#server-behaviour-5) - // But we will be paranoid here, and treat it as a situation where the room - // is not shared-history - const visibility = (_b = visibilityEvent === null || visibilityEvent === void 0 ? void 0 : visibilityEvent.getContent()) === null || _b === void 0 ? void 0 : _b.history_visibility; - return ["world_readable", "shared"].includes(visibility); -} -exports.isRoomSharedHistory = isRoomSharedHistory; -/** - * Tests whether an encrypted content has a ciphertext. - * Ciphertext can be a string or object depending on the content type {@link IEncryptedContent}. - * - * @param content - Encrypted content - * @returns true: has ciphertext, else false - */ -const hasCiphertext = (content) => { - return typeof content.ciphertext === "string" - ? !!content.ciphertext.length - : !!Object.keys(content.ciphertext).length; -}; -/** - * @internal - */ -class OutboundSessionInfo { - /** - * @param sharedHistory - whether the session can be freely shared with - * other group members, according to the room history visibility settings - */ - constructor(sessionId, sharedHistory = false) { - this.sessionId = sessionId; - this.sharedHistory = sharedHistory; - /** number of times this session has been used */ - this.useCount = 0; - /** devices with which we have shared the session key `userId -> {deviceId -> SharedWithData}` */ - this.sharedWithDevices = new utils_1.MapWithDefault(() => new Map()); - this.blockedDevicesNotified = new utils_1.MapWithDefault(() => new Map()); - this.creationTime = new Date().getTime(); - } - /** - * Check if it's time to rotate the session - */ - needsRotation(rotationPeriodMsgs, rotationPeriodMs) { - const sessionLifetime = new Date().getTime() - this.creationTime; - if (this.useCount >= rotationPeriodMsgs || sessionLifetime >= rotationPeriodMs) { - logger_1.logger.log("Rotating megolm session after " + this.useCount + " messages, " + sessionLifetime + "ms"); - return true; - } - return false; - } - markSharedWithDevice(userId, deviceId, deviceKey, chainIndex) { - this.sharedWithDevices.getOrCreate(userId).set(deviceId, { deviceKey, messageIndex: chainIndex }); - } - markNotifiedBlockedDevice(userId, deviceId) { - this.blockedDevicesNotified.getOrCreate(userId).set(deviceId, true); - } - /** - * Determine if this session has been shared with devices which it shouldn't - * have been. - * - * @param devicesInRoom - `userId -> {deviceId -> object}` - * devices we should shared the session with. - * - * @returns true if we have shared the session with devices which aren't - * in devicesInRoom. - */ - sharedWithTooManyDevices(devicesInRoom) { - var _a; - for (const [userId, devices] of this.sharedWithDevices) { - if (!devicesInRoom.has(userId)) { - logger_1.logger.log("Starting new megolm session because we shared with " + userId); - return true; - } - for (const [deviceId] of devices) { - if (!((_a = devicesInRoom.get(userId)) === null || _a === void 0 ? void 0 : _a.get(deviceId))) { - logger_1.logger.log("Starting new megolm session because we shared with " + userId + ":" + deviceId); - return true; - } - } - } - return false; - } -} -/** - * Megolm encryption implementation - * - * @param params - parameters, as per {@link EncryptionAlgorithm} - */ -class MegolmEncryption extends base_1.EncryptionAlgorithm { - constructor(params) { - var _a, _b, _c, _d; - super(params); - // the most recent attempt to set up a session. This is used to serialise - // the session setups, so that we have a race-free view of which session we - // are using, and which devices we have shared the keys with. It resolves - // with an OutboundSessionInfo (or undefined, for the first message in the - // room). - this.setupPromise = Promise.resolve(null); - // Map of outbound sessions by sessions ID. Used if we need a particular - // session (the session we're currently using to send is always obtained - // using setupPromise). - this.outboundSessions = {}; - this.roomId = params.roomId; - this.prefixedLogger = logger_1.logger.withPrefix(`[${this.roomId} encryption]`); - this.sessionRotationPeriodMsgs = (_b = (_a = params.config) === null || _a === void 0 ? void 0 : _a.rotation_period_msgs) !== null && _b !== void 0 ? _b : 100; - this.sessionRotationPeriodMs = (_d = (_c = params.config) === null || _c === void 0 ? void 0 : _c.rotation_period_ms) !== null && _d !== void 0 ? _d : 7 * 24 * 3600 * 1000; - } - /** - * @internal - * - * @param devicesInRoom - The devices in this room, indexed by user ID - * @param blocked - The devices that are blocked, indexed by user ID - * @param singleOlmCreationPhase - Only perform one round of olm - * session creation - * - * This method updates the setupPromise field of the class by chaining a new - * call on top of the existing promise, and then catching and discarding any - * errors that might happen while setting up the outbound group session. This - * is done to ensure that `setupPromise` always resolves to `null` or the - * `OutboundSessionInfo`. - * - * Using `>>=` to represent the promise chaining operation, it does the - * following: - * - * ``` - * setupPromise = previousSetupPromise >>= setup >>= discardErrors - * ``` - * - * The initial value for the `setupPromise` is a promise that resolves to - * `null`. The forceDiscardSession() resets setupPromise to this initial - * promise. - * - * @returns Promise which resolves to the - * OutboundSessionInfo when setup is complete. - */ - ensureOutboundSession(room, devicesInRoom, blocked, singleOlmCreationPhase = false) { - return __awaiter(this, void 0, void 0, function* () { - // takes the previous OutboundSessionInfo, and considers whether to create - // a new one. Also shares the key with any (new) devices in the room. - // - // returns a promise which resolves once the keyshare is successful. - const setup = (oldSession) => __awaiter(this, void 0, void 0, function* () { - const sharedHistory = isRoomSharedHistory(room); - const session = yield this.prepareSession(devicesInRoom, sharedHistory, oldSession); - yield this.shareSession(devicesInRoom, sharedHistory, singleOlmCreationPhase, blocked, session); - return session; - }); - // first wait for the previous share to complete - const fallible = this.setupPromise.then(setup); - // Ensure any failures are logged for debugging and make sure that the - // promise chain remains unbroken - // - // setupPromise resolves to `null` or the `OutboundSessionInfo` whether - // or not the share succeeds - this.setupPromise = fallible.catch((e) => { - this.prefixedLogger.error(`Failed to setup outbound session`, e); - return null; - }); - // but we return a promise which only resolves if the share was successful. - return fallible; - }); - } - prepareSession(devicesInRoom, sharedHistory, session) { - return __awaiter(this, void 0, void 0, function* () { - // history visibility changed - if (session && sharedHistory !== session.sharedHistory) { - session = null; - } - // need to make a brand new session? - if (session === null || session === void 0 ? void 0 : session.needsRotation(this.sessionRotationPeriodMsgs, this.sessionRotationPeriodMs)) { - this.prefixedLogger.log("Starting new megolm session because we need to rotate."); - session = null; - } - // determine if we have shared with anyone we shouldn't have - if (session === null || session === void 0 ? void 0 : session.sharedWithTooManyDevices(devicesInRoom)) { - session = null; - } - if (!session) { - this.prefixedLogger.log("Starting new megolm session"); - session = yield this.prepareNewSession(sharedHistory); - this.prefixedLogger.log(`Started new megolm session ${session.sessionId}`); - this.outboundSessions[session.sessionId] = session; - } - return session; - }); - } - shareSession(devicesInRoom, sharedHistory, singleOlmCreationPhase, blocked, session) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - // now check if we need to share with any devices - const shareMap = {}; - for (const [userId, userDevices] of devicesInRoom) { - for (const [deviceId, deviceInfo] of userDevices) { - const key = deviceInfo.getIdentityKey(); - if (key == this.olmDevice.deviceCurve25519Key) { - // don't bother sending to ourself - continue; - } - if (!((_a = session.sharedWithDevices.get(userId)) === null || _a === void 0 ? void 0 : _a.get(deviceId))) { - shareMap[userId] = shareMap[userId] || []; - shareMap[userId].push(deviceInfo); - } - } - } - const key = this.olmDevice.getOutboundGroupSessionKey(session.sessionId); - const payload = { - type: "m.room_key", - content: { - "algorithm": olmlib.MEGOLM_ALGORITHM, - "room_id": this.roomId, - "session_id": session.sessionId, - "session_key": key.key, - "chain_index": key.chain_index, - "org.matrix.msc3061.shared_history": sharedHistory, - }, - }; - const [devicesWithoutSession, olmSessions] = yield olmlib.getExistingOlmSessions(this.olmDevice, this.baseApis, shareMap); - yield Promise.all([ - (() => __awaiter(this, void 0, void 0, function* () { - // share keys with devices that we already have a session for - const olmSessionList = Array.from(olmSessions.entries()) - .map(([userId, sessionsByUser]) => Array.from(sessionsByUser.entries()).map(([deviceId, session]) => `${userId}/${deviceId}: ${session.sessionId}`)) - .flat(1); - this.prefixedLogger.debug("Sharing keys with devices with existing Olm sessions:", olmSessionList); - yield this.shareKeyWithOlmSessions(session, key, payload, olmSessions); - this.prefixedLogger.debug("Shared keys with existing Olm sessions"); - }))(), - (() => __awaiter(this, void 0, void 0, function* () { - const deviceList = Array.from(devicesWithoutSession.entries()) - .map(([userId, devicesByUser]) => devicesByUser.map((device) => `${userId}/${device.deviceId}`)) - .flat(1); - this.prefixedLogger.debug("Sharing keys (start phase 1) with devices without existing Olm sessions:", deviceList); - const errorDevices = []; - // meanwhile, establish olm sessions for devices that we don't - // already have a session for, and share keys with them. If - // we're doing two phases of olm session creation, use a - // shorter timeout when fetching one-time keys for the first - // phase. - const start = Date.now(); - const failedServers = []; - yield this.shareKeyWithDevices(session, key, payload, devicesWithoutSession, errorDevices, singleOlmCreationPhase ? 10000 : 2000, failedServers); - this.prefixedLogger.debug("Shared keys (end phase 1) with devices without existing Olm sessions"); - if (!singleOlmCreationPhase && Date.now() - start < 10000) { - // perform the second phase of olm session creation if requested, - // and if the first phase didn't take too long - (() => __awaiter(this, void 0, void 0, function* () { - // Retry sending keys to devices that we were unable to establish - // an olm session for. This time, we use a longer timeout, but we - // do this in the background and don't block anything else while we - // do this. We only need to retry users from servers that didn't - // respond the first time. - const retryDevices = new utils_1.MapWithDefault(() => []); - const failedServerMap = new Set(); - for (const server of failedServers) { - failedServerMap.add(server); - } - const failedDevices = []; - for (const { userId, deviceInfo } of errorDevices) { - const userHS = userId.slice(userId.indexOf(":") + 1); - if (failedServerMap.has(userHS)) { - retryDevices.getOrCreate(userId).push(deviceInfo); - } - else { - // if we aren't going to retry, then handle it - // as a failed device - failedDevices.push({ userId, deviceInfo }); - } - } - const retryDeviceList = Array.from(retryDevices.entries()) - .map(([userId, devicesByUser]) => devicesByUser.map((device) => `${userId}/${device.deviceId}`)) - .flat(1); - if (retryDeviceList.length > 0) { - this.prefixedLogger.debug("Sharing keys (start phase 2) with devices without existing Olm sessions:", retryDeviceList); - yield this.shareKeyWithDevices(session, key, payload, retryDevices, failedDevices, 30000); - this.prefixedLogger.debug("Shared keys (end phase 2) with devices without existing Olm sessions"); - } - yield this.notifyFailedOlmDevices(session, key, failedDevices); - }))(); - } - else { - yield this.notifyFailedOlmDevices(session, key, errorDevices); - } - }))(), - (() => __awaiter(this, void 0, void 0, function* () { - var _b; - this.prefixedLogger.debug(`There are ${blocked.size} blocked devices:`, Array.from(blocked.entries()) - .map(([userId, blockedByUser]) => Array.from(blockedByUser.entries()).map(([deviceId, _deviceInfo]) => `${userId}/${deviceId}`)) - .flat(1)); - // also, notify newly blocked devices that they're blocked - const blockedMap = new utils_1.MapWithDefault(() => new Map()); - let blockedCount = 0; - for (const [userId, userBlockedDevices] of blocked) { - for (const [deviceId, device] of userBlockedDevices) { - if (((_b = session.blockedDevicesNotified.get(userId)) === null || _b === void 0 ? void 0 : _b.get(deviceId)) === undefined) { - blockedMap.getOrCreate(userId).set(deviceId, { device }); - blockedCount++; - } - } - } - if (blockedCount) { - this.prefixedLogger.debug(`Notifying ${blockedCount} newly blocked devices:`, Array.from(blockedMap.entries()) - .map(([userId, blockedByUser]) => Object.entries(blockedByUser).map(([deviceId, _deviceInfo]) => `${userId}/${deviceId}`)) - .flat(1)); - yield this.notifyBlockedDevices(session, blockedMap); - this.prefixedLogger.debug(`Notified ${blockedCount} newly blocked devices`); - } - }))(), - ]); - }); - } - /** - * @internal - * - * - * @returns session - */ - prepareNewSession(sharedHistory) { - return __awaiter(this, void 0, void 0, function* () { - const sessionId = this.olmDevice.createOutboundGroupSession(); - const key = this.olmDevice.getOutboundGroupSessionKey(sessionId); - yield this.olmDevice.addInboundGroupSession(this.roomId, this.olmDevice.deviceCurve25519Key, [], sessionId, key.key, { ed25519: this.olmDevice.deviceEd25519Key }, false, { sharedHistory }); - // don't wait for it to complete - this.crypto.backupManager.backupGroupSession(this.olmDevice.deviceCurve25519Key, sessionId); - return new OutboundSessionInfo(sessionId, sharedHistory); - }); - } - /** - * Determines what devices in devicesByUser don't have an olm session as given - * in devicemap. - * - * @internal - * - * @param deviceMap - the devices that have olm sessions, as returned by - * olmlib.ensureOlmSessionsForDevices. - * @param devicesByUser - a map of user IDs to array of deviceInfo - * @param noOlmDevices - an array to fill with devices that don't have - * olm sessions - * - * @returns an array of devices that don't have olm sessions. If - * noOlmDevices is specified, then noOlmDevices will be returned. - */ - getDevicesWithoutSessions(deviceMap, devicesByUser, noOlmDevices = []) { - for (const [userId, devicesToShareWith] of devicesByUser) { - const sessionResults = deviceMap.get(userId); - for (const deviceInfo of devicesToShareWith) { - const deviceId = deviceInfo.deviceId; - const sessionResult = sessionResults === null || sessionResults === void 0 ? void 0 : sessionResults.get(deviceId); - if (!(sessionResult === null || sessionResult === void 0 ? void 0 : sessionResult.sessionId)) { - // no session with this device, probably because there - // were no one-time keys. - noOlmDevices.push({ userId, deviceInfo }); - sessionResults === null || sessionResults === void 0 ? void 0 : sessionResults.delete(deviceId); - // ensureOlmSessionsForUsers has already done the logging, - // so just skip it. - continue; - } - } - } - return noOlmDevices; - } - /** - * Splits the user device map into multiple chunks to reduce the number of - * devices we encrypt to per API call. - * - * @internal - * - * @param devicesByUser - map from userid to list of devices - * - * @returns the blocked devices, split into chunks - */ - splitDevices(devicesByUser) { - const maxDevicesPerRequest = 20; - // use an array where the slices of a content map gets stored - let currentSlice = []; - const mapSlices = [currentSlice]; - for (const [userId, userDevices] of devicesByUser) { - for (const deviceInfo of userDevices.values()) { - currentSlice.push({ - userId: userId, - deviceInfo: deviceInfo.device, - }); - } - // We do this in the per-user loop as we prefer that all messages to the - // same user end up in the same API call to make it easier for the - // server (e.g. only have to send one EDU if a remote user, etc). This - // does mean that if a user has many devices we may go over the desired - // limit, but its not a hard limit so that is fine. - if (currentSlice.length > maxDevicesPerRequest) { - // the current slice is filled up. Start inserting into the next slice - currentSlice = []; - mapSlices.push(currentSlice); - } - } - if (currentSlice.length === 0) { - mapSlices.pop(); - } - return mapSlices; - } - /** - * @internal - * - * - * @param chainIndex - current chain index - * - * @param userDeviceMap - mapping from userId to deviceInfo - * - * @param payload - fields to include in the encrypted payload - * - * @returns Promise which resolves once the key sharing - * for the given userDeviceMap is generated and has been sent. - */ - encryptAndSendKeysToDevices(session, chainIndex, devices, payload) { - return this.crypto - .encryptAndSendToDevices(devices, payload) - .then(() => { - // store that we successfully uploaded the keys of the current slice - for (const device of devices) { - session.markSharedWithDevice(device.userId, device.deviceInfo.deviceId, device.deviceInfo.getIdentityKey(), chainIndex); - } - }) - .catch((error) => { - this.prefixedLogger.error("failed to encryptAndSendToDevices", error); - throw error; - }); - } - /** - * @internal - * - * - * @param userDeviceMap - list of blocked devices to notify - * - * @param payload - fields to include in the notification payload - * - * @returns Promise which resolves once the notifications - * for the given userDeviceMap is generated and has been sent. - */ - sendBlockedNotificationsToDevices(session, userDeviceMap, payload) { - return __awaiter(this, void 0, void 0, function* () { - const contentMap = new utils_1.MapWithDefault(() => new Map()); - for (const val of userDeviceMap) { - const userId = val.userId; - const blockedInfo = val.deviceInfo; - const deviceInfo = blockedInfo.deviceInfo; - const deviceId = deviceInfo.deviceId; - const message = Object.assign(Object.assign({}, payload), { code: blockedInfo.code, reason: blockedInfo.reason, [event_1.ToDeviceMessageId]: (0, uuid_1.v4)() }); - if (message.code === "m.no_olm") { - delete message.room_id; - delete message.session_id; - } - contentMap.getOrCreate(userId).set(deviceId, message); - } - yield this.baseApis.sendToDevice("m.room_key.withheld", contentMap); - // record the fact that we notified these blocked devices - for (const [userId, userDeviceMap] of contentMap) { - for (const deviceId of userDeviceMap.keys()) { - session.markNotifiedBlockedDevice(userId, deviceId); - } - } - }); - } - /** - * Re-shares a megolm session key with devices if the key has already been - * sent to them. - * - * @param senderKey - The key of the originating device for the session - * @param sessionId - ID of the outbound session to share - * @param userId - ID of the user who owns the target device - * @param device - The target device - */ - reshareKeyWithDevice(senderKey, sessionId, userId, device) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const obSessionInfo = this.outboundSessions[sessionId]; - if (!obSessionInfo) { - this.prefixedLogger.debug(`megolm session ${senderKey}|${sessionId} not found: not re-sharing keys`); - return; - } - // The chain index of the key we previously sent this device - if (!obSessionInfo.sharedWithDevices.has(userId)) { - this.prefixedLogger.debug(`megolm session ${senderKey}|${sessionId} never shared with user ${userId}`); - return; - } - const sessionSharedData = (_a = obSessionInfo.sharedWithDevices.get(userId)) === null || _a === void 0 ? void 0 : _a.get(device.deviceId); - if (sessionSharedData === undefined) { - this.prefixedLogger.debug(`megolm session ${senderKey}|${sessionId} never shared with device ${userId}:${device.deviceId}`); - return; - } - if (sessionSharedData.deviceKey !== device.getIdentityKey()) { - this.prefixedLogger.warn(`Megolm session ${senderKey}|${sessionId} has been shared with device ${device.deviceId} but ` + - `with identity key ${sessionSharedData.deviceKey}. Key is now ${device.getIdentityKey()}!`); - return; - } - // get the key from the inbound session: the outbound one will already - // have been ratcheted to the next chain index. - const key = yield this.olmDevice.getInboundGroupSessionKey(this.roomId, senderKey, sessionId, sessionSharedData.messageIndex); - if (!key) { - this.prefixedLogger.warn(`No inbound session key found for megolm session ${senderKey}|${sessionId}: not re-sharing keys`); - return; - } - yield olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, new Map([[userId, [device]]])); - const payload = { - type: "m.forwarded_room_key", - content: { - "algorithm": olmlib.MEGOLM_ALGORITHM, - "room_id": this.roomId, - "session_id": sessionId, - "session_key": key.key, - "chain_index": key.chain_index, - "sender_key": senderKey, - "sender_claimed_ed25519_key": key.sender_claimed_ed25519_key, - "forwarding_curve25519_key_chain": key.forwarding_curve25519_key_chain, - "org.matrix.msc3061.shared_history": key.shared_history || false, - }, - }; - const encryptedContent = { - algorithm: olmlib.OLM_ALGORITHM, - sender_key: this.olmDevice.deviceCurve25519Key, - ciphertext: {}, - [event_1.ToDeviceMessageId]: (0, uuid_1.v4)(), - }; - yield olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this.userId, this.deviceId, this.olmDevice, userId, device, payload); - yield this.baseApis.sendToDevice("m.room.encrypted", new Map([[userId, new Map([[device.deviceId, encryptedContent]])]])); - this.prefixedLogger.debug(`Re-shared key for megolm session ${senderKey}|${sessionId} with ${userId}:${device.deviceId}`); - }); - } - /** - * @internal - * - * - * @param key - the session key as returned by - * OlmDevice.getOutboundGroupSessionKey - * - * @param payload - the base to-device message payload for sharing keys - * - * @param devicesByUser - map from userid to list of devices - * - * @param errorDevices - array that will be populated with the devices that we can't get an - * olm session for - * - * @param otkTimeout - The timeout in milliseconds when requesting - * one-time keys for establishing new olm sessions. - * - * @param failedServers - An array to fill with remote servers that - * failed to respond to one-time-key requests. - */ - shareKeyWithDevices(session, key, payload, devicesByUser, errorDevices, otkTimeout, failedServers) { - return __awaiter(this, void 0, void 0, function* () { - const devicemap = yield olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, devicesByUser, false, otkTimeout, failedServers, this.prefixedLogger); - this.getDevicesWithoutSessions(devicemap, devicesByUser, errorDevices); - yield this.shareKeyWithOlmSessions(session, key, payload, devicemap); - }); - } - shareKeyWithOlmSessions(session, key, payload, deviceMap) { - return __awaiter(this, void 0, void 0, function* () { - const userDeviceMaps = this.splitDevices(deviceMap); - for (let i = 0; i < userDeviceMaps.length; i++) { - const taskDetail = `megolm keys for ${session.sessionId} (slice ${i + 1}/${userDeviceMaps.length})`; - try { - this.prefixedLogger.debug(`Sharing ${taskDetail}`, userDeviceMaps[i].map((d) => `${d.userId}/${d.deviceInfo.deviceId}`)); - yield this.encryptAndSendKeysToDevices(session, key.chain_index, userDeviceMaps[i], payload); - this.prefixedLogger.debug(`Shared ${taskDetail}`); - } - catch (e) { - this.prefixedLogger.error(`Failed to share ${taskDetail}`); - throw e; - } - } - }); - } - /** - * Notify devices that we weren't able to create olm sessions. - * - * - * - * @param failedDevices - the devices that we were unable to - * create olm sessions for, as returned by shareKeyWithDevices - */ - notifyFailedOlmDevices(session, key, failedDevices) { - return __awaiter(this, void 0, void 0, function* () { - this.prefixedLogger.debug(`Notifying ${failedDevices.length} devices we failed to create Olm sessions`); - // mark the devices that failed as "handled" because we don't want to try - // to claim a one-time-key for dead devices on every message. - for (const { userId, deviceInfo } of failedDevices) { - const deviceId = deviceInfo.deviceId; - session.markSharedWithDevice(userId, deviceId, deviceInfo.getIdentityKey(), key.chain_index); - } - const unnotifiedFailedDevices = yield this.olmDevice.filterOutNotifiedErrorDevices(failedDevices); - this.prefixedLogger.debug(`Need to notify ${unnotifiedFailedDevices.length} failed devices which haven't been notified before`); - const blockedMap = new utils_1.MapWithDefault(() => new Map()); - for (const { userId, deviceInfo } of unnotifiedFailedDevices) { - // we use a similar format to what - // olmlib.ensureOlmSessionsForDevices returns, so that - // we can use the same function to split - blockedMap.getOrCreate(userId).set(deviceInfo.deviceId, { - device: { - code: "m.no_olm", - reason: OlmDevice_1.WITHHELD_MESSAGES["m.no_olm"], - deviceInfo, - }, - }); - } - // send the notifications - yield this.notifyBlockedDevices(session, blockedMap); - this.prefixedLogger.debug(`Notified ${unnotifiedFailedDevices.length} devices we failed to create Olm sessions`); - }); - } - /** - * Notify blocked devices that they have been blocked. - * - * - * @param devicesByUser - map from userid to device ID to blocked data - */ - notifyBlockedDevices(session, devicesByUser) { - return __awaiter(this, void 0, void 0, function* () { - const payload = { - room_id: this.roomId, - session_id: session.sessionId, - algorithm: olmlib.MEGOLM_ALGORITHM, - sender_key: this.olmDevice.deviceCurve25519Key, - }; - const userDeviceMaps = this.splitDevices(devicesByUser); - for (let i = 0; i < userDeviceMaps.length; i++) { - try { - yield this.sendBlockedNotificationsToDevices(session, userDeviceMaps[i], payload); - this.prefixedLogger.log(`Completed blacklist notification for ${session.sessionId} ` + - `(slice ${i + 1}/${userDeviceMaps.length})`); - } - catch (e) { - this.prefixedLogger.log(`blacklist notification for ${session.sessionId} ` + - `(slice ${i + 1}/${userDeviceMaps.length}) failed`); - throw e; - } - } - }); - } - /** - * Perform any background tasks that can be done before a message is ready to - * send, in order to speed up sending of the message. - * - * @param room - the room the event is in - * @returns A function that, when called, will stop the preparation - */ - prepareToEncrypt(room) { - if (room.roomId !== this.roomId) { - throw new Error("MegolmEncryption.prepareToEncrypt called on unexpected room"); - } - if (this.encryptionPreparation != null) { - // We're already preparing something, so don't do anything else. - const elapsedTime = Date.now() - this.encryptionPreparation.startTime; - this.prefixedLogger.debug(`Already started preparing to encrypt for this room ${elapsedTime}ms ago, skipping`); - return this.encryptionPreparation.cancel; - } - this.prefixedLogger.debug("Preparing to encrypt events"); - let cancelled = false; - const isCancelled = () => cancelled; - this.encryptionPreparation = { - startTime: Date.now(), - promise: (() => __awaiter(this, void 0, void 0, function* () { - try { - // Attempt to enumerate the devices in room, and gracefully - // handle cancellation if it occurs. - const getDevicesResult = yield this.getDevicesInRoom(room, false, isCancelled); - if (getDevicesResult === null) - return; - const [devicesInRoom, blocked] = getDevicesResult; - if (this.crypto.globalErrorOnUnknownDevices) { - // Drop unknown devices for now. When the message gets sent, we'll - // throw an error, but we'll still be prepared to send to the known - // devices. - this.removeUnknownDevices(devicesInRoom); - } - this.prefixedLogger.debug("Ensuring outbound megolm session"); - yield this.ensureOutboundSession(room, devicesInRoom, blocked, true); - this.prefixedLogger.debug("Ready to encrypt events"); - } - catch (e) { - this.prefixedLogger.error("Failed to prepare to encrypt events", e); - } - finally { - delete this.encryptionPreparation; - } - }))(), - cancel: () => { - // The caller has indicated that the process should be cancelled, - // so tell the promise that we'd like to halt, and reset the preparation state. - cancelled = true; - delete this.encryptionPreparation; - }, - }; - return this.encryptionPreparation.cancel; - } - /** - * @param content - plaintext event content - * - * @returns Promise which resolves to the new event body - */ - encryptMessage(room, eventType, content) { - return __awaiter(this, void 0, void 0, function* () { - this.prefixedLogger.log("Starting to encrypt event"); - if (this.encryptionPreparation != null) { - // If we started sending keys, wait for it to be done. - // FIXME: check if we need to cancel - // (https://github.com/matrix-org/matrix-js-sdk/issues/1255) - try { - yield this.encryptionPreparation.promise; - } - catch (e) { - // ignore any errors -- if the preparation failed, we'll just - // restart everything here - } - } - /** - * When using in-room messages and the room has encryption enabled, - * clients should ensure that encryption does not hinder the verification. - */ - const forceDistributeToUnverified = this.isVerificationEvent(eventType, content); - const [devicesInRoom, blocked] = yield this.getDevicesInRoom(room, forceDistributeToUnverified); - // check if any of these devices are not yet known to the user. - // if so, warn the user so they can verify or ignore. - if (this.crypto.globalErrorOnUnknownDevices) { - this.checkForUnknownDevices(devicesInRoom); - } - const session = yield this.ensureOutboundSession(room, devicesInRoom, blocked); - const payloadJson = { - room_id: this.roomId, - type: eventType, - content: content, - }; - const ciphertext = this.olmDevice.encryptGroupMessage(session.sessionId, JSON.stringify(payloadJson)); - const encryptedContent = { - algorithm: olmlib.MEGOLM_ALGORITHM, - sender_key: this.olmDevice.deviceCurve25519Key, - ciphertext: ciphertext, - session_id: session.sessionId, - // Include our device ID so that recipients can send us a - // m.new_device message if they don't have our session key. - // XXX: Do we still need this now that m.new_device messages - // no longer exist since #483? - device_id: this.deviceId, - }; - session.useCount++; - return encryptedContent; - }); - } - isVerificationEvent(eventType, content) { - switch (eventType) { - case event_1.EventType.KeyVerificationCancel: - case event_1.EventType.KeyVerificationDone: - case event_1.EventType.KeyVerificationMac: - case event_1.EventType.KeyVerificationStart: - case event_1.EventType.KeyVerificationKey: - case event_1.EventType.KeyVerificationReady: - case event_1.EventType.KeyVerificationAccept: { - return true; - } - case event_1.EventType.RoomMessage: { - return content["msgtype"] === event_1.MsgType.KeyVerificationRequest; - } - default: { - return false; - } - } - } - /** - * Forces the current outbound group session to be discarded such - * that another one will be created next time an event is sent. - * - * This should not normally be necessary. - */ - forceDiscardSession() { - this.setupPromise = this.setupPromise.then(() => null); - } - /** - * Checks the devices we're about to send to and see if any are entirely - * unknown to the user. If so, warn the user, and mark them as known to - * give the user a chance to go verify them before re-sending this message. - * - * @param devicesInRoom - `userId -> {deviceId -> object}` - * devices we should shared the session with. - */ - checkForUnknownDevices(devicesInRoom) { - const unknownDevices = new utils_1.MapWithDefault(() => new Map()); - for (const [userId, userDevices] of devicesInRoom) { - for (const [deviceId, device] of userDevices) { - if (device.isUnverified() && !device.isKnown()) { - unknownDevices.getOrCreate(userId).set(deviceId, device); - } - } - } - if (unknownDevices.size) { - // it'd be kind to pass unknownDevices up to the user in this error - throw new base_1.UnknownDeviceError("This room contains unknown devices which have not been verified. " + - "We strongly recommend you verify them before continuing.", unknownDevices); - } - } - /** - * Remove unknown devices from a set of devices. The devicesInRoom parameter - * will be modified. - * - * @param devicesInRoom - `userId -> {deviceId -> object}` - * devices we should shared the session with. - */ - removeUnknownDevices(devicesInRoom) { - for (const [userId, userDevices] of devicesInRoom) { - for (const [deviceId, device] of userDevices) { - if (device.isUnverified() && !device.isKnown()) { - userDevices.delete(deviceId); - } - } - if (userDevices.size === 0) { - devicesInRoom.delete(userId); - } - } - } - getDevicesInRoom(room, forceDistributeToUnverified = false, isCancelled) { - return __awaiter(this, void 0, void 0, function* () { - const members = yield room.getEncryptionTargetMembers(); - this.prefixedLogger.debug(`Encrypting for users (shouldEncryptForInvitedMembers: ${room.shouldEncryptForInvitedMembers()}):`, members.map((u) => `${u.userId} (${u.membership})`)); - const roomMembers = members.map(function (u) { - return u.userId; - }); - // The global value is treated as a default for when rooms don't specify a value. - let isBlacklisting = this.crypto.globalBlacklistUnverifiedDevices; - const isRoomBlacklisting = room.getBlacklistUnverifiedDevices(); - if (typeof isRoomBlacklisting === "boolean") { - isBlacklisting = isRoomBlacklisting; - } - // We are happy to use a cached version here: we assume that if we already - // have a list of the user's devices, then we already share an e2e room - // with them, which means that they will have announced any new devices via - // device_lists in their /sync response. This cache should then be maintained - // using all the device_lists changes and left fields. - // See https://github.com/vector-im/element-web/issues/2305 for details. - const devices = yield this.crypto.downloadKeys(roomMembers, false); - if ((isCancelled === null || isCancelled === void 0 ? void 0 : isCancelled()) === true) { - return null; - } - const blocked = new utils_1.MapWithDefault(() => new Map()); - // remove any blocked devices - for (const [userId, userDevices] of devices) { - for (const [deviceId, userDevice] of userDevices) { - // Yield prior to checking each device so that we don't block - // updating/rendering for too long. - // See https://github.com/vector-im/element-web/issues/21612 - if (isCancelled !== undefined) - yield (0, utils_1.immediate)(); - if ((isCancelled === null || isCancelled === void 0 ? void 0 : isCancelled()) === true) - return null; - const deviceTrust = this.crypto.checkDeviceTrust(userId, deviceId); - if (userDevice.isBlocked() || - (!deviceTrust.isVerified() && isBlacklisting && !forceDistributeToUnverified)) { - const blockedDevices = blocked.getOrCreate(userId); - const isBlocked = userDevice.isBlocked(); - blockedDevices.set(deviceId, { - code: isBlocked ? "m.blacklisted" : "m.unverified", - reason: OlmDevice_1.WITHHELD_MESSAGES[isBlocked ? "m.blacklisted" : "m.unverified"], - deviceInfo: userDevice, - }); - userDevices.delete(deviceId); - } - } - } - return [devices, blocked]; - }); - } -} -exports.MegolmEncryption = MegolmEncryption; -/** - * Megolm decryption implementation - * - * @param params - parameters, as per {@link DecryptionAlgorithm} - */ -class MegolmDecryption extends base_1.DecryptionAlgorithm { - constructor(params) { - super(params); - // events which we couldn't decrypt due to unknown sessions / - // indexes, or which we could only decrypt with untrusted keys: - // map from senderKey|sessionId to Set of MatrixEvents - this.pendingEvents = new Map(); - // this gets stubbed out by the unit tests. - this.olmlib = olmlib; - this.roomId = params.roomId; - this.prefixedLogger = logger_1.logger.withPrefix(`[${this.roomId} decryption]`); - } - /** - * returns a promise which resolves to a - * {@link EventDecryptionResult} once we have finished - * decrypting, or rejects with an `algorithms.DecryptionError` if there is a - * problem decrypting the event. - */ - decryptEvent(event) { - return __awaiter(this, void 0, void 0, function* () { - const content = event.getWireContent(); - if (!content.sender_key || !content.session_id || !content.ciphertext) { - throw new base_1.DecryptionError("MEGOLM_MISSING_FIELDS", "Missing fields in input"); - } - // we add the event to the pending list *before* we start decryption. - // - // then, if the key turns up while decryption is in progress (and - // decryption fails), we will schedule a retry. - // (fixes https://github.com/vector-im/element-web/issues/5001) - this.addEventToPendingList(event); - let res; - try { - res = yield this.olmDevice.decryptGroupMessage(event.getRoomId(), content.sender_key, content.session_id, content.ciphertext, event.getId(), event.getTs()); - } - catch (e) { - if (e.name === "DecryptionError") { - // re-throw decryption errors as-is - throw e; - } - let errorCode = "OLM_DECRYPT_GROUP_MESSAGE_ERROR"; - if ((e === null || e === void 0 ? void 0 : e.message) === "OLM.UNKNOWN_MESSAGE_INDEX") { - this.requestKeysForEvent(event); - errorCode = "OLM_UNKNOWN_MESSAGE_INDEX"; - } - throw new base_1.DecryptionError(errorCode, e instanceof Error ? e.message : "Unknown Error: Error is undefined", { - session: content.sender_key + "|" + content.session_id, - }); - } - if (res === null) { - // We've got a message for a session we don't have. - // try and get the missing key from the backup first - this.crypto.backupManager.queryKeyBackupRateLimited(event.getRoomId(), content.session_id).catch(() => { }); - // (XXX: We might actually have received this key since we started - // decrypting, in which case we'll have scheduled a retry, and this - // request will be redundant. We could probably check to see if the - // event is still in the pending list; if not, a retry will have been - // scheduled, so we needn't send out the request here.) - this.requestKeysForEvent(event); - // See if there was a problem with the olm session at the time the - // event was sent. Use a fuzz factor of 2 minutes. - const problem = yield this.olmDevice.sessionMayHaveProblems(content.sender_key, event.getTs() - 120000); - if (problem) { - this.prefixedLogger.info(`When handling UISI from ${event.getSender()} (sender key ${content.sender_key}): ` + - `recent session problem with that sender:`, problem); - let problemDescription = PROBLEM_DESCRIPTIONS[problem.type] || PROBLEM_DESCRIPTIONS.unknown; - if (problem.fixed) { - problemDescription += " Trying to create a new secure channel and re-requesting the keys."; - } - throw new base_1.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID", problemDescription, { - session: content.sender_key + "|" + content.session_id, - }); - } - throw new base_1.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID", "The sender's device has not sent us the keys for this message.", { - session: content.sender_key + "|" + content.session_id, - }); - } - // Success. We can remove the event from the pending list, if - // that hasn't already happened. However, if the event was - // decrypted with an untrusted key, leave it on the pending - // list so it will be retried if we find a trusted key later. - if (!res.untrusted) { - this.removeEventFromPendingList(event); - } - const payload = JSON.parse(res.result); - // belt-and-braces check that the room id matches that indicated by the HS - // (this is somewhat redundant, since the megolm session is scoped to the - // room, so neither the sender nor a MITM can lie about the room_id). - if (payload.room_id !== event.getRoomId()) { - throw new base_1.DecryptionError("MEGOLM_BAD_ROOM", "Message intended for room " + payload.room_id); - } - return { - clearEvent: payload, - senderCurve25519Key: res.senderKey, - claimedEd25519Key: res.keysClaimed.ed25519, - forwardingCurve25519KeyChain: res.forwardingCurve25519KeyChain, - untrusted: res.untrusted, - }; - }); - } - requestKeysForEvent(event) { - const wireContent = event.getWireContent(); - const recipients = event.getKeyRequestRecipients(this.userId); - this.crypto.requestRoomKey({ - room_id: event.getRoomId(), - algorithm: wireContent.algorithm, - sender_key: wireContent.sender_key, - session_id: wireContent.session_id, - }, recipients); - } - /** - * Add an event to the list of those awaiting their session keys. - * - * @internal - * - */ - addEventToPendingList(event) { - var _a; - const content = event.getWireContent(); - const senderKey = content.sender_key; - const sessionId = content.session_id; - if (!this.pendingEvents.has(senderKey)) { - this.pendingEvents.set(senderKey, new Map()); - } - const senderPendingEvents = this.pendingEvents.get(senderKey); - if (!senderPendingEvents.has(sessionId)) { - senderPendingEvents.set(sessionId, new Set()); - } - (_a = senderPendingEvents.get(sessionId)) === null || _a === void 0 ? void 0 : _a.add(event); - } - /** - * Remove an event from the list of those awaiting their session keys. - * - * @internal - * - */ - removeEventFromPendingList(event) { - const content = event.getWireContent(); - const senderKey = content.sender_key; - const sessionId = content.session_id; - const senderPendingEvents = this.pendingEvents.get(senderKey); - const pendingEvents = senderPendingEvents === null || senderPendingEvents === void 0 ? void 0 : senderPendingEvents.get(sessionId); - if (!pendingEvents) { - return; - } - pendingEvents.delete(event); - if (pendingEvents.size === 0) { - senderPendingEvents.delete(sessionId); - } - if (senderPendingEvents.size === 0) { - this.pendingEvents.delete(senderKey); - } - } - /** - * Parse a RoomKey out of an `m.room_key` event. - * - * @param event - the event containing the room key. - * - * @returns The `RoomKey` if it could be successfully parsed out of the - * event. - * - * @internal - * - */ - roomKeyFromEvent(event) { - const senderKey = event.getSenderKey(); - const content = event.getContent(); - const extraSessionData = {}; - if (!content.room_id || !content.session_key || !content.session_id || !content.algorithm) { - this.prefixedLogger.error("key event is missing fields"); - return; - } - if (!olmlib.isOlmEncrypted(event)) { - this.prefixedLogger.error("key event not properly encrypted"); - return; - } - if (content["org.matrix.msc3061.shared_history"]) { - extraSessionData.sharedHistory = true; - } - const roomKey = { - senderKey: senderKey, - sessionId: content.session_id, - sessionKey: content.session_key, - extraSessionData, - exportFormat: false, - roomId: content.room_id, - algorithm: content.algorithm, - forwardingKeyChain: [], - keysClaimed: event.getKeysClaimed(), - }; - return roomKey; - } - /** - * Parse a RoomKey out of an `m.forwarded_room_key` event. - * - * @param event - the event containing the forwarded room key. - * - * @returns The `RoomKey` if it could be successfully parsed out of the - * event. - * - * @internal - * - */ - forwardedRoomKeyFromEvent(event) { - // the properties in m.forwarded_room_key are a superset of those in m.room_key, so - // start by parsing the m.room_key fields. - const roomKey = this.roomKeyFromEvent(event); - if (!roomKey) { - return; - } - const senderKey = event.getSenderKey(); - const content = event.getContent(); - const senderKeyUser = this.baseApis.crypto.deviceList.getUserByIdentityKey(olmlib.OLM_ALGORITHM, senderKey); - // We received this to-device event from event.getSenderKey(), but the original - // creator of the room key is claimed in the content. - const claimedCurve25519Key = content.sender_key; - const claimedEd25519Key = content.sender_claimed_ed25519_key; - let forwardingKeyChain = Array.isArray(content.forwarding_curve25519_key_chain) - ? content.forwarding_curve25519_key_chain - : []; - // copy content before we modify it - forwardingKeyChain = forwardingKeyChain.slice(); - forwardingKeyChain.push(senderKey); - // Check if we have all the fields we need. - if (senderKeyUser !== event.getSender()) { - this.prefixedLogger.error("sending device does not belong to the user it claims to be from"); - return; - } - if (!claimedCurve25519Key) { - this.prefixedLogger.error("forwarded_room_key event is missing sender_key field"); - return; - } - if (!claimedEd25519Key) { - this.prefixedLogger.error(`forwarded_room_key_event is missing sender_claimed_ed25519_key field`); - return; - } - const keysClaimed = { - ed25519: claimedEd25519Key, - }; - // FIXME: We're reusing the same field to track both: - // - // 1. The Olm identity we've received this room key from. - // 2. The Olm identity deduced (in the trusted case) or claiming (in the - // untrusted case) to be the original creator of this room key. - // - // We now overwrite the value tracking usage 1 with the value tracking usage 2. - roomKey.senderKey = claimedCurve25519Key; - // Replace our keysClaimed as well. - roomKey.keysClaimed = keysClaimed; - roomKey.exportFormat = true; - roomKey.forwardingKeyChain = forwardingKeyChain; - // forwarded keys are always untrusted - roomKey.extraSessionData.untrusted = true; - return roomKey; - } - /** - * Determine if we should accept the forwarded room key that was found in the given - * event. - * - * @param event - An `m.forwarded_room_key` event. - * @param roomKey - The room key that was found in the event. - * - * @returns promise that will resolve to a boolean telling us if it's ok to - * accept the given forwarded room key. - * - * @internal - * - */ - shouldAcceptForwardedKey(event, roomKey) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const senderKey = event.getSenderKey(); - const sendingDevice = (_a = this.crypto.deviceList.getDeviceByIdentityKey(olmlib.OLM_ALGORITHM, senderKey)) !== null && _a !== void 0 ? _a : undefined; - const deviceTrust = this.crypto.checkDeviceInfoTrust(event.getSender(), sendingDevice); - // Using the plaintext sender here is fine since we checked that the - // sender matches to the user id in the device keys when this event was - // originally decrypted. This can obviously only happen if the device - // keys have been downloaded, but if they haven't the - // `deviceTrust.isVerified()` flag would be false as well. - // - // It would still be far nicer if the `sendingDevice` had a user ID - // attached to it that went through signature checks. - const fromUs = event.getSender() === this.baseApis.getUserId(); - const keyFromOurVerifiedDevice = deviceTrust.isVerified() && fromUs; - const weRequested = yield this.wasRoomKeyRequested(event, roomKey); - const fromInviter = this.wasRoomKeyForwardedByInviter(event, roomKey); - const sharedAsHistory = this.wasRoomKeyForwardedAsHistory(roomKey); - return (weRequested && keyFromOurVerifiedDevice) || (fromInviter && sharedAsHistory); - }); - } - /** - * Did we ever request the given room key from the event sender and its - * accompanying device. - * - * @param event - An `m.forwarded_room_key` event. - * @param roomKey - The room key that was found in the event. - * - * @internal - * - */ - wasRoomKeyRequested(event, roomKey) { - return __awaiter(this, void 0, void 0, function* () { - // We send the `m.room_key_request` out as a wildcard to-device request, - // otherwise we would have to duplicate the same content for each - // device. This is why we need to pass in "*" as the device id here. - const outgoingRequests = yield this.crypto.cryptoStore.getOutgoingRoomKeyRequestsByTarget(event.getSender(), "*", [OutgoingRoomKeyRequestManager_1.RoomKeyRequestState.Sent]); - return outgoingRequests.some((req) => req.requestBody.room_id === roomKey.roomId && req.requestBody.session_id === roomKey.sessionId); - }); - } - wasRoomKeyForwardedByInviter(event, roomKey) { - var _a, _b, _c; - // TODO: This is supposed to have a time limit. We should only accept - // such keys if we happen to receive them for a recently joined room. - const room = this.baseApis.getRoom(roomKey.roomId); - const senderKey = event.getSenderKey(); - if (!senderKey) { - return false; - } - const senderKeyUser = this.crypto.deviceList.getUserByIdentityKey(olmlib.OLM_ALGORITHM, senderKey); - if (!senderKeyUser) { - return false; - } - const memberEvent = (_a = room === null || room === void 0 ? void 0 : room.getMember(this.userId)) === null || _a === void 0 ? void 0 : _a.events.member; - const fromInviter = (memberEvent === null || memberEvent === void 0 ? void 0 : memberEvent.getSender()) === senderKeyUser || - (((_b = memberEvent === null || memberEvent === void 0 ? void 0 : memberEvent.getUnsigned()) === null || _b === void 0 ? void 0 : _b.prev_sender) === senderKeyUser && - ((_c = memberEvent === null || memberEvent === void 0 ? void 0 : memberEvent.getPrevContent()) === null || _c === void 0 ? void 0 : _c.membership) === "invite"); - if (room && fromInviter) { - return true; - } - else { - return false; - } - } - wasRoomKeyForwardedAsHistory(roomKey) { - const room = this.baseApis.getRoom(roomKey.roomId); - // If the key is not for a known room, then something fishy is going on, - // so we reject the key out of caution. In practice, this is a bit moot - // because we'll only accept shared_history forwarded by the inviter, and - // we won't know who was the inviter for an unknown room, so we'll reject - // it anyway. - if (room && roomKey.extraSessionData.sharedHistory) { - return true; - } - else { - return false; - } - } - /** - * Check if a forwarded room key should be parked. - * - * A forwarded room key should be parked if it's a key for a room we're not - * in. We park the forwarded room key in case *this sender* invites us to - * that room later. - */ - shouldParkForwardedKey(roomKey) { - const room = this.baseApis.getRoom(roomKey.roomId); - if (!room && roomKey.extraSessionData.sharedHistory) { - return true; - } - else { - return false; - } - } - /** - * Park the given room key to our store. - * - * @param event - An `m.forwarded_room_key` event. - * @param roomKey - The room key that was found in the event. - * - * @internal - * - */ - parkForwardedKey(event, roomKey) { - return __awaiter(this, void 0, void 0, function* () { - const parkedData = { - senderId: event.getSender(), - senderKey: roomKey.senderKey, - sessionId: roomKey.sessionId, - sessionKey: roomKey.sessionKey, - keysClaimed: roomKey.keysClaimed, - forwardingCurve25519KeyChain: roomKey.forwardingKeyChain, - }; - yield this.crypto.cryptoStore.doTxn("readwrite", ["parked_shared_history"], (txn) => this.crypto.cryptoStore.addParkedSharedHistory(roomKey.roomId, parkedData, txn), logger_1.logger.withPrefix("[addParkedSharedHistory]")); - }); - } - /** - * Add the given room key to our store. - * - * @param roomKey - The room key that should be added to the store. - * - * @internal - * - */ - addRoomKey(roomKey) { - return __awaiter(this, void 0, void 0, function* () { - try { - yield this.olmDevice.addInboundGroupSession(roomKey.roomId, roomKey.senderKey, roomKey.forwardingKeyChain, roomKey.sessionId, roomKey.sessionKey, roomKey.keysClaimed, roomKey.exportFormat, roomKey.extraSessionData); - // have another go at decrypting events sent with this session. - if (yield this.retryDecryption(roomKey.senderKey, roomKey.sessionId, !roomKey.extraSessionData.untrusted)) { - // cancel any outstanding room key requests for this session. - // Only do this if we managed to decrypt every message in the - // session, because if we didn't, we leave the other key - // requests in the hopes that someone sends us a key that - // includes an earlier index. - this.crypto.cancelRoomKeyRequest({ - algorithm: roomKey.algorithm, - room_id: roomKey.roomId, - session_id: roomKey.sessionId, - sender_key: roomKey.senderKey, - }); - } - // don't wait for the keys to be backed up for the server - yield this.crypto.backupManager.backupGroupSession(roomKey.senderKey, roomKey.sessionId); - } - catch (e) { - this.prefixedLogger.error(`Error handling m.room_key_event: ${e}`); - } - }); - } - /** - * Handle room keys that have been forwarded to us as an - * `m.forwarded_room_key` event. - * - * Forwarded room keys need special handling since we have no way of knowing - * who the original creator of the room key was. This naturally means that - * forwarded room keys are always untrusted and should only be accepted in - * some cases. - * - * @param event - An `m.forwarded_room_key` event. - * - * @internal - * - */ - onForwardedRoomKey(event) { - return __awaiter(this, void 0, void 0, function* () { - const roomKey = this.forwardedRoomKeyFromEvent(event); - if (!roomKey) { - return; - } - if (yield this.shouldAcceptForwardedKey(event, roomKey)) { - yield this.addRoomKey(roomKey); - } - else if (this.shouldParkForwardedKey(roomKey)) { - yield this.parkForwardedKey(event, roomKey); - } - }); - } - onRoomKeyEvent(event) { - return __awaiter(this, void 0, void 0, function* () { - if (event.getType() == "m.forwarded_room_key") { - yield this.onForwardedRoomKey(event); - } - else { - const roomKey = this.roomKeyFromEvent(event); - if (!roomKey) { - return; - } - yield this.addRoomKey(roomKey); - } - }); - } - /** - * @param event - key event - */ - onRoomKeyWithheldEvent(event) { - return __awaiter(this, void 0, void 0, function* () { - const content = event.getContent(); - const senderKey = content.sender_key; - if (content.code === "m.no_olm") { - yield this.onNoOlmWithheldEvent(event); - } - else if (content.code === "m.unavailable") { - // this simply means that the other device didn't have the key, which isn't very useful information. Don't - // record it in the storage - } - else { - yield this.olmDevice.addInboundGroupSessionWithheld(content.room_id, senderKey, content.session_id, content.code, content.reason); - } - // Having recorded the problem, retry decryption on any affected messages. - // It's unlikely we'll be able to decrypt sucessfully now, but this will - // update the error message. - // - if (content.session_id) { - yield this.retryDecryption(senderKey, content.session_id); - } - else { - // no_olm messages aren't specific to a given megolm session, so - // we trigger retrying decryption for all the messages from the sender's - // key, so that we can update the error message to indicate the olm - // session problem. - yield this.retryDecryptionFromSender(senderKey); - } - }); - } - onNoOlmWithheldEvent(event) { - return __awaiter(this, void 0, void 0, function* () { - const content = event.getContent(); - const senderKey = content.sender_key; - const sender = event.getSender(); - this.prefixedLogger.warn(`${sender}:${senderKey} was unable to establish an olm session with us`); - // if the sender says that they haven't been able to establish an olm - // session, let's proactively establish one - if (yield this.olmDevice.getSessionIdForDevice(senderKey)) { - // a session has already been established, so we don't need to - // create a new one. - this.prefixedLogger.debug("New session already created. Not creating a new one."); - yield this.olmDevice.recordSessionProblem(senderKey, "no_olm", true); - return; - } - let device = this.crypto.deviceList.getDeviceByIdentityKey(content.algorithm, senderKey); - if (!device) { - // if we don't know about the device, fetch the user's devices again - // and retry before giving up - yield this.crypto.downloadKeys([sender], false); - device = this.crypto.deviceList.getDeviceByIdentityKey(content.algorithm, senderKey); - if (!device) { - this.prefixedLogger.info("Couldn't find device for identity key " + senderKey + ": not establishing session"); - yield this.olmDevice.recordSessionProblem(senderKey, "no_olm", false); - return; - } - } - // XXX: switch this to use encryptAndSendToDevices() rather than duplicating it? - yield olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, new Map([[sender, [device]]]), false); - const encryptedContent = { - algorithm: olmlib.OLM_ALGORITHM, - sender_key: this.olmDevice.deviceCurve25519Key, - ciphertext: {}, - [event_1.ToDeviceMessageId]: (0, uuid_1.v4)(), - }; - yield olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this.userId, undefined, this.olmDevice, sender, device, { type: "m.dummy" }); - yield this.olmDevice.recordSessionProblem(senderKey, "no_olm", true); - yield this.baseApis.sendToDevice("m.room.encrypted", new Map([[sender, new Map([[device.deviceId, encryptedContent]])]])); - }); - } - hasKeysForKeyRequest(keyRequest) { - const body = keyRequest.requestBody; - return this.olmDevice.hasInboundSessionKeys(body.room_id, body.sender_key, body.session_id); - } - shareKeysWithDevice(keyRequest) { - const userId = keyRequest.userId; - const deviceId = keyRequest.deviceId; - const deviceInfo = this.crypto.getStoredDevice(userId, deviceId); - const body = keyRequest.requestBody; - // XXX: switch this to use encryptAndSendToDevices()? - this.olmlib - .ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, new Map([[userId, [deviceInfo]]])) - .then((devicemap) => { - var _a; - const olmSessionResult = (_a = devicemap.get(userId)) === null || _a === void 0 ? void 0 : _a.get(deviceId); - if (!(olmSessionResult === null || olmSessionResult === void 0 ? void 0 : olmSessionResult.sessionId)) { - // no session with this device, probably because there - // were no one-time keys. - // - // ensureOlmSessionsForUsers has already done the logging, - // so just skip it. - return null; - } - this.prefixedLogger.log("sharing keys for session " + - body.sender_key + - "|" + - body.session_id + - " with device " + - userId + - ":" + - deviceId); - return this.buildKeyForwardingMessage(body.room_id, body.sender_key, body.session_id); - }) - .then((payload) => { - const encryptedContent = { - algorithm: olmlib.OLM_ALGORITHM, - sender_key: this.olmDevice.deviceCurve25519Key, - ciphertext: {}, - [event_1.ToDeviceMessageId]: (0, uuid_1.v4)(), - }; - return this.olmlib - .encryptMessageForDevice(encryptedContent.ciphertext, this.userId, undefined, this.olmDevice, userId, deviceInfo, payload) - .then(() => { - // TODO: retries - return this.baseApis.sendToDevice("m.room.encrypted", new Map([[userId, new Map([[deviceId, encryptedContent]])]])); - }); - }); - } - buildKeyForwardingMessage(roomId, senderKey, sessionId) { - return __awaiter(this, void 0, void 0, function* () { - const key = yield this.olmDevice.getInboundGroupSessionKey(roomId, senderKey, sessionId); - return { - type: "m.forwarded_room_key", - content: { - "algorithm": olmlib.MEGOLM_ALGORITHM, - "room_id": roomId, - "sender_key": senderKey, - "sender_claimed_ed25519_key": key.sender_claimed_ed25519_key, - "session_id": sessionId, - "session_key": key.key, - "chain_index": key.chain_index, - "forwarding_curve25519_key_chain": key.forwarding_curve25519_key_chain, - "org.matrix.msc3061.shared_history": key.shared_history || false, - }, - }; - }); - } - /** - * @param untrusted - whether the key should be considered as untrusted - * @param source - where the key came from - */ - importRoomKey(session, { untrusted, source } = {}) { - const extraSessionData = {}; - if (untrusted || session.untrusted) { - extraSessionData.untrusted = true; - } - if (session["org.matrix.msc3061.shared_history"]) { - extraSessionData.sharedHistory = true; - } - return this.olmDevice - .addInboundGroupSession(session.room_id, session.sender_key, session.forwarding_curve25519_key_chain, session.session_id, session.session_key, session.sender_claimed_keys, true, extraSessionData) - .then(() => { - if (source !== "backup") { - // don't wait for it to complete - this.crypto.backupManager.backupGroupSession(session.sender_key, session.session_id).catch((e) => { - // This throws if the upload failed, but this is fine - // since it will have written it to the db and will retry. - this.prefixedLogger.log("Failed to back up megolm session", e); - }); - } - // have another go at decrypting events sent with this session. - this.retryDecryption(session.sender_key, session.session_id, !extraSessionData.untrusted); - }); - } - /** - * Have another go at decrypting events after we receive a key. Resolves once - * decryption has been re-attempted on all events. - * - * @internal - * @param forceRedecryptIfUntrusted - whether messages that were already - * successfully decrypted using untrusted keys should be re-decrypted - * - * @returns whether all messages were successfully - * decrypted with trusted keys - */ - retryDecryption(senderKey, sessionId, forceRedecryptIfUntrusted) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const senderPendingEvents = this.pendingEvents.get(senderKey); - if (!senderPendingEvents) { - return true; - } - const pending = senderPendingEvents.get(sessionId); - if (!pending) { - return true; - } - const pendingList = [...pending]; - this.prefixedLogger.debug("Retrying decryption on events:", pendingList.map((e) => `${e.getId()}`)); - yield Promise.all(pendingList.map((ev) => __awaiter(this, void 0, void 0, function* () { - try { - yield ev.attemptDecryption(this.crypto, { isRetry: true, forceRedecryptIfUntrusted }); - } - catch (e) { - // don't die if something goes wrong - } - }))); - // If decrypted successfully with trusted keys, they'll have - // been removed from pendingEvents - return !((_a = this.pendingEvents.get(senderKey)) === null || _a === void 0 ? void 0 : _a.has(sessionId)); - }); - } - retryDecryptionFromSender(senderKey) { - return __awaiter(this, void 0, void 0, function* () { - const senderPendingEvents = this.pendingEvents.get(senderKey); - if (!senderPendingEvents) { - return true; - } - this.pendingEvents.delete(senderKey); - yield Promise.all([...senderPendingEvents].map(([_sessionId, pending]) => __awaiter(this, void 0, void 0, function* () { - yield Promise.all([...pending].map((ev) => __awaiter(this, void 0, void 0, function* () { - try { - yield ev.attemptDecryption(this.crypto); - } - catch (e) { - // don't die if something goes wrong - } - }))); - }))); - return !this.pendingEvents.has(senderKey); - }); - } - sendSharedHistoryInboundSessions(devicesByUser) { - return __awaiter(this, void 0, void 0, function* () { - yield olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, devicesByUser); - const sharedHistorySessions = yield this.olmDevice.getSharedHistoryInboundGroupSessions(this.roomId); - this.prefixedLogger.log(`Sharing history in with users ${Array.from(devicesByUser.keys())}`, sharedHistorySessions.map(([senderKey, sessionId]) => `${senderKey}|${sessionId}`)); - for (const [senderKey, sessionId] of sharedHistorySessions) { - const payload = yield this.buildKeyForwardingMessage(this.roomId, senderKey, sessionId); - // FIXME: use encryptAndSendToDevices() rather than duplicating it here. - const promises = []; - const contentMap = new Map(); - for (const [userId, devices] of devicesByUser) { - const deviceMessages = new Map(); - contentMap.set(userId, deviceMessages); - for (const deviceInfo of devices) { - const encryptedContent = { - algorithm: olmlib.OLM_ALGORITHM, - sender_key: this.olmDevice.deviceCurve25519Key, - ciphertext: {}, - [event_1.ToDeviceMessageId]: (0, uuid_1.v4)(), - }; - deviceMessages.set(deviceInfo.deviceId, encryptedContent); - promises.push(olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this.userId, undefined, this.olmDevice, userId, deviceInfo, payload)); - } - } - yield Promise.all(promises); - // prune out any devices that encryptMessageForDevice could not encrypt for, - // in which case it will have just not added anything to the ciphertext object. - // There's no point sending messages to devices if we couldn't encrypt to them, - // since that's effectively a blank message. - for (const [userId, deviceMessages] of contentMap) { - for (const [deviceId, content] of deviceMessages) { - if (!hasCiphertext(content)) { - this.prefixedLogger.log("No ciphertext for device " + userId + ":" + deviceId + ": pruning"); - deviceMessages.delete(deviceId); - } - } - // No devices left for that user? Strip that too. - if (deviceMessages.size === 0) { - this.prefixedLogger.log("Pruned all devices for user " + userId); - contentMap.delete(userId); - } - } - // Is there anything left? - if (contentMap.size === 0) { - this.prefixedLogger.log("No users left to send to: aborting"); - return; - } - yield this.baseApis.sendToDevice("m.room.encrypted", contentMap); - } - }); - } -} -exports.MegolmDecryption = MegolmDecryption; -const PROBLEM_DESCRIPTIONS = { - no_olm: "The sender was unable to establish a secure channel.", - unknown: "The secure channel with the sender was corrupted.", -}; -(0, base_1.registerAlgorithm)(olmlib.MEGOLM_ALGORITHM, MegolmEncryption, MegolmDecryption); - -},{"../../@types/event":306,"../../logger":374,"../../utils":416,"../OlmDevice":327,"../OutgoingRoomKeyRequestManager":328,"../olmlib":343,"./base":332,"uuid":287}],335:[function(require,module,exports){ -"use strict"; -/* -Copyright 2016 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const logger_1 = require("../../logger"); -const olmlib = __importStar(require("../olmlib")); -const deviceinfo_1 = require("../deviceinfo"); -const base_1 = require("./base"); -const DeviceVerification = deviceinfo_1.DeviceInfo.DeviceVerification; -/** - * Olm encryption implementation - * - * @param params - parameters, as per {@link EncryptionAlgorithm} - */ -class OlmEncryption extends base_1.EncryptionAlgorithm { - constructor() { - super(...arguments); - this.sessionPrepared = false; - this.prepPromise = null; - } - /** - * @internal - - * @param roomMembers - list of currently-joined users in the room - * @returns Promise which resolves when setup is complete - */ - ensureSession(roomMembers) { - if (this.prepPromise) { - // prep already in progress - return this.prepPromise; - } - if (this.sessionPrepared) { - // prep already done - return Promise.resolve(); - } - this.prepPromise = this.crypto - .downloadKeys(roomMembers) - .then(() => { - return this.crypto.ensureOlmSessionsForUsers(roomMembers); - }) - .then(() => { - this.sessionPrepared = true; - }) - .finally(() => { - this.prepPromise = null; - }); - return this.prepPromise; - } - /** - * @param content - plaintext event content - * - * @returns Promise which resolves to the new event body - */ - encryptMessage(room, eventType, content) { - return __awaiter(this, void 0, void 0, function* () { - // pick the list of recipients based on the membership list. - // - // TODO: there is a race condition here! What if a new user turns up - // just as you are sending a secret message? - const members = yield room.getEncryptionTargetMembers(); - const users = members.map(function (u) { - return u.userId; - }); - yield this.ensureSession(users); - const payloadFields = { - room_id: room.roomId, - type: eventType, - content: content, - }; - const encryptedContent = { - algorithm: olmlib.OLM_ALGORITHM, - sender_key: this.olmDevice.deviceCurve25519Key, - ciphertext: {}, - }; - const promises = []; - for (const userId of users) { - const devices = this.crypto.getStoredDevicesForUser(userId) || []; - for (const deviceInfo of devices) { - const key = deviceInfo.getIdentityKey(); - if (key == this.olmDevice.deviceCurve25519Key) { - // don't bother sending to ourself - continue; - } - if (deviceInfo.verified == DeviceVerification.BLOCKED) { - // don't bother setting up sessions with blocked users - continue; - } - promises.push(olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this.userId, this.deviceId, this.olmDevice, userId, deviceInfo, payloadFields)); - } - } - return Promise.all(promises).then(() => encryptedContent); - }); - } -} -/** - * Olm decryption implementation - * - * @param params - parameters, as per {@link DecryptionAlgorithm} - */ -class OlmDecryption extends base_1.DecryptionAlgorithm { - /** - * returns a promise which resolves to a - * {@link EventDecryptionResult} once we have finished - * decrypting. Rejects with an `algorithms.DecryptionError` if there is a - * problem decrypting the event. - */ - decryptEvent(event) { - return __awaiter(this, void 0, void 0, function* () { - const content = event.getWireContent(); - const deviceKey = content.sender_key; - const ciphertext = content.ciphertext; - if (!ciphertext) { - throw new base_1.DecryptionError("OLM_MISSING_CIPHERTEXT", "Missing ciphertext"); - } - if (!(this.olmDevice.deviceCurve25519Key in ciphertext)) { - throw new base_1.DecryptionError("OLM_NOT_INCLUDED_IN_RECIPIENTS", "Not included in recipients"); - } - const message = ciphertext[this.olmDevice.deviceCurve25519Key]; - let payloadString; - try { - payloadString = yield this.decryptMessage(deviceKey, message); - } - catch (e) { - throw new base_1.DecryptionError("OLM_BAD_ENCRYPTED_MESSAGE", "Bad Encrypted Message", { - sender: deviceKey, - err: e, - }); - } - const payload = JSON.parse(payloadString); - // check that we were the intended recipient, to avoid unknown-key attack - // https://github.com/vector-im/vector-web/issues/2483 - if (payload.recipient != this.userId) { - throw new base_1.DecryptionError("OLM_BAD_RECIPIENT", "Message was intented for " + payload.recipient); - } - if (payload.recipient_keys.ed25519 != this.olmDevice.deviceEd25519Key) { - throw new base_1.DecryptionError("OLM_BAD_RECIPIENT_KEY", "Message not intended for this device", { - intended: payload.recipient_keys.ed25519, - our_key: this.olmDevice.deviceEd25519Key, - }); - } - // check that the device that encrypted the event belongs to the user - // that the event claims it's from. We need to make sure that our - // device list is up-to-date. If the device is unknown, we can only - // assume that the device logged out. Some event handlers, such as - // secret sharing, may be more strict and reject events that come from - // unknown devices. - yield this.crypto.deviceList.downloadKeys([event.getSender()], false); - const senderKeyUser = this.crypto.deviceList.getUserByIdentityKey(olmlib.OLM_ALGORITHM, deviceKey); - if (senderKeyUser !== event.getSender() && senderKeyUser != undefined) { - throw new base_1.DecryptionError("OLM_BAD_SENDER", "Message claimed to be from " + event.getSender(), { - real_sender: senderKeyUser, - }); - } - // check that the original sender matches what the homeserver told us, to - // avoid people masquerading as others. - // (this check is also provided via the sender's embedded ed25519 key, - // which is checked elsewhere). - if (payload.sender != event.getSender()) { - throw new base_1.DecryptionError("OLM_FORWARDED_MESSAGE", "Message forwarded from " + payload.sender, { - reported_sender: event.getSender(), - }); - } - // Olm events intended for a room have a room_id. - if (payload.room_id !== event.getRoomId()) { - throw new base_1.DecryptionError("OLM_BAD_ROOM", "Message intended for room " + payload.room_id, { - reported_room: event.getRoomId() || "ROOM_ID_UNDEFINED", - }); - } - const claimedKeys = payload.keys || {}; - return { - clearEvent: payload, - senderCurve25519Key: deviceKey, - claimedEd25519Key: claimedKeys.ed25519 || null, - }; - }); - } - /** - * Attempt to decrypt an Olm message - * - * @param theirDeviceIdentityKey - Curve25519 identity key of the sender - * @param message - message object, with 'type' and 'body' fields - * - * @returns payload, if decrypted successfully. - */ - decryptMessage(theirDeviceIdentityKey, message) { - // This is a wrapper that serialises decryptions of prekey messages, because - // otherwise we race between deciding we have no active sessions for the message - // and creating a new one, which we can only do once because it removes the OTK. - if (message.type !== 0) { - // not a prekey message: we can safely just try & decrypt it - return this.reallyDecryptMessage(theirDeviceIdentityKey, message); - } - else { - const myPromise = this.olmDevice.olmPrekeyPromise.then(() => { - return this.reallyDecryptMessage(theirDeviceIdentityKey, message); - }); - // we want the error, but don't propagate it to the next decryption - this.olmDevice.olmPrekeyPromise = myPromise.catch(() => { }); - return myPromise; - } - } - reallyDecryptMessage(theirDeviceIdentityKey, message) { - return __awaiter(this, void 0, void 0, function* () { - const sessionIds = yield this.olmDevice.getSessionIdsForDevice(theirDeviceIdentityKey); - // try each session in turn. - const decryptionErrors = {}; - for (const sessionId of sessionIds) { - try { - const payload = yield this.olmDevice.decryptMessage(theirDeviceIdentityKey, sessionId, message.type, message.body); - logger_1.logger.log("Decrypted Olm message from " + theirDeviceIdentityKey + " with session " + sessionId); - return payload; - } - catch (e) { - const foundSession = yield this.olmDevice.matchesSession(theirDeviceIdentityKey, sessionId, message.type, message.body); - if (foundSession) { - // decryption failed, but it was a prekey message matching this - // session, so it should have worked. - throw new Error("Error decrypting prekey message with existing session id " + - sessionId + - ": " + - e.message); - } - // otherwise it's probably a message for another session; carry on, but - // keep a record of the error - decryptionErrors[sessionId] = e.message; - } - } - if (message.type !== 0) { - // not a prekey message, so it should have matched an existing session, but it - // didn't work. - if (sessionIds.length === 0) { - throw new Error("No existing sessions"); - } - throw new Error("Error decrypting non-prekey message with existing sessions: " + JSON.stringify(decryptionErrors)); - } - // prekey message which doesn't match any existing sessions: make a new - // session. - let res; - try { - res = yield this.olmDevice.createInboundSession(theirDeviceIdentityKey, message.type, message.body); - } - catch (e) { - decryptionErrors["(new)"] = e.message; - throw new Error("Error decrypting prekey message: " + JSON.stringify(decryptionErrors)); - } - logger_1.logger.log("created new inbound Olm session ID " + res.session_id + " with " + theirDeviceIdentityKey); - return res.payload; - }); - } -} -(0, base_1.registerAlgorithm)(olmlib.OLM_ALGORITHM, OlmEncryption, OlmDecryption); - -},{"../../logger":374,"../deviceinfo":340,"../olmlib":343,"./base":332}],336:[function(require,module,exports){ -"use strict"; -/* -Copyright 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CrossSigningKey = void 0; -// TODO: Merge this with crypto.js once converted -var CrossSigningKey; -(function (CrossSigningKey) { - CrossSigningKey["Master"] = "master"; - CrossSigningKey["SelfSigning"] = "self_signing"; - CrossSigningKey["UserSigning"] = "user_signing"; -})(CrossSigningKey = exports.CrossSigningKey || (exports.CrossSigningKey = {})); - -},{}],337:[function(require,module,exports){ -(function (global){(function (){ -"use strict"; -/* -Copyright 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DefaultAlgorithm = exports.algorithmsByName = exports.Aes256 = exports.Curve25519 = exports.BackupManager = void 0; -const client_1 = require("../client"); -const logger_1 = require("../logger"); -const olmlib_1 = require("./olmlib"); -const key_passphrase_1 = require("./key_passphrase"); -const utils_1 = require("../utils"); -const indexeddb_crypto_store_1 = require("./store/indexeddb-crypto-store"); -const recoverykey_1 = require("./recoverykey"); -const aes_1 = require("./aes"); -const NamespacedValue_1 = require("../NamespacedValue"); -const index_1 = require("./index"); -const crypto_1 = require("./crypto"); -const http_api_1 = require("../http-api"); -const KEY_BACKUP_KEYS_PER_REQUEST = 200; -const KEY_BACKUP_CHECK_RATE_LIMIT = 5000; // ms -/** - * Manages the key backup. - */ -class BackupManager { - constructor(baseApis, getKey) { - this.baseApis = baseApis; - this.getKey = getKey; - this.sessionLastCheckAttemptedTime = {}; // When did we last try to check the server for a given session id? - this.checkedForBackup = false; - this.sendingBackups = false; - } - get version() { - return this.backupInfo && this.backupInfo.version; - } - /** - * Performs a quick check to ensure that the backup info looks sane. - * - * Throws an error if a problem is detected. - * - * @param info - the key backup info - */ - static checkBackupVersion(info) { - const Algorithm = exports.algorithmsByName[info.algorithm]; - if (!Algorithm) { - throw new Error("Unknown backup algorithm: " + info.algorithm); - } - if (typeof info.auth_data !== "object") { - throw new Error("Invalid backup data returned"); - } - return Algorithm.checkBackupVersion(info); - } - static makeAlgorithm(info, getKey) { - const Algorithm = exports.algorithmsByName[info.algorithm]; - if (!Algorithm) { - throw new Error("Unknown backup algorithm"); - } - return Algorithm.init(info.auth_data, getKey); - } - enableKeyBackup(info) { - return __awaiter(this, void 0, void 0, function* () { - this.backupInfo = info; - if (this.algorithm) { - this.algorithm.free(); - } - this.algorithm = yield BackupManager.makeAlgorithm(info, this.getKey); - this.baseApis.emit(index_1.CryptoEvent.KeyBackupStatus, true); - // There may be keys left over from a partially completed backup, so - // schedule a send to check. - this.scheduleKeyBackupSend(); - }); - } - /** - * Disable backing up of keys. - */ - disableKeyBackup() { - if (this.algorithm) { - this.algorithm.free(); - } - this.algorithm = undefined; - this.backupInfo = undefined; - this.baseApis.emit(index_1.CryptoEvent.KeyBackupStatus, false); - } - getKeyBackupEnabled() { - if (!this.checkedForBackup) { - return null; - } - return Boolean(this.algorithm); - } - prepareKeyBackupVersion(key, algorithm) { - return __awaiter(this, void 0, void 0, function* () { - const Algorithm = algorithm ? exports.algorithmsByName[algorithm] : exports.DefaultAlgorithm; - if (!Algorithm) { - throw new Error("Unknown backup algorithm"); - } - const [privateKey, authData] = yield Algorithm.prepare(key); - const recoveryKey = (0, recoverykey_1.encodeRecoveryKey)(privateKey); - return { - algorithm: Algorithm.algorithmName, - auth_data: authData, - recovery_key: recoveryKey, - privateKey, - }; - }); - } - createKeyBackupVersion(info) { - return __awaiter(this, void 0, void 0, function* () { - this.algorithm = yield BackupManager.makeAlgorithm(info, this.getKey); - }); - } - /** - * Check the server for an active key backup and - * if one is present and has a valid signature from - * one of the user's verified devices, start backing up - * to it. - */ - checkAndStart() { - var _a; - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.log("Checking key backup status..."); - if (this.baseApis.isGuest()) { - logger_1.logger.log("Skipping key backup check since user is guest"); - this.checkedForBackup = true; - return null; - } - let backupInfo; - try { - backupInfo = (_a = (yield this.baseApis.getKeyBackupVersion())) !== null && _a !== void 0 ? _a : undefined; - } - catch (e) { - logger_1.logger.log("Error checking for active key backup", e); - if (e.httpStatus === 404) { - // 404 is returned when the key backup does not exist, so that - // counts as successfully checking. - this.checkedForBackup = true; - } - return null; - } - this.checkedForBackup = true; - const trustInfo = yield this.isKeyBackupTrusted(backupInfo); - if (trustInfo.usable && !this.backupInfo) { - logger_1.logger.log(`Found usable key backup v${backupInfo.version}: enabling key backups`); - yield this.enableKeyBackup(backupInfo); - } - else if (!trustInfo.usable && this.backupInfo) { - logger_1.logger.log("No usable key backup: disabling key backup"); - this.disableKeyBackup(); - } - else if (!trustInfo.usable && !this.backupInfo) { - logger_1.logger.log("No usable key backup: not enabling key backup"); - } - else if (trustInfo.usable && this.backupInfo) { - // may not be the same version: if not, we should switch - if (backupInfo.version !== this.backupInfo.version) { - logger_1.logger.log(`On backup version ${this.backupInfo.version} but ` + - `found version ${backupInfo.version}: switching.`); - this.disableKeyBackup(); - yield this.enableKeyBackup(backupInfo); - // We're now using a new backup, so schedule all the keys we have to be - // uploaded to the new backup. This is a bit of a workaround to upload - // keys to a new backup in *most* cases, but it won't cover all cases - // because we don't remember what backup version we uploaded keys to: - // see https://github.com/vector-im/element-web/issues/14833 - yield this.scheduleAllGroupSessionsForBackup(); - } - else { - logger_1.logger.log(`Backup version ${backupInfo.version} still current`); - } - } - return { backupInfo, trustInfo }; - }); - } - /** - * Forces a re-check of the key backup and enables/disables it - * as appropriate. - * - * @returns Object with backup info (as returned by - * getKeyBackupVersion) in backupInfo and - * trust information (as returned by isKeyBackupTrusted) - * in trustInfo. - */ - checkKeyBackup() { - return __awaiter(this, void 0, void 0, function* () { - this.checkedForBackup = false; - return this.checkAndStart(); - }); - } - /** - * Attempts to retrieve a session from a key backup, if enough time - * has elapsed since the last check for this session id. - */ - queryKeyBackupRateLimited(targetRoomId, targetSessionId) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.backupInfo) { - return; - } - const now = new Date().getTime(); - if (!this.sessionLastCheckAttemptedTime[targetSessionId] || - now - this.sessionLastCheckAttemptedTime[targetSessionId] > KEY_BACKUP_CHECK_RATE_LIMIT) { - this.sessionLastCheckAttemptedTime[targetSessionId] = now; - yield this.baseApis.restoreKeyBackupWithCache(targetRoomId, targetSessionId, this.backupInfo, {}); - } - }); - } - /** - * Check if the given backup info is trusted. - * - * @param backupInfo - key backup info dict from /room_keys/version - */ - isKeyBackupTrusted(backupInfo) { - return __awaiter(this, void 0, void 0, function* () { - const ret = { - usable: false, - trusted_locally: false, - sigs: [], - }; - if (!backupInfo || !backupInfo.algorithm || !backupInfo.auth_data || !backupInfo.auth_data.signatures) { - logger_1.logger.info("Key backup is absent or missing required data"); - return ret; - } - const userId = this.baseApis.getUserId(); - const privKey = yield this.baseApis.crypto.getSessionBackupPrivateKey(); - if (privKey) { - let algorithm = null; - try { - algorithm = yield BackupManager.makeAlgorithm(backupInfo, () => __awaiter(this, void 0, void 0, function* () { return privKey; })); - if (yield algorithm.keyMatches(privKey)) { - logger_1.logger.info("Backup is trusted locally"); - ret.trusted_locally = true; - } - } - catch (_a) { - // do nothing -- if we have an error, then we don't mark it as - // locally trusted - } - finally { - algorithm === null || algorithm === void 0 ? void 0 : algorithm.free(); - } - } - const mySigs = backupInfo.auth_data.signatures[userId] || {}; - for (const keyId of Object.keys(mySigs)) { - const keyIdParts = keyId.split(":"); - if (keyIdParts[0] !== "ed25519") { - logger_1.logger.log("Ignoring unknown signature type: " + keyIdParts[0]); - continue; - } - // Could be a cross-signing master key, but just say this is the device - // ID for backwards compat - const sigInfo = { deviceId: keyIdParts[1] }; - // first check to see if it's from our cross-signing key - const crossSigningId = this.baseApis.crypto.crossSigningInfo.getId(); - if (crossSigningId === sigInfo.deviceId) { - sigInfo.crossSigningId = true; - try { - yield (0, olmlib_1.verifySignature)(this.baseApis.crypto.olmDevice, backupInfo.auth_data, userId, sigInfo.deviceId, crossSigningId); - sigInfo.valid = true; - } - catch (e) { - logger_1.logger.warn("Bad signature from cross signing key " + crossSigningId, e); - sigInfo.valid = false; - } - ret.sigs.push(sigInfo); - continue; - } - // Now look for a sig from a device - // At some point this can probably go away and we'll just support - // it being signed by the cross-signing master key - const device = this.baseApis.crypto.deviceList.getStoredDevice(userId, sigInfo.deviceId); - if (device) { - sigInfo.device = device; - sigInfo.deviceTrust = this.baseApis.checkDeviceTrust(userId, sigInfo.deviceId); - try { - yield (0, olmlib_1.verifySignature)(this.baseApis.crypto.olmDevice, backupInfo.auth_data, userId, device.deviceId, device.getFingerprint()); - sigInfo.valid = true; - } - catch (e) { - logger_1.logger.info("Bad signature from key ID " + - keyId + - " userID " + - this.baseApis.getUserId() + - " device ID " + - device.deviceId + - " fingerprint: " + - device.getFingerprint(), backupInfo.auth_data, e); - sigInfo.valid = false; - } - } - else { - sigInfo.valid = null; // Can't determine validity because we don't have the signing device - logger_1.logger.info("Ignoring signature from unknown key " + keyId); - } - ret.sigs.push(sigInfo); - } - ret.usable = ret.sigs.some((s) => { - var _a; - return s.valid && ((s.device && ((_a = s.deviceTrust) === null || _a === void 0 ? void 0 : _a.isVerified())) || s.crossSigningId); - }); - return ret; - }); - } - /** - * Schedules sending all keys waiting to be sent to the backup, if not already - * scheduled. Retries if necessary. - * - * @param maxDelay - Maximum delay to wait in ms. 0 means no delay. - */ - scheduleKeyBackupSend(maxDelay = 10000) { - return __awaiter(this, void 0, void 0, function* () { - if (this.sendingBackups) - return; - this.sendingBackups = true; - try { - // wait between 0 and `maxDelay` seconds, to avoid backup - // requests from different clients hitting the server all at - // the same time when a new key is sent - const delay = Math.random() * maxDelay; - yield (0, utils_1.sleep)(delay); - let numFailures = 0; // number of consecutive failures - for (;;) { - if (!this.algorithm) { - return; - } - try { - const numBackedUp = yield this.backupPendingKeys(KEY_BACKUP_KEYS_PER_REQUEST); - if (numBackedUp === 0) { - // no sessions left needing backup: we're done - return; - } - numFailures = 0; - } - catch (err) { - numFailures++; - logger_1.logger.log("Key backup request failed", err); - if (err.data) { - if (err.data.errcode == "M_NOT_FOUND" || - err.data.errcode == "M_WRONG_ROOM_KEYS_VERSION") { - // Re-check key backup status on error, so we can be - // sure to present the current situation when asked. - yield this.checkKeyBackup(); - // Backup version has changed or this backup version - // has been deleted - this.baseApis.crypto.emit(index_1.CryptoEvent.KeyBackupFailed, err.data.errcode); - throw err; - } - } - } - if (numFailures) { - // exponential backoff if we have failures - yield (0, utils_1.sleep)(1000 * Math.pow(2, Math.min(numFailures - 1, 4))); - } - } - } - finally { - this.sendingBackups = false; - } - }); - } - /** - * Take some e2e keys waiting to be backed up and send them - * to the backup. - * - * @param limit - Maximum number of keys to back up - * @returns Number of sessions backed up - */ - backupPendingKeys(limit) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const sessions = yield this.baseApis.crypto.cryptoStore.getSessionsNeedingBackup(limit); - if (!sessions.length) { - return 0; - } - let remaining = yield this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup(); - this.baseApis.crypto.emit(index_1.CryptoEvent.KeyBackupSessionsRemaining, remaining); - const rooms = {}; - for (const session of sessions) { - const roomId = session.sessionData.room_id; - (0, utils_1.safeSet)(rooms, roomId, rooms[roomId] || { sessions: {} }); - const sessionData = this.baseApis.crypto.olmDevice.exportInboundGroupSession(session.senderKey, session.sessionId, session.sessionData); - sessionData.algorithm = olmlib_1.MEGOLM_ALGORITHM; - const forwardedCount = (sessionData.forwarding_curve25519_key_chain || []).length; - const userId = this.baseApis.crypto.deviceList.getUserByIdentityKey(olmlib_1.MEGOLM_ALGORITHM, session.senderKey); - const device = (_a = this.baseApis.crypto.deviceList.getDeviceByIdentityKey(olmlib_1.MEGOLM_ALGORITHM, session.senderKey)) !== null && _a !== void 0 ? _a : undefined; - const verified = this.baseApis.crypto.checkDeviceInfoTrust(userId, device).isVerified(); - (0, utils_1.safeSet)(rooms[roomId]["sessions"], session.sessionId, { - first_message_index: sessionData.first_known_index, - forwarded_count: forwardedCount, - is_verified: verified, - session_data: yield this.algorithm.encryptSession(sessionData), - }); - } - yield this.baseApis.sendKeyBackup(undefined, undefined, this.backupInfo.version, { rooms }); - yield this.baseApis.crypto.cryptoStore.unmarkSessionsNeedingBackup(sessions); - remaining = yield this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup(); - this.baseApis.crypto.emit(index_1.CryptoEvent.KeyBackupSessionsRemaining, remaining); - return sessions.length; - }); - } - backupGroupSession(senderKey, sessionId) { - return __awaiter(this, void 0, void 0, function* () { - yield this.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([ - { - senderKey: senderKey, - sessionId: sessionId, - }, - ]); - if (this.backupInfo) { - // don't wait for this to complete: it will delay so - // happens in the background - this.scheduleKeyBackupSend(); - } - // if this.backupInfo is not set, then the keys will be backed up when - // this.enableKeyBackup is called - }); - } - /** - * Marks all group sessions as needing to be backed up and schedules them to - * upload in the background as soon as possible. - */ - scheduleAllGroupSessionsForBackup() { - return __awaiter(this, void 0, void 0, function* () { - yield this.flagAllGroupSessionsForBackup(); - // Schedule keys to upload in the background as soon as possible. - this.scheduleKeyBackupSend(0 /* maxDelay */); - }); - } - /** - * Marks all group sessions as needing to be backed up without scheduling - * them to upload in the background. - * @returns Promise which resolves to the number of sessions now requiring a backup - * (which will be equal to the number of sessions in the store). - */ - flagAllGroupSessionsForBackup() { - return __awaiter(this, void 0, void 0, function* () { - yield this.baseApis.crypto.cryptoStore.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_BACKUP], (txn) => { - this.baseApis.crypto.cryptoStore.getAllEndToEndInboundGroupSessions(txn, (session) => { - if (session !== null) { - this.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([session], txn); - } - }); - }); - const remaining = yield this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup(); - this.baseApis.emit(index_1.CryptoEvent.KeyBackupSessionsRemaining, remaining); - return remaining; - }); - } - /** - * Counts the number of end to end session keys that are waiting to be backed up - * @returns Promise which resolves to the number of sessions requiring backup - */ - countSessionsNeedingBackup() { - return this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup(); - } -} -exports.BackupManager = BackupManager; -class Curve25519 { - constructor(authData, publicKey, // FIXME: PkEncryption - getKey) { - this.authData = authData; - this.publicKey = publicKey; - this.getKey = getKey; - } - static init(authData, getKey) { - return __awaiter(this, void 0, void 0, function* () { - if (!authData || !("public_key" in authData)) { - throw new Error("auth_data missing required information"); - } - const publicKey = new global.Olm.PkEncryption(); - publicKey.set_recipient_key(authData.public_key); - return new Curve25519(authData, publicKey, getKey); - }); - } - static prepare(key) { - return __awaiter(this, void 0, void 0, function* () { - const decryption = new global.Olm.PkDecryption(); - try { - const authData = {}; - if (!key) { - authData.public_key = decryption.generate_key(); - } - else if (key instanceof Uint8Array) { - authData.public_key = decryption.init_with_private_key(key); - } - else { - const derivation = yield (0, key_passphrase_1.keyFromPassphrase)(key); - authData.private_key_salt = derivation.salt; - authData.private_key_iterations = derivation.iterations; - authData.public_key = decryption.init_with_private_key(derivation.key); - } - const publicKey = new global.Olm.PkEncryption(); - publicKey.set_recipient_key(authData.public_key); - return [decryption.get_private_key(), authData]; - } - finally { - decryption.free(); - } - }); - } - static checkBackupVersion(info) { - if (!("public_key" in info.auth_data)) { - throw new Error("Invalid backup data returned"); - } - } - get untrusted() { - return true; - } - encryptSession(data) { - return __awaiter(this, void 0, void 0, function* () { - const plainText = Object.assign({}, data); - delete plainText.session_id; - delete plainText.room_id; - delete plainText.first_known_index; - return this.publicKey.encrypt(JSON.stringify(plainText)); - }); - } - decryptSessions(sessions) { - return __awaiter(this, void 0, void 0, function* () { - const privKey = yield this.getKey(); - const decryption = new global.Olm.PkDecryption(); - try { - const backupPubKey = decryption.init_with_private_key(privKey); - if (backupPubKey !== this.authData.public_key) { - throw new http_api_1.MatrixError({ errcode: client_1.MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY }); - } - const keys = []; - for (const [sessionId, sessionData] of Object.entries(sessions)) { - try { - const decrypted = JSON.parse(decryption.decrypt(sessionData.session_data.ephemeral, sessionData.session_data.mac, sessionData.session_data.ciphertext)); - decrypted.session_id = sessionId; - keys.push(decrypted); - } - catch (e) { - logger_1.logger.log("Failed to decrypt megolm session from backup", e, sessionData); - } - } - return keys; - } - finally { - decryption.free(); - } - }); - } - keyMatches(key) { - return __awaiter(this, void 0, void 0, function* () { - const decryption = new global.Olm.PkDecryption(); - let pubKey; - try { - pubKey = decryption.init_with_private_key(key); - } - finally { - decryption.free(); - } - return pubKey === this.authData.public_key; - }); - } - free() { - this.publicKey.free(); - } -} -exports.Curve25519 = Curve25519; -Curve25519.algorithmName = "m.megolm_backup.v1.curve25519-aes-sha2"; -function randomBytes(size) { - const buf = new Uint8Array(size); - crypto_1.crypto.getRandomValues(buf); - return buf; -} -const UNSTABLE_MSC3270_NAME = new NamespacedValue_1.UnstableValue("m.megolm_backup.v1.aes-hmac-sha2", "org.matrix.msc3270.v1.aes-hmac-sha2"); -class Aes256 { - constructor(authData, key) { - this.authData = authData; - this.key = key; - } - static init(authData, getKey) { - return __awaiter(this, void 0, void 0, function* () { - if (!authData) { - throw new Error("auth_data missing"); - } - const key = yield getKey(); - if (authData.mac) { - const { mac } = yield (0, aes_1.calculateKeyCheck)(key, authData.iv); - if (authData.mac.replace(/=+$/g, "") !== mac.replace(/=+/g, "")) { - throw new Error("Key does not match"); - } - } - return new Aes256(authData, key); - }); - } - static prepare(key) { - return __awaiter(this, void 0, void 0, function* () { - let outKey; - const authData = {}; - if (!key) { - outKey = randomBytes(32); - } - else if (key instanceof Uint8Array) { - outKey = new Uint8Array(key); - } - else { - const derivation = yield (0, key_passphrase_1.keyFromPassphrase)(key); - authData.private_key_salt = derivation.salt; - authData.private_key_iterations = derivation.iterations; - outKey = derivation.key; - } - const { iv, mac } = yield (0, aes_1.calculateKeyCheck)(outKey); - authData.iv = iv; - authData.mac = mac; - return [outKey, authData]; - }); - } - static checkBackupVersion(info) { - if (!("iv" in info.auth_data && "mac" in info.auth_data)) { - throw new Error("Invalid backup data returned"); - } - } - get untrusted() { - return false; - } - encryptSession(data) { - const plainText = Object.assign({}, data); - delete plainText.session_id; - delete plainText.room_id; - delete plainText.first_known_index; - return (0, aes_1.encryptAES)(JSON.stringify(plainText), this.key, data.session_id); - } - decryptSessions(sessions) { - return __awaiter(this, void 0, void 0, function* () { - const keys = []; - for (const [sessionId, sessionData] of Object.entries(sessions)) { - try { - const decrypted = JSON.parse(yield (0, aes_1.decryptAES)(sessionData.session_data, this.key, sessionId)); - decrypted.session_id = sessionId; - keys.push(decrypted); - } - catch (e) { - logger_1.logger.log("Failed to decrypt megolm session from backup", e, sessionData); - } - } - return keys; - }); - } - keyMatches(key) { - return __awaiter(this, void 0, void 0, function* () { - if (this.authData.mac) { - const { mac } = yield (0, aes_1.calculateKeyCheck)(key, this.authData.iv); - return this.authData.mac.replace(/=+$/g, "") === mac.replace(/=+/g, ""); - } - else { - // if we have no information, we have to assume the key is right - return true; - } - }); - } - free() { - this.key.fill(0); - } -} -exports.Aes256 = Aes256; -Aes256.algorithmName = UNSTABLE_MSC3270_NAME.name; -exports.algorithmsByName = { - [Curve25519.algorithmName]: Curve25519, - [Aes256.algorithmName]: Aes256, -}; -exports.DefaultAlgorithm = Curve25519; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"../NamespacedValue":316,"../client":321,"../http-api":367,"../logger":374,"../utils":416,"./aes":331,"./crypto":338,"./index":341,"./key_passphrase":342,"./olmlib":343,"./recoverykey":344,"./store/indexeddb-crypto-store":346}],338:[function(require,module,exports){ -(function (global){(function (){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var _a, _b, _c, _d, _e, _f, _g; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.setTextEncoder = exports.setCrypto = exports.TextEncoder = exports.subtleCrypto = exports.crypto = void 0; -const logger_1 = require("../logger"); -exports.crypto = (_a = global.window) === null || _a === void 0 ? void 0 : _a.crypto; -exports.subtleCrypto = (_d = (_c = (_b = global.window) === null || _b === void 0 ? void 0 : _b.crypto) === null || _c === void 0 ? void 0 : _c.subtle) !== null && _d !== void 0 ? _d : (_f = (_e = global.window) === null || _e === void 0 ? void 0 : _e.crypto) === null || _f === void 0 ? void 0 : _f.webkitSubtle; -exports.TextEncoder = (_g = global.window) === null || _g === void 0 ? void 0 : _g.TextEncoder; -/* eslint-disable @typescript-eslint/no-var-requires */ -if (!exports.crypto) { - try { - exports.crypto = require("crypto").webcrypto; - } - catch (e) { - logger_1.logger.error("Failed to load webcrypto", e); - } -} -if (!exports.subtleCrypto) { - exports.subtleCrypto = exports.crypto === null || exports.crypto === void 0 ? void 0 : exports.crypto.subtle; -} -if (!exports.TextEncoder) { - try { - exports.TextEncoder = require("util").TextEncoder; - } - catch (e) { - logger_1.logger.error("Failed to load TextEncoder util", e); - } -} -/* eslint-enable @typescript-eslint/no-var-requires */ -function setCrypto(_crypto) { - var _a; - exports.crypto = _crypto; - exports.subtleCrypto = (_a = _crypto.subtle) !== null && _a !== void 0 ? _a : _crypto.webkitSubtle; -} -exports.setCrypto = setCrypto; -function setTextEncoder(_TextEncoder) { - exports.TextEncoder = _TextEncoder; -} -exports.setTextEncoder = setTextEncoder; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"../logger":374,"crypto":78,"util":286}],339:[function(require,module,exports){ -(function (global,Buffer){(function (){ -"use strict"; -/* -Copyright 2020-2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DehydrationManager = exports.DEHYDRATION_ALGORITHM = void 0; -const another_json_1 = __importDefault(require("another-json")); -const olmlib_1 = require("./olmlib"); -const indexeddb_crypto_store_1 = require("../crypto/store/indexeddb-crypto-store"); -const aes_1 = require("./aes"); -const logger_1 = require("../logger"); -const http_api_1 = require("../http-api"); -exports.DEHYDRATION_ALGORITHM = "org.matrix.msc2697.v1.olm.libolm_pickle"; -const oneweek = 7 * 24 * 60 * 60 * 1000; -class DehydrationManager { - constructor(crypto) { - this.crypto = crypto; - this.inProgress = false; - this.getDehydrationKeyFromCache(); - } - getDehydrationKeyFromCache() { - return this.crypto.cryptoStore.doTxn("readonly", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { - this.crypto.cryptoStore.getSecretStorePrivateKey(txn, (result) => __awaiter(this, void 0, void 0, function* () { - if (result) { - const { key, keyInfo, deviceDisplayName, time } = result; - const pickleKey = Buffer.from(this.crypto.olmDevice.pickleKey); - const decrypted = yield (0, aes_1.decryptAES)(key, pickleKey, exports.DEHYDRATION_ALGORITHM); - this.key = (0, olmlib_1.decodeBase64)(decrypted); - this.keyInfo = keyInfo; - this.deviceDisplayName = deviceDisplayName; - const now = Date.now(); - const delay = Math.max(1, time + oneweek - now); - this.timeoutId = global.setTimeout(this.dehydrateDevice.bind(this), delay); - } - }), "dehydration"); - }); - } - /** set the key, and queue periodic dehydration to the server in the background */ - setKeyAndQueueDehydration(key, keyInfo = {}, deviceDisplayName) { - return __awaiter(this, void 0, void 0, function* () { - const matches = yield this.setKey(key, keyInfo, deviceDisplayName); - if (!matches) { - // start dehydration in the background - this.dehydrateDevice(); - } - }); - } - setKey(key, keyInfo = {}, deviceDisplayName) { - return __awaiter(this, void 0, void 0, function* () { - if (!key) { - // unsetting the key -- cancel any pending dehydration task - if (this.timeoutId) { - global.clearTimeout(this.timeoutId); - this.timeoutId = undefined; - } - // clear storage - yield this.crypto.cryptoStore.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { - this.crypto.cryptoStore.storeSecretStorePrivateKey(txn, "dehydration", null); - }); - this.key = undefined; - this.keyInfo = undefined; - return; - } - // Check to see if it's the same key as before. If it's different, - // dehydrate a new device. If it's the same, we can keep the same - // device. (Assume that keyInfo and deviceDisplayName will be the - // same if the key is the same.) - let matches = !!this.key && key.length == this.key.length; - for (let i = 0; matches && i < key.length; i++) { - if (key[i] != this.key[i]) { - matches = false; - } - } - if (!matches) { - this.key = key; - this.keyInfo = keyInfo; - this.deviceDisplayName = deviceDisplayName; - } - return matches; - }); - } - /** returns the device id of the newly created dehydrated device */ - dehydrateDevice() { - return __awaiter(this, void 0, void 0, function* () { - if (this.inProgress) { - logger_1.logger.log("Dehydration already in progress -- not starting new dehydration"); - return; - } - this.inProgress = true; - if (this.timeoutId) { - global.clearTimeout(this.timeoutId); - this.timeoutId = undefined; - } - try { - const pickleKey = Buffer.from(this.crypto.olmDevice.pickleKey); - // update the crypto store with the timestamp - const key = yield (0, aes_1.encryptAES)((0, olmlib_1.encodeBase64)(this.key), pickleKey, exports.DEHYDRATION_ALGORITHM); - yield this.crypto.cryptoStore.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { - this.crypto.cryptoStore.storeSecretStorePrivateKey(txn, "dehydration", { - keyInfo: this.keyInfo, - key, - deviceDisplayName: this.deviceDisplayName, - time: Date.now(), - }); - }); - logger_1.logger.log("Attempting to dehydrate device"); - logger_1.logger.log("Creating account"); - // create the account and all the necessary keys - const account = new global.Olm.Account(); - account.create(); - const e2eKeys = JSON.parse(account.identity_keys()); - const maxKeys = account.max_number_of_one_time_keys(); - // FIXME: generate in small batches? - account.generate_one_time_keys(maxKeys / 2); - account.generate_fallback_key(); - const otks = JSON.parse(account.one_time_keys()); - const fallbacks = JSON.parse(account.fallback_key()); - account.mark_keys_as_published(); - // dehydrate the account and store it on the server - const pickledAccount = account.pickle(new Uint8Array(this.key)); - const deviceData = { - algorithm: exports.DEHYDRATION_ALGORITHM, - account: pickledAccount, - }; - if (this.keyInfo.passphrase) { - deviceData.passphrase = this.keyInfo.passphrase; - } - logger_1.logger.log("Uploading account to server"); - // eslint-disable-next-line camelcase - const dehydrateResult = yield this.crypto.baseApis.http.authedRequest(http_api_1.Method.Put, "/dehydrated_device", undefined, { - device_data: deviceData, - initial_device_display_name: this.deviceDisplayName, - }, { - prefix: "/_matrix/client/unstable/org.matrix.msc2697.v2", - }); - // send the keys to the server - const deviceId = dehydrateResult.device_id; - logger_1.logger.log("Preparing device keys", deviceId); - const deviceKeys = { - algorithms: this.crypto.supportedAlgorithms, - device_id: deviceId, - user_id: this.crypto.userId, - keys: { - [`ed25519:${deviceId}`]: e2eKeys.ed25519, - [`curve25519:${deviceId}`]: e2eKeys.curve25519, - }, - }; - const deviceSignature = account.sign(another_json_1.default.stringify(deviceKeys)); - deviceKeys.signatures = { - [this.crypto.userId]: { - [`ed25519:${deviceId}`]: deviceSignature, - }, - }; - if (this.crypto.crossSigningInfo.getId("self_signing")) { - yield this.crypto.crossSigningInfo.signObject(deviceKeys, "self_signing"); - } - logger_1.logger.log("Preparing one-time keys"); - const oneTimeKeys = {}; - for (const [keyId, key] of Object.entries(otks.curve25519)) { - const k = { key }; - const signature = account.sign(another_json_1.default.stringify(k)); - k.signatures = { - [this.crypto.userId]: { - [`ed25519:${deviceId}`]: signature, - }, - }; - oneTimeKeys[`signed_curve25519:${keyId}`] = k; - } - logger_1.logger.log("Preparing fallback keys"); - const fallbackKeys = {}; - for (const [keyId, key] of Object.entries(fallbacks.curve25519)) { - const k = { key, fallback: true }; - const signature = account.sign(another_json_1.default.stringify(k)); - k.signatures = { - [this.crypto.userId]: { - [`ed25519:${deviceId}`]: signature, - }, - }; - fallbackKeys[`signed_curve25519:${keyId}`] = k; - } - logger_1.logger.log("Uploading keys to server"); - yield this.crypto.baseApis.http.authedRequest(http_api_1.Method.Post, "/keys/upload/" + encodeURI(deviceId), undefined, { - "device_keys": deviceKeys, - "one_time_keys": oneTimeKeys, - "org.matrix.msc2732.fallback_keys": fallbackKeys, - }); - logger_1.logger.log("Done dehydrating"); - // dehydrate again in a week - this.timeoutId = global.setTimeout(this.dehydrateDevice.bind(this), oneweek); - return deviceId; - } - finally { - this.inProgress = false; - } - }); - } - stop() { - if (this.timeoutId) { - global.clearTimeout(this.timeoutId); - this.timeoutId = undefined; - } - } -} -exports.DehydrationManager = DehydrationManager; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) - -},{"../crypto/store/indexeddb-crypto-store":346,"../http-api":367,"../logger":374,"./aes":331,"./olmlib":343,"another-json":1,"buffer":68}],340:[function(require,module,exports){ -"use strict"; -/* -Copyright 2016 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DeviceInfo = void 0; -var DeviceVerification; -(function (DeviceVerification) { - DeviceVerification[DeviceVerification["Blocked"] = -1] = "Blocked"; - DeviceVerification[DeviceVerification["Unverified"] = 0] = "Unverified"; - DeviceVerification[DeviceVerification["Verified"] = 1] = "Verified"; -})(DeviceVerification || (DeviceVerification = {})); -/** - * Information about a user's device - */ -class DeviceInfo { - /** - * rehydrate a DeviceInfo from the session store - * - * @param obj - raw object from session store - * @param deviceId - id of the device - * - * @returns new DeviceInfo - */ - static fromStorage(obj, deviceId) { - const res = new DeviceInfo(deviceId); - for (const prop in obj) { - if (obj.hasOwnProperty(prop)) { - // @ts-ignore - this is messy and typescript doesn't like it - res[prop] = obj[prop]; - } - } - return res; - } - /** - * @param deviceId - id of the device - */ - constructor(deviceId) { - this.deviceId = deviceId; - /** list of algorithms supported by this device */ - this.algorithms = []; - /** a map from `: -> ` */ - this.keys = {}; - /** whether the device has been verified/blocked by the user */ - this.verified = DeviceVerification.Unverified; - /** - * whether the user knows of this device's existence - * (useful when warning the user that a user has added new devices) - */ - this.known = false; - /** additional data from the homeserver */ - this.unsigned = {}; - this.signatures = {}; - } - /** - * Prepare a DeviceInfo for JSON serialisation in the session store - * - * @returns deviceinfo with non-serialised members removed - */ - toStorage() { - return { - algorithms: this.algorithms, - keys: this.keys, - verified: this.verified, - known: this.known, - unsigned: this.unsigned, - signatures: this.signatures, - }; - } - /** - * Get the fingerprint for this device (ie, the Ed25519 key) - * - * @returns base64-encoded fingerprint of this device - */ - getFingerprint() { - return this.keys["ed25519:" + 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["curve25519:" + this.deviceId]; - } - /** - * Get the configured display name for this device, if any - * - * @returns displayname - */ - getDisplayName() { - return this.unsigned.device_display_name || null; - } - /** - * Returns true if this device is blocked - * - * @returns true if blocked - */ - isBlocked() { - return this.verified == DeviceVerification.Blocked; - } - /** - * Returns true if this device is verified - * - * @returns true if verified - */ - isVerified() { - return this.verified == DeviceVerification.Verified; - } - /** - * Returns true if this device is unverified - * - * @returns true if unverified - */ - isUnverified() { - return this.verified == DeviceVerification.Unverified; - } - /** - * Returns true if the user knows about this device's existence - * - * @returns true if known - */ - isKnown() { - return this.known === true; - } -} -exports.DeviceInfo = DeviceInfo; -DeviceInfo.DeviceVerification = { - VERIFIED: DeviceVerification.Verified, - UNVERIFIED: DeviceVerification.Unverified, - BLOCKED: DeviceVerification.Blocked, -}; - -},{}],341:[function(require,module,exports){ -(function (global,Buffer){(function (){ -"use strict"; -/* -Copyright 2016 OpenMarket Ltd -Copyright 2017 Vector Creations Ltd -Copyright 2018-2019 New Vector Ltd -Copyright 2019-2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.IncomingRoomKeyRequest = exports.fixBackupKey = exports.Crypto = exports.CryptoEvent = exports.isCryptoAvailable = exports.verificationMethods = void 0; -const another_json_1 = __importDefault(require("another-json")); -const uuid_1 = require("uuid"); -const event_1 = require("../@types/event"); -const ReEmitter_1 = require("../ReEmitter"); -const logger_1 = require("../logger"); -const OlmDevice_1 = require("./OlmDevice"); -const olmlib = __importStar(require("./olmlib")); -const DeviceList_1 = require("./DeviceList"); -const deviceinfo_1 = require("./deviceinfo"); -const algorithms = __importStar(require("./algorithms")); -const CrossSigning_1 = require("./CrossSigning"); -const EncryptionSetup_1 = require("./EncryptionSetup"); -const SecretStorage_1 = require("./SecretStorage"); -const OutgoingRoomKeyRequestManager_1 = require("./OutgoingRoomKeyRequestManager"); -const indexeddb_crypto_store_1 = require("./store/indexeddb-crypto-store"); -const QRCode_1 = require("./verification/QRCode"); -const SAS_1 = require("./verification/SAS"); -const key_passphrase_1 = require("./key_passphrase"); -const recoverykey_1 = require("./recoverykey"); -const VerificationRequest_1 = require("./verification/request/VerificationRequest"); -const InRoomChannel_1 = require("./verification/request/InRoomChannel"); -const ToDeviceChannel_1 = require("./verification/request/ToDeviceChannel"); -const IllegalMethod_1 = require("./verification/IllegalMethod"); -const errors_1 = require("../errors"); -const aes_1 = require("./aes"); -const dehydration_1 = require("./dehydration"); -const backup_1 = require("./backup"); -const room_1 = require("../models/room"); -const room_member_1 = require("../models/room-member"); -const event_2 = require("../models/event"); -const client_1 = require("../client"); -const typed_event_emitter_1 = require("../models/typed-event-emitter"); -const room_state_1 = require("../models/room-state"); -const utils_1 = require("../utils"); -const DeviceVerification = deviceinfo_1.DeviceInfo.DeviceVerification; -const defaultVerificationMethods = { - [QRCode_1.ReciprocateQRCode.NAME]: QRCode_1.ReciprocateQRCode, - [SAS_1.SAS.NAME]: SAS_1.SAS, - // These two can't be used for actual verification, but we do - // need to be able to define them here for the verification flows - // to start. - [QRCode_1.SHOW_QR_CODE_METHOD]: IllegalMethod_1.IllegalMethod, - [QRCode_1.SCAN_QR_CODE_METHOD]: IllegalMethod_1.IllegalMethod, -}; -/** - * verification method names - */ -// legacy export identifier -exports.verificationMethods = { - RECIPROCATE_QR_CODE: QRCode_1.ReciprocateQRCode.NAME, - SAS: SAS_1.SAS.NAME, -}; -function isCryptoAvailable() { - return Boolean(global.Olm); -} -exports.isCryptoAvailable = isCryptoAvailable; -const MIN_FORCE_SESSION_INTERVAL_MS = 60 * 60 * 1000; -var CryptoEvent; -(function (CryptoEvent) { - CryptoEvent["DeviceVerificationChanged"] = "deviceVerificationChanged"; - CryptoEvent["UserTrustStatusChanged"] = "userTrustStatusChanged"; - CryptoEvent["UserCrossSigningUpdated"] = "userCrossSigningUpdated"; - CryptoEvent["RoomKeyRequest"] = "crypto.roomKeyRequest"; - CryptoEvent["RoomKeyRequestCancellation"] = "crypto.roomKeyRequestCancellation"; - CryptoEvent["KeyBackupStatus"] = "crypto.keyBackupStatus"; - CryptoEvent["KeyBackupFailed"] = "crypto.keyBackupFailed"; - CryptoEvent["KeyBackupSessionsRemaining"] = "crypto.keyBackupSessionsRemaining"; - CryptoEvent["KeySignatureUploadFailure"] = "crypto.keySignatureUploadFailure"; - CryptoEvent["VerificationRequest"] = "crypto.verification.request"; - CryptoEvent["Warning"] = "crypto.warning"; - CryptoEvent["WillUpdateDevices"] = "crypto.willUpdateDevices"; - CryptoEvent["DevicesUpdated"] = "crypto.devicesUpdated"; - CryptoEvent["KeysChanged"] = "crossSigning.keysChanged"; -})(CryptoEvent = exports.CryptoEvent || (exports.CryptoEvent = {})); -class Crypto extends typed_event_emitter_1.TypedEventEmitter { - /** - * @returns The version of Olm. - */ - static getOlmVersion() { - return OlmDevice_1.OlmDevice.getOlmVersion(); - } - /** - * Cryptography bits - * - * This module is internal to the js-sdk; the public API is via MatrixClient. - * - * @internal - * - * @param baseApis - base matrix api interface - * - * @param userId - The user ID for the local user - * - * @param deviceId - The identifier for this device. - * - * @param clientStore - the MatrixClient data store. - * - * @param cryptoStore - storage for the crypto layer. - * - * @param roomList - An initialised RoomList object - * - * @param verificationMethods - Array of verification methods to use. - * Each element can either be a string from MatrixClient.verificationMethods - * or a class that implements a verification method. - */ - constructor(baseApis, userId, deviceId, clientStore, cryptoStore, roomList, verificationMethods) { - super(); - this.baseApis = baseApis; - this.userId = userId; - this.deviceId = deviceId; - this.clientStore = clientStore; - this.cryptoStore = cryptoStore; - this.roomList = roomList; - this.trustCrossSignedDevices = true; - // the last time we did a check for the number of one-time-keys on the server. - this.lastOneTimeKeyCheck = null; - this.oneTimeKeyCheckInProgress = false; - // EncryptionAlgorithm instance for each room - this.roomEncryptors = new Map(); - // map from algorithm to DecryptionAlgorithm instance, for each room - this.roomDecryptors = new Map(); - this.deviceKeys = {}; // type: key - this.globalBlacklistUnverifiedDevices = false; - this.globalErrorOnUnknownDevices = true; - // list of IncomingRoomKeyRequests/IncomingRoomKeyRequestCancellations - // we received in the current sync. - this.receivedRoomKeyRequests = []; - this.receivedRoomKeyRequestCancellations = []; - // true if we are currently processing received room key requests - this.processingRoomKeyRequests = false; - // controls whether device tracking is delayed - // until calling encryptEvent or trackRoomDevices, - // or done immediately upon enabling room encryption. - this.lazyLoadMembers = false; - // in case lazyLoadMembers is true, - // track if an initial tracking of all the room members - // has happened for a given room. This is delayed - // to avoid loading room members as long as possible. - this.roomDeviceTrackingState = {}; - // The timestamp of the last time we forced establishment - // of a new session for each device, in milliseconds. - // { - // userId: { - // deviceId: 1234567890000, - // }, - // } - // Map: user Id → device Id → timestamp - this.lastNewSessionForced = new utils_1.MapWithDefault(() => new utils_1.MapWithDefault(() => 0)); - // This flag will be unset whilst the client processes a sync response - // so that we don't start requesting keys until we've actually finished - // processing the response. - this.sendKeyRequestsImmediately = false; - /* - * Event handler for DeviceList's userNewDevices event - */ - this.onDeviceListUserCrossSigningUpdated = (userId) => __awaiter(this, void 0, void 0, function* () { - if (userId === this.userId) { - // An update to our own cross-signing key. - // Get the new key first: - const newCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId); - const seenPubkey = newCrossSigning ? newCrossSigning.getId() : null; - const currentPubkey = this.crossSigningInfo.getId(); - const changed = currentPubkey !== seenPubkey; - if (currentPubkey && seenPubkey && !changed) { - // If it's not changed, just make sure everything is up to date - yield this.checkOwnCrossSigningTrust(); - } - else { - // We'll now be in a state where cross-signing on the account is not trusted - // because our locally stored cross-signing keys will not match the ones - // on the server for our account. So we clear our own stored cross-signing keys, - // effectively disabling cross-signing until the user gets verified by the device - // that reset the keys - this.storeTrustedSelfKeys(null); - // emit cross-signing has been disabled - this.emit(CryptoEvent.KeysChanged, {}); - // as the trust for our own user has changed, - // also emit an event for this - this.emit(CryptoEvent.UserTrustStatusChanged, this.userId, this.checkUserTrust(userId)); - } - } - else { - yield this.checkDeviceVerifications(userId); - // Update verified before latch using the current state and save the new - // latch value in the device list store. - const crossSigning = this.deviceList.getStoredCrossSigningForUser(userId); - if (crossSigning) { - crossSigning.updateCrossSigningVerifiedBefore(this.checkUserTrust(userId).isCrossSigningVerified()); - this.deviceList.setRawStoredCrossSigningForUser(userId, crossSigning.toStorage()); - } - this.emit(CryptoEvent.UserTrustStatusChanged, userId, this.checkUserTrust(userId)); - } - }); - this.onMembership = (event, member, oldMembership) => { - try { - this.onRoomMembership(event, member, oldMembership); - } - catch (e) { - logger_1.logger.error("Error handling membership change:", e); - } - }; - this.onToDeviceEvent = (event) => { - try { - logger_1.logger.log(`received to-device ${event.getType()} from: ` + - `${event.getSender()} id: ${event.getContent()[event_1.ToDeviceMessageId]}`); - if (event.getType() == "m.room_key" || event.getType() == "m.forwarded_room_key") { - this.onRoomKeyEvent(event); - } - else if (event.getType() == "m.room_key_request") { - this.onRoomKeyRequestEvent(event); - } - else if (event.getType() === "m.secret.request") { - this.secretStorage.onRequestReceived(event); - } - else if (event.getType() === "m.secret.send") { - this.secretStorage.onSecretReceived(event); - } - else if (event.getType() === "m.room_key.withheld") { - this.onRoomKeyWithheldEvent(event); - } - else if (event.getContent().transaction_id) { - this.onKeyVerificationMessage(event); - } - else if (event.getContent().msgtype === "m.bad.encrypted") { - this.onToDeviceBadEncrypted(event); - } - else if (event.isBeingDecrypted() || event.shouldAttemptDecryption()) { - if (!event.isBeingDecrypted()) { - event.attemptDecryption(this); - } - // once the event has been decrypted, try again - event.once(event_2.MatrixEventEvent.Decrypted, (ev) => { - this.onToDeviceEvent(ev); - }); - } - } - catch (e) { - logger_1.logger.error("Error handling toDeviceEvent:", e); - } - }; - /** - * Handle key verification requests sent as timeline events - * - * @internal - * @param event - the timeline event - * @param room - not used - * @param atStart - not used - * @param removed - not used - * @param whether - this is a live event - */ - this.onTimelineEvent = (event, room, atStart, removed, { liveEvent = true } = {}) => { - if (!InRoomChannel_1.InRoomChannel.validateEvent(event, this.baseApis)) { - return; - } - const createRequest = (event) => { - const channel = new InRoomChannel_1.InRoomChannel(this.baseApis, event.getRoomId()); - return new VerificationRequest_1.VerificationRequest(channel, this.verificationMethods, this.baseApis); - }; - this.handleVerificationEvent(event, this.inRoomVerificationRequests, createRequest, liveEvent); - }; - this.reEmitter = new ReEmitter_1.TypedReEmitter(this); - if (verificationMethods) { - this.verificationMethods = new Map(); - for (const method of verificationMethods) { - if (typeof method === "string") { - if (defaultVerificationMethods[method]) { - this.verificationMethods.set(method, defaultVerificationMethods[method]); - } - } - else if (method["NAME"]) { - this.verificationMethods.set(method["NAME"], method); - } - else { - logger_1.logger.warn(`Excluding unknown verification method ${method}`); - } - } - } - else { - this.verificationMethods = new Map(Object.entries(defaultVerificationMethods)); - } - this.backupManager = new backup_1.BackupManager(baseApis, () => __awaiter(this, void 0, void 0, function* () { - // try to get key from cache - const cachedKey = yield this.getSessionBackupPrivateKey(); - if (cachedKey) { - return cachedKey; - } - // try to get key from secret storage - const storedKey = yield this.getSecret("m.megolm_backup.v1"); - if (storedKey) { - // ensure that the key is in the right format. If not, fix the key and - // store the fixed version - const fixedKey = fixBackupKey(storedKey); - if (fixedKey) { - const keys = yield this.getSecretStorageKey(); - yield this.storeSecret("m.megolm_backup.v1", fixedKey, [keys[0]]); - } - return olmlib.decodeBase64(fixedKey || storedKey); - } - // try to get key from app - if (this.baseApis.cryptoCallbacks && this.baseApis.cryptoCallbacks.getBackupKey) { - return this.baseApis.cryptoCallbacks.getBackupKey(); - } - throw new Error("Unable to get private key"); - })); - this.olmDevice = new OlmDevice_1.OlmDevice(cryptoStore); - this.deviceList = new DeviceList_1.DeviceList(baseApis, cryptoStore, this.olmDevice); - // XXX: This isn't removed at any point, but then none of the event listeners - // this class sets seem to be removed at any point... :/ - this.deviceList.on(CryptoEvent.UserCrossSigningUpdated, this.onDeviceListUserCrossSigningUpdated); - this.reEmitter.reEmit(this.deviceList, [CryptoEvent.DevicesUpdated, CryptoEvent.WillUpdateDevices]); - this.supportedAlgorithms = Array.from(algorithms.DECRYPTION_CLASSES.keys()); - this.outgoingRoomKeyRequestManager = new OutgoingRoomKeyRequestManager_1.OutgoingRoomKeyRequestManager(baseApis, this.deviceId, this.cryptoStore); - this.toDeviceVerificationRequests = new ToDeviceChannel_1.ToDeviceRequests(); - this.inRoomVerificationRequests = new InRoomChannel_1.InRoomRequests(); - const cryptoCallbacks = this.baseApis.cryptoCallbacks || {}; - const cacheCallbacks = (0, CrossSigning_1.createCryptoStoreCacheCallbacks)(cryptoStore, this.olmDevice); - this.crossSigningInfo = new CrossSigning_1.CrossSigningInfo(userId, cryptoCallbacks, cacheCallbacks); - // Yes, we pass the client twice here: see SecretStorage - this.secretStorage = new SecretStorage_1.SecretStorage(baseApis, cryptoCallbacks, baseApis); - this.dehydrationManager = new dehydration_1.DehydrationManager(this); - // Assuming no app-supplied callback, default to getting from SSSS. - if (!cryptoCallbacks.getCrossSigningKey && cryptoCallbacks.getSecretStorageKey) { - cryptoCallbacks.getCrossSigningKey = (type) => __awaiter(this, void 0, void 0, function* () { - return CrossSigning_1.CrossSigningInfo.getFromSecretStorage(type, this.secretStorage); - }); - } - } - /** - * Initialise the crypto module so that it is ready for use - * - * Returns a promise which resolves once the crypto module is ready for use. - * - * @param exportedOlmDevice - (Optional) data from exported device - * that must be re-created. - */ - init({ exportedOlmDevice, pickleKey } = {}) { - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.log("Crypto: initialising Olm..."); - yield global.Olm.init(); - logger_1.logger.log(exportedOlmDevice - ? "Crypto: initialising Olm device from exported device..." - : "Crypto: initialising Olm device..."); - yield this.olmDevice.init({ fromExportedDevice: exportedOlmDevice, pickleKey }); - logger_1.logger.log("Crypto: loading device list..."); - yield this.deviceList.load(); - // build our device keys: these will later be uploaded - this.deviceKeys["ed25519:" + this.deviceId] = this.olmDevice.deviceEd25519Key; - this.deviceKeys["curve25519:" + this.deviceId] = this.olmDevice.deviceCurve25519Key; - logger_1.logger.log("Crypto: fetching own devices..."); - let myDevices = this.deviceList.getRawStoredDevicesForUser(this.userId); - if (!myDevices) { - myDevices = {}; - } - if (!myDevices[this.deviceId]) { - // add our own deviceinfo to the cryptoStore - logger_1.logger.log("Crypto: adding this device to the store..."); - const deviceInfo = { - keys: this.deviceKeys, - algorithms: this.supportedAlgorithms, - verified: DeviceVerification.VERIFIED, - known: true, - }; - myDevices[this.deviceId] = deviceInfo; - this.deviceList.storeDevicesForUser(this.userId, myDevices); - this.deviceList.saveIfDirty(); - } - yield this.cryptoStore.doTxn("readonly", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { - this.cryptoStore.getCrossSigningKeys(txn, (keys) => { - // can be an empty object after resetting cross-signing keys, see storeTrustedSelfKeys - if (keys && Object.keys(keys).length !== 0) { - logger_1.logger.log("Loaded cross-signing public keys from crypto store"); - this.crossSigningInfo.setKeys(keys); - } - }); - }); - // make sure we are keeping track of our own devices - // (this is important for key backups & things) - this.deviceList.startTrackingDeviceList(this.userId); - logger_1.logger.log("Crypto: checking for key backup..."); - this.backupManager.checkAndStart(); - }); - } - /** - * Whether to trust a others users signatures of their devices. - * If false, devices will only be considered 'verified' if we have - * verified that device individually (effectively disabling cross-signing). - * - * Default: true - * - * @returns True if trusting cross-signed devices - */ - getCryptoTrustCrossSignedDevices() { - return this.trustCrossSignedDevices; - } - /** - * See getCryptoTrustCrossSignedDevices - - * This may be set before initCrypto() is called to ensure no races occur. - * - * @param val - True to trust cross-signed devices - */ - setCryptoTrustCrossSignedDevices(val) { - this.trustCrossSignedDevices = val; - for (const userId of this.deviceList.getKnownUserIds()) { - const devices = this.deviceList.getRawStoredDevicesForUser(userId); - for (const deviceId of Object.keys(devices)) { - const deviceTrust = this.checkDeviceTrust(userId, deviceId); - // If the device is locally verified then isVerified() is always true, - // so this will only have caused the value to change if the device is - // cross-signing verified but not locally verified - if (!deviceTrust.isLocallyVerified() && deviceTrust.isCrossSigningVerified()) { - const deviceObj = this.deviceList.getStoredDevice(userId, deviceId); - this.emit(CryptoEvent.DeviceVerificationChanged, userId, deviceId, deviceObj); - } - } - } - } - /** - * Create a recovery key from a user-supplied passphrase. - * - * @param password - Passphrase string that can be entered by the user - * when restoring the backup as an alternative to entering the recovery key. - * Optional. - * @returns Object with public key metadata, encoded private - * recovery key which should be disposed of after displaying to the user, - * and raw private key to avoid round tripping if needed. - */ - createRecoveryKeyFromPassphrase(password) { - return __awaiter(this, void 0, void 0, function* () { - const decryption = new global.Olm.PkDecryption(); - try { - const keyInfo = {}; - if (password) { - const derivation = yield (0, key_passphrase_1.keyFromPassphrase)(password); - keyInfo.passphrase = { - algorithm: "m.pbkdf2", - iterations: derivation.iterations, - salt: derivation.salt, - }; - keyInfo.pubkey = decryption.init_with_private_key(derivation.key); - } - else { - keyInfo.pubkey = decryption.generate_key(); - } - const privateKey = decryption.get_private_key(); - const encodedPrivateKey = (0, recoverykey_1.encodeRecoveryKey)(privateKey); - return { - keyInfo: keyInfo, - encodedPrivateKey, - privateKey, - }; - } - finally { - decryption === null || decryption === void 0 ? void 0 : decryption.free(); - } - }); - } - /** - * Checks if the user has previously published cross-signing keys - * - * This means downloading the devicelist for the user and checking if the list includes - * the cross-signing pseudo-device. - * - * @internal - */ - userHasCrossSigningKeys() { - return __awaiter(this, void 0, void 0, function* () { - yield this.downloadKeys([this.userId]); - return this.deviceList.getStoredCrossSigningForUser(this.userId) !== null; - }); - } - /** - * Checks whether cross signing: - * - is enabled on this account and trusted by this device - * - has private keys either cached locally or stored in secret storage - * - * If this function returns false, bootstrapCrossSigning() can be used - * to fix things such that it returns true. That is to say, after - * bootstrapCrossSigning() completes successfully, this function should - * return true. - * - * The cross-signing API is currently UNSTABLE and may change without notice. - * - * @returns True if cross-signing is ready to be used on this device - */ - isCrossSigningReady() { - return __awaiter(this, void 0, void 0, function* () { - const publicKeysOnDevice = this.crossSigningInfo.getId(); - const privateKeysExistSomewhere = (yield this.crossSigningInfo.isStoredInKeyCache()) || - (yield this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage)); - return !!(publicKeysOnDevice && privateKeysExistSomewhere); - }); - } - /** - * Checks whether secret storage: - * - is enabled on this account - * - is storing cross-signing private keys - * - is storing session backup key (if enabled) - * - * If this function returns false, bootstrapSecretStorage() can be used - * to fix things such that it returns true. That is to say, after - * bootstrapSecretStorage() completes successfully, this function should - * return true. - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @returns True if secret storage is ready to be used on this device - */ - isSecretStorageReady() { - return __awaiter(this, void 0, void 0, function* () { - const secretStorageKeyInAccount = yield this.secretStorage.hasKey(); - const privateKeysInStorage = yield this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage); - const sessionBackupInStorage = !this.backupManager.getKeyBackupEnabled() || (yield this.baseApis.isKeyBackupKeyStored()); - return !!(secretStorageKeyInAccount && privateKeysInStorage && sessionBackupInStorage); - }); - } - /** - * Bootstrap cross-signing by creating keys if needed. If everything is already - * set up, then no changes are made, so this is safe to run to ensure - * cross-signing is ready for use. - * - * This function: - * - creates new cross-signing keys if they are not found locally cached nor in - * secret storage (if it has been setup) - * - * The cross-signing API is currently UNSTABLE and may change without notice. - * - * @param authUploadDeviceSigningKeys - Function - * called to await an interactive auth flow when uploading device signing keys. - * @param setupNewCrossSigning - Optional. Reset even if keys - * already exist. - * Args: - * A function that makes the request requiring auth. Receives the - * auth data as an object. Can be called multiple times, first with an empty - * authDict, to obtain the flows. - */ - bootstrapCrossSigning({ authUploadDeviceSigningKeys, setupNewCrossSigning, } = {}) { - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.log("Bootstrapping cross-signing"); - const delegateCryptoCallbacks = this.baseApis.cryptoCallbacks; - const builder = new EncryptionSetup_1.EncryptionSetupBuilder(this.baseApis.store.accountData, delegateCryptoCallbacks); - const crossSigningInfo = new CrossSigning_1.CrossSigningInfo(this.userId, builder.crossSigningCallbacks, builder.crossSigningCallbacks); - // Reset the cross-signing keys - const resetCrossSigning = () => __awaiter(this, void 0, void 0, function* () { - crossSigningInfo.resetKeys(); - // Sign master key with device key - yield this.signObject(crossSigningInfo.keys.master); - // Store auth flow helper function, as we need to call it when uploading - // to ensure we handle auth errors properly. - builder.addCrossSigningKeys(authUploadDeviceSigningKeys, crossSigningInfo.keys); - // Cross-sign own device - const device = this.deviceList.getStoredDevice(this.userId, this.deviceId); - const deviceSignature = yield crossSigningInfo.signDevice(this.userId, device); - builder.addKeySignature(this.userId, this.deviceId, deviceSignature); - // Sign message key backup with cross-signing master key - if (this.backupManager.backupInfo) { - yield crossSigningInfo.signObject(this.backupManager.backupInfo.auth_data, "master"); - builder.addSessionBackup(this.backupManager.backupInfo); - } - }); - const publicKeysOnDevice = this.crossSigningInfo.getId(); - const privateKeysInCache = yield this.crossSigningInfo.isStoredInKeyCache(); - const privateKeysInStorage = yield this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage); - const privateKeysExistSomewhere = privateKeysInCache || privateKeysInStorage; - // Log all relevant state for easier parsing of debug logs. - logger_1.logger.log({ - setupNewCrossSigning, - publicKeysOnDevice, - privateKeysInCache, - privateKeysInStorage, - privateKeysExistSomewhere, - }); - if (!privateKeysExistSomewhere || setupNewCrossSigning) { - logger_1.logger.log("Cross-signing private keys not found locally or in secret storage, " + "creating new keys"); - // If a user has multiple devices, it important to only call bootstrap - // as part of some UI flow (and not silently during startup), as they - // may have setup cross-signing on a platform which has not saved keys - // to secret storage, and this would reset them. In such a case, you - // should prompt the user to verify any existing devices first (and - // request private keys from those devices) before calling bootstrap. - yield resetCrossSigning(); - } - else if (publicKeysOnDevice && privateKeysInCache) { - logger_1.logger.log("Cross-signing public keys trusted and private keys found locally"); - } - else if (privateKeysInStorage) { - logger_1.logger.log("Cross-signing private keys not found locally, but they are available " + - "in secret storage, reading storage and caching locally"); - yield this.checkOwnCrossSigningTrust({ - allowPrivateKeyRequests: true, - }); - } - // Assuming no app-supplied callback, default to storing new private keys in - // secret storage if it exists. If it does not, it is assumed this will be - // done as part of setting up secret storage later. - const crossSigningPrivateKeys = builder.crossSigningCallbacks.privateKeys; - if (crossSigningPrivateKeys.size && !this.baseApis.cryptoCallbacks.saveCrossSigningKeys) { - const secretStorage = new SecretStorage_1.SecretStorage(builder.accountDataClientAdapter, builder.ssssCryptoCallbacks, undefined); - if (yield secretStorage.hasKey()) { - logger_1.logger.log("Storing new cross-signing private keys in secret storage"); - // This is writing to in-memory account data in - // builder.accountDataClientAdapter so won't fail - yield CrossSigning_1.CrossSigningInfo.storeInSecretStorage(crossSigningPrivateKeys, secretStorage); - } - } - const operation = builder.buildOperation(); - yield operation.apply(this); - // This persists private keys and public keys as trusted, - // only do this if apply succeeded for now as retry isn't in place yet - yield builder.persist(this); - logger_1.logger.log("Cross-signing ready"); - }); - } - /** - * Bootstrap Secure Secret Storage if needed by creating a default key. If everything is - * already set up, then no changes are made, so this is safe to run to ensure secret - * storage is ready for use. - * - * This function - * - creates a new Secure Secret Storage key if no default key exists - * - if a key backup exists, it is migrated to store the key in the Secret - * Storage - * - creates a backup if none exists, and one is requested - * - migrates Secure Secret Storage to use the latest algorithm, if an outdated - * algorithm is found - * - * The Secure Secret Storage API is currently UNSTABLE and may change without notice. - * - * @param createSecretStorageKey - Optional. Function - * called to await a secret storage key creation flow. - * Returns a Promise which resolves to an object with public key metadata, encoded private - * recovery key which should be disposed of after displaying to the user, - * and raw private key to avoid round tripping if needed. - * @param keyBackupInfo - The current key backup object. If passed, - * the passphrase and recovery key from this backup will be used. - * @param setupNewKeyBackup - If true, a new key backup version will be - * created and the private key stored in the new SSSS store. Ignored if keyBackupInfo - * is supplied. - * @param setupNewSecretStorage - Optional. Reset even if keys already exist. - * @param getKeyBackupPassphrase - Optional. Function called to get the user's - * current key backup passphrase. Should return a promise that resolves with a Buffer - * containing the key, or rejects if the key cannot be obtained. - * Returns: - * A promise which resolves to key creation data for - * SecretStorage#addKey: an object with `passphrase` etc fields. - */ - // TODO this does not resolve with what it says it does - bootstrapSecretStorage({ createSecretStorageKey = () => __awaiter(this, void 0, void 0, function* () { return ({}); }), keyBackupInfo, setupNewKeyBackup, setupNewSecretStorage, getKeyBackupPassphrase, } = {}) { - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.log("Bootstrapping Secure Secret Storage"); - const delegateCryptoCallbacks = this.baseApis.cryptoCallbacks; - const builder = new EncryptionSetup_1.EncryptionSetupBuilder(this.baseApis.store.accountData, delegateCryptoCallbacks); - const secretStorage = new SecretStorage_1.SecretStorage(builder.accountDataClientAdapter, builder.ssssCryptoCallbacks, undefined); - // the ID of the new SSSS key, if we create one - let newKeyId = null; - // create a new SSSS key and set it as default - const createSSSS = (opts, privateKey) => __awaiter(this, void 0, void 0, function* () { - if (privateKey) { - opts.key = privateKey; - } - const { keyId, keyInfo } = yield secretStorage.addKey(SecretStorage_1.SECRET_STORAGE_ALGORITHM_V1_AES, opts); - if (privateKey) { - // make the private key available to encrypt 4S secrets - builder.ssssCryptoCallbacks.addPrivateKey(keyId, keyInfo, privateKey); - } - yield secretStorage.setDefaultKeyId(keyId); - return keyId; - }); - const ensureCanCheckPassphrase = (keyId, keyInfo) => __awaiter(this, void 0, void 0, function* () { - var _a, _b; - if (!keyInfo.mac) { - const key = yield ((_b = (_a = this.baseApis.cryptoCallbacks).getSecretStorageKey) === null || _b === void 0 ? void 0 : _b.call(_a, { keys: { [keyId]: keyInfo } }, "")); - if (key) { - const privateKey = key[1]; - builder.ssssCryptoCallbacks.addPrivateKey(keyId, keyInfo, privateKey); - const { iv, mac } = yield (0, aes_1.calculateKeyCheck)(privateKey); - keyInfo.iv = iv; - keyInfo.mac = mac; - yield builder.setAccountData(`m.secret_storage.key.${keyId}`, keyInfo); - } - } - }); - const signKeyBackupWithCrossSigning = (keyBackupAuthData) => __awaiter(this, void 0, void 0, function* () { - if (this.crossSigningInfo.getId() && (yield this.crossSigningInfo.isStoredInKeyCache("master"))) { - try { - logger_1.logger.log("Adding cross-signing signature to key backup"); - yield this.crossSigningInfo.signObject(keyBackupAuthData, "master"); - } - catch (e) { - // This step is not critical (just helpful), so we catch here - // and continue if it fails. - logger_1.logger.error("Signing key backup with cross-signing keys failed", e); - } - } - else { - logger_1.logger.warn("Cross-signing keys not available, skipping signature on key backup"); - } - }); - const oldSSSSKey = yield this.getSecretStorageKey(); - const [oldKeyId, oldKeyInfo] = oldSSSSKey || [null, null]; - const storageExists = !setupNewSecretStorage && oldKeyInfo && oldKeyInfo.algorithm === SecretStorage_1.SECRET_STORAGE_ALGORITHM_V1_AES; - // Log all relevant state for easier parsing of debug logs. - logger_1.logger.log({ - keyBackupInfo, - setupNewKeyBackup, - setupNewSecretStorage, - storageExists, - oldKeyInfo, - }); - if (!storageExists && !keyBackupInfo) { - // either we don't have anything, or we've been asked to restart - // from scratch - logger_1.logger.log("Secret storage does not exist, creating new storage key"); - // if we already have a usable default SSSS key and aren't resetting - // SSSS just use it. otherwise, create a new one - // Note: we leave the old SSSS key in place: there could be other - // secrets using it, in theory. We could move them to the new key but a) - // that would mean we'd need to prompt for the old passphrase, and b) - // it's not clear that would be the right thing to do anyway. - const { keyInfo = {}, privateKey } = yield createSecretStorageKey(); - newKeyId = yield createSSSS(keyInfo, privateKey); - } - else if (!storageExists && keyBackupInfo) { - // we have an existing backup, but no SSSS - logger_1.logger.log("Secret storage does not exist, using key backup key"); - // if we have the backup key already cached, use it; otherwise use the - // callback to prompt for the key - const backupKey = (yield this.getSessionBackupPrivateKey()) || (yield (getKeyBackupPassphrase === null || getKeyBackupPassphrase === void 0 ? void 0 : getKeyBackupPassphrase())); - // create a new SSSS key and use the backup key as the new SSSS key - const opts = {}; - if (keyBackupInfo.auth_data.private_key_salt && keyBackupInfo.auth_data.private_key_iterations) { - // FIXME: ??? - opts.passphrase = { - algorithm: "m.pbkdf2", - iterations: keyBackupInfo.auth_data.private_key_iterations, - salt: keyBackupInfo.auth_data.private_key_salt, - bits: 256, - }; - } - newKeyId = yield createSSSS(opts, backupKey); - // store the backup key in secret storage - yield secretStorage.store("m.megolm_backup.v1", olmlib.encodeBase64(backupKey), [newKeyId]); - // The backup is trusted because the user provided the private key. - // Sign the backup with the cross-signing key so the key backup can - // be trusted via cross-signing. - yield signKeyBackupWithCrossSigning(keyBackupInfo.auth_data); - builder.addSessionBackup(keyBackupInfo); - } - else { - // 4S is already set up - logger_1.logger.log("Secret storage exists"); - if (oldKeyInfo && oldKeyInfo.algorithm === SecretStorage_1.SECRET_STORAGE_ALGORITHM_V1_AES) { - // make sure that the default key has the information needed to - // check the passphrase - yield ensureCanCheckPassphrase(oldKeyId, oldKeyInfo); - } - } - // If we have cross-signing private keys cached, store them in secret - // storage if they are not there already. - if (!this.baseApis.cryptoCallbacks.saveCrossSigningKeys && - (yield this.isCrossSigningReady()) && - (newKeyId || !(yield this.crossSigningInfo.isStoredInSecretStorage(secretStorage)))) { - logger_1.logger.log("Copying cross-signing private keys from cache to secret storage"); - const crossSigningPrivateKeys = yield this.crossSigningInfo.getCrossSigningKeysFromCache(); - // This is writing to in-memory account data in - // builder.accountDataClientAdapter so won't fail - yield CrossSigning_1.CrossSigningInfo.storeInSecretStorage(crossSigningPrivateKeys, secretStorage); - } - if (setupNewKeyBackup && !keyBackupInfo) { - logger_1.logger.log("Creating new message key backup version"); - const info = yield this.baseApis.prepareKeyBackupVersion(null /* random key */, - // don't write to secret storage, as it will write to this.secretStorage. - // Here, we want to capture all the side-effects of bootstrapping, - // and want to write to the local secretStorage object - { secureSecretStorage: false }); - // write the key ourselves to 4S - const privateKey = (0, recoverykey_1.decodeRecoveryKey)(info.recovery_key); - yield secretStorage.store("m.megolm_backup.v1", olmlib.encodeBase64(privateKey)); - // create keyBackupInfo object to add to builder - const data = { - algorithm: info.algorithm, - auth_data: info.auth_data, - }; - // Sign with cross-signing master key - yield signKeyBackupWithCrossSigning(data.auth_data); - // sign with the device fingerprint - yield this.signObject(data.auth_data); - builder.addSessionBackup(data); - } - // Cache the session backup key - const sessionBackupKey = yield secretStorage.get("m.megolm_backup.v1"); - if (sessionBackupKey) { - logger_1.logger.info("Got session backup key from secret storage: caching"); - // fix up the backup key if it's in the wrong format, and replace - // in secret storage - const fixedBackupKey = fixBackupKey(sessionBackupKey); - if (fixedBackupKey) { - const keyId = newKeyId || oldKeyId; - yield secretStorage.store("m.megolm_backup.v1", fixedBackupKey, keyId ? [keyId] : null); - } - const decodedBackupKey = new Uint8Array(olmlib.decodeBase64(fixedBackupKey || sessionBackupKey)); - builder.addSessionBackupPrivateKeyToCache(decodedBackupKey); - } - else if (this.backupManager.getKeyBackupEnabled()) { - // key backup is enabled but we don't have a session backup key in SSSS: see if we have one in - // the cache or the user can provide one, and if so, write it to SSSS - const backupKey = (yield this.getSessionBackupPrivateKey()) || (yield (getKeyBackupPassphrase === null || getKeyBackupPassphrase === void 0 ? void 0 : getKeyBackupPassphrase())); - if (!backupKey) { - // This will require user intervention to recover from since we don't have the key - // backup key anywhere. The user should probably just set up a new key backup and - // the key for the new backup will be stored. If we hit this scenario in the wild - // with any frequency, we should do more than just log an error. - logger_1.logger.error("Key backup is enabled but couldn't get key backup key!"); - return; - } - logger_1.logger.info("Got session backup key from cache/user that wasn't in SSSS: saving to SSSS"); - yield secretStorage.store("m.megolm_backup.v1", olmlib.encodeBase64(backupKey)); - } - const operation = builder.buildOperation(); - yield operation.apply(this); - // this persists private keys and public keys as trusted, - // only do this if apply succeeded for now as retry isn't in place yet - yield builder.persist(this); - logger_1.logger.log("Secure Secret Storage ready"); - }); - } - addSecretStorageKey(algorithm, opts, keyID) { - return this.secretStorage.addKey(algorithm, opts, keyID); - } - hasSecretStorageKey(keyID) { - return this.secretStorage.hasKey(keyID); - } - getSecretStorageKey(keyID) { - return this.secretStorage.getKey(keyID); - } - storeSecret(name, secret, keys) { - return this.secretStorage.store(name, secret, keys); - } - getSecret(name) { - return this.secretStorage.get(name); - } - isSecretStored(name) { - return this.secretStorage.isStored(name); - } - requestSecret(name, devices) { - if (!devices) { - devices = Object.keys(this.deviceList.getRawStoredDevicesForUser(this.userId)); - } - return this.secretStorage.request(name, devices); - } - getDefaultSecretStorageKeyId() { - return this.secretStorage.getDefaultKeyId(); - } - setDefaultSecretStorageKeyId(k) { - return this.secretStorage.setDefaultKeyId(k); - } - checkSecretStorageKey(key, info) { - return this.secretStorage.checkKey(key, info); - } - /** - * Checks that a given secret storage private key matches a given public key. - * This can be used by the getSecretStorageKey callback to verify that the - * private key it is about to supply is the one that was requested. - * - * @param privateKey - The private key - * @param expectedPublicKey - The public key - * @returns true if the key matches, otherwise false - */ - checkSecretStoragePrivateKey(privateKey, expectedPublicKey) { - let decryption = null; - try { - decryption = new global.Olm.PkDecryption(); - const gotPubkey = decryption.init_with_private_key(privateKey); - // make sure it agrees with the given pubkey - return gotPubkey === expectedPublicKey; - } - finally { - decryption === null || decryption === void 0 ? void 0 : decryption.free(); - } - } - /** - * Fetches the backup private key, if cached - * @returns the key, if any, or null - */ - getSessionBackupPrivateKey() { - return __awaiter(this, void 0, void 0, function* () { - let key = yield new Promise((resolve) => { - // TODO types - this.cryptoStore.doTxn("readonly", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { - this.cryptoStore.getSecretStorePrivateKey(txn, resolve, "m.megolm_backup.v1"); - }); - }); - // make sure we have a Uint8Array, rather than a string - if (key && typeof key === "string") { - key = new Uint8Array(olmlib.decodeBase64(fixBackupKey(key) || key)); - yield this.storeSessionBackupPrivateKey(key); - } - if (key && key.ciphertext) { - const pickleKey = Buffer.from(this.olmDevice.pickleKey); - const decrypted = yield (0, aes_1.decryptAES)(key, pickleKey, "m.megolm_backup.v1"); - key = olmlib.decodeBase64(decrypted); - } - return key; - }); - } - /** - * Stores the session backup key to the cache - * @param key - the private key - * @returns a promise so you can catch failures - */ - storeSessionBackupPrivateKey(key) { - return __awaiter(this, void 0, void 0, function* () { - if (!(key instanceof Uint8Array)) { - // eslint-disable-next-line @typescript-eslint/no-base-to-string - throw new Error(`storeSessionBackupPrivateKey expects Uint8Array, got ${key}`); - } - const pickleKey = Buffer.from(this.olmDevice.pickleKey); - const encryptedKey = yield (0, aes_1.encryptAES)(olmlib.encodeBase64(key), pickleKey, "m.megolm_backup.v1"); - return this.cryptoStore.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { - this.cryptoStore.storeSecretStorePrivateKey(txn, "m.megolm_backup.v1", encryptedKey); - }); - }); - } - /** - * Checks that a given cross-signing private key matches a given public key. - * This can be used by the getCrossSigningKey callback to verify that the - * private key it is about to supply is the one that was requested. - * - * @param privateKey - The private key - * @param expectedPublicKey - The public key - * @returns true if the key matches, otherwise false - */ - checkCrossSigningPrivateKey(privateKey, expectedPublicKey) { - let signing = null; - try { - signing = new global.Olm.PkSigning(); - const gotPubkey = signing.init_with_seed(privateKey); - // make sure it agrees with the given pubkey - return gotPubkey === expectedPublicKey; - } - finally { - signing === null || signing === void 0 ? void 0 : signing.free(); - } - } - /** - * Run various follow-up actions after cross-signing keys have changed locally - * (either by resetting the keys for the account or by getting them from secret - * storage), such as signing the current device, upgrading device - * verifications, etc. - */ - afterCrossSigningLocalKeyChange() { - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.info("Starting cross-signing key change post-processing"); - // sign the current device with the new key, and upload to the server - const device = this.deviceList.getStoredDevice(this.userId, this.deviceId); - const signedDevice = yield this.crossSigningInfo.signDevice(this.userId, device); - logger_1.logger.info(`Starting background key sig upload for ${this.deviceId}`); - const upload = ({ shouldEmit = false }) => { - return this.baseApis - .uploadKeySignatures({ - [this.userId]: { - [this.deviceId]: signedDevice, - }, - }) - .then((response) => { - const { failures } = response || {}; - if (Object.keys(failures || []).length > 0) { - if (shouldEmit) { - this.baseApis.emit(CryptoEvent.KeySignatureUploadFailure, failures, "afterCrossSigningLocalKeyChange", upload); - } - throw new errors_1.KeySignatureUploadError("Key upload failed", { failures }); - } - logger_1.logger.info(`Finished background key sig upload for ${this.deviceId}`); - }) - .catch((e) => { - logger_1.logger.error(`Error during background key sig upload for ${this.deviceId}`, e); - }); - }; - upload({ shouldEmit: true }); - const shouldUpgradeCb = this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications; - if (shouldUpgradeCb) { - logger_1.logger.info("Starting device verification upgrade"); - // Check all users for signatures if upgrade callback present - // FIXME: do this in batches - const users = {}; - for (const [userId, crossSigningInfo] of Object.entries(this.deviceList.crossSigningInfo)) { - const upgradeInfo = yield this.checkForDeviceVerificationUpgrade(userId, CrossSigning_1.CrossSigningInfo.fromStorage(crossSigningInfo, userId)); - if (upgradeInfo) { - users[userId] = upgradeInfo; - } - } - if (Object.keys(users).length > 0) { - logger_1.logger.info(`Found ${Object.keys(users).length} verif users to upgrade`); - try { - const usersToUpgrade = yield shouldUpgradeCb({ users: users }); - if (usersToUpgrade) { - for (const userId of usersToUpgrade) { - if (userId in users) { - yield this.baseApis.setDeviceVerified(userId, users[userId].crossSigningInfo.getId()); - } - } - } - } - catch (e) { - logger_1.logger.log("shouldUpgradeDeviceVerifications threw an error: not upgrading", e); - } - } - logger_1.logger.info("Finished device verification upgrade"); - } - logger_1.logger.info("Finished cross-signing key change post-processing"); - }); - } - /** - * Check if a user's cross-signing key is a candidate for upgrading from device - * verification. - * - * @param userId - the user whose cross-signing information is to be checked - * @param crossSigningInfo - the cross-signing information to check - */ - checkForDeviceVerificationUpgrade(userId, crossSigningInfo) { - return __awaiter(this, void 0, void 0, function* () { - // only upgrade if this is the first cross-signing key that we've seen for - // them, and if their cross-signing key isn't already verified - const trustLevel = this.crossSigningInfo.checkUserTrust(crossSigningInfo); - if (crossSigningInfo.firstUse && !trustLevel.isVerified()) { - const devices = this.deviceList.getRawStoredDevicesForUser(userId); - const deviceIds = yield this.checkForValidDeviceSignature(userId, crossSigningInfo.keys.master, devices); - if (deviceIds.length) { - return { - devices: deviceIds.map((deviceId) => deviceinfo_1.DeviceInfo.fromStorage(devices[deviceId], deviceId)), - crossSigningInfo, - }; - } - } - }); - } - /** - * Check if the cross-signing key is signed by a verified device. - * - * @param userId - the user ID whose key is being checked - * @param key - the key that is being checked - * @param devices - the user's devices. Should be a map from device ID - * to device info - */ - checkForValidDeviceSignature(userId, key, devices) { - return __awaiter(this, void 0, void 0, function* () { - const deviceIds = []; - if (devices && key.signatures && key.signatures[userId]) { - for (const signame of Object.keys(key.signatures[userId])) { - const [, deviceId] = signame.split(":", 2); - if (deviceId in devices && devices[deviceId].verified === DeviceVerification.VERIFIED) { - try { - yield olmlib.verifySignature(this.olmDevice, key, userId, deviceId, devices[deviceId].keys[signame]); - deviceIds.push(deviceId); - } - catch (e) { } - } - } - } - return deviceIds; - }); - } - /** - * Get the user's cross-signing key ID. - * - * @param type - The type of key to get the ID of. One of - * "master", "self_signing", or "user_signing". Defaults to "master". - * - * @returns the key ID - */ - getCrossSigningId(type) { - return this.crossSigningInfo.getId(type); - } - /** - * Get the cross signing information for a given user. - * - * @param userId - the user ID to get the cross-signing info for. - * - * @returns the cross signing information for the user. - */ - getStoredCrossSigningForUser(userId) { - return this.deviceList.getStoredCrossSigningForUser(userId); - } - /** - * Check whether a given user is trusted. - * - * @param userId - The ID of the user to check. - * - * @returns - */ - checkUserTrust(userId) { - const userCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId); - if (!userCrossSigning) { - return new CrossSigning_1.UserTrustLevel(false, false, false); - } - return this.crossSigningInfo.checkUserTrust(userCrossSigning); - } - /** - * Check whether a given device is trusted. - * - * @param userId - The ID of the user whose devices is to be checked. - * @param deviceId - The ID of the device to check - * - * @returns - */ - checkDeviceTrust(userId, deviceId) { - const device = this.deviceList.getStoredDevice(userId, deviceId); - return this.checkDeviceInfoTrust(userId, device); - } - /** - * Check whether a given deviceinfo is trusted. - * - * @param userId - The ID of the user whose devices is to be checked. - * @param device - The device info object to check - * - * @returns - */ - checkDeviceInfoTrust(userId, device) { - const trustedLocally = !!(device === null || device === void 0 ? void 0 : device.isVerified()); - const userCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId); - if (device && userCrossSigning) { - // The trustCrossSignedDevices only affects trust of other people's cross-signing - // signatures - const trustCrossSig = this.trustCrossSignedDevices || userId === this.userId; - return this.crossSigningInfo.checkDeviceTrust(userCrossSigning, device, trustedLocally, trustCrossSig); - } - else { - return new CrossSigning_1.DeviceTrustLevel(false, false, trustedLocally, false); - } - } - /** - * Check whether one of our own devices is cross-signed by our - * user's stored keys, regardless of whether we trust those keys yet. - * - * @param deviceId - The ID of the device to check - * - * @returns true if the device is cross-signed - */ - checkIfOwnDeviceCrossSigned(deviceId) { - var _a; - const device = this.deviceList.getStoredDevice(this.userId, deviceId); - if (!device) - return false; - const userCrossSigning = this.deviceList.getStoredCrossSigningForUser(this.userId); - return ((_a = userCrossSigning === null || userCrossSigning === void 0 ? void 0 : userCrossSigning.checkDeviceTrust(userCrossSigning, device, false, true).isCrossSigningVerified()) !== null && _a !== void 0 ? _a : false); - } - /** - * Check the copy of our cross-signing key that we have in the device list and - * see if we can get the private key. If so, mark it as trusted. - */ - checkOwnCrossSigningTrust({ allowPrivateKeyRequests = false, } = {}) { - return __awaiter(this, void 0, void 0, function* () { - const userId = this.userId; - // Before proceeding, ensure our cross-signing public keys have been - // downloaded via the device list. - yield this.downloadKeys([this.userId]); - // Also check which private keys are locally cached. - const crossSigningPrivateKeys = yield this.crossSigningInfo.getCrossSigningKeysFromCache(); - // If we see an update to our own master key, check it against the master - // key we have and, if it matches, mark it as verified - // First, get the new cross-signing info - const newCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId); - if (!newCrossSigning) { - logger_1.logger.error("Got cross-signing update event for user " + userId + " but no new cross-signing information found!"); - return; - } - const seenPubkey = newCrossSigning.getId(); - const masterChanged = this.crossSigningInfo.getId() !== seenPubkey; - const masterExistsNotLocallyCached = newCrossSigning.getId() && !crossSigningPrivateKeys.has("master"); - if (masterChanged) { - logger_1.logger.info("Got new master public key", seenPubkey); - } - if (allowPrivateKeyRequests && (masterChanged || masterExistsNotLocallyCached)) { - logger_1.logger.info("Attempting to retrieve cross-signing master private key"); - let signing = null; - // It's important for control flow that we leave any errors alone for - // higher levels to handle so that e.g. cancelling access properly - // aborts any larger operation as well. - try { - const ret = yield this.crossSigningInfo.getCrossSigningKey("master", seenPubkey); - signing = ret[1]; - logger_1.logger.info("Got cross-signing master private key"); - } - finally { - signing === null || signing === void 0 ? void 0 : signing.free(); - } - } - const oldSelfSigningId = this.crossSigningInfo.getId("self_signing"); - const oldUserSigningId = this.crossSigningInfo.getId("user_signing"); - // Update the version of our keys in our cross-signing object and the local store - this.storeTrustedSelfKeys(newCrossSigning.keys); - const selfSigningChanged = oldSelfSigningId !== newCrossSigning.getId("self_signing"); - const userSigningChanged = oldUserSigningId !== newCrossSigning.getId("user_signing"); - const selfSigningExistsNotLocallyCached = newCrossSigning.getId("self_signing") && !crossSigningPrivateKeys.has("self_signing"); - const userSigningExistsNotLocallyCached = newCrossSigning.getId("user_signing") && !crossSigningPrivateKeys.has("user_signing"); - const keySignatures = {}; - if (selfSigningChanged) { - logger_1.logger.info("Got new self-signing key", newCrossSigning.getId("self_signing")); - } - if (allowPrivateKeyRequests && (selfSigningChanged || selfSigningExistsNotLocallyCached)) { - logger_1.logger.info("Attempting to retrieve cross-signing self-signing private key"); - let signing = null; - try { - const ret = yield this.crossSigningInfo.getCrossSigningKey("self_signing", newCrossSigning.getId("self_signing")); - signing = ret[1]; - logger_1.logger.info("Got cross-signing self-signing private key"); - } - finally { - signing === null || signing === void 0 ? void 0 : signing.free(); - } - const device = this.deviceList.getStoredDevice(this.userId, this.deviceId); - const signedDevice = yield this.crossSigningInfo.signDevice(this.userId, device); - keySignatures[this.deviceId] = signedDevice; - } - if (userSigningChanged) { - logger_1.logger.info("Got new user-signing key", newCrossSigning.getId("user_signing")); - } - if (allowPrivateKeyRequests && (userSigningChanged || userSigningExistsNotLocallyCached)) { - logger_1.logger.info("Attempting to retrieve cross-signing user-signing private key"); - let signing = null; - try { - const ret = yield this.crossSigningInfo.getCrossSigningKey("user_signing", newCrossSigning.getId("user_signing")); - signing = ret[1]; - logger_1.logger.info("Got cross-signing user-signing private key"); - } - finally { - signing === null || signing === void 0 ? void 0 : signing.free(); - } - } - if (masterChanged) { - const masterKey = this.crossSigningInfo.keys.master; - yield this.signObject(masterKey); - const deviceSig = masterKey.signatures[this.userId]["ed25519:" + this.deviceId]; - // Include only the _new_ device signature in the upload. - // We may have existing signatures from deleted devices, which will cause - // the entire upload to fail. - keySignatures[this.crossSigningInfo.getId()] = Object.assign({}, masterKey, { - signatures: { - [this.userId]: { - ["ed25519:" + this.deviceId]: deviceSig, - }, - }, - }); - } - const keysToUpload = Object.keys(keySignatures); - if (keysToUpload.length) { - const upload = ({ shouldEmit = false }) => { - logger_1.logger.info(`Starting background key sig upload for ${keysToUpload}`); - return this.baseApis - .uploadKeySignatures({ [this.userId]: keySignatures }) - .then((response) => { - const { failures } = response || {}; - logger_1.logger.info(`Finished background key sig upload for ${keysToUpload}`); - if (Object.keys(failures || []).length > 0) { - if (shouldEmit) { - this.baseApis.emit(CryptoEvent.KeySignatureUploadFailure, failures, "checkOwnCrossSigningTrust", upload); - } - throw new errors_1.KeySignatureUploadError("Key upload failed", { failures }); - } - }) - .catch((e) => { - logger_1.logger.error(`Error during background key sig upload for ${keysToUpload}`, e); - }); - }; - upload({ shouldEmit: true }); - } - this.emit(CryptoEvent.UserTrustStatusChanged, userId, this.checkUserTrust(userId)); - if (masterChanged) { - this.emit(CryptoEvent.KeysChanged, {}); - yield this.afterCrossSigningLocalKeyChange(); - } - // Now we may be able to trust our key backup - yield this.backupManager.checkKeyBackup(); - // FIXME: if we previously trusted the backup, should we automatically sign - // the backup with the new key (if not already signed)? - }); - } - /** - * Store a set of keys as our own, trusted, cross-signing keys. - * - * @param keys - The new trusted set of keys - */ - storeTrustedSelfKeys(keys) { - return __awaiter(this, void 0, void 0, function* () { - if (keys) { - this.crossSigningInfo.setKeys(keys); - } - else { - this.crossSigningInfo.clearKeys(); - } - yield this.cryptoStore.doTxn("readwrite", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => { - this.cryptoStore.storeCrossSigningKeys(txn, this.crossSigningInfo.keys); - }); - }); - } - /** - * Check if the master key is signed by a verified device, and if so, prompt - * the application to mark it as verified. - * - * @param userId - the user ID whose key should be checked - */ - checkDeviceVerifications(userId) { - return __awaiter(this, void 0, void 0, function* () { - const shouldUpgradeCb = this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications; - if (!shouldUpgradeCb) { - // Upgrading skipped when callback is not present. - return; - } - logger_1.logger.info(`Starting device verification upgrade for ${userId}`); - if (this.crossSigningInfo.keys.user_signing) { - const crossSigningInfo = this.deviceList.getStoredCrossSigningForUser(userId); - if (crossSigningInfo) { - const upgradeInfo = yield this.checkForDeviceVerificationUpgrade(userId, crossSigningInfo); - if (upgradeInfo) { - const usersToUpgrade = yield shouldUpgradeCb({ - users: { - [userId]: upgradeInfo, - }, - }); - if (usersToUpgrade.includes(userId)) { - yield this.baseApis.setDeviceVerified(userId, crossSigningInfo.getId()); - } - } - } - } - logger_1.logger.info(`Finished device verification upgrade for ${userId}`); - }); - } - /** - */ - enableLazyLoading() { - this.lazyLoadMembers = true; - } - /** - * Tell the crypto module to register for MatrixClient events which it needs to - * listen for - * - * @param eventEmitter - event source where we can register - * for event notifications - */ - registerEventHandlers(eventEmitter) { - eventEmitter.on(room_member_1.RoomMemberEvent.Membership, this.onMembership); - eventEmitter.on(client_1.ClientEvent.ToDeviceEvent, this.onToDeviceEvent); - eventEmitter.on(room_1.RoomEvent.Timeline, this.onTimelineEvent); - eventEmitter.on(event_2.MatrixEventEvent.Decrypted, this.onTimelineEvent); - } - /** - * @deprecated this does nothing and will be removed in a future version - */ - start() { - logger_1.logger.warn("MatrixClient.crypto.start() is deprecated"); - } - /** Stop background processes related to crypto */ - stop() { - this.outgoingRoomKeyRequestManager.stop(); - this.deviceList.stop(); - this.dehydrationManager.stop(); - } - /** - * Get the Ed25519 key for this device - * - * @returns base64-encoded ed25519 key. - */ - getDeviceEd25519Key() { - return this.olmDevice.deviceEd25519Key; - } - /** - * Get the Curve25519 key for this device - * - * @returns base64-encoded curve25519 key. - */ - getDeviceCurve25519Key() { - return this.olmDevice.deviceCurve25519Key; - } - /** - * Set the global override for whether the client should ever send encrypted - * messages to unverified devices. This provides the default for rooms which - * do not specify a value. - * - * @param value - whether to blacklist all unverified devices by default - * - * @deprecated For external code, use {@link MatrixClient#setGlobalBlacklistUnverifiedDevices}. For - * internal code, set {@link MatrixClient#globalBlacklistUnverifiedDevices} directly. - */ - setGlobalBlacklistUnverifiedDevices(value) { - this.globalBlacklistUnverifiedDevices = value; - } - /** - * @returns whether to blacklist all unverified devices by default - * - * @deprecated For external code, use {@link MatrixClient#getGlobalBlacklistUnverifiedDevices}. For - * internal code, reference {@link MatrixClient#globalBlacklistUnverifiedDevices} directly. - */ - getGlobalBlacklistUnverifiedDevices() { - return this.globalBlacklistUnverifiedDevices; - } - /** - * Upload the device keys to the homeserver. - * @returns A promise that will resolve when the keys are uploaded. - */ - uploadDeviceKeys() { - const deviceKeys = { - algorithms: this.supportedAlgorithms, - device_id: this.deviceId, - keys: this.deviceKeys, - user_id: this.userId, - }; - return this.signObject(deviceKeys).then(() => { - return this.baseApis.uploadKeysRequest({ - device_keys: deviceKeys, - }); - }); - } - /** - * Stores the current one_time_key count which will be handled later (in a call of - * onSyncCompleted). The count is e.g. coming from a /sync response. - * - * @param currentCount - The current count of one_time_keys to be stored - */ - updateOneTimeKeyCount(currentCount) { - if (isFinite(currentCount)) { - this.oneTimeKeyCount = currentCount; - } - else { - throw new TypeError("Parameter for updateOneTimeKeyCount has to be a number"); - } - } - setNeedsNewFallback(needsNewFallback) { - this.needsNewFallback = needsNewFallback; - } - getNeedsNewFallback() { - return !!this.needsNewFallback; - } - // check if it's time to upload one-time keys, and do so if so. - maybeUploadOneTimeKeys() { - // frequency with which to check & upload one-time keys - const uploadPeriod = 1000 * 60; // one minute - // max number of keys to upload at once - // Creating keys can be an expensive operation so we limit the - // number we generate in one go to avoid blocking the application - // for too long. - const maxKeysPerCycle = 5; - if (this.oneTimeKeyCheckInProgress) { - return; - } - const now = Date.now(); - if (this.lastOneTimeKeyCheck !== null && now - this.lastOneTimeKeyCheck < uploadPeriod) { - // we've done a key upload recently. - return; - } - this.lastOneTimeKeyCheck = now; - // We need to keep a pool of one time public keys on the server so that - // other devices can start conversations with us. But we can only store - // a finite number of private keys in the olm Account object. - // To complicate things further then can be a delay between a device - // claiming a public one time key from the server and it sending us a - // message. We need to keep the corresponding private key locally until - // we receive the message. - // But that message might never arrive leaving us stuck with duff - // private keys clogging up our local storage. - // So we need some kind of engineering compromise to balance all of - // these factors. - // Check how many keys we can store in the Account object. - const maxOneTimeKeys = this.olmDevice.maxNumberOfOneTimeKeys(); - // Try to keep at most half that number on the server. This leaves the - // rest of the slots free to hold keys that have been claimed from the - // server but we haven't received a message for. - // If we run out of slots when generating new keys then olm will - // discard the oldest private keys first. This will eventually clean - // out stale private keys that won't receive a message. - const keyLimit = Math.floor(maxOneTimeKeys / 2); - const uploadLoop = (keyCount) => __awaiter(this, void 0, void 0, function* () { - while (keyLimit > keyCount || this.getNeedsNewFallback()) { - // Ask olm to generate new one time keys, then upload them to synapse. - if (keyLimit > keyCount) { - logger_1.logger.info("generating oneTimeKeys"); - const keysThisLoop = Math.min(keyLimit - keyCount, maxKeysPerCycle); - yield this.olmDevice.generateOneTimeKeys(keysThisLoop); - } - if (this.getNeedsNewFallback()) { - const fallbackKeys = yield this.olmDevice.getFallbackKey(); - // if fallbackKeys is non-empty, we've already generated a - // fallback key, but it hasn't been published yet, so we - // can use that instead of generating a new one - if (!fallbackKeys.curve25519 || Object.keys(fallbackKeys.curve25519).length == 0) { - logger_1.logger.info("generating fallback key"); - if (this.fallbackCleanup) { - // cancel any pending fallback cleanup because generating - // a new fallback key will already drop the old fallback - // that would have been dropped, and we don't want to kill - // the current key - clearTimeout(this.fallbackCleanup); - delete this.fallbackCleanup; - } - yield this.olmDevice.generateFallbackKey(); - } - } - logger_1.logger.info("calling uploadOneTimeKeys"); - const res = yield this.uploadOneTimeKeys(); - if (res.one_time_key_counts && res.one_time_key_counts.signed_curve25519) { - // if the response contains a more up to date value use this - // for the next loop - keyCount = res.one_time_key_counts.signed_curve25519; - } - else { - throw new Error("response for uploading keys does not contain " + "one_time_key_counts.signed_curve25519"); - } - } - }); - this.oneTimeKeyCheckInProgress = true; - Promise.resolve() - .then(() => { - if (this.oneTimeKeyCount !== undefined) { - // We already have the current one_time_key count from a /sync response. - // Use this value instead of asking the server for the current key count. - return Promise.resolve(this.oneTimeKeyCount); - } - // ask the server how many keys we have - return this.baseApis.uploadKeysRequest({}).then((res) => { - return res.one_time_key_counts.signed_curve25519 || 0; - }); - }) - .then((keyCount) => { - // Start the uploadLoop with the current keyCount. The function checks if - // we need to upload new keys or not. - // If there are too many keys on the server then we don't need to - // create any more keys. - return uploadLoop(keyCount); - }) - .catch((e) => { - logger_1.logger.error("Error uploading one-time keys", e.stack || e); - }) - .finally(() => { - // reset oneTimeKeyCount to prevent start uploading based on old data. - // it will be set again on the next /sync-response - this.oneTimeKeyCount = undefined; - this.oneTimeKeyCheckInProgress = false; - }); - } - // returns a promise which resolves to the response - uploadOneTimeKeys() { - return __awaiter(this, void 0, void 0, function* () { - const promises = []; - let fallbackJson; - if (this.getNeedsNewFallback()) { - fallbackJson = {}; - const fallbackKeys = yield this.olmDevice.getFallbackKey(); - for (const [keyId, key] of Object.entries(fallbackKeys.curve25519)) { - const k = { key, fallback: true }; - fallbackJson["signed_curve25519:" + keyId] = k; - promises.push(this.signObject(k)); - } - this.setNeedsNewFallback(false); - } - const oneTimeKeys = yield this.olmDevice.getOneTimeKeys(); - const oneTimeJson = {}; - for (const keyId in oneTimeKeys.curve25519) { - if (oneTimeKeys.curve25519.hasOwnProperty(keyId)) { - const k = { - key: oneTimeKeys.curve25519[keyId], - }; - oneTimeJson["signed_curve25519:" + keyId] = k; - promises.push(this.signObject(k)); - } - } - yield Promise.all(promises); - const requestBody = { - one_time_keys: oneTimeJson, - }; - if (fallbackJson) { - requestBody["org.matrix.msc2732.fallback_keys"] = fallbackJson; - requestBody["fallback_keys"] = fallbackJson; - } - const res = yield this.baseApis.uploadKeysRequest(requestBody); - if (fallbackJson) { - this.fallbackCleanup = setTimeout(() => { - delete this.fallbackCleanup; - this.olmDevice.forgetOldFallbackKey(); - }, 60 * 60 * 1000); - } - yield this.olmDevice.markKeysAsPublished(); - return res; - }); - } - /** - * Download the keys for a list of users and stores the keys in the session - * store. - * @param userIds - The users to fetch. - * @param forceDownload - Always download the keys even if cached. - * - * @returns A promise which resolves to a map `userId->deviceId->{@link DeviceInfo}`. - */ - downloadKeys(userIds, forceDownload) { - return this.deviceList.downloadKeys(userIds, !!forceDownload); - } - /** - * Get the stored device keys for a user id - * - * @param userId - the user to list keys for. - * - * @returns list of devices, or null if we haven't - * managed to get a list of devices for this user yet. - */ - getStoredDevicesForUser(userId) { - return this.deviceList.getStoredDevicesForUser(userId); - } - /** - * Get the stored keys for a single device - * - * - * @returns device, or undefined - * if we don't know about this device - */ - getStoredDevice(userId, deviceId) { - return this.deviceList.getStoredDevice(userId, deviceId); - } - /** - * Save the device list, if necessary - * - * @param delay - Time in ms before which the save actually happens. - * By default, the save is delayed for a short period in order to batch - * multiple writes, but this behaviour can be disabled by passing 0. - * - * @returns true if the data was saved, false if - * it was not (eg. because no changes were pending). The promise - * will only resolve once the data is saved, so may take some time - * to resolve. - */ - saveDeviceList(delay) { - return this.deviceList.saveIfDirty(delay); - } - /** - * Update the blocked/verified state of the given device - * - * @param userId - owner of the device - * @param deviceId - unique identifier for the device or user's - * cross-signing public key ID. - * - * @param verified - whether to mark the device as verified. Null to - * leave unchanged. - * - * @param blocked - whether to mark the device as blocked. Null to - * leave unchanged. - * - * @param known - whether to mark that the user has been made aware of - * the existence of this device. Null to leave unchanged - * - * @param keys - The list of keys that was present - * during the device verification. This will be double checked with the list - * of keys the given device has currently. - * - * @returns updated DeviceInfo - */ - setDeviceVerification(userId, deviceId, verified = null, blocked = null, known = null, keys) { - return __awaiter(this, void 0, void 0, function* () { - // Check if the 'device' is actually a cross signing key - // The js-sdk's verification treats cross-signing keys as devices - // and so uses this method to mark them verified. - const xsk = this.deviceList.getStoredCrossSigningForUser(userId); - if (xsk && xsk.getId() === deviceId) { - if (blocked !== null || known !== null) { - throw new Error("Cannot set blocked or known for a cross-signing key"); - } - if (!verified) { - throw new Error("Cannot set a cross-signing key as unverified"); - } - const gotKeyId = keys ? Object.values(keys)[0] : null; - if (keys && (Object.values(keys).length !== 1 || gotKeyId !== xsk.getId())) { - throw new Error(`Key did not match expected value: expected ${xsk.getId()}, got ${gotKeyId}`); - } - if (!this.crossSigningInfo.getId() && userId === this.crossSigningInfo.userId) { - this.storeTrustedSelfKeys(xsk.keys); - // This will cause our own user trust to change, so emit the event - this.emit(CryptoEvent.UserTrustStatusChanged, this.userId, this.checkUserTrust(userId)); - } - // Now sign the master key with our user signing key (unless it's ourself) - if (userId !== this.userId) { - logger_1.logger.info("Master key " + xsk.getId() + " for " + userId + " marked verified. Signing..."); - const device = yield this.crossSigningInfo.signUser(xsk); - if (device) { - const upload = ({ shouldEmit = false }) => __awaiter(this, void 0, void 0, function* () { - logger_1.logger.info("Uploading signature for " + userId + "..."); - const response = yield this.baseApis.uploadKeySignatures({ - [userId]: { - [deviceId]: device, - }, - }); - const { failures } = response || {}; - if (Object.keys(failures || []).length > 0) { - if (shouldEmit) { - this.baseApis.emit(CryptoEvent.KeySignatureUploadFailure, failures, "setDeviceVerification", upload); - } - /* Throwing here causes the process to be cancelled and the other - * user to be notified */ - throw new errors_1.KeySignatureUploadError("Key upload failed", { failures }); - } - }); - yield upload({ shouldEmit: true }); - // This will emit events when it comes back down the sync - // (we could do local echo to speed things up) - } - return device; // TODO types - } - else { - return xsk; - } - } - const devices = this.deviceList.getRawStoredDevicesForUser(userId); - if (!devices || !devices[deviceId]) { - throw new Error("Unknown device " + userId + ":" + deviceId); - } - const dev = devices[deviceId]; - let verificationStatus = dev.verified; - if (verified) { - if (keys) { - for (const [keyId, key] of Object.entries(keys)) { - if (dev.keys[keyId] !== key) { - throw new Error(`Key did not match expected value: expected ${key}, got ${dev.keys[keyId]}`); - } - } - } - verificationStatus = DeviceVerification.VERIFIED; - } - else if (verified !== null && verificationStatus == DeviceVerification.VERIFIED) { - verificationStatus = DeviceVerification.UNVERIFIED; - } - if (blocked) { - verificationStatus = DeviceVerification.BLOCKED; - } - else if (blocked !== null && verificationStatus == DeviceVerification.BLOCKED) { - verificationStatus = DeviceVerification.UNVERIFIED; - } - let knownStatus = dev.known; - if (known !== null) { - knownStatus = known; - } - if (dev.verified !== verificationStatus || dev.known !== knownStatus) { - dev.verified = verificationStatus; - dev.known = knownStatus; - this.deviceList.storeDevicesForUser(userId, devices); - this.deviceList.saveIfDirty(); - } - // do cross-signing - if (verified && userId === this.userId) { - logger_1.logger.info("Own device " + deviceId + " marked verified: signing"); - // Signing only needed if other device not already signed - let device; - const deviceTrust = this.checkDeviceTrust(userId, deviceId); - if (deviceTrust.isCrossSigningVerified()) { - logger_1.logger.log(`Own device ${deviceId} already cross-signing verified`); - } - else { - device = (yield this.crossSigningInfo.signDevice(userId, deviceinfo_1.DeviceInfo.fromStorage(dev, deviceId))); - } - if (device) { - const upload = ({ shouldEmit = false }) => __awaiter(this, void 0, void 0, function* () { - logger_1.logger.info("Uploading signature for " + deviceId); - const response = yield this.baseApis.uploadKeySignatures({ - [userId]: { - [deviceId]: device, - }, - }); - const { failures } = response || {}; - if (Object.keys(failures || []).length > 0) { - if (shouldEmit) { - this.baseApis.emit(CryptoEvent.KeySignatureUploadFailure, failures, "setDeviceVerification", upload); - } - throw new errors_1.KeySignatureUploadError("Key upload failed", { failures }); - } - }); - yield upload({ shouldEmit: true }); - // XXX: we'll need to wait for the device list to be updated - } - } - const deviceObj = deviceinfo_1.DeviceInfo.fromStorage(dev, deviceId); - this.emit(CryptoEvent.DeviceVerificationChanged, userId, deviceId, deviceObj); - return deviceObj; - }); - } - findVerificationRequestDMInProgress(roomId) { - return this.inRoomVerificationRequests.findRequestInProgress(roomId); - } - getVerificationRequestsToDeviceInProgress(userId) { - return this.toDeviceVerificationRequests.getRequestsInProgress(userId); - } - requestVerificationDM(userId, roomId) { - const existingRequest = this.inRoomVerificationRequests.findRequestInProgress(roomId); - if (existingRequest) { - return Promise.resolve(existingRequest); - } - const channel = new InRoomChannel_1.InRoomChannel(this.baseApis, roomId, userId); - return this.requestVerificationWithChannel(userId, channel, this.inRoomVerificationRequests); - } - requestVerification(userId, devices) { - if (!devices) { - devices = Object.keys(this.deviceList.getRawStoredDevicesForUser(userId)); - } - const existingRequest = this.toDeviceVerificationRequests.findRequestInProgress(userId, devices); - if (existingRequest) { - return Promise.resolve(existingRequest); - } - const channel = new ToDeviceChannel_1.ToDeviceChannel(this.baseApis, userId, devices, ToDeviceChannel_1.ToDeviceChannel.makeTransactionId()); - return this.requestVerificationWithChannel(userId, channel, this.toDeviceVerificationRequests); - } - requestVerificationWithChannel(userId, channel, requestsMap) { - return __awaiter(this, void 0, void 0, function* () { - let request = new VerificationRequest_1.VerificationRequest(channel, this.verificationMethods, this.baseApis); - // if transaction id is already known, add request - if (channel.transactionId) { - requestsMap.setRequestByChannel(channel, request); - } - yield request.sendRequest(); - // don't replace the request created by a racing remote echo - const racingRequest = requestsMap.getRequestByChannel(channel); - if (racingRequest) { - request = racingRequest; - } - else { - logger_1.logger.log(`Crypto: adding new request to ` + `requestsByTxnId with id ${channel.transactionId} ${channel.roomId}`); - requestsMap.setRequestByChannel(channel, request); - } - return request; - }); - } - beginKeyVerification(method, userId, deviceId, transactionId = null) { - let request; - if (transactionId) { - request = this.toDeviceVerificationRequests.getRequestBySenderAndTxnId(userId, transactionId); - if (!request) { - throw new Error(`No request found for user ${userId} with ` + `transactionId ${transactionId}`); - } - } - else { - transactionId = ToDeviceChannel_1.ToDeviceChannel.makeTransactionId(); - const channel = new ToDeviceChannel_1.ToDeviceChannel(this.baseApis, userId, [deviceId], transactionId, deviceId); - request = new VerificationRequest_1.VerificationRequest(channel, this.verificationMethods, this.baseApis); - this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(userId, transactionId, request); - } - return request.beginKeyVerification(method, { userId, deviceId }); - } - legacyDeviceVerification(userId, deviceId, method) { - return __awaiter(this, void 0, void 0, function* () { - const transactionId = ToDeviceChannel_1.ToDeviceChannel.makeTransactionId(); - const channel = new ToDeviceChannel_1.ToDeviceChannel(this.baseApis, userId, [deviceId], transactionId, deviceId); - const request = new VerificationRequest_1.VerificationRequest(channel, this.verificationMethods, this.baseApis); - this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(userId, transactionId, request); - const verifier = request.beginKeyVerification(method, { userId, deviceId }); - // either reject by an error from verify() while sending .start - // or resolve when the request receives the - // local (fake remote) echo for sending the .start event - yield Promise.race([verifier.verify(), request.waitFor((r) => r.started)]); - return request; - }); - } - /** - * Get information on the active olm sessions with a user - *

- * Returns a map from device id to an object with keys 'deviceIdKey' (the - * device's curve25519 identity key) and 'sessions' (an array of objects in the - * same format as that returned by - * {@link OlmDevice#getSessionInfoForDevice}). - *

- * This method is provided for debugging purposes. - * - * @param userId - id of user to inspect - */ - getOlmSessionsForUser(userId) { - return __awaiter(this, void 0, void 0, function* () { - const devices = this.getStoredDevicesForUser(userId) || []; - const result = {}; - for (const device of devices) { - const deviceKey = device.getIdentityKey(); - const sessions = yield this.olmDevice.getSessionInfoForDevice(deviceKey); - result[device.deviceId] = { - deviceIdKey: deviceKey, - sessions: sessions, - }; - } - return result; - }); - } - /** - * Get the device which sent an event - * - * @param event - event to be checked - */ - getEventSenderDeviceInfo(event) { - const senderKey = event.getSenderKey(); - const algorithm = event.getWireContent().algorithm; - if (!senderKey || !algorithm) { - return null; - } - if (event.isKeySourceUntrusted()) { - // we got the key for this event from a source that we consider untrusted - return null; - } - // senderKey is the Curve25519 identity key of the device which the event - // was sent from. In the case of Megolm, it's actually the Curve25519 - // identity key of the device which set up the Megolm session. - const device = this.deviceList.getDeviceByIdentityKey(algorithm, senderKey); - if (device === null) { - // we haven't downloaded the details of this device yet. - return null; - } - // so far so good, but now we need to check that the sender of this event - // hadn't advertised someone else's Curve25519 key as their own. We do that - // by checking the Ed25519 claimed by the event (or, in the case of megolm, - // the event which set up the megolm session), to check that it matches the - // fingerprint of the purported sending device. - // - // (see https://github.com/vector-im/vector-web/issues/2215) - const claimedKey = event.getClaimedEd25519Key(); - if (!claimedKey) { - logger_1.logger.warn("Event " + event.getId() + " claims no ed25519 key: " + "cannot verify sending device"); - return null; - } - if (claimedKey !== device.getFingerprint()) { - logger_1.logger.warn("Event " + - event.getId() + - " claims ed25519 key " + - claimedKey + - " but sender device has key " + - device.getFingerprint()); - return null; - } - return device; - } - /** - * Get information about the encryption of an event - * - * @param event - event to be checked - * - * @returns An object with the fields: - * - encrypted: whether the event is encrypted (if not encrypted, some of the - * other properties may not be set) - * - senderKey: the sender's key - * - algorithm: the algorithm used to encrypt the event - * - authenticated: whether we can be sure that the owner of the senderKey - * sent the event - * - sender: the sender's device information, if available - * - mismatchedSender: if the event's ed25519 and curve25519 keys don't match - * (only meaningful if `sender` is set) - */ - getEventEncryptionInfo(event) { - var _a, _b; - const ret = {}; - ret.senderKey = (_a = event.getSenderKey()) !== null && _a !== void 0 ? _a : undefined; - ret.algorithm = event.getWireContent().algorithm; - if (!ret.senderKey || !ret.algorithm) { - ret.encrypted = false; - return ret; - } - ret.encrypted = true; - if (event.isKeySourceUntrusted()) { - // we got the key this event from somewhere else - // TODO: check if we can trust the forwarders. - ret.authenticated = false; - } - else { - ret.authenticated = true; - } - // senderKey is the Curve25519 identity key of the device which the event - // was sent from. In the case of Megolm, it's actually the Curve25519 - // identity key of the device which set up the Megolm session. - ret.sender = (_b = this.deviceList.getDeviceByIdentityKey(ret.algorithm, ret.senderKey)) !== null && _b !== void 0 ? _b : undefined; - // so far so good, but now we need to check that the sender of this event - // hadn't advertised someone else's Curve25519 key as their own. We do that - // by checking the Ed25519 claimed by the event (or, in the case of megolm, - // the event which set up the megolm session), to check that it matches the - // fingerprint of the purported sending device. - // - // (see https://github.com/vector-im/vector-web/issues/2215) - const claimedKey = event.getClaimedEd25519Key(); - if (!claimedKey) { - logger_1.logger.warn("Event " + event.getId() + " claims no ed25519 key: " + "cannot verify sending device"); - ret.mismatchedSender = true; - } - if (ret.sender && claimedKey !== ret.sender.getFingerprint()) { - logger_1.logger.warn("Event " + - event.getId() + - " claims ed25519 key " + - claimedKey + - "but sender device has key " + - ret.sender.getFingerprint()); - ret.mismatchedSender = true; - } - return ret; - } - /** - * Forces the current outbound group session to be discarded such - * that another one will be created next time an event is sent. - * - * @param roomId - The ID of the room to discard the session for - * - * This should not normally be necessary. - */ - forceDiscardSession(roomId) { - const alg = this.roomEncryptors.get(roomId); - if (alg === undefined) - throw new Error("Room not encrypted"); - if (alg.forceDiscardSession === undefined) { - throw new Error("Room encryption algorithm doesn't support session discarding"); - } - alg.forceDiscardSession(); - return Promise.resolve(); - } - /** - * Configure a room to use encryption (ie, save a flag in the cryptoStore). - * - * @param roomId - The room ID to enable encryption in. - * - * @param config - The encryption config for the room. - * - * @param inhibitDeviceQuery - true to suppress device list query for - * users in the room (for now). In case lazy loading is enabled, - * the device query is always inhibited as the members are not tracked. - * - * @deprecated It is normally incorrect to call this method directly. Encryption - * is enabled by receiving an `m.room.encryption` event (which we may have sent - * previously). - */ - setRoomEncryption(roomId, config, inhibitDeviceQuery) { - return __awaiter(this, void 0, void 0, function* () { - const room = this.clientStore.getRoom(roomId); - if (!room) { - throw new Error(`Unable to enable encryption tracking devices in unknown room ${roomId}`); - } - yield this.setRoomEncryptionImpl(room, config); - if (!this.lazyLoadMembers && !inhibitDeviceQuery) { - this.deviceList.refreshOutdatedDeviceLists(); - } - }); - } - /** - * Set up encryption for a room. - * - * This is called when an m.room.encryption event is received. It saves a flag - * for the room in the cryptoStore (if it wasn't already set), sets up an "encryptor" for - * the room, and enables device-list tracking for the room. - * - * It does not initiate a device list query for the room. That is normally - * done once we finish processing the sync, in onSyncCompleted. - * - * @param room - The room to enable encryption in. - * @param config - The encryption config for the room. - */ - setRoomEncryptionImpl(room, config) { - return __awaiter(this, void 0, void 0, function* () { - const roomId = room.roomId; - // ignore crypto events with no algorithm defined - // This will happen if a crypto event is redacted before we fetch the room state - // It would otherwise just throw later as an unknown algorithm would, but we may - // as well catch this here - if (!config.algorithm) { - logger_1.logger.log("Ignoring setRoomEncryption with no algorithm"); - return; - } - // if state is being replayed from storage, we might already have a configuration - // for this room as they are persisted as well. - // We just need to make sure the algorithm is initialized in this case. - // However, if the new config is different, - // we should bail out as room encryption can't be changed once set. - const existingConfig = this.roomList.getRoomEncryption(roomId); - if (existingConfig) { - if (JSON.stringify(existingConfig) != JSON.stringify(config)) { - logger_1.logger.error("Ignoring m.room.encryption event which requests " + "a change of config in " + roomId); - return; - } - } - // if we already have encryption in this room, we should ignore this event, - // as it would reset the encryption algorithm. - // This is at least expected to be called twice, as sync calls onCryptoEvent - // for both the timeline and state sections in the /sync response, - // the encryption event would appear in both. - // If it's called more than twice though, - // it signals a bug on client or server. - const existingAlg = this.roomEncryptors.get(roomId); - if (existingAlg) { - return; - } - // _roomList.getRoomEncryption will not race with _roomList.setRoomEncryption - // because it first stores in memory. We should await the promise only - // after all the in-memory state (roomEncryptors and _roomList) has been updated - // to avoid races when calling this method multiple times. Hence keep a hold of the promise. - let storeConfigPromise = null; - if (!existingConfig) { - storeConfigPromise = this.roomList.setRoomEncryption(roomId, config); - } - const AlgClass = algorithms.ENCRYPTION_CLASSES.get(config.algorithm); - if (!AlgClass) { - throw new Error("Unable to encrypt with " + config.algorithm); - } - const alg = new AlgClass({ - userId: this.userId, - deviceId: this.deviceId, - crypto: this, - olmDevice: this.olmDevice, - baseApis: this.baseApis, - roomId, - config, - }); - this.roomEncryptors.set(roomId, alg); - if (storeConfigPromise) { - yield storeConfigPromise; - } - logger_1.logger.log(`Enabling encryption in ${roomId}`); - // we don't want to force a download of the full membership list of this room, but as soon as we have that - // list we can start tracking the device list. - if (room.membersLoaded()) { - yield this.trackRoomDevicesImpl(room); - } - else { - // wait for the membership list to be loaded - const onState = (_state) => { - room.off(room_state_1.RoomStateEvent.Update, onState); - if (room.membersLoaded()) { - this.trackRoomDevicesImpl(room).catch((e) => { - logger_1.logger.error(`Error enabling device tracking in ${roomId}`, e); - }); - } - }; - room.on(room_state_1.RoomStateEvent.Update, onState); - } - }); - } - /** - * Make sure we are tracking the device lists for all users in this room. - * - * @param roomId - The room ID to start tracking devices in. - * @returns when all devices for the room have been fetched and marked to track - * @deprecated there's normally no need to call this function: device list tracking - * will be enabled as soon as we have the full membership list. - */ - trackRoomDevices(roomId) { - const room = this.clientStore.getRoom(roomId); - if (!room) { - throw new Error(`Unable to start tracking devices in unknown room ${roomId}`); - } - return this.trackRoomDevicesImpl(room); - } - /** - * Make sure we are tracking the device lists for all users in this room. - * - * This is normally called when we are about to send an encrypted event, to make sure - * we have all the devices in the room; but it is also called when processing an - * m.room.encryption state event (if lazy-loading is disabled), or when members are - * loaded (if lazy-loading is enabled), to prepare the device list. - * - * @param room - Room to enable device-list tracking in - */ - trackRoomDevicesImpl(room) { - const roomId = room.roomId; - const trackMembers = () => __awaiter(this, void 0, void 0, function* () { - // not an encrypted room - if (!this.roomEncryptors.has(roomId)) { - return; - } - logger_1.logger.log(`Starting to track devices for room ${roomId} ...`); - const members = yield room.getEncryptionTargetMembers(); - members.forEach((m) => { - this.deviceList.startTrackingDeviceList(m.userId); - }); - }); - let promise = this.roomDeviceTrackingState[roomId]; - if (!promise) { - promise = trackMembers(); - this.roomDeviceTrackingState[roomId] = promise.catch((err) => { - delete this.roomDeviceTrackingState[roomId]; - throw err; - }); - } - return promise; - } - /** - * Try to make sure we have established olm sessions for all known devices for - * the given users. - * - * @param users - list of user ids - * @param force - If true, force a new Olm session to be created. Default false. - * - * @returns resolves once the sessions are complete, to - * an Object mapping from userId to deviceId to - * {@link OlmSessionResult} - */ - ensureOlmSessionsForUsers(users, force) { - // map user Id → DeviceInfo[] - const devicesByUser = new Map(); - for (const userId of users) { - const userDevices = []; - devicesByUser.set(userId, userDevices); - const devices = this.getStoredDevicesForUser(userId) || []; - for (const deviceInfo of devices) { - const key = deviceInfo.getIdentityKey(); - if (key == this.olmDevice.deviceCurve25519Key) { - // don't bother setting up session to ourself - continue; - } - if (deviceInfo.verified == DeviceVerification.BLOCKED) { - // don't bother setting up sessions with blocked users - continue; - } - userDevices.push(deviceInfo); - } - } - return olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, devicesByUser, force); - } - /** - * Get a list containing all of the room keys - * - * @returns a list of session export objects - */ - exportRoomKeys() { - return __awaiter(this, void 0, void 0, function* () { - const exportedSessions = []; - yield this.cryptoStore.doTxn("readonly", [indexeddb_crypto_store_1.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS], (txn) => { - this.cryptoStore.getAllEndToEndInboundGroupSessions(txn, (s) => { - if (s === null) - return; - const sess = this.olmDevice.exportInboundGroupSession(s.senderKey, s.sessionId, s.sessionData); - delete sess.first_known_index; - sess.algorithm = olmlib.MEGOLM_ALGORITHM; - exportedSessions.push(sess); - }); - }); - return exportedSessions; - }); - } - /** - * Import a list of room keys previously exported by exportRoomKeys - * - * @param keys - a list of session export objects - * @returns a promise which resolves once the keys have been imported - */ - importRoomKeys(keys, opts = {}) { - let successes = 0; - let failures = 0; - const total = keys.length; - function updateProgress() { - var _a; - (_a = opts.progressCallback) === null || _a === void 0 ? void 0 : _a.call(opts, { - stage: "load_keys", - successes, - failures, - total, - }); - } - return Promise.all(keys.map((key) => { - if (!key.room_id || !key.algorithm) { - logger_1.logger.warn("ignoring room key entry with missing fields", key); - failures++; - if (opts.progressCallback) { - updateProgress(); - } - return null; - } - const alg = this.getRoomDecryptor(key.room_id, key.algorithm); - return alg.importRoomKey(key, opts).finally(() => { - successes++; - if (opts.progressCallback) { - updateProgress(); - } - }); - })).then(); - } - /** - * Counts the number of end to end session keys that are waiting to be backed up - * @returns Promise which resolves to the number of sessions requiring backup - */ - countSessionsNeedingBackup() { - return this.backupManager.countSessionsNeedingBackup(); - } - /** - * Perform any background tasks that can be done before a message is ready to - * send, in order to speed up sending of the message. - * - * @param room - the room the event is in - */ - prepareToEncrypt(room) { - const alg = this.roomEncryptors.get(room.roomId); - if (alg) { - alg.prepareToEncrypt(room); - } - } - /** - * Encrypt an event according to the configuration of the room. - * - * @param event - event to be sent - * - * @param room - destination room. - * - * @returns Promise which resolves when the event has been - * encrypted, or null if nothing was needed - */ - encryptEvent(event, room) { - return __awaiter(this, void 0, void 0, function* () { - const roomId = event.getRoomId(); - const alg = this.roomEncryptors.get(roomId); - if (!alg) { - // MatrixClient has already checked that this room should be encrypted, - // so this is an unexpected situation. - throw new Error("Room " + - roomId + - " was previously configured to use encryption, but is " + - "no longer. Perhaps the homeserver is hiding the " + - "configuration event."); - } - // wait for all the room devices to be loaded - yield this.trackRoomDevicesImpl(room); - let content = event.getContent(); - // If event has an m.relates_to then we need - // to put this on the wrapping event instead - const mRelatesTo = content["m.relates_to"]; - if (mRelatesTo) { - // Clone content here so we don't remove `m.relates_to` from the local-echo - content = Object.assign({}, content); - delete content["m.relates_to"]; - } - // Treat element's performance metrics the same as `m.relates_to` (when present) - const elementPerfMetrics = content["io.element.performance_metrics"]; - if (elementPerfMetrics) { - content = Object.assign({}, content); - delete content["io.element.performance_metrics"]; - } - const encryptedContent = (yield alg.encryptMessage(room, event.getType(), content)); - if (mRelatesTo) { - encryptedContent["m.relates_to"] = mRelatesTo; - } - if (elementPerfMetrics) { - encryptedContent["io.element.performance_metrics"] = elementPerfMetrics; - } - event.makeEncrypted("m.room.encrypted", encryptedContent, this.olmDevice.deviceCurve25519Key, this.olmDevice.deviceEd25519Key); - }); - } - /** - * Decrypt a received event - * - * - * @returns resolves once we have - * finished decrypting. Rejects with an `algorithms.DecryptionError` if there - * is a problem decrypting the event. - */ - decryptEvent(event) { - return __awaiter(this, void 0, void 0, function* () { - if (event.isRedacted()) { - // Try to decrypt the redaction event, to support encrypted - // redaction reasons. If we can't decrypt, just fall back to using - // the original redacted_because. - const redactionEvent = new event_2.MatrixEvent(Object.assign({ room_id: event.getRoomId() }, event.getUnsigned().redacted_because)); - let redactedBecause = event.getUnsigned().redacted_because; - if (redactionEvent.isEncrypted()) { - try { - const decryptedEvent = yield this.decryptEvent(redactionEvent); - redactedBecause = decryptedEvent.clearEvent; - } - catch (e) { - logger_1.logger.warn("Decryption of redaction failed. Falling back to unencrypted event.", e); - } - } - return { - clearEvent: { - room_id: event.getRoomId(), - type: "m.room.message", - content: {}, - unsigned: { - redacted_because: redactedBecause, - }, - }, - }; - } - else { - const content = event.getWireContent(); - const alg = this.getRoomDecryptor(event.getRoomId(), content.algorithm); - return alg.decryptEvent(event); - } - }); - } - /** - * Handle the notification from /sync or /keys/changes that device lists have - * been changed. - * - * @param syncData - Object containing sync tokens associated with this sync - * @param syncDeviceLists - device_lists field from /sync, or response from - * /keys/changes - */ - handleDeviceListChanges(syncData, syncDeviceLists) { - return __awaiter(this, void 0, void 0, function* () { - // Initial syncs don't have device change lists. We'll either get the complete list - // of changes for the interval or will have invalidated everything in willProcessSync - if (!syncData.oldSyncToken) - return; - // Here, we're relying on the fact that we only ever save the sync data after - // sucessfully saving the device list data, so we're guaranteed that the device - // list store is at least as fresh as the sync token from the sync store, ie. - // any device changes received in sync tokens prior to the 'next' token here - // have been processed and are reflected in the current device list. - // If we didn't make this assumption, we'd have to use the /keys/changes API - // to get key changes between the sync token in the device list and the 'old' - // sync token used here to make sure we didn't miss any. - yield this.evalDeviceListChanges(syncDeviceLists); - }); - } - /** - * Send a request for some room keys, if we have not already done so - * - * @param resend - whether to resend the key request if there is - * already one - * - * @returns a promise that resolves when the key request is queued - */ - requestRoomKey(requestBody, recipients, resend = false) { - return this.outgoingRoomKeyRequestManager - .queueRoomKeyRequest(requestBody, recipients, resend) - .then(() => { - if (this.sendKeyRequestsImmediately) { - this.outgoingRoomKeyRequestManager.sendQueuedRequests(); - } - }) - .catch((e) => { - // this normally means we couldn't talk to the store - logger_1.logger.error("Error requesting key for event", e); - }); - } - /** - * Cancel any earlier room key request - * - * @param requestBody - parameters to match for cancellation - */ - cancelRoomKeyRequest(requestBody) { - this.outgoingRoomKeyRequestManager.cancelRoomKeyRequest(requestBody).catch((e) => { - logger_1.logger.warn("Error clearing pending room key requests", e); - }); - } - /** - * Re-send any outgoing key requests, eg after verification - * @returns - */ - cancelAndResendAllOutgoingKeyRequests() { - return __awaiter(this, void 0, void 0, function* () { - yield this.outgoingRoomKeyRequestManager.cancelAndResendAllOutgoingRequests(); - }); - } - /** - * handle an m.room.encryption event - * - * @param room - in which the event was received - * @param event - encryption event to be processed - */ - onCryptoEvent(room, event) { - return __awaiter(this, void 0, void 0, function* () { - const content = event.getContent(); - yield this.setRoomEncryptionImpl(room, content); - }); - } - /** - * Called before the result of a sync is processed - * - * @param syncData - the data from the 'MatrixClient.sync' event - */ - onSyncWillProcess(syncData) { - return __awaiter(this, void 0, void 0, function* () { - if (!syncData.oldSyncToken) { - // If there is no old sync token, we start all our tracking from - // scratch, so mark everything as untracked. onCryptoEvent will - // be called for all e2e rooms during the processing of the sync, - // at which point we'll start tracking all the users of that room. - logger_1.logger.log("Initial sync performed - resetting device tracking state"); - this.deviceList.stopTrackingAllDeviceLists(); - // we always track our own device list (for key backups etc) - this.deviceList.startTrackingDeviceList(this.userId); - this.roomDeviceTrackingState = {}; - } - this.sendKeyRequestsImmediately = false; - }); - } - /** - * handle the completion of a /sync - * - * This is called after the processing of each successful /sync response. - * It is an opportunity to do a batch process on the information received. - * - * @param syncData - the data from the 'MatrixClient.sync' event - */ - onSyncCompleted(syncData) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - this.deviceList.setSyncToken((_a = syncData.nextSyncToken) !== null && _a !== void 0 ? _a : null); - this.deviceList.saveIfDirty(); - // we always track our own device list (for key backups etc) - this.deviceList.startTrackingDeviceList(this.userId); - this.deviceList.refreshOutdatedDeviceLists(); - // we don't start uploading one-time keys until we've caught up with - // to-device messages, to help us avoid throwing away one-time-keys that we - // are about to receive messages for - // (https://github.com/vector-im/element-web/issues/2782). - if (!syncData.catchingUp) { - this.maybeUploadOneTimeKeys(); - this.processReceivedRoomKeyRequests(); - // likewise don't start requesting keys until we've caught up - // on to_device messages, otherwise we'll request keys that we're - // just about to get. - this.outgoingRoomKeyRequestManager.sendQueuedRequests(); - // Sync has finished so send key requests straight away. - this.sendKeyRequestsImmediately = true; - } - }); - } - /** - * Trigger the appropriate invalidations and removes for a given - * device list - * - * @param deviceLists - device_lists field from /sync, or response from - * /keys/changes - */ - evalDeviceListChanges(deviceLists) { - return __awaiter(this, void 0, void 0, function* () { - if (Array.isArray(deviceLists === null || deviceLists === void 0 ? void 0 : deviceLists.changed)) { - deviceLists.changed.forEach((u) => { - this.deviceList.invalidateUserDeviceList(u); - }); - } - if (Array.isArray(deviceLists === null || deviceLists === void 0 ? void 0 : deviceLists.left) && deviceLists.left.length) { - // Check we really don't share any rooms with these users - // any more: the server isn't required to give us the - // exact correct set. - const e2eUserIds = new Set(yield this.getTrackedE2eUsers()); - deviceLists.left.forEach((u) => { - if (!e2eUserIds.has(u)) { - this.deviceList.stopTrackingDeviceList(u); - } - }); - } - }); - } - /** - * Get a list of all the IDs of users we share an e2e room with - * for which we are tracking devices already - * - * @returns List of user IDs - */ - getTrackedE2eUsers() { - return __awaiter(this, void 0, void 0, function* () { - const e2eUserIds = []; - for (const room of this.getTrackedE2eRooms()) { - const members = yield room.getEncryptionTargetMembers(); - for (const member of members) { - e2eUserIds.push(member.userId); - } - } - return e2eUserIds; - }); - } - /** - * Get a list of the e2e-enabled rooms we are members of, - * and for which we are already tracking the devices - * - * @returns - */ - getTrackedE2eRooms() { - return this.clientStore.getRooms().filter((room) => { - // check for rooms with encryption enabled - const alg = this.roomEncryptors.get(room.roomId); - if (!alg) { - return false; - } - if (!this.roomDeviceTrackingState[room.roomId]) { - return false; - } - // ignore any rooms which we have left - const myMembership = room.getMyMembership(); - return myMembership === "join" || myMembership === "invite"; - }); - } - /** - * Encrypts and sends a given object via Olm to-device messages to a given - * set of devices. - * @param userDeviceInfoArr - the devices to send to - * @param payload - fields to include in the encrypted payload - * @returns Promise which - * resolves once the message has been encrypted and sent to the given - * userDeviceMap, and returns the `{ contentMap, deviceInfoByDeviceId }` - * of the successfully sent messages. - */ - encryptAndSendToDevices(userDeviceInfoArr, payload) { - return __awaiter(this, void 0, void 0, function* () { - const toDeviceBatch = { - eventType: event_1.EventType.RoomMessageEncrypted, - batch: [], - }; - try { - yield Promise.all(userDeviceInfoArr.map(({ userId, deviceInfo }) => __awaiter(this, void 0, void 0, function* () { - const deviceId = deviceInfo.deviceId; - const encryptedContent = { - algorithm: olmlib.OLM_ALGORITHM, - sender_key: this.olmDevice.deviceCurve25519Key, - ciphertext: {}, - [event_1.ToDeviceMessageId]: (0, uuid_1.v4)(), - }; - toDeviceBatch.batch.push({ - userId, - deviceId, - payload: encryptedContent, - }); - yield olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, new Map([[userId, [deviceInfo]]])); - yield olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this.userId, this.deviceId, this.olmDevice, userId, deviceInfo, payload); - }))); - // prune out any devices that encryptMessageForDevice could not encrypt for, - // in which case it will have just not added anything to the ciphertext object. - // There's no point sending messages to devices if we couldn't encrypt to them, - // since that's effectively a blank message. - toDeviceBatch.batch = toDeviceBatch.batch.filter((msg) => { - if (Object.keys(msg.payload.ciphertext).length > 0) { - return true; - } - else { - logger_1.logger.log(`No ciphertext for device ${msg.userId}:${msg.deviceId}: pruning`); - return false; - } - }); - try { - yield this.baseApis.queueToDevice(toDeviceBatch); - } - catch (e) { - logger_1.logger.error("sendToDevice failed", e); - throw e; - } - } - catch (e) { - logger_1.logger.error("encryptAndSendToDevices promises failed", e); - throw e; - } - }); - } - preprocessToDeviceMessages(events) { - return __awaiter(this, void 0, void 0, function* () { - // all we do here is filter out encrypted to-device messages with the wrong algorithm. Decryption - // happens later in decryptEvent, via the EventMapper - return events.filter((toDevice) => { - var _a; - if (toDevice.type === event_1.EventType.RoomMessageEncrypted && - !["m.olm.v1.curve25519-aes-sha2"].includes((_a = toDevice.content) === null || _a === void 0 ? void 0 : _a.algorithm)) { - logger_1.logger.log("Ignoring invalid encrypted to-device event from " + toDevice.sender); - return false; - } - return true; - }); - }); - } - preprocessOneTimeKeyCounts(oneTimeKeysCounts) { - const currentCount = oneTimeKeysCounts.get("signed_curve25519") || 0; - this.updateOneTimeKeyCount(currentCount); - return Promise.resolve(); - } - preprocessUnusedFallbackKeys(unusedFallbackKeys) { - this.setNeedsNewFallback(!unusedFallbackKeys.has("signed_curve25519")); - return Promise.resolve(); - } - /** - * Handle a key event - * - * @internal - * @param event - key event - */ - onRoomKeyEvent(event) { - const content = event.getContent(); - if (!content.room_id || !content.algorithm) { - logger_1.logger.error("key event is missing fields"); - return; - } - if (!this.backupManager.checkedForBackup) { - // don't bother awaiting on this - the important thing is that we retry if we - // haven't managed to check before - this.backupManager.checkAndStart(); - } - const alg = this.getRoomDecryptor(content.room_id, content.algorithm); - alg.onRoomKeyEvent(event); - } - /** - * Handle a key withheld event - * - * @internal - * @param event - key withheld event - */ - onRoomKeyWithheldEvent(event) { - const content = event.getContent(); - if ((content.code !== "m.no_olm" && (!content.room_id || !content.session_id)) || - !content.algorithm || - !content.sender_key) { - logger_1.logger.error("key withheld event is missing fields"); - return; - } - logger_1.logger.info(`Got room key withheld event from ${event.getSender()} ` + - `for ${content.algorithm} session ${content.sender_key}|${content.session_id} ` + - `in room ${content.room_id} with code ${content.code} (${content.reason})`); - const alg = this.getRoomDecryptor(content.room_id, content.algorithm); - if (alg.onRoomKeyWithheldEvent) { - alg.onRoomKeyWithheldEvent(event); - } - if (!content.room_id) { - // retry decryption for all events sent by the sender_key. This will - // update the events to show a message indicating that the olm session was - // wedged. - const roomDecryptors = this.getRoomDecryptors(content.algorithm); - for (const decryptor of roomDecryptors) { - decryptor.retryDecryptionFromSender(content.sender_key); - } - } - } - /** - * Handle a general key verification event. - * - * @internal - * @param event - verification start event - */ - onKeyVerificationMessage(event) { - if (!ToDeviceChannel_1.ToDeviceChannel.validateEvent(event, this.baseApis)) { - return; - } - const createRequest = (event) => { - if (!ToDeviceChannel_1.ToDeviceChannel.canCreateRequest(ToDeviceChannel_1.ToDeviceChannel.getEventType(event))) { - return; - } - const content = event.getContent(); - const deviceId = content && content.from_device; - if (!deviceId) { - return; - } - const userId = event.getSender(); - const channel = new ToDeviceChannel_1.ToDeviceChannel(this.baseApis, userId, [deviceId]); - return new VerificationRequest_1.VerificationRequest(channel, this.verificationMethods, this.baseApis); - }; - this.handleVerificationEvent(event, this.toDeviceVerificationRequests, createRequest); - } - handleVerificationEvent(event, requestsMap, createRequest, isLiveEvent = true) { - return __awaiter(this, void 0, void 0, function* () { - // Wait for event to get its final ID with pendingEventOrdering: "chronological", since DM channels depend on it. - if (event.isSending() && event.status != event_2.EventStatus.SENT) { - let eventIdListener; - let statusListener; - try { - yield new Promise((resolve, reject) => { - eventIdListener = resolve; - statusListener = () => { - if (event.status == event_2.EventStatus.CANCELLED) { - reject(new Error("Event status set to CANCELLED.")); - } - }; - event.once(event_2.MatrixEventEvent.LocalEventIdReplaced, eventIdListener); - event.on(event_2.MatrixEventEvent.Status, statusListener); - }); - } - catch (err) { - logger_1.logger.error("error while waiting for the verification event to be sent: ", err); - return; - } - finally { - event.removeListener(event_2.MatrixEventEvent.LocalEventIdReplaced, eventIdListener); - event.removeListener(event_2.MatrixEventEvent.Status, statusListener); - } - } - let request = requestsMap.getRequest(event); - let isNewRequest = false; - if (!request) { - request = createRequest(event); - // a request could not be made from this event, so ignore event - if (!request) { - logger_1.logger.log(`Crypto: could not find VerificationRequest for ` + - `${event.getType()}, and could not create one, so ignoring.`); - return; - } - isNewRequest = true; - requestsMap.setRequest(event, request); - } - event.setVerificationRequest(request); - try { - yield request.channel.handleEvent(event, request, isLiveEvent); - } - catch (err) { - logger_1.logger.error("error while handling verification event", err); - } - const shouldEmit = isNewRequest && - !request.initiatedByMe && - !request.invalid && // check it has enough events to pass the UNSENT stage - !request.observeOnly; - if (shouldEmit) { - this.baseApis.emit(CryptoEvent.VerificationRequest, request); - } - }); - } - /** - * Handle a toDevice event that couldn't be decrypted - * - * @internal - * @param event - undecryptable event - */ - onToDeviceBadEncrypted(event) { - return __awaiter(this, void 0, void 0, function* () { - const content = event.getWireContent(); - const sender = event.getSender(); - const algorithm = content.algorithm; - const deviceKey = content.sender_key; - this.baseApis.emit(client_1.ClientEvent.UndecryptableToDeviceEvent, event); - // retry decryption for all events sent by the sender_key. This will - // update the events to show a message indicating that the olm session was - // wedged. - const retryDecryption = () => { - const roomDecryptors = this.getRoomDecryptors(olmlib.MEGOLM_ALGORITHM); - for (const decryptor of roomDecryptors) { - decryptor.retryDecryptionFromSender(deviceKey); - } - }; - if (sender === undefined || deviceKey === undefined || deviceKey === undefined) { - return; - } - // check when we last forced a new session with this device: if we've already done so - // recently, don't do it again. - const lastNewSessionDevices = this.lastNewSessionForced.getOrCreate(sender); - const lastNewSessionForced = lastNewSessionDevices.getOrCreate(deviceKey); - if (lastNewSessionForced + MIN_FORCE_SESSION_INTERVAL_MS > Date.now()) { - logger_1.logger.debug("New session already forced with device " + - sender + - ":" + - deviceKey + - " at " + - lastNewSessionForced + - ": not forcing another"); - yield this.olmDevice.recordSessionProblem(deviceKey, "wedged", true); - retryDecryption(); - return; - } - // establish a new olm session with this device since we're failing to decrypt messages - // on a current session. - // Note that an undecryptable message from another device could easily be spoofed - - // is there anything we can do to mitigate this? - let device = this.deviceList.getDeviceByIdentityKey(algorithm, deviceKey); - if (!device) { - // if we don't know about the device, fetch the user's devices again - // and retry before giving up - yield this.downloadKeys([sender], false); - device = this.deviceList.getDeviceByIdentityKey(algorithm, deviceKey); - if (!device) { - logger_1.logger.info("Couldn't find device for identity key " + deviceKey + ": not re-establishing session"); - yield this.olmDevice.recordSessionProblem(deviceKey, "wedged", false); - retryDecryption(); - return; - } - } - const devicesByUser = new Map([[sender, [device]]]); - yield olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, devicesByUser, true); - lastNewSessionDevices.set(deviceKey, Date.now()); - // Now send a blank message on that session so the other side knows about it. - // (The keyshare request is sent in the clear so that won't do) - // We send this first such that, as long as the toDevice messages arrive in the - // same order we sent them, the other end will get this first, set up the new session, - // then get the keyshare request and send the key over this new session (because it - // is the session it has most recently received a message on). - const encryptedContent = { - algorithm: olmlib.OLM_ALGORITHM, - sender_key: this.olmDevice.deviceCurve25519Key, - ciphertext: {}, - [event_1.ToDeviceMessageId]: (0, uuid_1.v4)(), - }; - yield olmlib.encryptMessageForDevice(encryptedContent.ciphertext, this.userId, this.deviceId, this.olmDevice, sender, device, { type: "m.dummy" }); - yield this.olmDevice.recordSessionProblem(deviceKey, "wedged", true); - retryDecryption(); - yield this.baseApis.sendToDevice("m.room.encrypted", new Map([[sender, new Map([[device.deviceId, encryptedContent]])]])); - // Most of the time this probably won't be necessary since we'll have queued up a key request when - // we failed to decrypt the message and will be waiting a bit for the key to arrive before sending - // it. This won't always be the case though so we need to re-send any that have already been sent - // to avoid races. - const requestsToResend = yield this.outgoingRoomKeyRequestManager.getOutgoingSentRoomKeyRequest(sender, device.deviceId); - for (const keyReq of requestsToResend) { - this.requestRoomKey(keyReq.requestBody, keyReq.recipients, true); - } - }); - } - /** - * Handle a change in the membership state of a member of a room - * - * @internal - * @param event - event causing the change - * @param member - user whose membership changed - * @param oldMembership - previous membership - */ - onRoomMembership(event, member, oldMembership) { - // this event handler is registered on the *client* (as opposed to the room - // member itself), which means it is only called on changes to the *live* - // membership state (ie, it is not called when we back-paginate, nor when - // we load the state in the initialsync). - // - // Further, it is automatically registered and called when new members - // arrive in the room. - var _a; - const roomId = member.roomId; - const alg = this.roomEncryptors.get(roomId); - if (!alg) { - // not encrypting in this room - return; - } - // only mark users in this room as tracked if we already started tracking in this room - // this way we don't start device queries after sync on behalf of this room which we won't use - // the result of anyway, as we'll need to do a query again once all the members are fetched - // by calling _trackRoomDevices - if (roomId in this.roomDeviceTrackingState) { - if (member.membership == "join") { - logger_1.logger.log("Join event for " + member.userId + " in " + roomId); - // make sure we are tracking the deviceList for this user - this.deviceList.startTrackingDeviceList(member.userId); - } - else if (member.membership == "invite" && - ((_a = this.clientStore.getRoom(roomId)) === null || _a === void 0 ? void 0 : _a.shouldEncryptForInvitedMembers())) { - logger_1.logger.log("Invite event for " + member.userId + " in " + roomId); - this.deviceList.startTrackingDeviceList(member.userId); - } - } - alg.onRoomMembership(event, member, oldMembership); - } - /** - * Called when we get an m.room_key_request event. - * - * @internal - * @param event - key request event - */ - onRoomKeyRequestEvent(event) { - const content = event.getContent(); - if (content.action === "request") { - // Queue it up for now, because they tend to arrive before the room state - // events at initial sync, and we want to see if we know anything about the - // room before passing them on to the app. - const req = new IncomingRoomKeyRequest(event); - this.receivedRoomKeyRequests.push(req); - } - else if (content.action === "request_cancellation") { - const req = new IncomingRoomKeyRequestCancellation(event); - this.receivedRoomKeyRequestCancellations.push(req); - } - } - /** - * Process any m.room_key_request events which were queued up during the - * current sync. - * - * @internal - */ - processReceivedRoomKeyRequests() { - return __awaiter(this, void 0, void 0, function* () { - if (this.processingRoomKeyRequests) { - // we're still processing last time's requests; keep queuing new ones - // up for now. - return; - } - this.processingRoomKeyRequests = true; - try { - // we need to grab and clear the queues in the synchronous bit of this method, - // so that we don't end up racing with the next /sync. - const requests = this.receivedRoomKeyRequests; - this.receivedRoomKeyRequests = []; - const cancellations = this.receivedRoomKeyRequestCancellations; - this.receivedRoomKeyRequestCancellations = []; - // Process all of the requests, *then* all of the cancellations. - // - // This makes sure that if we get a request and its cancellation in the - // same /sync result, then we process the request before the - // cancellation (and end up with a cancelled request), rather than the - // cancellation before the request (and end up with an outstanding - // request which should have been cancelled.) - yield Promise.all(requests.map((req) => this.processReceivedRoomKeyRequest(req))); - yield Promise.all(cancellations.map((cancellation) => this.processReceivedRoomKeyRequestCancellation(cancellation))); - } - catch (e) { - logger_1.logger.error(`Error processing room key requsts: ${e}`); - } - finally { - this.processingRoomKeyRequests = false; - } - }); - } - /** - * Helper for processReceivedRoomKeyRequests - * - */ - processReceivedRoomKeyRequest(req) { - return __awaiter(this, void 0, void 0, function* () { - const userId = req.userId; - const deviceId = req.deviceId; - const body = req.requestBody; - const roomId = body.room_id; - const alg = body.algorithm; - logger_1.logger.log(`m.room_key_request from ${userId}:${deviceId}` + - ` for ${roomId} / ${body.session_id} (id ${req.requestId})`); - if (userId !== this.userId) { - if (!this.roomEncryptors.get(roomId)) { - logger_1.logger.debug(`room key request for unencrypted room ${roomId}`); - return; - } - const encryptor = this.roomEncryptors.get(roomId); - const device = this.deviceList.getStoredDevice(userId, deviceId); - if (!device) { - logger_1.logger.debug(`Ignoring keyshare for unknown device ${userId}:${deviceId}`); - return; - } - try { - yield encryptor.reshareKeyWithDevice(body.sender_key, body.session_id, userId, device); - } - catch (e) { - logger_1.logger.warn("Failed to re-share keys for session " + - body.session_id + - " with device " + - userId + - ":" + - device.deviceId, e); - } - return; - } - if (deviceId === this.deviceId) { - // We'll always get these because we send room key requests to - // '*' (ie. 'all devices') which includes the sending device, - // so ignore requests from ourself because apart from it being - // very silly, it won't work because an Olm session cannot send - // messages to itself. - // The log here is probably superfluous since we know this will - // always happen, but let's log anyway for now just in case it - // causes issues. - logger_1.logger.log("Ignoring room key request from ourselves"); - return; - } - // todo: should we queue up requests we don't yet have keys for, - // in case they turn up later? - // if we don't have a decryptor for this room/alg, we don't have - // the keys for the requested events, and can drop the requests. - if (!this.roomDecryptors.has(roomId)) { - logger_1.logger.log(`room key request for unencrypted room ${roomId}`); - return; - } - const decryptor = this.roomDecryptors.get(roomId).get(alg); - if (!decryptor) { - logger_1.logger.log(`room key request for unknown alg ${alg} in room ${roomId}`); - return; - } - if (!(yield decryptor.hasKeysForKeyRequest(req))) { - logger_1.logger.log(`room key request for unknown session ${roomId} / ` + body.session_id); - return; - } - req.share = () => { - decryptor.shareKeysWithDevice(req); - }; - // if the device is verified already, share the keys - if (this.checkDeviceTrust(userId, deviceId).isVerified()) { - logger_1.logger.log("device is already verified: sharing keys"); - req.share(); - return; - } - this.emit(CryptoEvent.RoomKeyRequest, req); - }); - } - /** - * Helper for processReceivedRoomKeyRequests - * - */ - processReceivedRoomKeyRequestCancellation(cancellation) { - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.log(`m.room_key_request cancellation for ${cancellation.userId}:` + - `${cancellation.deviceId} (id ${cancellation.requestId})`); - // we should probably only notify the app of cancellations we told it - // about, but we don't currently have a record of that, so we just pass - // everything through. - this.emit(CryptoEvent.RoomKeyRequestCancellation, cancellation); - }); - } - /** - * Get a decryptor for a given room and algorithm. - * - * If we already have a decryptor for the given room and algorithm, return - * it. Otherwise try to instantiate it. - * - * @internal - * - * @param roomId - room id for decryptor. If undefined, a temporary - * decryptor is instantiated. - * - * @param algorithm - crypto algorithm - * - * @throws {@link DecryptionError} if the algorithm is unknown - */ - getRoomDecryptor(roomId, algorithm) { - let decryptors; - let alg; - if (roomId) { - decryptors = this.roomDecryptors.get(roomId); - if (!decryptors) { - decryptors = new Map(); - this.roomDecryptors.set(roomId, decryptors); - } - alg = decryptors.get(algorithm); - if (alg) { - return alg; - } - } - const AlgClass = algorithms.DECRYPTION_CLASSES.get(algorithm); - if (!AlgClass) { - throw new algorithms.DecryptionError("UNKNOWN_ENCRYPTION_ALGORITHM", 'Unknown encryption algorithm "' + algorithm + '".'); - } - alg = new AlgClass({ - userId: this.userId, - crypto: this, - olmDevice: this.olmDevice, - baseApis: this.baseApis, - roomId: roomId !== null && roomId !== void 0 ? roomId : undefined, - }); - if (decryptors) { - decryptors.set(algorithm, alg); - } - return alg; - } - /** - * Get all the room decryptors for a given encryption algorithm. - * - * @param algorithm - The encryption algorithm - * - * @returns An array of room decryptors - */ - getRoomDecryptors(algorithm) { - const decryptors = []; - for (const d of this.roomDecryptors.values()) { - if (d.has(algorithm)) { - decryptors.push(d.get(algorithm)); - } - } - return decryptors; - } - /** - * sign the given object with our ed25519 key - * - * @param obj - Object to which we will add a 'signatures' property - */ - signObject(obj) { - return __awaiter(this, void 0, void 0, function* () { - const sigs = new Map(Object.entries(obj.signatures || {})); - const unsigned = obj.unsigned; - delete obj.signatures; - delete obj.unsigned; - const userSignatures = sigs.get(this.userId) || {}; - sigs.set(this.userId, userSignatures); - userSignatures["ed25519:" + this.deviceId] = yield this.olmDevice.sign(another_json_1.default.stringify(obj)); - obj.signatures = (0, utils_1.recursiveMapToObject)(sigs); - if (unsigned !== undefined) - obj.unsigned = unsigned; - }); - } -} -exports.Crypto = Crypto; -/** - * Fix up the backup key, that may be in the wrong format due to a bug in a - * migration step. Some backup keys were stored as a comma-separated list of - * integers, rather than a base64-encoded byte array. If this function is - * passed a string that looks like a list of integers rather than a base64 - * string, it will attempt to convert it to the right format. - * - * @param key - the key to check - * @returns If the key is in the wrong format, then the fixed - * key will be returned. Otherwise null will be returned. - * - */ -function fixBackupKey(key) { - if (typeof key !== "string" || key.indexOf(",") < 0) { - return null; - } - const fixedKey = Uint8Array.from(key.split(","), (x) => parseInt(x)); - return olmlib.encodeBase64(fixedKey); -} -exports.fixBackupKey = fixBackupKey; -/** - * Represents a received m.room_key_request event - */ -class IncomingRoomKeyRequest { - constructor(event) { - const content = event.getContent(); - this.userId = event.getSender(); - this.deviceId = content.requesting_device_id; - this.requestId = content.request_id; - this.requestBody = content.body || {}; - this.share = () => { - throw new Error("don't know how to share keys for this request yet"); - }; - } -} -exports.IncomingRoomKeyRequest = IncomingRoomKeyRequest; -/** - * Represents a received m.room_key_request cancellation - */ -class IncomingRoomKeyRequestCancellation { - constructor(event) { - const content = event.getContent(); - this.userId = event.getSender(); - this.deviceId = content.requesting_device_id; - this.requestId = content.request_id; - } -} - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) - -},{"../@types/event":306,"../ReEmitter":317,"../client":321,"../errors":359,"../logger":374,"../models/event":383,"../models/room":392,"../models/room-member":389,"../models/room-state":390,"../models/typed-event-emitter":395,"../utils":416,"./CrossSigning":324,"./DeviceList":325,"./EncryptionSetup":326,"./OlmDevice":327,"./OutgoingRoomKeyRequestManager":328,"./SecretStorage":330,"./aes":331,"./algorithms":333,"./backup":337,"./dehydration":339,"./deviceinfo":340,"./key_passphrase":342,"./olmlib":343,"./recoverykey":344,"./store/indexeddb-crypto-store":346,"./verification/IllegalMethod":351,"./verification/QRCode":352,"./verification/SAS":353,"./verification/request/InRoomChannel":355,"./verification/request/ToDeviceChannel":356,"./verification/request/VerificationRequest":357,"another-json":1,"buffer":68,"uuid":287}],342:[function(require,module,exports){ -(function (global){(function (){ -"use strict"; -/* -Copyright 2018 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.deriveKey = exports.keyFromPassphrase = exports.keyFromAuthData = void 0; -const randomstring_1 = require("../randomstring"); -const crypto_1 = require("./crypto"); -const DEFAULT_ITERATIONS = 500000; -const DEFAULT_BITSIZE = 256; -function keyFromAuthData(authData, password) { - if (!global.Olm) { - throw new Error("Olm is not available"); - } - if (!authData.private_key_salt || !authData.private_key_iterations) { - throw new Error("Salt and/or iterations not found: " + "this backup cannot be restored with a passphrase"); - } - return deriveKey(password, authData.private_key_salt, authData.private_key_iterations, authData.private_key_bits || DEFAULT_BITSIZE); -} -exports.keyFromAuthData = keyFromAuthData; -function keyFromPassphrase(password) { - return __awaiter(this, void 0, void 0, function* () { - if (!global.Olm) { - throw new Error("Olm is not available"); - } - const salt = (0, randomstring_1.randomString)(32); - const key = yield deriveKey(password, salt, DEFAULT_ITERATIONS, DEFAULT_BITSIZE); - return { key, salt, iterations: DEFAULT_ITERATIONS }; - }); -} -exports.keyFromPassphrase = keyFromPassphrase; -function deriveKey(password, salt, iterations, numBits = DEFAULT_BITSIZE) { - return __awaiter(this, void 0, void 0, function* () { - if (!crypto_1.subtleCrypto || !crypto_1.TextEncoder) { - throw new Error("Password-based backup is not available on this platform"); - } - const key = yield crypto_1.subtleCrypto.importKey("raw", new crypto_1.TextEncoder().encode(password), { name: "PBKDF2" }, false, [ - "deriveBits", - ]); - const keybits = yield crypto_1.subtleCrypto.deriveBits({ - name: "PBKDF2", - salt: new crypto_1.TextEncoder().encode(salt), - iterations: iterations, - hash: "SHA-512", - }, key, numBits); - return new Uint8Array(keybits); - }); -} -exports.deriveKey = deriveKey; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"../randomstring":398,"./crypto":338}],343:[function(require,module,exports){ -(function (global,Buffer){(function (){ -"use strict"; -/* -Copyright 2016 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.decodeBase64 = exports.encodeUnpaddedBase64 = exports.encodeBase64 = exports.isOlmEncrypted = exports.pkVerify = exports.pkSign = exports.verifySignature = exports.ensureOlmSessionsForDevices = exports.getExistingOlmSessions = exports.encryptMessageForDevice = exports.MEGOLM_BACKUP_ALGORITHM = exports.MEGOLM_ALGORITHM = exports.OLM_ALGORITHM = void 0; -/** - * Utilities common to olm encryption algorithms - */ -const another_json_1 = __importDefault(require("another-json")); -const logger_1 = require("../logger"); -const event_1 = require("../@types/event"); -const utils_1 = require("../utils"); -var Algorithm; -(function (Algorithm) { - Algorithm["Olm"] = "m.olm.v1.curve25519-aes-sha2"; - Algorithm["Megolm"] = "m.megolm.v1.aes-sha2"; - Algorithm["MegolmBackup"] = "m.megolm_backup.v1.curve25519-aes-sha2"; -})(Algorithm || (Algorithm = {})); -/** - * matrix algorithm tag for olm - */ -exports.OLM_ALGORITHM = Algorithm.Olm; -/** - * matrix algorithm tag for megolm - */ -exports.MEGOLM_ALGORITHM = Algorithm.Megolm; -/** - * matrix algorithm tag for megolm backups - */ -exports.MEGOLM_BACKUP_ALGORITHM = Algorithm.MegolmBackup; -/** - * Encrypt an event payload for an Olm device - * - * @param resultsObject - The `ciphertext` property - * of the m.room.encrypted event to which to add our result - * - * @param olmDevice - olm.js wrapper - * @param payloadFields - fields to include in the encrypted payload - * - * Returns a promise which resolves (to undefined) when the payload - * has been encrypted into `resultsObject` - */ -function encryptMessageForDevice(resultsObject, ourUserId, ourDeviceId, olmDevice, recipientUserId, recipientDevice, payloadFields) { - return __awaiter(this, void 0, void 0, function* () { - const deviceKey = recipientDevice.getIdentityKey(); - const sessionId = yield olmDevice.getSessionIdForDevice(deviceKey); - if (sessionId === null) { - // If we don't have a session for a device then - // we can't encrypt a message for it. - logger_1.logger.log(`[olmlib.encryptMessageForDevice] Unable to find Olm session for device ` + - `${recipientUserId}:${recipientDevice.deviceId}`); - return; - } - logger_1.logger.log(`[olmlib.encryptMessageForDevice] Using Olm session ${sessionId} for device ` + - `${recipientUserId}:${recipientDevice.deviceId}`); - const payload = Object.assign({ sender: ourUserId, - // TODO this appears to no longer be used whatsoever - sender_device: ourDeviceId, - // Include the Ed25519 key so that the recipient knows what - // device this message came from. - // We don't need to include the curve25519 key since the - // recipient will already know this from the olm headers. - // When combined with the device keys retrieved from the - // homeserver signed by the ed25519 key this proves that - // the curve25519 key and the ed25519 key are owned by - // the same device. - keys: { - ed25519: olmDevice.deviceEd25519Key, - }, - // include the recipient device details in the payload, - // to avoid unknown key attacks, per - // https://github.com/vector-im/vector-web/issues/2483 - recipient: recipientUserId, recipient_keys: { - ed25519: recipientDevice.getFingerprint(), - } }, payloadFields); - // TODO: technically, a bunch of that stuff only needs to be included for - // pre-key messages: after that, both sides know exactly which devices are - // involved in the session. If we're looking to reduce data transfer in the - // future, we could elide them for subsequent messages. - resultsObject[deviceKey] = yield olmDevice.encryptMessage(deviceKey, sessionId, JSON.stringify(payload)); - }); -} -exports.encryptMessageForDevice = encryptMessageForDevice; -/** - * Get the existing olm sessions for the given devices, and the devices that - * don't have olm sessions. - * - * - * - * @param devicesByUser - map from userid to list of devices to ensure sessions for - * - * @returns resolves to an array. The first element of the array is a - * a map of user IDs to arrays of deviceInfo, representing the devices that - * don't have established olm sessions. The second element of the array is - * a map from userId to deviceId to {@link OlmSessionResult} - */ -function getExistingOlmSessions(olmDevice, baseApis, devicesByUser) { - return __awaiter(this, void 0, void 0, function* () { - // map user Id → DeviceInfo[] - const devicesWithoutSession = new utils_1.MapWithDefault(() => []); - // map user Id → device Id → IExistingOlmSession - const sessions = new utils_1.MapWithDefault(() => new Map()); - const promises = []; - for (const [userId, devices] of Object.entries(devicesByUser)) { - for (const deviceInfo of devices) { - const deviceId = deviceInfo.deviceId; - const key = deviceInfo.getIdentityKey(); - promises.push((() => __awaiter(this, void 0, void 0, function* () { - const sessionId = yield olmDevice.getSessionIdForDevice(key, true); - if (sessionId === null) { - devicesWithoutSession.getOrCreate(userId).push(deviceInfo); - } - else { - sessions.getOrCreate(userId).set(deviceId, { - device: deviceInfo, - sessionId: sessionId, - }); - } - }))()); - } - } - yield Promise.all(promises); - return [devicesWithoutSession, sessions]; - }); -} -exports.getExistingOlmSessions = getExistingOlmSessions; -/** - * Try to make sure we have established olm sessions for the given devices. - * - * @param devicesByUser - map from userid to list of devices to ensure sessions for - * - * @param force - If true, establish a new session even if one - * already exists. - * - * @param otkTimeout - The timeout in milliseconds when requesting - * one-time keys for establishing new olm sessions. - * - * @param failedServers - An array to fill with remote servers that - * failed to respond to one-time-key requests. - * - * @param log - A possibly customised log - * - * @returns resolves once the sessions are complete, to - * an Object mapping from userId to deviceId to - * {@link OlmSessionResult} - */ -function ensureOlmSessionsForDevices(olmDevice, baseApis, devicesByUser, force = false, otkTimeout, failedServers, log = logger_1.logger) { - var _a, _b, _c; - return __awaiter(this, void 0, void 0, function* () { - const devicesWithoutSession = [ - // [userId, deviceId], ... - ]; - // map user Id → device Id → IExistingOlmSession - const result = new Map(); - // map device key → resolve session fn - const resolveSession = new Map(); - // Mark all sessions this task intends to update as in progress. It is - // important to do this for all devices this task cares about in a single - // synchronous operation, as otherwise it is possible to have deadlocks - // where multiple tasks wait indefinitely on another task to update some set - // of common devices. - for (const devices of devicesByUser.values()) { - for (const deviceInfo of devices) { - const key = deviceInfo.getIdentityKey(); - if (key === olmDevice.deviceCurve25519Key) { - // We don't start sessions with ourself, so there's no need to - // mark it in progress. - continue; - } - if (!olmDevice.sessionsInProgress[key]) { - // pre-emptively mark the session as in-progress to avoid race - // conditions. If we find that we already have a session, then - // we'll resolve - olmDevice.sessionsInProgress[key] = new Promise((resolve) => { - resolveSession.set(key, (v) => { - delete olmDevice.sessionsInProgress[key]; - resolve(v); - }); - }); - } - } - } - for (const [userId, devices] of devicesByUser) { - const resultDevices = new Map(); - result.set(userId, resultDevices); - for (const deviceInfo of devices) { - const deviceId = deviceInfo.deviceId; - const key = deviceInfo.getIdentityKey(); - if (key === olmDevice.deviceCurve25519Key) { - // We should never be trying to start a session with ourself. - // Apart from talking to yourself being the first sign of madness, - // olm sessions can't do this because they get confused when - // they get a message and see that the 'other side' has started a - // new chain when this side has an active sender chain. - // If you see this message being logged in the wild, we should find - // the thing that is trying to send Olm messages to itself and fix it. - log.info("Attempted to start session with ourself! Ignoring"); - // We must fill in the section in the return value though, as callers - // expect it to be there. - resultDevices.set(deviceId, { - device: deviceInfo, - sessionId: null, - }); - continue; - } - const forWhom = `for ${key} (${userId}:${deviceId})`; - const sessionId = yield olmDevice.getSessionIdForDevice(key, !!resolveSession.get(key), log); - const resolveSessionFn = resolveSession.get(key); - if (sessionId !== null && resolveSessionFn) { - // we found a session, but we had marked the session as - // in-progress, so resolve it now, which will unmark it and - // unblock anything that was waiting - resolveSessionFn(); - } - if (sessionId === null || force) { - if (force) { - log.info(`Forcing new Olm session ${forWhom}`); - } - else { - log.info(`Making new Olm session ${forWhom}`); - } - devicesWithoutSession.push([userId, deviceId]); - } - resultDevices.set(deviceId, { - device: deviceInfo, - sessionId: sessionId, - }); - } - } - if (devicesWithoutSession.length === 0) { - return result; - } - const oneTimeKeyAlgorithm = "signed_curve25519"; - let res; - let taskDetail = `one-time keys for ${devicesWithoutSession.length} devices`; - try { - log.debug(`Claiming ${taskDetail}`); - res = yield baseApis.claimOneTimeKeys(devicesWithoutSession, oneTimeKeyAlgorithm, otkTimeout); - log.debug(`Claimed ${taskDetail}`); - } - catch (e) { - for (const resolver of resolveSession.values()) { - resolver(); - } - log.log(`Failed to claim ${taskDetail}`, e, devicesWithoutSession); - throw e; - } - if (failedServers && "failures" in res) { - failedServers.push(...Object.keys(res.failures)); - } - const otkResult = res.one_time_keys || {}; - const promises = []; - for (const [userId, devices] of devicesByUser) { - const userRes = otkResult[userId] || {}; - for (const deviceInfo of devices) { - const deviceId = deviceInfo.deviceId; - const key = deviceInfo.getIdentityKey(); - if (key === olmDevice.deviceCurve25519Key) { - // We've already logged about this above. Skip here too - // otherwise we'll log saying there are no one-time keys - // which will be confusing. - continue; - } - if (((_b = (_a = result.get(userId)) === null || _a === void 0 ? void 0 : _a.get(deviceId)) === null || _b === void 0 ? void 0 : _b.sessionId) && !force) { - // we already have a result for this device - continue; - } - const deviceRes = userRes[deviceId] || {}; - let oneTimeKey = null; - for (const keyId in deviceRes) { - if (keyId.indexOf(oneTimeKeyAlgorithm + ":") === 0) { - oneTimeKey = deviceRes[keyId]; - } - } - if (!oneTimeKey) { - log.warn(`No one-time keys (alg=${oneTimeKeyAlgorithm}) ` + `for device ${userId}:${deviceId}`); - (_c = resolveSession.get(key)) === null || _c === void 0 ? void 0 : _c(); - continue; - } - promises.push(_verifyKeyAndStartSession(olmDevice, oneTimeKey, userId, deviceInfo).then((sid) => { - var _a, _b; - (_a = resolveSession.get(key)) === null || _a === void 0 ? void 0 : _a(sid !== null && sid !== void 0 ? sid : undefined); - const deviceInfo = (_b = result.get(userId)) === null || _b === void 0 ? void 0 : _b.get(deviceId); - if (deviceInfo) - deviceInfo.sessionId = sid; - }, (e) => { - var _a; - (_a = resolveSession.get(key)) === null || _a === void 0 ? void 0 : _a(); - throw e; - })); - } - } - taskDetail = `Olm sessions for ${promises.length} devices`; - log.debug(`Starting ${taskDetail}`); - yield Promise.all(promises); - log.debug(`Started ${taskDetail}`); - return result; - }); -} -exports.ensureOlmSessionsForDevices = ensureOlmSessionsForDevices; -function _verifyKeyAndStartSession(olmDevice, oneTimeKey, userId, deviceInfo) { - return __awaiter(this, void 0, void 0, function* () { - const deviceId = deviceInfo.deviceId; - try { - yield verifySignature(olmDevice, oneTimeKey, userId, deviceId, deviceInfo.getFingerprint()); - } - catch (e) { - logger_1.logger.error("Unable to verify signature on one-time key for device " + userId + ":" + deviceId + ":", e); - return null; - } - let sid; - try { - sid = yield olmDevice.createOutboundSession(deviceInfo.getIdentityKey(), oneTimeKey.key); - } - catch (e) { - // possibly a bad key - logger_1.logger.error("Error starting olm session with device " + userId + ":" + deviceId + ": " + e); - return null; - } - logger_1.logger.log("Started new olm sessionid " + sid + " for device " + userId + ":" + deviceId); - return sid; - }); -} -/** - * Verify the signature on an object - * - * @param olmDevice - olm wrapper to use for verify op - * - * @param obj - object to check signature on. - * - * @param signingUserId - ID of the user whose signature should be checked - * - * @param signingDeviceId - ID of the device whose signature should be checked - * - * @param signingKey - base64-ed ed25519 public key - * - * Returns a promise which resolves (to undefined) if the the signature is good, - * or rejects with an Error if it is bad. - */ -function verifySignature(olmDevice, obj, signingUserId, signingDeviceId, signingKey) { - return __awaiter(this, void 0, void 0, function* () { - const signKeyId = "ed25519:" + signingDeviceId; - const signatures = obj.signatures || {}; - const userSigs = signatures[signingUserId] || {}; - const signature = userSigs[signKeyId]; - if (!signature) { - throw Error("No signature"); - } - // prepare the canonical json: remove unsigned and signatures, and stringify with anotherjson - const mangledObj = Object.assign({}, obj); - if ("unsigned" in mangledObj) { - delete mangledObj.unsigned; - } - delete mangledObj.signatures; - const json = another_json_1.default.stringify(mangledObj); - olmDevice.verifySignature(signingKey, json, signature); - }); -} -exports.verifySignature = verifySignature; -/** - * Sign a JSON object using public key cryptography - * @param obj - Object to sign. The object will be modified to include - * the new signature - * @param key - the signing object or the private key - * seed - * @param userId - The user ID who owns the signing key - * @param pubKey - The public key (ignored if key is a seed) - * @returns the signature for the object - */ -function pkSign(obj, key, userId, pubKey) { - let createdKey = false; - if (key instanceof Uint8Array) { - const keyObj = new global.Olm.PkSigning(); - pubKey = keyObj.init_with_seed(key); - key = keyObj; - createdKey = true; - } - const sigs = obj.signatures || {}; - delete obj.signatures; - const unsigned = obj.unsigned; - if (obj.unsigned) - delete obj.unsigned; - try { - const mysigs = sigs[userId] || {}; - sigs[userId] = mysigs; - return (mysigs["ed25519:" + pubKey] = key.sign(another_json_1.default.stringify(obj))); - } - finally { - obj.signatures = sigs; - if (unsigned) - obj.unsigned = unsigned; - if (createdKey) { - key.free(); - } - } -} -exports.pkSign = pkSign; -/** - * Verify a signed JSON object - * @param obj - Object to verify - * @param pubKey - The public key to use to verify - * @param userId - The user ID who signed the object - */ -function pkVerify(obj, pubKey, userId) { - const keyId = "ed25519:" + pubKey; - if (!(obj.signatures && obj.signatures[userId] && obj.signatures[userId][keyId])) { - throw new Error("No signature"); - } - const signature = obj.signatures[userId][keyId]; - const util = new global.Olm.Utility(); - const sigs = obj.signatures; - delete obj.signatures; - const unsigned = obj.unsigned; - if (obj.unsigned) - delete obj.unsigned; - try { - util.ed25519_verify(pubKey, another_json_1.default.stringify(obj), signature); - } - finally { - obj.signatures = sigs; - if (unsigned) - obj.unsigned = unsigned; - util.free(); - } -} -exports.pkVerify = pkVerify; -/** - * Check that an event was encrypted using olm. - */ -function isOlmEncrypted(event) { - if (!event.getSenderKey()) { - logger_1.logger.error("Event has no sender key (not encrypted?)"); - return false; - } - if (event.getWireType() !== event_1.EventType.RoomMessageEncrypted || - !["m.olm.v1.curve25519-aes-sha2"].includes(event.getWireContent().algorithm)) { - logger_1.logger.error("Event was not encrypted using an appropriate algorithm"); - return false; - } - return true; -} -exports.isOlmEncrypted = isOlmEncrypted; -/** - * Encode a typed array of uint8 as base64. - * @param uint8Array - The data to encode. - * @returns The base64. - */ -function encodeBase64(uint8Array) { - return Buffer.from(uint8Array).toString("base64"); -} -exports.encodeBase64 = encodeBase64; -/** - * Encode a typed array of uint8 as unpadded base64. - * @param uint8Array - The data to encode. - * @returns The unpadded base64. - */ -function encodeUnpaddedBase64(uint8Array) { - return encodeBase64(uint8Array).replace(/=+$/g, ""); -} -exports.encodeUnpaddedBase64 = encodeUnpaddedBase64; -/** - * Decode a base64 string to a typed array of uint8. - * @param base64 - The base64 to decode. - * @returns The decoded data. - */ -function decodeBase64(base64) { - return Buffer.from(base64, "base64"); -} -exports.decodeBase64 = decodeBase64; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) - -},{"../@types/event":306,"../logger":374,"../utils":416,"another-json":1,"buffer":68}],344:[function(require,module,exports){ -(function (global,Buffer){(function (){ -"use strict"; -/* -Copyright 2018 New Vector Ltd - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.decodeRecoveryKey = exports.encodeRecoveryKey = void 0; -const bs58 = __importStar(require("bs58")); -// picked arbitrarily but to try & avoid clashing with any bitcoin ones -// (which are also base58 encoded, but bitcoin's involve a lot more hashing) -const OLM_RECOVERY_KEY_PREFIX = [0x8b, 0x01]; -function encodeRecoveryKey(key) { - var _a; - const buf = Buffer.alloc(OLM_RECOVERY_KEY_PREFIX.length + key.length + 1); - buf.set(OLM_RECOVERY_KEY_PREFIX, 0); - buf.set(key, OLM_RECOVERY_KEY_PREFIX.length); - let parity = 0; - for (let i = 0; i < buf.length - 1; ++i) { - parity ^= buf[i]; - } - buf[buf.length - 1] = parity; - const base58key = bs58.encode(buf); - return (_a = base58key.match(/.{1,4}/g)) === null || _a === void 0 ? void 0 : _a.join(" "); -} -exports.encodeRecoveryKey = encodeRecoveryKey; -function decodeRecoveryKey(recoveryKey) { - const result = bs58.decode(recoveryKey.replace(/ /g, "")); - let parity = 0; - for (const b of result) { - parity ^= b; - } - if (parity !== 0) { - throw new Error("Incorrect parity"); - } - for (let 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 + global.Olm.PRIVATE_KEY_LENGTH + 1) { - throw new Error("Incorrect length"); - } - return Uint8Array.from(result.slice(OLM_RECOVERY_KEY_PREFIX.length, OLM_RECOVERY_KEY_PREFIX.length + global.Olm.PRIVATE_KEY_LENGTH)); -} -exports.decodeRecoveryKey = decodeRecoveryKey; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) - -},{"bs58":65,"buffer":68}],345:[function(require,module,exports){ -"use strict"; -/* -Copyright 2017 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.upgradeDatabase = exports.VERSION = exports.Backend = void 0; -const logger_1 = require("../../logger"); -const utils = __importStar(require("../../utils")); -const 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. - */ -class Backend { - /** - */ - constructor(db) { - this.db = db; - this.nextTxnId = 0; - // make sure we close the db on `onversionchange` - otherwise - // attempts to delete the database will block (and subsequent - // attempts to re-create it will also block). - db.onversionchange = () => { - logger_1.logger.log(`versionchange for indexeddb ${this.db.name}: closing`); - db.close(); - }; - } - startup() { - return __awaiter(this, void 0, void 0, function* () { - // No work to do, as the startup is done by the caller (e.g IndexedDBCryptoStore) - // by passing us a ready IDBDatabase instance - return this; - }); - } - deleteAllData() { - return __awaiter(this, void 0, void 0, function* () { - throw Error("This is not implemented, call IDBFactory::deleteDatabase(dbName) instead."); - }); - } - /** - * Look for an existing outgoing room key request, and if none is found, - * add a new one - * - * - * @returns resolves to - * {@link OutgoingRoomKeyRequest}: either the - * same instance as passed in, or the existing one. - */ - getOrAddOutgoingRoomKeyRequest(request) { - const requestBody = request.requestBody; - return new Promise((resolve, reject) => { - const txn = this.db.transaction("outgoingRoomKeyRequests", "readwrite"); - txn.onerror = reject; - // first see if we already have an entry for this request. - this._getOutgoingRoomKeyRequest(txn, requestBody, (existing) => { - if (existing) { - // this entry matches the request - return it. - logger_1.logger.log(`already have key request outstanding for ` + - `${requestBody.room_id} / ${requestBody.session_id}: ` + - `not sending another`); - resolve(existing); - return; - } - // we got to the end of the list without finding a match - // - add the new request. - logger_1.logger.log(`enqueueing key request for ${requestBody.room_id} / ` + requestBody.session_id); - txn.oncomplete = () => { - resolve(request); - }; - const store = txn.objectStore("outgoingRoomKeyRequests"); - store.add(request); - }); - }); - } - /** - * Look for an existing room key request - * - * @param requestBody - existing request to look for - * - * @returns resolves to the matching - * {@link OutgoingRoomKeyRequest}, or null if - * not found - */ - getOutgoingRoomKeyRequest(requestBody) { - return new Promise((resolve, reject) => { - const txn = this.db.transaction("outgoingRoomKeyRequests", "readonly"); - txn.onerror = reject; - this._getOutgoingRoomKeyRequest(txn, requestBody, (existing) => { - resolve(existing); - }); - }); - } - /** - * look for an existing room key request in the db - * - * @internal - * @param txn - database transaction - * @param requestBody - existing request to look for - * @param callback - function to call with the results of the - * search. Either passed a matching - * {@link OutgoingRoomKeyRequest}, or null if - * not found. - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - _getOutgoingRoomKeyRequest(txn, requestBody, callback) { - const store = txn.objectStore("outgoingRoomKeyRequests"); - const idx = store.index("session"); - const cursorReq = idx.openCursor([requestBody.room_id, requestBody.session_id]); - cursorReq.onsuccess = () => { - const cursor = cursorReq.result; - if (!cursor) { - // no match found - callback(null); - return; - } - const existing = cursor.value; - if (utils.deepCompare(existing.requestBody, requestBody)) { - // got a match - callback(existing); - return; - } - // look at the next entry in the index - cursor.continue(); - }; - } - /** - * Look for room key requests by state - * - * @param wantedStates - list of acceptable states - * - * @returns resolves to the a - * {@link OutgoingRoomKeyRequest}, or null if - * there are no pending requests in those states. If there are multiple - * requests in those states, an arbitrary one is chosen. - */ - getOutgoingRoomKeyRequestByState(wantedStates) { - if (wantedStates.length === 0) { - return Promise.resolve(null); - } - // this is a bit tortuous because we need to make sure we do the lookup - // in a single transaction, to avoid having a race with the insertion - // code. - // index into the wantedStates array - let stateIndex = 0; - let result; - function onsuccess() { - const cursor = this.result; - if (cursor) { - // got a match - result = cursor.value; - return; - } - // try the next state in the list - stateIndex++; - if (stateIndex >= wantedStates.length) { - // no matches - return; - } - const wantedState = wantedStates[stateIndex]; - const cursorReq = this.source.openCursor(wantedState); - cursorReq.onsuccess = onsuccess; - } - const txn = this.db.transaction("outgoingRoomKeyRequests", "readonly"); - const store = txn.objectStore("outgoingRoomKeyRequests"); - const wantedState = wantedStates[stateIndex]; - const cursorReq = store.index("state").openCursor(wantedState); - cursorReq.onsuccess = onsuccess; - return promiseifyTxn(txn).then(() => result); - } - /** - * - * @returns All elements in a given state - */ - getAllOutgoingRoomKeyRequestsByState(wantedState) { - return new Promise((resolve, reject) => { - const txn = this.db.transaction("outgoingRoomKeyRequests", "readonly"); - const store = txn.objectStore("outgoingRoomKeyRequests"); - const index = store.index("state"); - const request = index.getAll(wantedState); - request.onsuccess = () => resolve(request.result); - request.onerror = () => reject(request.error); - }); - } - getOutgoingRoomKeyRequestsByTarget(userId, deviceId, wantedStates) { - let stateIndex = 0; - const results = []; - function onsuccess() { - const cursor = this.result; - if (cursor) { - const keyReq = cursor.value; - if (keyReq.recipients.some((recipient) => recipient.userId === userId && recipient.deviceId === deviceId)) { - results.push(keyReq); - } - cursor.continue(); - } - else { - // try the next state in the list - stateIndex++; - if (stateIndex >= wantedStates.length) { - // no matches - return; - } - const wantedState = wantedStates[stateIndex]; - const cursorReq = this.source.openCursor(wantedState); - cursorReq.onsuccess = onsuccess; - } - } - const txn = this.db.transaction("outgoingRoomKeyRequests", "readonly"); - const store = txn.objectStore("outgoingRoomKeyRequests"); - const wantedState = wantedStates[stateIndex]; - const cursorReq = store.index("state").openCursor(wantedState); - cursorReq.onsuccess = onsuccess; - return promiseifyTxn(txn).then(() => results); - } - /** - * Look for an existing room key request by id and state, and update it if - * found - * - * @param requestId - ID of request to update - * @param expectedState - state we expect to find the request in - * @param updates - name/value map of updates to apply - * - * @returns resolves to - * {@link OutgoingRoomKeyRequest} - * updated request, or null if no matching row was found - */ - updateOutgoingRoomKeyRequest(requestId, expectedState, updates) { - let result = null; - function onsuccess() { - const cursor = this.result; - if (!cursor) { - return; - } - const data = cursor.value; - if (data.state != expectedState) { - logger_1.logger.warn(`Cannot update room key request from ${expectedState} ` + - `as it was already updated to ${data.state}`); - return; - } - Object.assign(data, updates); - cursor.update(data); - result = data; - } - const txn = this.db.transaction("outgoingRoomKeyRequests", "readwrite"); - const cursorReq = txn.objectStore("outgoingRoomKeyRequests").openCursor(requestId); - cursorReq.onsuccess = onsuccess; - return promiseifyTxn(txn).then(() => result); - } - /** - * Look for an existing room key request by id and state, and delete it if - * found - * - * @param requestId - ID of request to update - * @param expectedState - state we expect to find the request in - * - * @returns resolves once the operation is completed - */ - deleteOutgoingRoomKeyRequest(requestId, expectedState) { - const txn = this.db.transaction("outgoingRoomKeyRequests", "readwrite"); - const cursorReq = txn.objectStore("outgoingRoomKeyRequests").openCursor(requestId); - cursorReq.onsuccess = () => { - const cursor = cursorReq.result; - if (!cursor) { - return; - } - const data = cursor.value; - if (data.state != expectedState) { - logger_1.logger.warn(`Cannot delete room key request in state ${data.state} ` + `(expected ${expectedState})`); - return; - } - cursor.delete(); - }; - return promiseifyTxn(txn); - } - // Olm Account - getAccount(txn, func) { - const objectStore = txn.objectStore("account"); - const getReq = objectStore.get("-"); - getReq.onsuccess = function () { - try { - func(getReq.result || null); - } - catch (e) { - abortWithException(txn, e); - } - }; - } - storeAccount(txn, accountPickle) { - const objectStore = txn.objectStore("account"); - objectStore.put(accountPickle, "-"); - } - getCrossSigningKeys(txn, func) { - const objectStore = txn.objectStore("account"); - const getReq = objectStore.get("crossSigningKeys"); - getReq.onsuccess = function () { - try { - func(getReq.result || null); - } - catch (e) { - abortWithException(txn, e); - } - }; - } - getSecretStorePrivateKey(txn, func, type) { - const objectStore = txn.objectStore("account"); - const getReq = objectStore.get(`ssss_cache:${type}`); - getReq.onsuccess = function () { - try { - func(getReq.result || null); - } - catch (e) { - abortWithException(txn, e); - } - }; - } - storeCrossSigningKeys(txn, keys) { - const objectStore = txn.objectStore("account"); - objectStore.put(keys, "crossSigningKeys"); - } - storeSecretStorePrivateKey(txn, type, key) { - const objectStore = txn.objectStore("account"); - objectStore.put(key, `ssss_cache:${type}`); - } - // Olm Sessions - countEndToEndSessions(txn, func) { - const objectStore = txn.objectStore("sessions"); - const countReq = objectStore.count(); - countReq.onsuccess = function () { - try { - func(countReq.result); - } - catch (e) { - abortWithException(txn, e); - } - }; - } - getEndToEndSessions(deviceKey, txn, func) { - const objectStore = txn.objectStore("sessions"); - const idx = objectStore.index("deviceKey"); - const getReq = idx.openCursor(deviceKey); - const results = {}; - getReq.onsuccess = function () { - const 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) { - const objectStore = txn.objectStore("sessions"); - const getReq = objectStore.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); - } - }; - } - getAllEndToEndSessions(txn, func) { - const objectStore = txn.objectStore("sessions"); - const getReq = objectStore.openCursor(); - getReq.onsuccess = function () { - try { - const cursor = getReq.result; - if (cursor) { - func(cursor.value); - cursor.continue(); - } - else { - func(null); - } - } - catch (e) { - abortWithException(txn, e); - } - }; - } - storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn) { - const objectStore = txn.objectStore("sessions"); - objectStore.put({ - deviceKey, - sessionId, - session: sessionInfo.session, - lastReceivedMessageTs: sessionInfo.lastReceivedMessageTs, - }); - } - storeEndToEndSessionProblem(deviceKey, type, fixed) { - return __awaiter(this, void 0, void 0, function* () { - const txn = this.db.transaction("session_problems", "readwrite"); - const objectStore = txn.objectStore("session_problems"); - objectStore.put({ - deviceKey, - type, - fixed, - time: Date.now(), - }); - yield promiseifyTxn(txn); - }); - } - getEndToEndSessionProblem(deviceKey, timestamp) { - return __awaiter(this, void 0, void 0, function* () { - let result = null; - const txn = this.db.transaction("session_problems", "readwrite"); - const objectStore = txn.objectStore("session_problems"); - const index = objectStore.index("deviceKey"); - const req = index.getAll(deviceKey); - req.onsuccess = () => { - const problems = req.result; - if (!problems.length) { - result = null; - return; - } - problems.sort((a, b) => { - return a.time - b.time; - }); - const lastProblem = problems[problems.length - 1]; - for (const problem of problems) { - if (problem.time > timestamp) { - result = Object.assign({}, problem, { fixed: lastProblem.fixed }); - return; - } - } - if (lastProblem.fixed) { - result = null; - } - else { - result = lastProblem; - } - }; - yield promiseifyTxn(txn); - return result; - }); - } - // FIXME: we should probably prune this when devices get deleted - filterOutNotifiedErrorDevices(devices) { - return __awaiter(this, void 0, void 0, function* () { - const txn = this.db.transaction("notified_error_devices", "readwrite"); - const objectStore = txn.objectStore("notified_error_devices"); - const ret = []; - yield Promise.all(devices.map((device) => { - return new Promise((resolve) => { - const { userId, deviceInfo } = device; - const getReq = objectStore.get([userId, deviceInfo.deviceId]); - getReq.onsuccess = function () { - if (!getReq.result) { - objectStore.put({ userId, deviceId: deviceInfo.deviceId }); - ret.push(device); - } - resolve(); - }; - }); - })); - return ret; - }); - } - // Inbound group sessions - getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) { - let session = false; - let withheld = false; - const objectStore = txn.objectStore("inbound_group_sessions"); - const getReq = objectStore.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); - } - }; - const withheldObjectStore = txn.objectStore("inbound_group_sessions_withheld"); - const withheldGetReq = withheldObjectStore.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); - } - }; - } - getAllEndToEndInboundGroupSessions(txn, func) { - const objectStore = txn.objectStore("inbound_group_sessions"); - const getReq = objectStore.openCursor(); - getReq.onsuccess = function () { - const cursor = getReq.result; - if (cursor) { - try { - func({ - senderKey: cursor.value.senderCurve25519Key, - sessionId: cursor.value.sessionId, - sessionData: cursor.value.session, - }); - } - catch (e) { - abortWithException(txn, e); - } - cursor.continue(); - } - else { - try { - func(null); - } - catch (e) { - abortWithException(txn, e); - } - } - }; - } - addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) { - const objectStore = txn.objectStore("inbound_group_sessions"); - const addReq = objectStore.add({ - senderCurve25519Key, - sessionId, - session: sessionData, - }); - addReq.onerror = (ev) => { - var _a; - if (((_a = addReq.error) === null || _a === void 0 ? void 0 : _a.name) === "ConstraintError") { - // This stops the error from triggering the txn's onerror - ev.stopPropagation(); - // ...and this stops it from aborting the transaction - ev.preventDefault(); - logger_1.logger.log("Ignoring duplicate inbound group session: " + senderCurve25519Key + " / " + sessionId); - } - else { - abortWithException(txn, new Error("Failed to add inbound group session: " + addReq.error)); - } - }; - } - storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) { - const objectStore = txn.objectStore("inbound_group_sessions"); - objectStore.put({ - senderCurve25519Key, - sessionId, - session: sessionData, - }); - } - storeEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId, sessionData, txn) { - const objectStore = txn.objectStore("inbound_group_sessions_withheld"); - objectStore.put({ - senderCurve25519Key, - sessionId, - session: sessionData, - }); - } - getEndToEndDeviceData(txn, func) { - const objectStore = txn.objectStore("device_data"); - const getReq = objectStore.get("-"); - getReq.onsuccess = function () { - try { - func(getReq.result || null); - } - catch (e) { - abortWithException(txn, e); - } - }; - } - storeEndToEndDeviceData(deviceData, txn) { - const objectStore = txn.objectStore("device_data"); - objectStore.put(deviceData, "-"); - } - storeEndToEndRoom(roomId, roomInfo, txn) { - const objectStore = txn.objectStore("rooms"); - objectStore.put(roomInfo, roomId); - } - getEndToEndRooms(txn, func) { - const rooms = {}; - const objectStore = txn.objectStore("rooms"); - const getReq = objectStore.openCursor(); - getReq.onsuccess = function () { - const cursor = getReq.result; - if (cursor) { - rooms[cursor.key] = cursor.value; - cursor.continue(); - } - else { - try { - func(rooms); - } - catch (e) { - abortWithException(txn, e); - } - } - }; - } - // session backups - getSessionsNeedingBackup(limit) { - return new Promise((resolve, reject) => { - const sessions = []; - const txn = this.db.transaction(["sessions_needing_backup", "inbound_group_sessions"], "readonly"); - txn.onerror = reject; - txn.oncomplete = function () { - resolve(sessions); - }; - const objectStore = txn.objectStore("sessions_needing_backup"); - const sessionStore = txn.objectStore("inbound_group_sessions"); - const getReq = objectStore.openCursor(); - getReq.onsuccess = function () { - const cursor = getReq.result; - if (cursor) { - const sessionGetReq = sessionStore.get(cursor.key); - sessionGetReq.onsuccess = function () { - sessions.push({ - senderKey: sessionGetReq.result.senderCurve25519Key, - sessionId: sessionGetReq.result.sessionId, - sessionData: sessionGetReq.result.session, - }); - }; - if (!limit || sessions.length < limit) { - cursor.continue(); - } - } - }; - }); - } - countSessionsNeedingBackup(txn) { - if (!txn) { - txn = this.db.transaction("sessions_needing_backup", "readonly"); - } - const objectStore = txn.objectStore("sessions_needing_backup"); - return new Promise((resolve, reject) => { - const req = objectStore.count(); - req.onerror = reject; - req.onsuccess = () => resolve(req.result); - }); - } - unmarkSessionsNeedingBackup(sessions, txn) { - return __awaiter(this, void 0, void 0, function* () { - if (!txn) { - txn = this.db.transaction("sessions_needing_backup", "readwrite"); - } - const objectStore = txn.objectStore("sessions_needing_backup"); - yield Promise.all(sessions.map((session) => { - return new Promise((resolve, reject) => { - const req = objectStore.delete([session.senderKey, session.sessionId]); - req.onsuccess = resolve; - req.onerror = reject; - }); - })); - }); - } - markSessionsNeedingBackup(sessions, txn) { - return __awaiter(this, void 0, void 0, function* () { - if (!txn) { - txn = this.db.transaction("sessions_needing_backup", "readwrite"); - } - const objectStore = txn.objectStore("sessions_needing_backup"); - yield Promise.all(sessions.map((session) => { - return new Promise((resolve, reject) => { - const req = objectStore.put({ - senderCurve25519Key: session.senderKey, - sessionId: session.sessionId, - }); - req.onsuccess = resolve; - req.onerror = reject; - }); - })); - }); - } - addSharedHistoryInboundGroupSession(roomId, senderKey, sessionId, txn) { - if (!txn) { - txn = this.db.transaction("shared_history_inbound_group_sessions", "readwrite"); - } - const objectStore = txn.objectStore("shared_history_inbound_group_sessions"); - const req = objectStore.get([roomId]); - req.onsuccess = () => { - const { sessions } = req.result || { sessions: [] }; - sessions.push([senderKey, sessionId]); - objectStore.put({ roomId, sessions }); - }; - } - getSharedHistoryInboundGroupSessions(roomId, txn) { - if (!txn) { - txn = this.db.transaction("shared_history_inbound_group_sessions", "readonly"); - } - const objectStore = txn.objectStore("shared_history_inbound_group_sessions"); - const req = objectStore.get([roomId]); - return new Promise((resolve, reject) => { - req.onsuccess = () => { - const { sessions } = req.result || { sessions: [] }; - resolve(sessions); - }; - req.onerror = reject; - }); - } - addParkedSharedHistory(roomId, parkedData, txn) { - if (!txn) { - txn = this.db.transaction("parked_shared_history", "readwrite"); - } - const objectStore = txn.objectStore("parked_shared_history"); - const req = objectStore.get([roomId]); - req.onsuccess = () => { - const { parked } = req.result || { parked: [] }; - parked.push(parkedData); - objectStore.put({ roomId, parked }); - }; - } - takeParkedSharedHistory(roomId, txn) { - if (!txn) { - txn = this.db.transaction("parked_shared_history", "readwrite"); - } - const cursorReq = txn.objectStore("parked_shared_history").openCursor(roomId); - return new Promise((resolve, reject) => { - cursorReq.onsuccess = () => { - const cursor = cursorReq.result; - if (!cursor) { - resolve([]); - return; - } - const data = cursor.value; - cursor.delete(); - resolve(data); - }; - cursorReq.onerror = reject; - }); - } - doTxn(mode, stores, func, log = logger_1.logger) { - let startTime; - let description; - if (PROFILE_TRANSACTIONS) { - const txnId = this.nextTxnId++; - startTime = Date.now(); - description = `${mode} crypto store transaction ${txnId} in ${stores}`; - log.debug(`Starting ${description}`); - } - const txn = this.db.transaction(stores, mode); - const promise = promiseifyTxn(txn); - const result = func(txn); - if (PROFILE_TRANSACTIONS) { - promise.then(() => { - const elapsedTime = Date.now() - startTime; - log.debug(`Finished ${description}, took ${elapsedTime} ms`); - }, () => { - const elapsedTime = Date.now() - startTime; - log.error(`Failed ${description}, took ${elapsedTime} ms`); - }); - } - return promise.then(() => { - return result; - }); - } -} -exports.Backend = Backend; -const DB_MIGRATIONS = [ - (db) => { - createDatabase(db); - }, - (db) => { - db.createObjectStore("account"); - }, - (db) => { - const sessionsStore = db.createObjectStore("sessions", { - keyPath: ["deviceKey", "sessionId"], - }); - sessionsStore.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) => { - const problemsStore = db.createObjectStore("session_problems", { - keyPath: ["deviceKey", "time"], - }); - problemsStore.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"], - }); - }, - // Expand as needed. -]; -exports.VERSION = DB_MIGRATIONS.length; -function upgradeDatabase(db, oldVersion) { - logger_1.logger.log(`Upgrading IndexedDBCryptoStore from version ${oldVersion}` + ` to ${exports.VERSION}`); - DB_MIGRATIONS.forEach((migration, index) => { - if (oldVersion <= index) - migration(db); - }); -} -exports.upgradeDatabase = upgradeDatabase; -function createDatabase(db) { - const outgoingRoomKeyRequestsStore = db.createObjectStore("outgoingRoomKeyRequests", { keyPath: "requestId" }); - // we assume that the RoomKeyRequestBody will have room_id and session_id - // properties, to make the index efficient. - outgoingRoomKeyRequestsStore.createIndex("session", ["requestBody.room_id", "requestBody.session_id"]); - outgoingRoomKeyRequestsStore.createIndex("state", "state"); -} -/* - * Aborts a transaction with a given exception - * The transaction promise will be rejected with this exception. - */ -function abortWithException(txn, e) { - // We cheekily stick our exception onto the transaction object here - // We could alternatively make the thing we pass back to the app - // an object containing the transaction and exception. - txn._mx_abortexception = e; - try { - txn.abort(); - } - catch (e) { - // sometimes we won't be able to abort the transaction - // (ie. if it's aborted or completed) - } -} -function promiseifyTxn(txn) { - return new Promise((resolve, reject) => { - txn.oncomplete = () => { - if (txn._mx_abortexception !== undefined) { - reject(txn._mx_abortexception); - } - resolve(null); - }; - txn.onerror = (event) => { - if (txn._mx_abortexception !== undefined) { - reject(txn._mx_abortexception); - } - else { - logger_1.logger.log("Error performing indexeddb txn", event); - reject(txn.error); - } - }; - txn.onabort = (event) => { - if (txn._mx_abortexception !== undefined) { - reject(txn._mx_abortexception); - } - else { - logger_1.logger.log("Error performing indexeddb txn", event); - reject(txn.error); - } - }; - }); -} - -},{"../../logger":374,"../../utils":416}],346:[function(require,module,exports){ -(function (global){(function (){ -"use strict"; -/* -Copyright 2017 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.IndexedDBCryptoStore = void 0; -const logger_1 = require("../../logger"); -const localStorage_crypto_store_1 = require("./localStorage-crypto-store"); -const memory_crypto_store_1 = require("./memory-crypto-store"); -const IndexedDBCryptoStoreBackend = __importStar(require("./indexeddb-crypto-store-backend")); -const errors_1 = require("../../errors"); -const IndexedDBHelpers = __importStar(require("../../indexeddb-helpers")); -/** - * Internal module. indexeddb storage for e2e. - */ -/** - * An implementation of CryptoStore, which is normally backed by an indexeddb, - * but with fallback to MemoryCryptoStore. - */ -class IndexedDBCryptoStore { - static exists(indexedDB, dbName) { - return IndexedDBHelpers.exists(indexedDB, dbName); - } - /** - * 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; - } - /** - * 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(new Error("no indexeddb support available")); - return; - } - logger_1.logger.log(`connecting to indexeddb ${this.dbName}`); - const req = this.indexedDB.open(this.dbName, IndexedDBCryptoStoreBackend.VERSION); - req.onupgradeneeded = (ev) => { - const db = req.result; - const oldVersion = ev.oldVersion; - IndexedDBCryptoStoreBackend.upgradeDatabase(db, oldVersion); - }; - req.onblocked = () => { - logger_1.logger.log(`can't yet open IndexedDBCryptoStore because it is open elsewhere`); - }; - req.onerror = (ev) => { - logger_1.logger.log("Error connecting to indexeddb", ev); - reject(req.error); - }; - req.onsuccess = () => { - const db = req.result; - logger_1.logger.log(`connected to indexeddb ${this.dbName}`); - resolve(new IndexedDBCryptoStoreBackend.Backend(db)); - }; - }) - .then((backend) => { - // Edge has IndexedDB but doesn't support compund keys which we use fairly extensively. - // Try a dummy query which will fail if the browser doesn't support compund keys, so - // we can fall back to a different 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_1.logger.warn("Crypto DB is too new for us to use!", e); - // don't fall back to a different store: the user has crypto data - // in this db so we should use it or nothing at all. - throw new errors_1.InvalidCryptoStoreError(errors_1.InvalidCryptoStoreState.TooNew); - } - logger_1.logger.warn(`unable to connect to indexeddb ${this.dbName}` + `: falling back to localStorage store: ${e}`); - try { - return new localStorage_crypto_store_1.LocalStorageCryptoStore(global.localStorage); - } - catch (e) { - logger_1.logger.warn(`unable to open localStorage: falling back to in-memory store: ${e}`); - return new memory_crypto_store_1.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(new Error("no indexeddb support available")); - return; - } - logger_1.logger.log(`Removing indexeddb instance: ${this.dbName}`); - const req = this.indexedDB.deleteDatabase(this.dbName); - req.onblocked = () => { - logger_1.logger.log(`can't yet delete IndexedDBCryptoStore because it is open elsewhere`); - }; - req.onerror = (ev) => { - logger_1.logger.log("Error deleting data from indexeddb", ev); - reject(req.error); - }; - req.onsuccess = () => { - logger_1.logger.log(`Removed indexeddb instance: ${this.dbName}`); - resolve(); - }; - }).catch((e) => { - // in firefox, with indexedDB disabled, this fails with a - // DOMError. We treat this as non-fatal, so that people can - // still use the app. - logger_1.logger.warn(`unable to delete IndexedDBCryptoStore: ${e}`); - }); - } - /** - * Look for an existing outgoing room key request, and if none is found, - * add a new one - * - * - * @returns resolves to - * {@link OutgoingRoomKeyRequest}: either the - * same instance as passed in, or the existing one. - */ - getOrAddOutgoingRoomKeyRequest(request) { - return this.backend.getOrAddOutgoingRoomKeyRequest(request); - } - /** - * Look for an existing room key request - * - * @param requestBody - existing request to look for - * - * @returns resolves to the matching - * {@link OutgoingRoomKeyRequest}, or null if - * not found - */ - getOutgoingRoomKeyRequest(requestBody) { - return this.backend.getOutgoingRoomKeyRequest(requestBody); - } - /** - * Look for room key requests by state - * - * @param wantedStates - list of acceptable states - * - * @returns resolves to the a - * {@link OutgoingRoomKeyRequest}, or null if - * there are no pending requests in those states. If there are multiple - * requests in those states, an arbitrary one is chosen. - */ - getOutgoingRoomKeyRequestByState(wantedStates) { - return this.backend.getOutgoingRoomKeyRequestByState(wantedStates); - } - /** - * Look for room key requests by state – - * unlike above, return a list of all entries in one state. - * - * @returns Returns an array of requests in the given state - */ - getAllOutgoingRoomKeyRequestsByState(wantedState) { - return this.backend.getAllOutgoingRoomKeyRequestsByState(wantedState); - } - /** - * Look for room key requests by target device and state - * - * @param userId - Target user ID - * @param deviceId - Target device ID - * @param wantedStates - list of acceptable states - * - * @returns resolves to a list of all the - * {@link OutgoingRoomKeyRequest} - */ - getOutgoingRoomKeyRequestsByTarget(userId, deviceId, wantedStates) { - return this.backend.getOutgoingRoomKeyRequestsByTarget(userId, deviceId, wantedStates); - } - /** - * Look for an existing room key request by id and state, and update it if - * found - * - * @param requestId - ID of request to update - * @param expectedState - state we expect to find the request in - * @param updates - name/value map of updates to apply - * - * @returns resolves to - * {@link OutgoingRoomKeyRequest} - * updated request, or null if no matching row was found - */ - updateOutgoingRoomKeyRequest(requestId, expectedState, updates) { - return this.backend.updateOutgoingRoomKeyRequest(requestId, expectedState, updates); - } - /** - * Look for an existing room key request by id and state, and delete it if - * found - * - * @param requestId - ID of request to update - * @param expectedState - state we expect to find the request in - * - * @returns resolves once the operation is completed - */ - deleteOutgoingRoomKeyRequest(requestId, expectedState) { - return this.backend.deleteOutgoingRoomKeyRequest(requestId, expectedState); - } - // Olm Account - /* - * Get the account pickle from the store. - * This requires an active transaction. See doTxn(). - * - * @param txn - An active transaction. See doTxn(). - * @param func - Called with the account pickle - */ - 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 keys back to the store - * - * @param txn - An active transaction. See doTxn(). - * @param keys - keys object as getCrossSigningKeys() - */ - storeCrossSigningKeys(txn, keys) { - this.backend.storeCrossSigningKeys(txn, keys); - } - /** - * 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); - } - // Olm sessions - /** - * 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); - } - /** - * Retrieve all end-to-end sessions - * @param txn - An active transaction. See doTxn(). - * @param func - Called one for each session with - * an object with, deviceKey, lastReceivedMessageTs, sessionId - * and session keys. - */ - getAllEndToEndSessions(txn, func) { - this.backend.getAllEndToEndSessions(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); - } - storeEndToEndSessionProblem(deviceKey, type, fixed) { - return this.backend.storeEndToEndSessionProblem(deviceKey, type, fixed); - } - getEndToEndSessionProblem(deviceKey, timestamp) { - return this.backend.getEndToEndSessionProblem(deviceKey, timestamp); - } - filterOutNotifiedErrorDevices(devices) { - return this.backend.filterOutNotifiedErrorDevices(devices); - } - // Inbound group 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); - } - /** - * Fetches all inbound group sessions in the store - * @param txn - An active transaction. See doTxn(). - * @param func - Called once for each group session - * in the store with an object having keys `{senderKey, sessionId, sessionData}`, - * then once with null to indicate the end of the list. - */ - getAllEndToEndInboundGroupSessions(txn, func) { - this.backend.getAllEndToEndInboundGroupSessions(txn, func); - } - /** - * Adds an end-to-end inbound group session to the store. - * If there already exists an inbound group session with the same - * senderCurve25519Key and sessionID, the session will not be added. - * @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(). - */ - addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) { - this.backend.addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn); - } - /** - * 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); - } - storeEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId, sessionData, txn) { - this.backend.storeEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId, sessionData, txn); - } - // End-to-end device tracking - /** - * Store the state of all tracked devices - * This contains devices for each user, a tracking state for each user - * and a sync token matching the point in time the snapshot represents. - * These all need to be written out in full each time such that the snapshot - * is always consistent, so they are stored in one object. - * - * @param txn - An active transaction. See doTxn(). - */ - storeEndToEndDeviceData(deviceData, txn) { - this.backend.storeEndToEndDeviceData(deviceData, txn); - } - /** - * Get the state of all tracked devices - * - * @param txn - An active transaction. See doTxn(). - * @param func - Function called with the - * device data - */ - getEndToEndDeviceData(txn, func) { - this.backend.getEndToEndDeviceData(txn, func); - } - // End to End Rooms - /** - * Store the end-to-end state for a room. - * @param roomId - The room's ID. - * @param roomInfo - The end-to-end info for the room. - * @param txn - An active transaction. See doTxn(). - */ - storeEndToEndRoom(roomId, roomInfo, txn) { - this.backend.storeEndToEndRoom(roomId, roomInfo, txn); - } - /** - * 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); - } - // session backups - /** - * Get the inbound group sessions that need to be backed up. - * @param limit - The maximum number of sessions to retrieve. 0 - * for no limit. - * @returns resolves to an array of inbound group sessions - */ - getSessionsNeedingBackup(limit) { - return this.backend.getSessionsNeedingBackup(limit); - } - /** - * Count the inbound group sessions that need to be backed up. - * @param txn - An active transaction. See doTxn(). (optional) - * @returns resolves to the number of sessions - */ - countSessionsNeedingBackup(txn) { - return this.backend.countSessionsNeedingBackup(txn); - } - /** - * Unmark 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 unmarked - */ - unmarkSessionsNeedingBackup(sessions, txn) { - return this.backend.unmarkSessionsNeedingBackup(sessions, txn); - } - /** - * 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); - } - /** - * Add a shared-history group session for a room. - * @param roomId - The room that the key belongs to - * @param senderKey - The sender's curve 25519 key - * @param sessionId - The ID of the session - * @param txn - An active transaction. See doTxn(). (optional) - */ - addSharedHistoryInboundGroupSession(roomId, senderKey, sessionId, txn) { - this.backend.addSharedHistoryInboundGroupSession(roomId, senderKey, sessionId, txn); - } - /** - * Get the shared-history group session for a room. - * @param roomId - The room that the key belongs to - * @param txn - An active transaction. See doTxn(). (optional) - * @returns Promise which resolves to an array of [senderKey, sessionId] - */ - getSharedHistoryInboundGroupSessions(roomId, txn) { - return this.backend.getSharedHistoryInboundGroupSessions(roomId, txn); - } - /** - * Park a shared-history group session for a room we may be invited to later. - */ - addParkedSharedHistory(roomId, parkedData, txn) { - this.backend.addParkedSharedHistory(roomId, parkedData, txn); - } - /** - * Pop out all shared-history group sessions for a room. - */ - takeParkedSharedHistory(roomId, txn) { - return this.backend.takeParkedSharedHistory(roomId, 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); - } -} -exports.IndexedDBCryptoStore = IndexedDBCryptoStore; -IndexedDBCryptoStore.STORE_ACCOUNT = "account"; -IndexedDBCryptoStore.STORE_SESSIONS = "sessions"; -IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS = "inbound_group_sessions"; -IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD = "inbound_group_sessions_withheld"; -IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS = "shared_history_inbound_group_sessions"; -IndexedDBCryptoStore.STORE_PARKED_SHARED_HISTORY = "parked_shared_history"; -IndexedDBCryptoStore.STORE_DEVICE_DATA = "device_data"; -IndexedDBCryptoStore.STORE_ROOMS = "rooms"; -IndexedDBCryptoStore.STORE_BACKUP = "sessions_needing_backup"; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"../../errors":359,"../../indexeddb-helpers":372,"../../logger":374,"./indexeddb-crypto-store-backend":345,"./localStorage-crypto-store":347,"./memory-crypto-store":348}],347:[function(require,module,exports){ -"use strict"; -/* -Copyright 2017 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.LocalStorageCryptoStore = void 0; -const logger_1 = require("../../logger"); -const memory_crypto_store_1 = require("./memory-crypto-store"); -const utils_1 = require("../../utils"); -/** - * 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". - */ -const E2E_PREFIX = "crypto."; -const KEY_END_TO_END_ACCOUNT = E2E_PREFIX + "account"; -const KEY_CROSS_SIGNING_KEYS = E2E_PREFIX + "cross_signing_keys"; -const KEY_NOTIFIED_ERROR_DEVICES = E2E_PREFIX + "notified_error_devices"; -const KEY_DEVICE_DATA = E2E_PREFIX + "device_data"; -const KEY_INBOUND_SESSION_PREFIX = E2E_PREFIX + "inboundgroupsessions/"; -const KEY_INBOUND_SESSION_WITHHELD_PREFIX = E2E_PREFIX + "inboundgroupsessions.withheld/"; -const KEY_ROOMS_PREFIX = E2E_PREFIX + "rooms/"; -const KEY_SESSIONS_NEEDING_BACKUP = E2E_PREFIX + "sessionsneedingbackup"; -function keyEndToEndSessions(deviceKey) { - return E2E_PREFIX + "sessions/" + deviceKey; -} -function keyEndToEndSessionProblems(deviceKey) { - return E2E_PREFIX + "session.problems/" + 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; -} -class LocalStorageCryptoStore extends memory_crypto_store_1.MemoryCryptoStore { - static exists(store) { - var _a; - const length = store.length; - for (let i = 0; i < length; i++) { - if ((_a = store.key(i)) === null || _a === void 0 ? void 0 : _a.startsWith(E2E_PREFIX)) { - return true; - } - } - return false; - } - constructor(store) { - super(); - this.store = store; - } - // Olm Sessions - countEndToEndSessions(txn, func) { - var _a; - let count = 0; - for (let i = 0; i < this.store.length; ++i) { - if ((_a = this.store.key(i)) === null || _a === void 0 ? void 0 : _a.startsWith(keyEndToEndSessions(""))) - ++count; - } - func(count); - } - // eslint-disable-next-line @typescript-eslint/naming-convention - _getEndToEndSessions(deviceKey) { - const sessions = getJsonItem(this.store, keyEndToEndSessions(deviceKey)); - const fixedSessions = {}; - // fix up any old sessions to be objects rather than just the base64 pickle - for (const [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) { - const sessions = this._getEndToEndSessions(deviceKey); - func(sessions[sessionId] || {}); - } - getEndToEndSessions(deviceKey, txn, func) { - func(this._getEndToEndSessions(deviceKey) || {}); - } - getAllEndToEndSessions(txn, func) { - var _a; - for (let i = 0; i < this.store.length; ++i) { - if ((_a = this.store.key(i)) === null || _a === void 0 ? void 0 : _a.startsWith(keyEndToEndSessions(""))) { - const deviceKey = this.store.key(i).split("/")[1]; - for (const sess of Object.values(this._getEndToEndSessions(deviceKey))) { - func(sess); - } - } - } - } - storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn) { - const sessions = this._getEndToEndSessions(deviceKey) || {}; - sessions[sessionId] = sessionInfo; - setJsonItem(this.store, keyEndToEndSessions(deviceKey), sessions); - } - storeEndToEndSessionProblem(deviceKey, type, fixed) { - return __awaiter(this, void 0, void 0, function* () { - const key = keyEndToEndSessionProblems(deviceKey); - const problems = getJsonItem(this.store, key) || []; - problems.push({ type, fixed, time: Date.now() }); - problems.sort((a, b) => { - return a.time - b.time; - }); - setJsonItem(this.store, key, problems); - }); - } - getEndToEndSessionProblem(deviceKey, timestamp) { - return __awaiter(this, void 0, void 0, function* () { - const key = keyEndToEndSessionProblems(deviceKey); - const problems = getJsonItem(this.store, key) || []; - if (!problems.length) { - return null; - } - const lastProblem = problems[problems.length - 1]; - for (const problem of problems) { - if (problem.time > timestamp) { - return Object.assign({}, problem, { fixed: lastProblem.fixed }); - } - } - if (lastProblem.fixed) { - return null; - } - else { - return lastProblem; - } - }); - } - filterOutNotifiedErrorDevices(devices) { - return __awaiter(this, void 0, void 0, function* () { - const notifiedErrorDevices = getJsonItem(this.store, KEY_NOTIFIED_ERROR_DEVICES) || {}; - const ret = []; - for (const device of devices) { - const { userId, deviceInfo } = device; - if (userId in notifiedErrorDevices) { - if (!(deviceInfo.deviceId in notifiedErrorDevices[userId])) { - ret.push(device); - (0, utils_1.safeSet)(notifiedErrorDevices[userId], deviceInfo.deviceId, true); - } - } - else { - ret.push(device); - (0, utils_1.safeSet)(notifiedErrorDevices, userId, { [deviceInfo.deviceId]: true }); - } - } - setJsonItem(this.store, KEY_NOTIFIED_ERROR_DEVICES, notifiedErrorDevices); - return ret; - }); - } - // Inbound Group Sessions - getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) { - func(getJsonItem(this.store, keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId)), getJsonItem(this.store, keyEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId))); - } - getAllEndToEndInboundGroupSessions(txn, func) { - for (let i = 0; i < this.store.length; ++i) { - const key = this.store.key(i); - if (key === null || key === void 0 ? void 0 : key.startsWith(KEY_INBOUND_SESSION_PREFIX)) { - // we can't use split, as the components we are trying to split out - // might themselves contain '/' characters. We rely on the - // senderKey being a (32-byte) curve25519 key, base64-encoded - // (hence 43 characters long). - func({ - senderKey: key.slice(KEY_INBOUND_SESSION_PREFIX.length, KEY_INBOUND_SESSION_PREFIX.length + 43), - sessionId: key.slice(KEY_INBOUND_SESSION_PREFIX.length + 44), - sessionData: getJsonItem(this.store, key), - }); - } - } - func(null); - } - addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) { - const existing = getJsonItem(this.store, keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId)); - if (!existing) { - this.storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn); - } - } - storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) { - setJsonItem(this.store, keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId), sessionData); - } - storeEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId, sessionData, txn) { - setJsonItem(this.store, keyEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId), sessionData); - } - getEndToEndDeviceData(txn, func) { - func(getJsonItem(this.store, KEY_DEVICE_DATA)); - } - storeEndToEndDeviceData(deviceData, txn) { - setJsonItem(this.store, KEY_DEVICE_DATA, deviceData); - } - storeEndToEndRoom(roomId, roomInfo, txn) { - setJsonItem(this.store, keyEndToEndRoomsPrefix(roomId), roomInfo); - } - getEndToEndRooms(txn, func) { - const result = {}; - const prefix = keyEndToEndRoomsPrefix(""); - for (let i = 0; i < this.store.length; ++i) { - const key = this.store.key(i); - if (key === null || key === void 0 ? void 0 : key.startsWith(prefix)) { - const roomId = key.slice(prefix.length); - result[roomId] = getJsonItem(this.store, key); - } - } - func(result); - } - getSessionsNeedingBackup(limit) { - const sessionsNeedingBackup = getJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {}; - const sessions = []; - for (const session in sessionsNeedingBackup) { - if (Object.prototype.hasOwnProperty.call(sessionsNeedingBackup, session)) { - // see getAllEndToEndInboundGroupSessions for the magic number explanations - const senderKey = session.slice(0, 43); - const sessionId = session.slice(44); - this.getEndToEndInboundGroupSession(senderKey, sessionId, null, (sessionData) => { - sessions.push({ - senderKey: senderKey, - sessionId: sessionId, - sessionData: sessionData, - }); - }); - if (limit && sessions.length >= limit) { - break; - } - } - } - return Promise.resolve(sessions); - } - countSessionsNeedingBackup() { - const sessionsNeedingBackup = getJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {}; - return Promise.resolve(Object.keys(sessionsNeedingBackup).length); - } - unmarkSessionsNeedingBackup(sessions) { - const sessionsNeedingBackup = getJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {}; - for (const session of sessions) { - delete sessionsNeedingBackup[session.senderKey + "/" + session.sessionId]; - } - setJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP, sessionsNeedingBackup); - return Promise.resolve(); - } - markSessionsNeedingBackup(sessions) { - const sessionsNeedingBackup = getJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {}; - for (const 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(); - } - // Olm account - getAccount(txn, func) { - const accountPickle = getJsonItem(this.store, KEY_END_TO_END_ACCOUNT); - func(accountPickle); - } - storeAccount(txn, accountPickle) { - setJsonItem(this.store, KEY_END_TO_END_ACCOUNT, accountPickle); - } - getCrossSigningKeys(txn, func) { - const keys = getJsonItem(this.store, KEY_CROSS_SIGNING_KEYS); - func(keys); - } - getSecretStorePrivateKey(txn, func, type) { - const key = getJsonItem(this.store, E2E_PREFIX + `ssss_cache.${type}`); - func(key); - } - storeCrossSigningKeys(txn, keys) { - setJsonItem(this.store, KEY_CROSS_SIGNING_KEYS, keys); - } - storeSecretStorePrivateKey(txn, type, key) { - setJsonItem(this.store, E2E_PREFIX + `ssss_cache.${type}`, key); - } - doTxn(mode, stores, func) { - return Promise.resolve(func(null)); - } -} -exports.LocalStorageCryptoStore = LocalStorageCryptoStore; -function getJsonItem(store, key) { - try { - // if the key is absent, store.getItem() returns null, and - // JSON.parse(null) === null, so this returns null. - return JSON.parse(store.getItem(key)); - } - catch (e) { - logger_1.logger.log("Error: Failed to get key %s: %s", key, e.message); - logger_1.logger.log(e.stack); - } - return null; -} -function setJsonItem(store, key, val) { - store.setItem(key, JSON.stringify(val)); -} - -},{"../../logger":374,"../../utils":416,"./memory-crypto-store":348}],348:[function(require,module,exports){ -"use strict"; -/* -Copyright 2017 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MemoryCryptoStore = void 0; -const logger_1 = require("../../logger"); -const utils = __importStar(require("../../utils")); -const utils_1 = require("../../utils"); -/** - * Internal module. in-memory storage for e2e. - */ -class MemoryCryptoStore { - constructor() { - this.outgoingRoomKeyRequests = []; - this.account = null; - this.crossSigningKeys = null; - this.privateKeys = {}; - this.sessions = {}; - this.sessionProblems = {}; - this.notifiedErrorDevices = {}; - this.inboundGroupSessions = {}; - this.inboundGroupSessionsWithheld = {}; - // Opaque device data object - this.deviceData = null; - this.rooms = {}; - this.sessionsNeedingBackup = {}; - this.sharedHistoryInboundGroupSessions = {}; - this.parkedSharedHistory = new Map(); // keyed by room ID - } - /** - * 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() { - return __awaiter(this, void 0, void 0, function* () { - // No startup work to do for the memory store. - return this; - }); - } - /** - * Delete all data from this store. - * - * @returns Promise which resolves when the store has been cleared. - */ - deleteAllData() { - return Promise.resolve(); - } - /** - * Look for an existing outgoing room key request, and if none is found, - * add a new one - * - * - * @returns resolves to - * {@link OutgoingRoomKeyRequest}: either the - * same instance as passed in, or the existing one. - */ - getOrAddOutgoingRoomKeyRequest(request) { - const requestBody = request.requestBody; - return utils.promiseTry(() => { - // first see if we already have an entry for this request. - const existing = this._getOutgoingRoomKeyRequest(requestBody); - if (existing) { - // this entry matches the request - return it. - logger_1.logger.log(`already have key request outstanding for ` + - `${requestBody.room_id} / ${requestBody.session_id}: ` + - `not sending another`); - return existing; - } - // we got to the end of the list without finding a match - // - add the new request. - logger_1.logger.log(`enqueueing key request for ${requestBody.room_id} / ` + requestBody.session_id); - this.outgoingRoomKeyRequests.push(request); - return request; - }); - } - /** - * Look for an existing room key request - * - * @param requestBody - existing request to look for - * - * @returns resolves to the matching - * {@link OutgoingRoomKeyRequest}, or null if - * not found - */ - getOutgoingRoomKeyRequest(requestBody) { - return Promise.resolve(this._getOutgoingRoomKeyRequest(requestBody)); - } - /** - * Looks for existing room key request, and returns the result synchronously. - * - * @internal - * - * @param requestBody - existing request to look for - * - * @returns - * the matching request, or null if not found - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - _getOutgoingRoomKeyRequest(requestBody) { - for (const existing of this.outgoingRoomKeyRequests) { - if (utils.deepCompare(existing.requestBody, requestBody)) { - return existing; - } - } - return null; - } - /** - * Look for room key requests by state - * - * @param wantedStates - list of acceptable states - * - * @returns resolves to the a - * {@link OutgoingRoomKeyRequest}, or null if - * there are no pending requests in those states - */ - getOutgoingRoomKeyRequestByState(wantedStates) { - for (const req of this.outgoingRoomKeyRequests) { - for (const state of wantedStates) { - if (req.state === state) { - return Promise.resolve(req); - } - } - } - return Promise.resolve(null); - } - /** - * - * @returns All OutgoingRoomKeyRequests in state - */ - getAllOutgoingRoomKeyRequestsByState(wantedState) { - return Promise.resolve(this.outgoingRoomKeyRequests.filter((r) => r.state == wantedState)); - } - getOutgoingRoomKeyRequestsByTarget(userId, deviceId, wantedStates) { - const results = []; - for (const req of this.outgoingRoomKeyRequests) { - for (const state of wantedStates) { - if (req.state === state && - req.recipients.some((recipient) => recipient.userId === userId && recipient.deviceId === deviceId)) { - results.push(req); - } - } - } - return Promise.resolve(results); - } - /** - * Look for an existing room key request by id and state, and update it if - * found - * - * @param requestId - ID of request to update - * @param expectedState - state we expect to find the request in - * @param updates - name/value map of updates to apply - * - * @returns resolves to - * {@link OutgoingRoomKeyRequest} - * updated request, or null if no matching row was found - */ - updateOutgoingRoomKeyRequest(requestId, expectedState, updates) { - for (const req of this.outgoingRoomKeyRequests) { - if (req.requestId !== requestId) { - continue; - } - if (req.state !== expectedState) { - logger_1.logger.warn(`Cannot update room key request from ${expectedState} ` + - `as it was already updated to ${req.state}`); - return Promise.resolve(null); - } - Object.assign(req, updates); - return Promise.resolve(req); - } - return Promise.resolve(null); - } - /** - * Look for an existing room key request by id and state, and delete it if - * found - * - * @param requestId - ID of request to update - * @param expectedState - state we expect to find the request in - * - * @returns resolves once the operation is completed - */ - deleteOutgoingRoomKeyRequest(requestId, expectedState) { - for (let i = 0; i < this.outgoingRoomKeyRequests.length; i++) { - const req = this.outgoingRoomKeyRequests[i]; - if (req.requestId !== requestId) { - continue; - } - if (req.state != expectedState) { - logger_1.logger.warn(`Cannot delete room key request in state ${req.state} ` + `(expected ${expectedState})`); - return Promise.resolve(null); - } - this.outgoingRoomKeyRequests.splice(i, 1); - return Promise.resolve(req); - } - return Promise.resolve(null); - } - // Olm Account - getAccount(txn, func) { - func(this.account); - } - storeAccount(txn, accountPickle) { - this.account = accountPickle; - } - getCrossSigningKeys(txn, func) { - func(this.crossSigningKeys); - } - getSecretStorePrivateKey(txn, func, type) { - const result = this.privateKeys[type]; - func(result || null); - } - storeCrossSigningKeys(txn, keys) { - this.crossSigningKeys = keys; - } - storeSecretStorePrivateKey(txn, type, key) { - this.privateKeys[type] = key; - } - // Olm Sessions - countEndToEndSessions(txn, func) { - func(Object.keys(this.sessions).length); - } - getEndToEndSession(deviceKey, sessionId, txn, func) { - const deviceSessions = this.sessions[deviceKey] || {}; - func(deviceSessions[sessionId] || null); - } - getEndToEndSessions(deviceKey, txn, func) { - func(this.sessions[deviceKey] || {}); - } - getAllEndToEndSessions(txn, func) { - Object.entries(this.sessions).forEach(([deviceKey, deviceSessions]) => { - Object.entries(deviceSessions).forEach(([sessionId, session]) => { - func(Object.assign(Object.assign({}, session), { deviceKey, - sessionId })); - }); - }); - } - storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn) { - let deviceSessions = this.sessions[deviceKey]; - if (deviceSessions === undefined) { - deviceSessions = {}; - this.sessions[deviceKey] = deviceSessions; - } - deviceSessions[sessionId] = sessionInfo; - } - storeEndToEndSessionProblem(deviceKey, type, fixed) { - return __awaiter(this, void 0, void 0, function* () { - const problems = (this.sessionProblems[deviceKey] = this.sessionProblems[deviceKey] || []); - problems.push({ type, fixed, time: Date.now() }); - problems.sort((a, b) => { - return a.time - b.time; - }); - }); - } - getEndToEndSessionProblem(deviceKey, timestamp) { - return __awaiter(this, void 0, void 0, function* () { - const problems = this.sessionProblems[deviceKey] || []; - if (!problems.length) { - return null; - } - const lastProblem = problems[problems.length - 1]; - for (const problem of problems) { - if (problem.time > timestamp) { - return Object.assign({}, problem, { fixed: lastProblem.fixed }); - } - } - if (lastProblem.fixed) { - return null; - } - else { - return lastProblem; - } - }); - } - filterOutNotifiedErrorDevices(devices) { - return __awaiter(this, void 0, void 0, function* () { - const notifiedErrorDevices = this.notifiedErrorDevices; - const ret = []; - for (const device of devices) { - const { userId, deviceInfo } = device; - if (userId in notifiedErrorDevices) { - if (!(deviceInfo.deviceId in notifiedErrorDevices[userId])) { - ret.push(device); - (0, utils_1.safeSet)(notifiedErrorDevices[userId], deviceInfo.deviceId, true); - } - } - else { - ret.push(device); - (0, utils_1.safeSet)(notifiedErrorDevices, userId, { [deviceInfo.deviceId]: true }); - } - } - return ret; - }); - } - // Inbound Group Sessions - getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func) { - const k = senderCurve25519Key + "/" + sessionId; - func(this.inboundGroupSessions[k] || null, this.inboundGroupSessionsWithheld[k] || null); - } - getAllEndToEndInboundGroupSessions(txn, func) { - for (const key of Object.keys(this.inboundGroupSessions)) { - // we can't use split, as the components we are trying to split out - // might themselves contain '/' characters. We rely on the - // senderKey being a (32-byte) curve25519 key, base64-encoded - // (hence 43 characters long). - func({ - senderKey: key.slice(0, 43), - sessionId: key.slice(44), - sessionData: this.inboundGroupSessions[key], - }); - } - func(null); - } - addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) { - const k = senderCurve25519Key + "/" + sessionId; - if (this.inboundGroupSessions[k] === undefined) { - this.inboundGroupSessions[k] = sessionData; - } - } - storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn) { - this.inboundGroupSessions[senderCurve25519Key + "/" + sessionId] = sessionData; - } - storeEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId, sessionData, txn) { - const k = senderCurve25519Key + "/" + sessionId; - this.inboundGroupSessionsWithheld[k] = sessionData; - } - // Device Data - getEndToEndDeviceData(txn, func) { - func(this.deviceData); - } - storeEndToEndDeviceData(deviceData, txn) { - this.deviceData = deviceData; - } - // E2E rooms - storeEndToEndRoom(roomId, roomInfo, txn) { - this.rooms[roomId] = roomInfo; - } - getEndToEndRooms(txn, func) { - func(this.rooms); - } - getSessionsNeedingBackup(limit) { - const sessions = []; - for (const session in this.sessionsNeedingBackup) { - if (this.inboundGroupSessions[session]) { - sessions.push({ - senderKey: session.slice(0, 43), - sessionId: session.slice(44), - sessionData: this.inboundGroupSessions[session], - }); - if (limit && session.length >= limit) { - break; - } - } - } - return Promise.resolve(sessions); - } - countSessionsNeedingBackup() { - return Promise.resolve(Object.keys(this.sessionsNeedingBackup).length); - } - unmarkSessionsNeedingBackup(sessions) { - for (const session of sessions) { - const sessionKey = session.senderKey + "/" + session.sessionId; - delete this.sessionsNeedingBackup[sessionKey]; - } - return Promise.resolve(); - } - markSessionsNeedingBackup(sessions) { - for (const session of sessions) { - const sessionKey = session.senderKey + "/" + session.sessionId; - this.sessionsNeedingBackup[sessionKey] = true; - } - return Promise.resolve(); - } - addSharedHistoryInboundGroupSession(roomId, senderKey, sessionId) { - const sessions = this.sharedHistoryInboundGroupSessions[roomId] || []; - sessions.push([senderKey, sessionId]); - this.sharedHistoryInboundGroupSessions[roomId] = sessions; - } - getSharedHistoryInboundGroupSessions(roomId) { - return Promise.resolve(this.sharedHistoryInboundGroupSessions[roomId] || []); - } - addParkedSharedHistory(roomId, parkedData) { - var _a; - const parked = (_a = this.parkedSharedHistory.get(roomId)) !== null && _a !== void 0 ? _a : []; - parked.push(parkedData); - this.parkedSharedHistory.set(roomId, parked); - } - takeParkedSharedHistory(roomId) { - var _a; - const parked = (_a = this.parkedSharedHistory.get(roomId)) !== null && _a !== void 0 ? _a : []; - this.parkedSharedHistory.delete(roomId); - return Promise.resolve(parked); - } - // Session key backups - doTxn(mode, stores, func) { - return Promise.resolve(func(null)); - } -} -exports.MemoryCryptoStore = MemoryCryptoStore; - -},{"../../logger":374,"../../utils":416}],349:[function(require,module,exports){ -"use strict"; -/* -Copyright 2018 New Vector Ltd -Copyright 2020 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.VerificationBase = exports.VerificationEvent = exports.SwitchStartEventError = void 0; -/** - * Base class for verification methods. - */ -const event_1 = require("../../models/event"); -const event_2 = require("../../@types/event"); -const logger_1 = require("../../logger"); -const deviceinfo_1 = require("../deviceinfo"); -const Error_1 = require("./Error"); -const CrossSigning_1 = require("../CrossSigning"); -const typed_event_emitter_1 = require("../../models/typed-event-emitter"); -const timeoutException = new Error("Verification timed out"); -class SwitchStartEventError extends Error { - constructor(startEvent) { - super(); - this.startEvent = startEvent; - } -} -exports.SwitchStartEventError = SwitchStartEventError; -var VerificationEvent; -(function (VerificationEvent) { - VerificationEvent["Cancel"] = "cancel"; -})(VerificationEvent = exports.VerificationEvent || (exports.VerificationEvent = {})); -class VerificationBase extends typed_event_emitter_1.TypedEventEmitter { - /** - * Base class for verification methods. - * - *

Once a verifier object is created, the verification can be started by - * calling the verify() method, which will return a promise that will - * resolve when the verification is completed, or reject if it could not - * complete.

- * - *

Subclasses must have a NAME class property.

- * - * @param channel - the verification channel to send verification messages over. - * TODO: Channel types - * - * @param baseApis - base matrix api interface - * - * @param userId - the user ID that is being verified - * - * @param deviceId - the device ID that is being verified - * - * @param startEvent - the m.key.verification.start event that - * initiated this verification, if any - * - * @param request - the key verification request object related to - * this verification, if any - */ - constructor(channel, baseApis, userId, deviceId, startEvent, request) { - super(); - this.channel = channel; - this.baseApis = baseApis; - this.userId = userId; - this.deviceId = deviceId; - this.startEvent = startEvent; - this.request = request; - this.cancelled = false; - this._done = false; - this.promise = null; - this.transactionTimeoutTimer = null; - } - get initiatedByMe() { - // if there is no start event yet, - // we probably want to send it, - // which happens if we initiate - if (!this.startEvent) { - return true; - } - const sender = this.startEvent.getSender(); - const content = this.startEvent.getContent(); - return sender === this.baseApis.getUserId() && content.from_device === this.baseApis.getDeviceId(); - } - get hasBeenCancelled() { - return this.cancelled; - } - resetTimer() { - logger_1.logger.info("Refreshing/starting the verification transaction timeout timer"); - if (this.transactionTimeoutTimer !== null) { - clearTimeout(this.transactionTimeoutTimer); - } - this.transactionTimeoutTimer = setTimeout(() => { - if (!this._done && !this.cancelled) { - logger_1.logger.info("Triggering verification timeout"); - this.cancel(timeoutException); - } - }, 10 * 60 * 1000); // 10 minutes - } - endTimer() { - if (this.transactionTimeoutTimer !== null) { - clearTimeout(this.transactionTimeoutTimer); - this.transactionTimeoutTimer = null; - } - } - send(type, uncompletedContent) { - return this.channel.send(type, uncompletedContent); - } - waitForEvent(type) { - if (this._done) { - return Promise.reject(new Error("Verification is already done")); - } - const existingEvent = this.request.getEventFromOtherParty(type); - if (existingEvent) { - return Promise.resolve(existingEvent); - } - this.expectedEvent = type; - return new Promise((resolve, reject) => { - this.resolveEvent = resolve; - this.rejectEvent = reject; - }); - } - canSwitchStartEvent(event) { - return false; - } - switchStartEvent(event) { - if (this.canSwitchStartEvent(event)) { - logger_1.logger.log("Verification Base: switching verification start event", { restartingFlow: !!this.rejectEvent }); - if (this.rejectEvent) { - const reject = this.rejectEvent; - this.rejectEvent = undefined; - reject(new SwitchStartEventError(event)); - } - else { - this.startEvent = event; - } - } - } - handleEvent(e) { - var _a; - if (this._done) { - return; - } - else if (e.getType() === this.expectedEvent) { - // if we receive an expected m.key.verification.done, then just - // ignore it, since we don't need to do anything about it - if (this.expectedEvent !== event_2.EventType.KeyVerificationDone) { - this.expectedEvent = undefined; - this.rejectEvent = undefined; - this.resetTimer(); - (_a = this.resolveEvent) === null || _a === void 0 ? void 0 : _a.call(this, e); - } - } - else if (e.getType() === event_2.EventType.KeyVerificationCancel) { - const reject = this.reject; - this.reject = undefined; - // there is only promise to reject if verify has been called - if (reject) { - const content = e.getContent(); - const { reason, code } = content; - reject(new Error(`Other side cancelled verification ` + `because ${reason} (${code})`)); - } - } - else if (this.expectedEvent) { - // only cancel if there is an event expected. - // if there is no event expected, it means verify() wasn't called - // and we're just replaying the timeline events when syncing - // after a refresh when the events haven't been stored in the cache yet. - const exception = new Error("Unexpected message: expecting " + this.expectedEvent + " but got " + e.getType()); - this.expectedEvent = undefined; - if (this.rejectEvent) { - const reject = this.rejectEvent; - this.rejectEvent = undefined; - reject(exception); - } - this.cancel(exception); - } - } - done() { - var _a; - return __awaiter(this, void 0, void 0, function* () { - this.endTimer(); // always kill the activity timer - if (!this._done) { - this.request.onVerifierFinished(); - (_a = this.resolve) === null || _a === void 0 ? void 0 : _a.call(this); - return (0, CrossSigning_1.requestKeysDuringVerification)(this.baseApis, this.userId, this.deviceId); - } - }); - } - cancel(e) { - this.endTimer(); // always kill the activity timer - if (!this._done) { - this.cancelled = true; - this.request.onVerifierCancelled(); - if (this.userId && this.deviceId) { - // send a cancellation to the other user (if it wasn't - // cancelled by the other user) - if (e === timeoutException) { - const timeoutEvent = (0, Error_1.newTimeoutError)(); - this.send(timeoutEvent.getType(), timeoutEvent.getContent()); - } - else if (e instanceof event_1.MatrixEvent) { - const sender = e.getSender(); - if (sender !== this.userId) { - const content = e.getContent(); - if (e.getType() === event_2.EventType.KeyVerificationCancel) { - content.code = content.code || "m.unknown"; - content.reason = content.reason || content.body || "Unknown reason"; - this.send(event_2.EventType.KeyVerificationCancel, content); - } - else { - this.send(event_2.EventType.KeyVerificationCancel, { - code: "m.unknown", - reason: content.body || "Unknown reason", - }); - } - } - } - else { - this.send(event_2.EventType.KeyVerificationCancel, { - code: "m.unknown", - reason: e.toString(), - }); - } - } - if (this.promise !== null) { - // when we cancel without a promise, we end up with a promise - // but no reject function. If cancel is called again, we'd error. - if (this.reject) - this.reject(e); - } - else { - // FIXME: this causes an "Uncaught promise" console message - // if nothing ends up chaining this promise. - this.promise = Promise.reject(e); - } - // Also emit a 'cancel' event that the app can listen for to detect cancellation - // before calling verify() - this.emit(VerificationEvent.Cancel, e); - } - } - /** - * Begin the key verification - * - * @returns Promise which resolves when the verification has - * completed. - */ - verify() { - if (this.promise) - return this.promise; - this.promise = new Promise((resolve, reject) => { - this.resolve = (...args) => { - this._done = true; - this.endTimer(); - resolve(...args); - }; - this.reject = (e) => { - this._done = true; - this.endTimer(); - reject(e); - }; - }); - if (this.doVerification && !this.started) { - this.started = true; - this.resetTimer(); // restart the timeout - new Promise((resolve, reject) => { - var _a; - const crossSignId = (_a = this.baseApis.crypto.deviceList.getStoredCrossSigningForUser(this.userId)) === null || _a === void 0 ? void 0 : _a.getId(); - if (crossSignId === this.deviceId) { - reject(new Error("Device ID is the same as the cross-signing ID")); - } - resolve(); - }) - .then(() => this.doVerification()) - .then(this.done.bind(this), this.cancel.bind(this)); - } - return this.promise; - } - verifyKeys(userId, keys, verifier) { - return __awaiter(this, void 0, void 0, function* () { - // we try to verify all the keys that we're told about, but we might - // not know about all of them, so keep track of the keys that we know - // about, and ignore the rest - const verifiedDevices = []; - for (const [keyId, keyInfo] of Object.entries(keys)) { - const deviceId = keyId.split(":", 2)[1]; - const device = this.baseApis.getStoredDevice(userId, deviceId); - if (device) { - verifier(keyId, device, keyInfo); - verifiedDevices.push([deviceId, keyId, device.keys[keyId]]); - } - else { - const crossSigningInfo = this.baseApis.crypto.deviceList.getStoredCrossSigningForUser(userId); - if (crossSigningInfo && crossSigningInfo.getId() === deviceId) { - verifier(keyId, deviceinfo_1.DeviceInfo.fromStorage({ - keys: { - [keyId]: deviceId, - }, - }, deviceId), keyInfo); - verifiedDevices.push([deviceId, keyId, deviceId]); - } - else { - logger_1.logger.warn(`verification: Could not find device ${deviceId} to verify`); - } - } - } - // if none of the keys could be verified, then error because the app - // should be informed about that - if (!verifiedDevices.length) { - throw new Error("No devices could be verified"); - } - logger_1.logger.info("Verification completed! Marking devices verified: ", verifiedDevices); - // TODO: There should probably be a batch version of this, otherwise it's going - // to upload each signature in a separate API call which is silly because the - // API supports as many signatures as you like. - for (const [deviceId, keyId, key] of verifiedDevices) { - yield this.baseApis.crypto.setDeviceVerification(userId, deviceId, true, null, null, { [keyId]: key }); - } - // if one of the user's own devices is being marked as verified / unverified, - // check the key backup status, since whether or not we use this depends on - // whether it has a signature from a verified device - if (userId == this.baseApis.credentials.userId) { - yield this.baseApis.checkKeyBackup(); - } - }); - } - get events() { - return undefined; - } -} -exports.VerificationBase = VerificationBase; - -},{"../../@types/event":306,"../../logger":374,"../../models/event":383,"../../models/typed-event-emitter":395,"../CrossSigning":324,"../deviceinfo":340,"./Error":350}],350:[function(require,module,exports){ -"use strict"; -/* -Copyright 2018 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.errorFromEvent = exports.newInvalidMessageError = exports.newKeyMismatchError = exports.newUnexpectedMessageError = exports.newUnknownMethodError = exports.newTimeoutError = exports.newUserCancelledError = exports.errorFactory = exports.newVerificationError = void 0; -/** - * Error messages. - */ -const event_1 = require("../../models/event"); -const event_2 = require("../../@types/event"); -function newVerificationError(code, reason, extraData) { - const content = Object.assign({}, { code, reason }, extraData); - return new event_1.MatrixEvent({ - type: event_2.EventType.KeyVerificationCancel, - content, - }); -} -exports.newVerificationError = newVerificationError; -function errorFactory(code, reason) { - return function (extraData) { - return newVerificationError(code, reason, extraData); - }; -} -exports.errorFactory = errorFactory; -/** - * The verification was cancelled by the user. - */ -exports.newUserCancelledError = errorFactory("m.user", "Cancelled by user"); -/** - * The verification timed out. - */ -exports.newTimeoutError = errorFactory("m.timeout", "Timed out"); -/** - * An unknown method was selected. - */ -exports.newUnknownMethodError = errorFactory("m.unknown_method", "Unknown method"); -/** - * An unexpected message was sent. - */ -exports.newUnexpectedMessageError = errorFactory("m.unexpected_message", "Unexpected message"); -/** - * The key does not match. - */ -exports.newKeyMismatchError = errorFactory("m.key_mismatch", "Key mismatch"); -/** - * An invalid message was sent. - */ -exports.newInvalidMessageError = errorFactory("m.invalid_message", "Invalid message"); -function errorFromEvent(event) { - const content = event.getContent(); - if (content) { - const { code, reason } = content; - return { code, reason }; - } - else { - return { code: "Unknown error", reason: "m.unknown" }; - } -} -exports.errorFromEvent = errorFromEvent; - -},{"../../@types/event":306,"../../models/event":383}],351:[function(require,module,exports){ -"use strict"; -/* -Copyright 2020 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.IllegalMethod = void 0; -/** - * Verification method that is illegal to have (cannot possibly - * do verification with this method). - */ -const Base_1 = require("./Base"); -class IllegalMethod extends Base_1.VerificationBase { - constructor() { - super(...arguments); - this.doVerification = () => __awaiter(this, void 0, void 0, function* () { - throw new Error("Verification is not possible with this method"); - }); - } - static factory(channel, baseApis, userId, deviceId, startEvent, request) { - return new IllegalMethod(channel, baseApis, userId, deviceId, startEvent, request); - } - // eslint-disable-next-line @typescript-eslint/naming-convention - static get NAME() { - // Typically the name will be something else, but to complete - // the contract we offer a default one here. - return "org.matrix.illegal_method"; - } -} -exports.IllegalMethod = IllegalMethod; - -},{"./Base":349}],352:[function(require,module,exports){ -(function (global,Buffer){(function (){ -"use strict"; -/* -Copyright 2018 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.QRCodeData = exports.ReciprocateQRCode = exports.QrCodeEvent = exports.SCAN_QR_CODE_METHOD = exports.SHOW_QR_CODE_METHOD = void 0; -/** - * QR code key verification. - */ -const Base_1 = require("./Base"); -const Error_1 = require("./Error"); -const olmlib_1 = require("../olmlib"); -const logger_1 = require("../../logger"); -exports.SHOW_QR_CODE_METHOD = "m.qr_code.show.v1"; -exports.SCAN_QR_CODE_METHOD = "m.qr_code.scan.v1"; -var QrCodeEvent; -(function (QrCodeEvent) { - QrCodeEvent["ShowReciprocateQr"] = "show_reciprocate_qr"; -})(QrCodeEvent = exports.QrCodeEvent || (exports.QrCodeEvent = {})); -class ReciprocateQRCode extends Base_1.VerificationBase { - constructor() { - super(...arguments); - this.doVerification = () => __awaiter(this, void 0, void 0, function* () { - if (!this.startEvent) { - // TODO: Support scanning QR codes - throw new Error("It is not currently possible to start verification" + "with this method yet."); - } - const { qrCodeData } = this.request; - // 1. check the secret - if (this.startEvent.getContent()["secret"] !== (qrCodeData === null || qrCodeData === void 0 ? void 0 : qrCodeData.encodedSharedSecret)) { - throw (0, Error_1.newKeyMismatchError)(); - } - // 2. ask if other user shows shield as well - yield new Promise((resolve, reject) => { - this.reciprocateQREvent = { - confirm: resolve, - cancel: () => reject((0, Error_1.newUserCancelledError)()), - }; - this.emit(QrCodeEvent.ShowReciprocateQr, this.reciprocateQREvent); - }); - // 3. determine key to sign / mark as trusted - const keys = {}; - switch (qrCodeData === null || qrCodeData === void 0 ? void 0 : qrCodeData.mode) { - case Mode.VerifyOtherUser: { - // add master key to keys to be signed, only if we're not doing self-verification - const masterKey = qrCodeData.otherUserMasterKey; - keys[`ed25519:${masterKey}`] = masterKey; - break; - } - case Mode.VerifySelfTrusted: { - const deviceId = this.request.targetDevice.deviceId; - keys[`ed25519:${deviceId}`] = qrCodeData.otherDeviceKey; - break; - } - case Mode.VerifySelfUntrusted: { - const masterKey = qrCodeData.myMasterKey; - keys[`ed25519:${masterKey}`] = masterKey; - break; - } - } - // 4. sign the key (or mark own MSK as verified in case of MODE_VERIFY_SELF_TRUSTED) - yield this.verifyKeys(this.userId, keys, (keyId, device, keyInfo) => { - // make sure the device has the expected keys - const targetKey = keys[keyId]; - if (!targetKey) - throw (0, Error_1.newKeyMismatchError)(); - if (keyInfo !== targetKey) { - logger_1.logger.error("key ID from key info does not match"); - throw (0, Error_1.newKeyMismatchError)(); - } - for (const deviceKeyId in device.keys) { - if (!deviceKeyId.startsWith("ed25519")) - continue; - const deviceTargetKey = keys[deviceKeyId]; - if (!deviceTargetKey) - throw (0, Error_1.newKeyMismatchError)(); - if (device.keys[deviceKeyId] !== deviceTargetKey) { - logger_1.logger.error("master key does not match"); - throw (0, Error_1.newKeyMismatchError)(); - } - } - }); - }); - } - static factory(channel, baseApis, userId, deviceId, startEvent, request) { - return new ReciprocateQRCode(channel, baseApis, userId, deviceId, startEvent, request); - } - // eslint-disable-next-line @typescript-eslint/naming-convention - static get NAME() { - return "m.reciprocate.v1"; - } -} -exports.ReciprocateQRCode = ReciprocateQRCode; -const CODE_VERSION = 0x02; // the version of binary QR codes we support -const BINARY_PREFIX = "MATRIX"; // ASCII, used to prefix the binary format -var Mode; -(function (Mode) { - Mode[Mode["VerifyOtherUser"] = 0] = "VerifyOtherUser"; - Mode[Mode["VerifySelfTrusted"] = 1] = "VerifySelfTrusted"; - Mode[Mode["VerifySelfUntrusted"] = 2] = "VerifySelfUntrusted"; -})(Mode || (Mode = {})); -class QRCodeData { - constructor(mode, sharedSecret, - // only set when mode is MODE_VERIFY_OTHER_USER, master key of other party at time of generating QR code - otherUserMasterKey, - // only set when mode is MODE_VERIFY_SELF_TRUSTED, device key of other party at time of generating QR code - otherDeviceKey, - // only set when mode is MODE_VERIFY_SELF_UNTRUSTED, own master key at time of generating QR code - myMasterKey, buffer) { - this.mode = mode; - this.sharedSecret = sharedSecret; - this.otherUserMasterKey = otherUserMasterKey; - this.otherDeviceKey = otherDeviceKey; - this.myMasterKey = myMasterKey; - this.buffer = buffer; - } - static create(request, client) { - return __awaiter(this, void 0, void 0, function* () { - const sharedSecret = QRCodeData.generateSharedSecret(); - const mode = QRCodeData.determineMode(request, client); - let otherUserMasterKey = null; - let otherDeviceKey = null; - let myMasterKey = null; - if (mode === Mode.VerifyOtherUser) { - const otherUserCrossSigningInfo = client.getStoredCrossSigningForUser(request.otherUserId); - otherUserMasterKey = otherUserCrossSigningInfo.getId("master"); - } - else if (mode === Mode.VerifySelfTrusted) { - otherDeviceKey = yield QRCodeData.getOtherDeviceKey(request, client); - } - else if (mode === Mode.VerifySelfUntrusted) { - const myUserId = client.getUserId(); - const myCrossSigningInfo = client.getStoredCrossSigningForUser(myUserId); - myMasterKey = myCrossSigningInfo.getId("master"); - } - const qrData = QRCodeData.generateQrData(request, client, mode, sharedSecret, otherUserMasterKey, otherDeviceKey, myMasterKey); - const buffer = QRCodeData.generateBuffer(qrData); - return new QRCodeData(mode, sharedSecret, otherUserMasterKey, otherDeviceKey, myMasterKey, buffer); - }); - } - /** - * The unpadded base64 encoded shared secret. - */ - get encodedSharedSecret() { - return this.sharedSecret; - } - getBuffer() { - return this.buffer; - } - static generateSharedSecret() { - const secretBytes = new Uint8Array(11); - global.crypto.getRandomValues(secretBytes); - return (0, olmlib_1.encodeUnpaddedBase64)(secretBytes); - } - static getOtherDeviceKey(request, client) { - return __awaiter(this, void 0, void 0, function* () { - const myUserId = client.getUserId(); - const otherDevice = request.targetDevice; - const device = otherDevice.deviceId ? client.getStoredDevice(myUserId, otherDevice.deviceId) : undefined; - if (!device) { - throw new Error("could not find device " + (otherDevice === null || otherDevice === void 0 ? void 0 : otherDevice.deviceId)); - } - return device.getFingerprint(); - }); - } - static determineMode(request, client) { - const myUserId = client.getUserId(); - const otherUserId = request.otherUserId; - let mode = Mode.VerifyOtherUser; - if (myUserId === otherUserId) { - // Mode changes depending on whether or not we trust the master cross signing key - const myTrust = client.checkUserTrust(myUserId); - if (myTrust.isCrossSigningVerified()) { - mode = Mode.VerifySelfTrusted; - } - else { - mode = Mode.VerifySelfUntrusted; - } - } - return mode; - } - static generateQrData(request, client, mode, encodedSharedSecret, otherUserMasterKey, otherDeviceKey, myMasterKey) { - const myUserId = client.getUserId(); - const transactionId = request.channel.transactionId; - const qrData = { - prefix: BINARY_PREFIX, - version: CODE_VERSION, - mode, - transactionId, - firstKeyB64: "", - secondKeyB64: "", - secretB64: encodedSharedSecret, - }; - const myCrossSigningInfo = client.getStoredCrossSigningForUser(myUserId); - if (mode === Mode.VerifyOtherUser) { - // First key is our master cross signing key - qrData.firstKeyB64 = myCrossSigningInfo.getId("master"); - // Second key is the other user's master cross signing key - qrData.secondKeyB64 = otherUserMasterKey; - } - else if (mode === Mode.VerifySelfTrusted) { - // First key is our master cross signing key - qrData.firstKeyB64 = myCrossSigningInfo.getId("master"); - qrData.secondKeyB64 = otherDeviceKey; - } - else if (mode === Mode.VerifySelfUntrusted) { - // First key is our device's key - qrData.firstKeyB64 = client.getDeviceEd25519Key(); - // Second key is what we think our master cross signing key is - qrData.secondKeyB64 = myMasterKey; - } - return qrData; - } - static generateBuffer(qrData) { - let buf = Buffer.alloc(0); // we'll concat our way through life - const appendByte = (b) => { - const tmpBuf = Buffer.from([b]); - buf = Buffer.concat([buf, tmpBuf]); - }; - const appendInt = (i) => { - const tmpBuf = Buffer.alloc(2); - tmpBuf.writeInt16BE(i, 0); - buf = Buffer.concat([buf, tmpBuf]); - }; - const appendStr = (s, enc, withLengthPrefix = true) => { - const tmpBuf = Buffer.from(s, enc); - if (withLengthPrefix) - appendInt(tmpBuf.byteLength); - buf = Buffer.concat([buf, tmpBuf]); - }; - const appendEncBase64 = (b64) => { - const b = (0, olmlib_1.decodeBase64)(b64); - const tmpBuf = Buffer.from(b); - buf = Buffer.concat([buf, tmpBuf]); - }; - // Actually build the buffer for the QR code - appendStr(qrData.prefix, "ascii", false); - appendByte(qrData.version); - appendByte(qrData.mode); - appendStr(qrData.transactionId, "utf-8"); - appendEncBase64(qrData.firstKeyB64); - appendEncBase64(qrData.secondKeyB64); - appendEncBase64(qrData.secretB64); - return buf; - } -} -exports.QRCodeData = QRCodeData; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) - -},{"../../logger":374,"../olmlib":343,"./Base":349,"./Error":350,"buffer":68}],353:[function(require,module,exports){ -(function (global){(function (){ -"use strict"; -/* -Copyright 2018 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SAS = exports.SasEvent = void 0; -/** - * Short Authentication String (SAS) verification. - */ -const another_json_1 = __importDefault(require("another-json")); -const Base_1 = require("./Base"); -const Error_1 = require("./Error"); -const logger_1 = require("../../logger"); -const SASDecimal_1 = require("./SASDecimal"); -const event_1 = require("../../@types/event"); -const START_TYPE = event_1.EventType.KeyVerificationStart; -const EVENTS = [event_1.EventType.KeyVerificationAccept, event_1.EventType.KeyVerificationKey, event_1.EventType.KeyVerificationMac]; -let olmutil; -const newMismatchedSASError = (0, Error_1.errorFactory)("m.mismatched_sas", "Mismatched short authentication string"); -const newMismatchedCommitmentError = (0, Error_1.errorFactory)("m.mismatched_commitment", "Mismatched commitment"); -const emojiMapping = [ - ["🐶", "dog"], - ["🐱", "cat"], - ["🦁", "lion"], - ["🐎", "horse"], - ["🦄", "unicorn"], - ["🐷", "pig"], - ["🐘", "elephant"], - ["🐰", "rabbit"], - ["🐼", "panda"], - ["🐓", "rooster"], - ["🐧", "penguin"], - ["🐢", "turtle"], - ["🐟", "fish"], - ["🐙", "octopus"], - ["🦋", "butterfly"], - ["🌷", "flower"], - ["🌳", "tree"], - ["🌵", "cactus"], - ["🍄", "mushroom"], - ["🌏", "globe"], - ["🌙", "moon"], - ["☁️", "cloud"], - ["🔥", "fire"], - ["🍌", "banana"], - ["🍎", "apple"], - ["🍓", "strawberry"], - ["🌽", "corn"], - ["🍕", "pizza"], - ["🎂", "cake"], - ["❤️", "heart"], - ["🙂", "smiley"], - ["🤖", "robot"], - ["🎩", "hat"], - ["👓", "glasses"], - ["🔧", "spanner"], - ["🎅", "santa"], - ["👍", "thumbs up"], - ["☂️", "umbrella"], - ["⌛", "hourglass"], - ["⏰", "clock"], - ["🎁", "gift"], - ["💡", "light bulb"], - ["📕", "book"], - ["✏️", "pencil"], - ["📎", "paperclip"], - ["✂️", "scissors"], - ["🔒", "lock"], - ["🔑", "key"], - ["🔨", "hammer"], - ["☎️", "telephone"], - ["🏁", "flag"], - ["🚂", "train"], - ["🚲", "bicycle"], - ["✈️", "aeroplane"], - ["🚀", "rocket"], - ["🏆", "trophy"], - ["⚽", "ball"], - ["🎸", "guitar"], - ["🎺", "trumpet"], - ["🔔", "bell"], - ["⚓️", "anchor"], - ["🎧", "headphones"], - ["📁", "folder"], - ["📌", "pin"], // 63 -]; -function generateEmojiSas(sasBytes) { - const emojis = [ - // just like base64 encoding - sasBytes[0] >> 2, - ((sasBytes[0] & 0x3) << 4) | (sasBytes[1] >> 4), - ((sasBytes[1] & 0xf) << 2) | (sasBytes[2] >> 6), - sasBytes[2] & 0x3f, - sasBytes[3] >> 2, - ((sasBytes[3] & 0x3) << 4) | (sasBytes[4] >> 4), - ((sasBytes[4] & 0xf) << 2) | (sasBytes[5] >> 6), - ]; - return emojis.map((num) => emojiMapping[num]); -} -const sasGenerators = { - decimal: SASDecimal_1.generateDecimalSas, - emoji: generateEmojiSas, -}; -function generateSas(sasBytes, methods) { - const sas = {}; - for (const method of methods) { - if (method in sasGenerators) { - // @ts-ignore - ts doesn't like us mixing types like this - sas[method] = sasGenerators[method](Array.from(sasBytes)); - } - } - return sas; -} -const macMethods = { - "hkdf-hmac-sha256": "calculate_mac", - "org.matrix.msc3783.hkdf-hmac-sha256": "calculate_mac_fixed_base64", - "hkdf-hmac-sha256.v2": "calculate_mac_fixed_base64", - "hmac-sha256": "calculate_mac_long_kdf", -}; -function calculateMAC(olmSAS, method) { - return function (input, info) { - const mac = olmSAS[macMethods[method]](input, info); - logger_1.logger.log("SAS calculateMAC:", method, [input, info], mac); - return mac; - }; -} -const calculateKeyAgreement = { - // eslint-disable-next-line @typescript-eslint/naming-convention - "curve25519-hkdf-sha256": function (sas, olmSAS, bytes) { - const ourInfo = `${sas.baseApis.getUserId()}|${sas.baseApis.deviceId}|` + `${sas.ourSASPubKey}|`; - const theirInfo = `${sas.userId}|${sas.deviceId}|${sas.theirSASPubKey}|`; - const sasInfo = "MATRIX_KEY_VERIFICATION_SAS|" + - (sas.initiatedByMe ? ourInfo + theirInfo : theirInfo + ourInfo) + - sas.channel.transactionId; - return olmSAS.generate_bytes(sasInfo, bytes); - }, - "curve25519": function (sas, olmSAS, bytes) { - const ourInfo = `${sas.baseApis.getUserId()}${sas.baseApis.deviceId}`; - const theirInfo = `${sas.userId}${sas.deviceId}`; - const sasInfo = "MATRIX_KEY_VERIFICATION_SAS" + - (sas.initiatedByMe ? ourInfo + theirInfo : theirInfo + ourInfo) + - sas.channel.transactionId; - return olmSAS.generate_bytes(sasInfo, bytes); - }, -}; -/* lists of algorithms/methods that are supported. The key agreement, hashes, - * and MAC lists should be sorted in order of preference (most preferred - * first). - */ -const KEY_AGREEMENT_LIST = ["curve25519-hkdf-sha256", "curve25519"]; -const HASHES_LIST = ["sha256"]; -const MAC_LIST = [ - "hkdf-hmac-sha256.v2", - "org.matrix.msc3783.hkdf-hmac-sha256", - "hkdf-hmac-sha256", - "hmac-sha256", -]; -const SAS_LIST = Object.keys(sasGenerators); -const KEY_AGREEMENT_SET = new Set(KEY_AGREEMENT_LIST); -const HASHES_SET = new Set(HASHES_LIST); -const MAC_SET = new Set(MAC_LIST); -const SAS_SET = new Set(SAS_LIST); -function intersection(anArray, aSet) { - return Array.isArray(anArray) ? anArray.filter((x) => aSet.has(x)) : []; -} -var SasEvent; -(function (SasEvent) { - SasEvent["ShowSas"] = "show_sas"; -})(SasEvent = exports.SasEvent || (exports.SasEvent = {})); -class SAS extends Base_1.VerificationBase { - constructor() { - super(...arguments); - this.doVerification = () => __awaiter(this, void 0, void 0, function* () { - yield global.Olm.init(); - olmutil = olmutil || new global.Olm.Utility(); - // make sure user's keys are downloaded - yield this.baseApis.downloadKeys([this.userId]); - let retry = false; - do { - try { - if (this.initiatedByMe) { - return yield this.doSendVerification(); - } - else { - return yield this.doRespondVerification(); - } - } - catch (err) { - if (err instanceof Base_1.SwitchStartEventError) { - // this changes what initiatedByMe returns - this.startEvent = err.startEvent; - retry = true; - } - else { - throw err; - } - } - } while (retry); - }); - } - // eslint-disable-next-line @typescript-eslint/naming-convention - static get NAME() { - return "m.sas.v1"; - } - get events() { - return EVENTS; - } - canSwitchStartEvent(event) { - if (event.getType() !== START_TYPE) { - return false; - } - const content = event.getContent(); - return (content === null || content === void 0 ? void 0 : content.method) === SAS.NAME && !!this.waitingForAccept; - } - sendStart() { - return __awaiter(this, void 0, void 0, function* () { - const startContent = this.channel.completeContent(START_TYPE, { - method: SAS.NAME, - from_device: this.baseApis.deviceId, - key_agreement_protocols: KEY_AGREEMENT_LIST, - hashes: HASHES_LIST, - message_authentication_codes: MAC_LIST, - // FIXME: allow app to specify what SAS methods can be used - short_authentication_string: SAS_LIST, - }); - yield this.channel.sendCompleted(START_TYPE, startContent); - return startContent; - }); - } - verifyAndCheckMAC(keyAgreement, sasMethods, olmSAS, macMethod) { - return __awaiter(this, void 0, void 0, function* () { - const sasBytes = calculateKeyAgreement[keyAgreement](this, olmSAS, 6); - const verifySAS = new Promise((resolve, reject) => { - this.sasEvent = { - sas: generateSas(sasBytes, sasMethods), - confirm: () => __awaiter(this, void 0, void 0, function* () { - try { - yield this.sendMAC(olmSAS, macMethod); - resolve(); - } - catch (err) { - reject(err); - } - }), - cancel: () => reject((0, Error_1.newUserCancelledError)()), - mismatch: () => reject(newMismatchedSASError()), - }; - this.emit(SasEvent.ShowSas, this.sasEvent); - }); - const [e] = yield Promise.all([ - this.waitForEvent(event_1.EventType.KeyVerificationMac).then((e) => { - // we don't expect any more messages from the other - // party, and they may send a m.key.verification.done - // when they're done on their end - this.expectedEvent = event_1.EventType.KeyVerificationDone; - return e; - }), - verifySAS, - ]); - const content = e.getContent(); - yield this.checkMAC(olmSAS, content, macMethod); - }); - } - doSendVerification() { - return __awaiter(this, void 0, void 0, function* () { - this.waitingForAccept = true; - let startContent; - if (this.startEvent) { - startContent = this.channel.completedContentFromEvent(this.startEvent); - } - else { - startContent = yield this.sendStart(); - } - // we might have switched to a different start event, - // but was we didn't call _waitForEvent there was no - // call that could throw yet. So check manually that - // we're still on the initiator side - if (!this.initiatedByMe) { - throw new Base_1.SwitchStartEventError(this.startEvent); - } - let e; - try { - e = yield this.waitForEvent(event_1.EventType.KeyVerificationAccept); - } - finally { - this.waitingForAccept = false; - } - let content = e.getContent(); - const sasMethods = intersection(content.short_authentication_string, SAS_SET); - if (!(KEY_AGREEMENT_SET.has(content.key_agreement_protocol) && - HASHES_SET.has(content.hash) && - MAC_SET.has(content.message_authentication_code) && - sasMethods.length)) { - throw (0, Error_1.newUnknownMethodError)(); - } - if (typeof content.commitment !== "string") { - throw (0, Error_1.newInvalidMessageError)(); - } - const keyAgreement = content.key_agreement_protocol; - const macMethod = content.message_authentication_code; - const hashCommitment = content.commitment; - const olmSAS = new global.Olm.SAS(); - try { - this.ourSASPubKey = olmSAS.get_pubkey(); - yield this.send(event_1.EventType.KeyVerificationKey, { - key: this.ourSASPubKey, - }); - e = yield this.waitForEvent(event_1.EventType.KeyVerificationKey); - // FIXME: make sure event is properly formed - content = e.getContent(); - const commitmentStr = content.key + another_json_1.default.stringify(startContent); - // TODO: use selected hash function (when we support multiple) - if (olmutil.sha256(commitmentStr) !== hashCommitment) { - throw newMismatchedCommitmentError(); - } - this.theirSASPubKey = content.key; - olmSAS.set_their_key(content.key); - yield this.verifyAndCheckMAC(keyAgreement, sasMethods, olmSAS, macMethod); - } - finally { - olmSAS.free(); - } - }); - } - doRespondVerification() { - return __awaiter(this, void 0, void 0, function* () { - // as m.related_to is not included in the encrypted content in e2e rooms, - // we need to make sure it is added - let content = this.channel.completedContentFromEvent(this.startEvent); - // Note: we intersect using our pre-made lists, rather than the sets, - // so that the result will be in our order of preference. Then - // fetching the first element from the array will give our preferred - // method out of the ones offered by the other party. - const keyAgreement = intersection(KEY_AGREEMENT_LIST, new Set(content.key_agreement_protocols))[0]; - const hashMethod = intersection(HASHES_LIST, new Set(content.hashes))[0]; - const macMethod = intersection(MAC_LIST, new Set(content.message_authentication_codes))[0]; - // FIXME: allow app to specify what SAS methods can be used - const sasMethods = intersection(content.short_authentication_string, SAS_SET); - if (!(keyAgreement !== undefined && hashMethod !== undefined && macMethod !== undefined && sasMethods.length)) { - throw (0, Error_1.newUnknownMethodError)(); - } - const olmSAS = new global.Olm.SAS(); - try { - const commitmentStr = olmSAS.get_pubkey() + another_json_1.default.stringify(content); - yield this.send(event_1.EventType.KeyVerificationAccept, { - key_agreement_protocol: keyAgreement, - hash: hashMethod, - message_authentication_code: macMethod, - short_authentication_string: sasMethods, - // TODO: use selected hash function (when we support multiple) - commitment: olmutil.sha256(commitmentStr), - }); - const e = yield this.waitForEvent(event_1.EventType.KeyVerificationKey); - // FIXME: make sure event is properly formed - content = e.getContent(); - this.theirSASPubKey = content.key; - olmSAS.set_their_key(content.key); - this.ourSASPubKey = olmSAS.get_pubkey(); - yield this.send(event_1.EventType.KeyVerificationKey, { - key: this.ourSASPubKey, - }); - yield this.verifyAndCheckMAC(keyAgreement, sasMethods, olmSAS, macMethod); - } - finally { - olmSAS.free(); - } - }); - } - sendMAC(olmSAS, method) { - const mac = {}; - const keyList = []; - const baseInfo = "MATRIX_KEY_VERIFICATION_MAC" + - this.baseApis.getUserId() + - this.baseApis.deviceId + - this.userId + - this.deviceId + - this.channel.transactionId; - const deviceKeyId = `ed25519:${this.baseApis.deviceId}`; - mac[deviceKeyId] = calculateMAC(olmSAS, method)(this.baseApis.getDeviceEd25519Key(), baseInfo + deviceKeyId); - keyList.push(deviceKeyId); - const crossSigningId = this.baseApis.getCrossSigningId(); - if (crossSigningId) { - const crossSigningKeyId = `ed25519:${crossSigningId}`; - mac[crossSigningKeyId] = calculateMAC(olmSAS, method)(crossSigningId, baseInfo + crossSigningKeyId); - keyList.push(crossSigningKeyId); - } - const keys = calculateMAC(olmSAS, method)(keyList.sort().join(","), baseInfo + "KEY_IDS"); - return this.send(event_1.EventType.KeyVerificationMac, { mac, keys }); - } - checkMAC(olmSAS, content, method) { - return __awaiter(this, void 0, void 0, function* () { - const baseInfo = "MATRIX_KEY_VERIFICATION_MAC" + - this.userId + - this.deviceId + - this.baseApis.getUserId() + - this.baseApis.deviceId + - this.channel.transactionId; - if (content.keys !== - calculateMAC(olmSAS, method)(Object.keys(content.mac).sort().join(","), baseInfo + "KEY_IDS")) { - throw (0, Error_1.newKeyMismatchError)(); - } - yield this.verifyKeys(this.userId, content.mac, (keyId, device, keyInfo) => { - if (keyInfo !== calculateMAC(olmSAS, method)(device.keys[keyId], baseInfo + keyId)) { - throw (0, Error_1.newKeyMismatchError)(); - } - }); - }); - } -} -exports.SAS = SAS; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"../../@types/event":306,"../../logger":374,"./Base":349,"./Error":350,"./SASDecimal":354,"another-json":1}],354:[function(require,module,exports){ -"use strict"; -/* -Copyright 2018 - 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.generateDecimalSas = void 0; -/** - * Implementation of decimal encoding of SAS as per: - * https://spec.matrix.org/v1.4/client-server-api/#sas-method-decimal - * @param sasBytes - the five bytes generated by HKDF - * @returns the derived three numbers between 1000 and 9191 inclusive - */ -function generateDecimalSas(sasBytes) { - /* - * +--------+--------+--------+--------+--------+ - * | Byte 0 | Byte 1 | Byte 2 | Byte 3 | Byte 4 | - * +--------+--------+--------+--------+--------+ - * bits: 87654321 87654321 87654321 87654321 87654321 - * \____________/\_____________/\____________/ - * 1st number 2nd number 3rd number - */ - return [ - ((sasBytes[0] << 5) | (sasBytes[1] >> 3)) + 1000, - (((sasBytes[1] & 0x7) << 10) | (sasBytes[2] << 2) | (sasBytes[3] >> 6)) + 1000, - (((sasBytes[3] & 0x3f) << 7) | (sasBytes[4] >> 1)) + 1000, - ]; -} -exports.generateDecimalSas = generateDecimalSas; - -},{}],355:[function(require,module,exports){ -"use strict"; -/* -Copyright 2018 New Vector Ltd -Copyright 2019 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.InRoomRequests = exports.InRoomChannel = void 0; -const VerificationRequest_1 = require("./VerificationRequest"); -const logger_1 = require("../../../logger"); -const event_1 = require("../../../@types/event"); -const MESSAGE_TYPE = event_1.EventType.RoomMessage; -const M_REFERENCE = "m.reference"; -const M_RELATES_TO = "m.relates_to"; -/** - * A key verification channel that sends verification events in the timeline of a room. - * Uses the event id of the initial m.key.verification.request event as a transaction id. - */ -class InRoomChannel { - /** - * @param client - the matrix client, to send messages with and get current user & device from. - * @param roomId - id of the room where verification events should be posted in, should be a DM with the given user. - * @param userId - id of user that the verification request is directed at, should be present in the room. - */ - constructor(client, roomId, userId) { - this.client = client; - this.roomId = roomId; - this.userId = userId; - } - get receiveStartFromOtherDevices() { - return true; - } - /** The transaction id generated/used by this verification channel */ - get transactionId() { - return this.requestEventId; - } - static getOtherPartyUserId(event, client) { - const type = InRoomChannel.getEventType(event); - if (type !== VerificationRequest_1.REQUEST_TYPE) { - return; - } - const ownUserId = client.getUserId(); - const sender = event.getSender(); - const content = event.getContent(); - const receiver = content.to; - if (sender === ownUserId) { - return receiver; - } - else if (receiver === ownUserId) { - return sender; - } - } - /** - * @param event - the event to get the timestamp of - * @returns the timestamp when the event was sent - */ - getTimestamp(event) { - return event.getTs(); - } - /** - * Checks whether the given event type should be allowed to initiate a new VerificationRequest over this channel - * @param type - the event type to check - * @returns boolean flag - */ - static canCreateRequest(type) { - return type === VerificationRequest_1.REQUEST_TYPE; - } - canCreateRequest(type) { - return InRoomChannel.canCreateRequest(type); - } - /** - * Extract the transaction id used by a given key verification event, if any - * @param event - the event - * @returns the transaction id - */ - static getTransactionId(event) { - if (InRoomChannel.getEventType(event) === VerificationRequest_1.REQUEST_TYPE) { - return event.getId(); - } - else { - const relation = event.getRelation(); - if ((relation === null || relation === void 0 ? void 0 : relation.rel_type) === M_REFERENCE) { - return relation.event_id; - } - } - } - /** - * Checks whether this event is a well-formed key verification event. - * This only does checks that don't rely on the current state of a potentially already channel - * so we can prevent channels being created by invalid events. - * `handleEvent` can do more checks and choose to ignore invalid events. - * @param event - the event to validate - * @param client - the client to get the current user and device id from - * @returns whether the event is valid and should be passed to handleEvent - */ - static validateEvent(event, client) { - const txnId = InRoomChannel.getTransactionId(event); - if (typeof txnId !== "string" || txnId.length === 0) { - return false; - } - const type = InRoomChannel.getEventType(event); - const content = event.getContent(); - // from here on we're fairly sure that this is supposed to be - // part of a verification request, so be noisy when rejecting something - if (type === VerificationRequest_1.REQUEST_TYPE) { - if (!content || typeof content.to !== "string" || !content.to.length) { - logger_1.logger.log("InRoomChannel: validateEvent: " + "no valid to " + (content && content.to)); - return false; - } - // ignore requests that are not direct to or sent by the syncing user - if (!InRoomChannel.getOtherPartyUserId(event, client)) { - logger_1.logger.log("InRoomChannel: validateEvent: " + - `not directed to or sent by me: ${event.getSender()}` + - `, ${content && content.to}`); - return false; - } - } - return VerificationRequest_1.VerificationRequest.validateEvent(type, event, client); - } - /** - * As m.key.verification.request events are as m.room.message events with the InRoomChannel - * to have a fallback message in non-supporting clients, we map the real event type - * to the symbolic one to keep things in unison with ToDeviceChannel - * @param event - the event to get the type of - * @returns the "symbolic" event type - */ - static getEventType(event) { - const type = event.getType(); - if (type === MESSAGE_TYPE) { - const content = event.getContent(); - if (content) { - const { msgtype } = content; - if (msgtype === VerificationRequest_1.REQUEST_TYPE) { - return VerificationRequest_1.REQUEST_TYPE; - } - } - } - if (type && type !== VerificationRequest_1.REQUEST_TYPE) { - return type; - } - else { - return ""; - } - } - /** - * Changes the state of the channel, request, and verifier in response to a key verification event. - * @param event - to handle - * @param request - the request to forward handling to - * @param isLiveEvent - whether this is an even received through sync or not - * @returns a promise that resolves when any requests as an answer to the passed-in event are sent. - */ - handleEvent(event, request, isLiveEvent = false) { - return __awaiter(this, void 0, void 0, function* () { - // prevent processing the same event multiple times, as under - // some circumstances Room.timeline can get emitted twice for the same event - if (request.hasEventId(event.getId())) { - return; - } - const type = InRoomChannel.getEventType(event); - // do validations that need state (roomId, userId), - // ignore if invalid - if (event.getRoomId() !== this.roomId) { - return; - } - // set userId if not set already - if (!this.userId) { - const userId = InRoomChannel.getOtherPartyUserId(event, this.client); - if (userId) { - this.userId = userId; - } - } - // ignore events not sent by us or the other party - const ownUserId = this.client.getUserId(); - const sender = event.getSender(); - if (this.userId) { - if (sender !== ownUserId && sender !== this.userId) { - logger_1.logger.log(`InRoomChannel: ignoring verification event from non-participating sender ${sender}`); - return; - } - } - if (!this.requestEventId) { - this.requestEventId = InRoomChannel.getTransactionId(event); - } - const isRemoteEcho = !!event.getUnsigned().transaction_id; - const isSentByUs = event.getSender() === this.client.getUserId(); - return request.handleEvent(type, event, isLiveEvent, isRemoteEcho, isSentByUs); - }); - } - /** - * Adds the transaction id (relation) back to a received event - * so it has the same format as returned by `completeContent` before sending. - * The relation can not appear on the event content because of encryption, - * relations are excluded from encryption. - * @param event - the received event - * @returns the content object with the relation added again - */ - completedContentFromEvent(event) { - // ensure m.related_to is included in e2ee rooms - // as the field is excluded from encryption - const content = Object.assign({}, event.getContent()); - content[M_RELATES_TO] = event.getRelation(); - return content; - } - /** - * Add all the fields to content needed for sending it over this channel. - * This is public so verification methods (SAS uses this) can get the exact - * content that will be sent independent of the used channel, - * as they need to calculate the hash of it. - * @param type - the event type - * @param content - the (incomplete) content - * @returns the complete content, as it will be sent. - */ - completeContent(type, content) { - content = Object.assign({}, content); - if (type === VerificationRequest_1.REQUEST_TYPE || type === VerificationRequest_1.READY_TYPE || type === VerificationRequest_1.START_TYPE) { - content.from_device = this.client.getDeviceId(); - } - if (type === VerificationRequest_1.REQUEST_TYPE) { - // type is mapped to m.room.message in the send method - content = { - body: this.client.getUserId() + - " is requesting to verify " + - "your key, but your client does not support in-chat key " + - "verification. You will need to use legacy key " + - "verification to verify keys.", - msgtype: VerificationRequest_1.REQUEST_TYPE, - to: this.userId, - from_device: content.from_device, - methods: content.methods, - }; - } - else { - content[M_RELATES_TO] = { - rel_type: M_REFERENCE, - event_id: this.transactionId, - }; - } - return content; - } - /** - * Send an event over the channel with the content not having gone through `completeContent`. - * @param type - the event type - * @param uncompletedContent - the (incomplete) content - * @returns the promise of the request - */ - send(type, uncompletedContent) { - const content = this.completeContent(type, uncompletedContent); - return this.sendCompleted(type, content); - } - /** - * Send an event over the channel with the content having gone through `completeContent` already. - * @param type - the event type - * @returns the promise of the request - */ - sendCompleted(type, content) { - return __awaiter(this, void 0, void 0, function* () { - let sendType = type; - if (type === VerificationRequest_1.REQUEST_TYPE) { - sendType = MESSAGE_TYPE; - } - const response = yield this.client.sendEvent(this.roomId, sendType, content); - if (type === VerificationRequest_1.REQUEST_TYPE) { - this.requestEventId = response.event_id; - } - }); - } -} -exports.InRoomChannel = InRoomChannel; -class InRoomRequests { - constructor() { - this.requestsByRoomId = new Map(); - } - getRequest(event) { - const roomId = event.getRoomId(); - const txnId = InRoomChannel.getTransactionId(event); - return this.getRequestByTxnId(roomId, txnId); - } - getRequestByChannel(channel) { - return this.getRequestByTxnId(channel.roomId, channel.transactionId); - } - getRequestByTxnId(roomId, txnId) { - const requestsByTxnId = this.requestsByRoomId.get(roomId); - if (requestsByTxnId) { - return requestsByTxnId.get(txnId); - } - } - setRequest(event, request) { - this.doSetRequest(event.getRoomId(), InRoomChannel.getTransactionId(event), request); - } - setRequestByChannel(channel, request) { - this.doSetRequest(channel.roomId, channel.transactionId, request); - } - doSetRequest(roomId, txnId, request) { - let requestsByTxnId = this.requestsByRoomId.get(roomId); - if (!requestsByTxnId) { - requestsByTxnId = new Map(); - this.requestsByRoomId.set(roomId, requestsByTxnId); - } - requestsByTxnId.set(txnId, request); - } - removeRequest(event) { - const roomId = event.getRoomId(); - const requestsByTxnId = this.requestsByRoomId.get(roomId); - if (requestsByTxnId) { - requestsByTxnId.delete(InRoomChannel.getTransactionId(event)); - if (requestsByTxnId.size === 0) { - this.requestsByRoomId.delete(roomId); - } - } - } - findRequestInProgress(roomId) { - const requestsByTxnId = this.requestsByRoomId.get(roomId); - if (requestsByTxnId) { - for (const request of requestsByTxnId.values()) { - if (request.pending) { - return request; - } - } - } - } -} -exports.InRoomRequests = InRoomRequests; - -},{"../../../@types/event":306,"../../../logger":374,"./VerificationRequest":357}],356:[function(require,module,exports){ -"use strict"; -/* -Copyright 2018 New Vector Ltd -Copyright 2019 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ToDeviceRequests = exports.ToDeviceChannel = void 0; -const randomstring_1 = require("../../../randomstring"); -const logger_1 = require("../../../logger"); -const VerificationRequest_1 = require("./VerificationRequest"); -const Error_1 = require("../Error"); -const event_1 = require("../../../models/event"); -/** - * A key verification channel that sends verification events over to_device messages. - * Generates its own transaction ids. - */ -class ToDeviceChannel { - // userId and devices of user we're about to verify - constructor(client, userId, devices, transactionId, deviceId) { - this.client = client; - this.userId = userId; - this.devices = devices; - this.transactionId = transactionId; - this.deviceId = deviceId; - } - isToDevices(devices) { - if (devices.length === this.devices.length) { - for (const device of devices) { - if (!this.devices.includes(device)) { - return false; - } - } - return true; - } - else { - return false; - } - } - static getEventType(event) { - return event.getType(); - } - /** - * Extract the transaction id used by a given key verification event, if any - * @param event - the event - * @returns the transaction id - */ - static getTransactionId(event) { - const content = event.getContent(); - return content && content.transaction_id; - } - /** - * Checks whether the given event type should be allowed to initiate a new VerificationRequest over this channel - * @param type - the event type to check - * @returns boolean flag - */ - static canCreateRequest(type) { - return type === VerificationRequest_1.REQUEST_TYPE || type === VerificationRequest_1.START_TYPE; - } - canCreateRequest(type) { - return ToDeviceChannel.canCreateRequest(type); - } - /** - * Checks whether this event is a well-formed key verification event. - * This only does checks that don't rely on the current state of a potentially already channel - * so we can prevent channels being created by invalid events. - * `handleEvent` can do more checks and choose to ignore invalid events. - * @param event - the event to validate - * @param client - the client to get the current user and device id from - * @returns whether the event is valid and should be passed to handleEvent - */ - static validateEvent(event, client) { - if (event.isCancelled()) { - logger_1.logger.warn("Ignoring flagged verification request from " + event.getSender()); - return false; - } - const content = event.getContent(); - if (!content) { - logger_1.logger.warn("ToDeviceChannel.validateEvent: invalid: no content"); - return false; - } - if (!content.transaction_id) { - logger_1.logger.warn("ToDeviceChannel.validateEvent: invalid: no transaction_id"); - return false; - } - const type = event.getType(); - if (type === VerificationRequest_1.REQUEST_TYPE) { - if (!Number.isFinite(content.timestamp)) { - logger_1.logger.warn("ToDeviceChannel.validateEvent: invalid: no timestamp"); - return false; - } - if (event.getSender() === client.getUserId() && content.from_device == client.getDeviceId()) { - // ignore requests from ourselves, because it doesn't make sense for a - // device to verify itself - logger_1.logger.warn("ToDeviceChannel.validateEvent: invalid: from own device"); - return false; - } - } - return VerificationRequest_1.VerificationRequest.validateEvent(type, event, client); - } - /** - * @param event - the event to get the timestamp of - * @returns the timestamp when the event was sent - */ - getTimestamp(event) { - const content = event.getContent(); - return content && content.timestamp; - } - /** - * Changes the state of the channel, request, and verifier in response to a key verification event. - * @param event - to handle - * @param request - the request to forward handling to - * @param isLiveEvent - whether this is an even received through sync or not - * @returns a promise that resolves when any requests as an answer to the passed-in event are sent. - */ - handleEvent(event, request, isLiveEvent = false) { - return __awaiter(this, void 0, void 0, function* () { - const type = event.getType(); - const content = event.getContent(); - if (type === VerificationRequest_1.REQUEST_TYPE || type === VerificationRequest_1.READY_TYPE || type === VerificationRequest_1.START_TYPE) { - if (!this.transactionId) { - this.transactionId = content.transaction_id; - } - const deviceId = content.from_device; - // adopt deviceId if not set before and valid - if (!this.deviceId && this.devices.includes(deviceId)) { - this.deviceId = deviceId; - } - // if no device id or different from adopted one, cancel with sender - if (!this.deviceId || this.deviceId !== deviceId) { - // also check that message came from the device we sent the request to earlier on - // and do send a cancel message to that device - // (but don't cancel the request for the device we should be talking to) - const cancelContent = this.completeContent(VerificationRequest_1.CANCEL_TYPE, (0, Error_1.errorFromEvent)((0, Error_1.newUnexpectedMessageError)())); - return this.sendToDevices(VerificationRequest_1.CANCEL_TYPE, cancelContent, [deviceId]); - } - } - const wasStarted = request.phase === VerificationRequest_1.PHASE_STARTED || request.phase === VerificationRequest_1.PHASE_READY; - yield request.handleEvent(event.getType(), event, isLiveEvent, false, false); - const isStarted = request.phase === VerificationRequest_1.PHASE_STARTED || request.phase === VerificationRequest_1.PHASE_READY; - const isAcceptingEvent = type === VerificationRequest_1.START_TYPE || type === VerificationRequest_1.READY_TYPE; - // the request has picked a ready or start event, tell the other devices about it - if (isAcceptingEvent && !wasStarted && isStarted && this.deviceId) { - const nonChosenDevices = this.devices.filter((d) => d !== this.deviceId && d !== this.client.getDeviceId()); - if (nonChosenDevices.length) { - const message = this.completeContent(VerificationRequest_1.CANCEL_TYPE, { - code: "m.accepted", - reason: "Verification request accepted by another device", - }); - yield this.sendToDevices(VerificationRequest_1.CANCEL_TYPE, message, nonChosenDevices); - } - } - }); - } - /** - * See {@link InRoomChannel#completedContentFromEvent} for why this is needed. - * @param event - the received event - * @returns the content object - */ - completedContentFromEvent(event) { - return event.getContent(); - } - /** - * Add all the fields to content needed for sending it over this channel. - * This is public so verification methods (SAS uses this) can get the exact - * content that will be sent independent of the used channel, - * as they need to calculate the hash of it. - * @param type - the event type - * @param content - the (incomplete) content - * @returns the complete content, as it will be sent. - */ - completeContent(type, content) { - // make a copy - content = Object.assign({}, content); - if (this.transactionId) { - content.transaction_id = this.transactionId; - } - if (type === VerificationRequest_1.REQUEST_TYPE || type === VerificationRequest_1.READY_TYPE || type === VerificationRequest_1.START_TYPE) { - content.from_device = this.client.getDeviceId(); - } - if (type === VerificationRequest_1.REQUEST_TYPE) { - content.timestamp = Date.now(); - } - return content; - } - /** - * Send an event over the channel with the content not having gone through `completeContent`. - * @param type - the event type - * @param uncompletedContent - the (incomplete) content - * @returns the promise of the request - */ - send(type, uncompletedContent = {}) { - // create transaction id when sending request - if ((type === VerificationRequest_1.REQUEST_TYPE || type === VerificationRequest_1.START_TYPE) && !this.transactionId) { - this.transactionId = ToDeviceChannel.makeTransactionId(); - } - const content = this.completeContent(type, uncompletedContent); - return this.sendCompleted(type, content); - } - /** - * Send an event over the channel with the content having gone through `completeContent` already. - * @param type - the event type - * @returns the promise of the request - */ - sendCompleted(type, content) { - return __awaiter(this, void 0, void 0, function* () { - let result; - if (type === VerificationRequest_1.REQUEST_TYPE || (type === VerificationRequest_1.CANCEL_TYPE && !this.deviceId)) { - result = yield this.sendToDevices(type, content, this.devices); - } - else { - result = yield this.sendToDevices(type, content, [this.deviceId]); - } - // the VerificationRequest state machine requires remote echos of the event - // the client sends itself, so we fake this for to_device messages - const remoteEchoEvent = new event_1.MatrixEvent({ - sender: this.client.getUserId(), - content, - type, - }); - yield this.request.handleEvent(type, remoteEchoEvent, - /*isLiveEvent=*/ true, - /*isRemoteEcho=*/ true, - /*isSentByUs=*/ true); - return result; - }); - } - sendToDevices(type, content, devices) { - return __awaiter(this, void 0, void 0, function* () { - if (devices.length) { - const deviceMessages = new Map(); - for (const deviceId of devices) { - deviceMessages.set(deviceId, content); - } - yield this.client.sendToDevice(type, new Map([[this.userId, deviceMessages]])); - } - }); - } - /** - * Allow Crypto module to create and know the transaction id before the .start event gets sent. - * @returns the transaction id - */ - static makeTransactionId() { - return (0, randomstring_1.randomString)(32); - } -} -exports.ToDeviceChannel = ToDeviceChannel; -class ToDeviceRequests { - constructor() { - this.requestsByUserId = new Map(); - } - getRequest(event) { - return this.getRequestBySenderAndTxnId(event.getSender(), ToDeviceChannel.getTransactionId(event)); - } - getRequestByChannel(channel) { - return this.getRequestBySenderAndTxnId(channel.userId, channel.transactionId); - } - getRequestBySenderAndTxnId(sender, txnId) { - const requestsByTxnId = this.requestsByUserId.get(sender); - if (requestsByTxnId) { - return requestsByTxnId.get(txnId); - } - } - setRequest(event, request) { - this.setRequestBySenderAndTxnId(event.getSender(), ToDeviceChannel.getTransactionId(event), request); - } - setRequestByChannel(channel, request) { - this.setRequestBySenderAndTxnId(channel.userId, channel.transactionId, request); - } - setRequestBySenderAndTxnId(sender, txnId, request) { - let requestsByTxnId = this.requestsByUserId.get(sender); - if (!requestsByTxnId) { - requestsByTxnId = new Map(); - this.requestsByUserId.set(sender, requestsByTxnId); - } - requestsByTxnId.set(txnId, request); - } - removeRequest(event) { - const userId = event.getSender(); - const requestsByTxnId = this.requestsByUserId.get(userId); - if (requestsByTxnId) { - requestsByTxnId.delete(ToDeviceChannel.getTransactionId(event)); - if (requestsByTxnId.size === 0) { - this.requestsByUserId.delete(userId); - } - } - } - findRequestInProgress(userId, devices) { - const requestsByTxnId = this.requestsByUserId.get(userId); - if (requestsByTxnId) { - for (const request of requestsByTxnId.values()) { - if (request.pending && request.channel.isToDevices(devices)) { - return request; - } - } - } - } - getRequestsInProgress(userId) { - const requestsByTxnId = this.requestsByUserId.get(userId); - if (requestsByTxnId) { - return Array.from(requestsByTxnId.values()).filter((r) => r.pending); - } - return []; - } -} -exports.ToDeviceRequests = ToDeviceRequests; - -},{"../../../logger":374,"../../../models/event":383,"../../../randomstring":398,"../Error":350,"./VerificationRequest":357}],357:[function(require,module,exports){ -"use strict"; -/* -Copyright 2018 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.VerificationRequest = exports.VerificationRequestEvent = exports.PHASE_DONE = exports.PHASE_CANCELLED = exports.PHASE_STARTED = exports.PHASE_READY = exports.PHASE_REQUESTED = exports.PHASE_UNSENT = exports.Phase = exports.READY_TYPE = exports.DONE_TYPE = exports.CANCEL_TYPE = exports.START_TYPE = exports.REQUEST_TYPE = exports.EVENT_PREFIX = void 0; -const logger_1 = require("../../../logger"); -const Error_1 = require("../Error"); -const QRCode_1 = require("../QRCode"); -const event_1 = require("../../../@types/event"); -const typed_event_emitter_1 = require("../../../models/typed-event-emitter"); -// How long after the event's timestamp that the request times out -const TIMEOUT_FROM_EVENT_TS = 10 * 60 * 1000; // 10 minutes -// How long after we receive the event that the request times out -const TIMEOUT_FROM_EVENT_RECEIPT = 2 * 60 * 1000; // 2 minutes -// to avoid almost expired verification notifications -// from showing a notification and almost immediately -// disappearing, also ignore verification requests that -// are this amount of time away from expiring. -const VERIFICATION_REQUEST_MARGIN = 3 * 1000; // 3 seconds -exports.EVENT_PREFIX = "m.key.verification."; -exports.REQUEST_TYPE = exports.EVENT_PREFIX + "request"; -exports.START_TYPE = exports.EVENT_PREFIX + "start"; -exports.CANCEL_TYPE = exports.EVENT_PREFIX + "cancel"; -exports.DONE_TYPE = exports.EVENT_PREFIX + "done"; -exports.READY_TYPE = exports.EVENT_PREFIX + "ready"; -var Phase; -(function (Phase) { - Phase[Phase["Unsent"] = 1] = "Unsent"; - Phase[Phase["Requested"] = 2] = "Requested"; - Phase[Phase["Ready"] = 3] = "Ready"; - Phase[Phase["Started"] = 4] = "Started"; - Phase[Phase["Cancelled"] = 5] = "Cancelled"; - Phase[Phase["Done"] = 6] = "Done"; -})(Phase = exports.Phase || (exports.Phase = {})); -// Legacy export fields -exports.PHASE_UNSENT = Phase.Unsent; -exports.PHASE_REQUESTED = Phase.Requested; -exports.PHASE_READY = Phase.Ready; -exports.PHASE_STARTED = Phase.Started; -exports.PHASE_CANCELLED = Phase.Cancelled; -exports.PHASE_DONE = Phase.Done; -var VerificationRequestEvent; -(function (VerificationRequestEvent) { - VerificationRequestEvent["Change"] = "change"; -})(VerificationRequestEvent = exports.VerificationRequestEvent || (exports.VerificationRequestEvent = {})); -/** - * State machine for verification requests. - * Things that differ based on what channel is used to - * send and receive verification events are put in `InRoomChannel` or `ToDeviceChannel`. - */ -class VerificationRequest extends typed_event_emitter_1.TypedEventEmitter { - constructor(channel, verificationMethods, client) { - super(); - this.channel = channel; - this.verificationMethods = verificationMethods; - this.client = client; - this.eventsByUs = new Map(); - this.eventsByThem = new Map(); - this._observeOnly = false; - this.timeoutTimer = null; - this._accepting = false; - this._declining = false; - this.verifierHasFinished = false; - this._cancelled = false; - this._chosenMethod = null; - // we keep a copy of the QR Code data (including other user master key) around - // for QR reciprocate verification, to protect against - // cross-signing identity reset between the .ready and .start event - // and signing the wrong key after .start - this._qrCodeData = null; - // The timestamp when we received the request event from the other side - this.requestReceivedAt = null; - this.commonMethods = []; - this.cancelOnTimeout = () => __awaiter(this, void 0, void 0, function* () { - try { - if (this.initiatedByMe) { - yield this.cancel({ - reason: "Other party didn't accept in time", - code: "m.timeout", - }); - } - else { - yield this.cancel({ - reason: "User didn't accept in time", - code: "m.timeout", - }); - } - } - catch (err) { - logger_1.logger.error("Error while cancelling verification request", err); - } - }); - this.channel.request = this; - this.setPhase(exports.PHASE_UNSENT, false); - } - /** - * Stateless validation logic not specific to the channel. - * Invoked by the same static method in either channel. - * @param type - the "symbolic" event type, as returned by the `getEventType` function on the channel. - * @param event - the event to validate. Don't call getType() on it but use the `type` parameter instead. - * @param client - the client to get the current user and device id from - * @returns whether the event is valid and should be passed to handleEvent - */ - static validateEvent(type, event, client) { - const content = event.getContent(); - if (!type || !type.startsWith(exports.EVENT_PREFIX)) { - return false; - } - // from here on we're fairly sure that this is supposed to be - // part of a verification request, so be noisy when rejecting something - if (!content) { - logger_1.logger.log("VerificationRequest: validateEvent: no content"); - return false; - } - if (type === exports.REQUEST_TYPE || type === exports.READY_TYPE) { - if (!Array.isArray(content.methods)) { - logger_1.logger.log("VerificationRequest: validateEvent: " + "fail because methods"); - return false; - } - } - if (type === exports.REQUEST_TYPE || type === exports.READY_TYPE || type === exports.START_TYPE) { - if (typeof content.from_device !== "string" || content.from_device.length === 0) { - logger_1.logger.log("VerificationRequest: validateEvent: " + "fail because from_device"); - return false; - } - } - return true; - } - get invalid() { - return this.phase === exports.PHASE_UNSENT; - } - /** returns whether the phase is PHASE_REQUESTED */ - get requested() { - return this.phase === exports.PHASE_REQUESTED; - } - /** returns whether the phase is PHASE_CANCELLED */ - get cancelled() { - return this.phase === exports.PHASE_CANCELLED; - } - /** returns whether the phase is PHASE_READY */ - get ready() { - return this.phase === exports.PHASE_READY; - } - /** returns whether the phase is PHASE_STARTED */ - get started() { - return this.phase === exports.PHASE_STARTED; - } - /** returns whether the phase is PHASE_DONE */ - get done() { - return this.phase === exports.PHASE_DONE; - } - /** once the phase is PHASE_STARTED (and !initiatedByMe) or PHASE_READY: common methods supported by both sides */ - get methods() { - return this.commonMethods; - } - /** the method picked in the .start event */ - get chosenMethod() { - return this._chosenMethod; - } - calculateEventTimeout(event) { - let effectiveExpiresAt = this.channel.getTimestamp(event) + TIMEOUT_FROM_EVENT_TS; - if (this.requestReceivedAt && !this.initiatedByMe && this.phase <= exports.PHASE_REQUESTED) { - const expiresAtByReceipt = this.requestReceivedAt + TIMEOUT_FROM_EVENT_RECEIPT; - effectiveExpiresAt = Math.min(effectiveExpiresAt, expiresAtByReceipt); - } - return Math.max(0, effectiveExpiresAt - Date.now()); - } - /** The current remaining amount of ms before the request should be automatically cancelled */ - get timeout() { - const requestEvent = this.getEventByEither(exports.REQUEST_TYPE); - if (requestEvent) { - return this.calculateEventTimeout(requestEvent); - } - return 0; - } - /** - * The key verification request event. - * @returns The request event, or falsey if not found. - */ - get requestEvent() { - return this.getEventByEither(exports.REQUEST_TYPE); - } - /** current phase of the request. Some properties might only be defined in a current phase. */ - get phase() { - return this._phase; - } - /** The verifier to do the actual verification, once the method has been established. Only defined when the `phase` is PHASE_STARTED. */ - get verifier() { - return this._verifier; - } - get canAccept() { - return this.phase < exports.PHASE_READY && !this._accepting && !this._declining; - } - get accepting() { - return this._accepting; - } - get declining() { - return this._declining; - } - /** whether this request has sent it's initial event and needs more events to complete */ - get pending() { - return !this.observeOnly && this._phase !== exports.PHASE_DONE && this._phase !== exports.PHASE_CANCELLED; - } - /** Only set after a .ready if the other party can scan a QR code */ - get qrCodeData() { - return this._qrCodeData; - } - /** Checks whether the other party supports a given verification method. - * This is useful when setting up the QR code UI, as it is somewhat asymmetrical: - * if the other party supports SCAN_QR, we should show a QR code in the UI, and vice versa. - * For methods that need to be supported by both ends, use the `methods` property. - * @param method - the method to check - * @param force - to check even if the phase is not ready or started yet, internal usage - * @returns whether or not the other party said the supported the method */ - otherPartySupportsMethod(method, force = false) { - if (!force && !this.ready && !this.started) { - return false; - } - const theirMethodEvent = this.eventsByThem.get(exports.REQUEST_TYPE) || this.eventsByThem.get(exports.READY_TYPE); - if (!theirMethodEvent) { - // if we started straight away with .start event, - // we are assuming that the other side will support the - // chosen method, so return true for that. - if (this.started && this.initiatedByMe) { - const myStartEvent = this.eventsByUs.get(exports.START_TYPE); - const content = myStartEvent && myStartEvent.getContent(); - const myStartMethod = content && content.method; - return method == myStartMethod; - } - return false; - } - const content = theirMethodEvent.getContent(); - if (!content) { - return false; - } - const { methods } = content; - if (!Array.isArray(methods)) { - return false; - } - return methods.includes(method); - } - /** Whether this request was initiated by the syncing user. - * For InRoomChannel, this is who sent the .request event. - * For ToDeviceChannel, this is who sent the .start event - */ - get initiatedByMe() { - // event created by us but no remote echo has been received yet - const noEventsYet = this.eventsByUs.size + this.eventsByThem.size === 0; - if (this._phase === exports.PHASE_UNSENT && noEventsYet) { - return true; - } - const hasMyRequest = this.eventsByUs.has(exports.REQUEST_TYPE); - const hasTheirRequest = this.eventsByThem.has(exports.REQUEST_TYPE); - if (hasMyRequest && !hasTheirRequest) { - return true; - } - if (!hasMyRequest && hasTheirRequest) { - return false; - } - const hasMyStart = this.eventsByUs.has(exports.START_TYPE); - const hasTheirStart = this.eventsByThem.has(exports.START_TYPE); - if (hasMyStart && !hasTheirStart) { - return true; - } - return false; - } - /** The id of the user that initiated the request */ - get requestingUserId() { - if (this.initiatedByMe) { - return this.client.getUserId(); - } - else { - return this.otherUserId; - } - } - /** The id of the user that (will) receive(d) the request */ - get receivingUserId() { - if (this.initiatedByMe) { - return this.otherUserId; - } - else { - return this.client.getUserId(); - } - } - /** The user id of the other party in this request */ - get otherUserId() { - return this.channel.userId; - } - get isSelfVerification() { - return this.client.getUserId() === this.otherUserId; - } - /** - * The id of the user that cancelled the request, - * only defined when phase is PHASE_CANCELLED - */ - get cancellingUserId() { - const myCancel = this.eventsByUs.get(exports.CANCEL_TYPE); - const theirCancel = this.eventsByThem.get(exports.CANCEL_TYPE); - if (myCancel && (!theirCancel || myCancel.getId() < theirCancel.getId())) { - return myCancel.getSender(); - } - if (theirCancel) { - return theirCancel.getSender(); - } - return undefined; - } - /** - * The cancellation code e.g m.user which is responsible for cancelling this verification - */ - get cancellationCode() { - const ev = this.getEventByEither(exports.CANCEL_TYPE); - return ev ? ev.getContent().code : null; - } - get observeOnly() { - return this._observeOnly; - } - /** - * Gets which device the verification should be started with - * given the events sent so far in the verification. This is the - * same algorithm used to determine which device to send the - * verification to when no specific device is specified. - * @returns The device information - */ - get targetDevice() { - const theirFirstEvent = this.eventsByThem.get(exports.REQUEST_TYPE) || - this.eventsByThem.get(exports.READY_TYPE) || - this.eventsByThem.get(exports.START_TYPE); - const theirFirstContent = theirFirstEvent === null || theirFirstEvent === void 0 ? void 0 : theirFirstEvent.getContent(); - const fromDevice = theirFirstContent === null || theirFirstContent === void 0 ? void 0 : theirFirstContent.from_device; - return { - userId: this.otherUserId, - deviceId: fromDevice, - }; - } - /* Start the key verification, creating a verifier and sending a .start event. - * If no previous events have been sent, pass in `targetDevice` to set who to direct this request to. - * @param method - the name of the verification method to use. - * @param targetDevice.userId the id of the user to direct this request to - * @param targetDevice.deviceId the id of the device to direct this request to - * @returns the verifier of the given method - */ - beginKeyVerification(method, targetDevice = null) { - // need to allow also when unsent in case of to_device - if (!this.observeOnly && !this._verifier) { - const validStartPhase = this.phase === exports.PHASE_REQUESTED || - this.phase === exports.PHASE_READY || - (this.phase === exports.PHASE_UNSENT && this.channel.canCreateRequest(exports.START_TYPE)); - if (validStartPhase) { - // when called on a request that was initiated with .request event - // check the method is supported by both sides - if (this.commonMethods.length && !this.commonMethods.includes(method)) { - throw (0, Error_1.newUnknownMethodError)(); - } - this._verifier = this.createVerifier(method, null, targetDevice); - if (!this._verifier) { - throw (0, Error_1.newUnknownMethodError)(); - } - this._chosenMethod = method; - } - } - return this._verifier; - } - /** - * sends the initial .request event. - * @returns resolves when the event has been sent. - */ - sendRequest() { - return __awaiter(this, void 0, void 0, function* () { - if (!this.observeOnly && this._phase === exports.PHASE_UNSENT) { - const methods = [...this.verificationMethods.keys()]; - yield this.channel.send(exports.REQUEST_TYPE, { methods }); - } - }); - } - /** - * Cancels the request, sending a cancellation to the other party - * @param reason - the error reason to send the cancellation with - * @param code - the error code to send the cancellation with - * @returns resolves when the event has been sent. - */ - cancel({ reason = "User declined", code = "m.user" } = {}) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.observeOnly && this._phase !== exports.PHASE_CANCELLED) { - this._declining = true; - this.emit(VerificationRequestEvent.Change); - if (this._verifier) { - return this._verifier.cancel((0, Error_1.errorFactory)(code, reason)()); - } - else { - this._cancellingUserId = this.client.getUserId(); - yield this.channel.send(exports.CANCEL_TYPE, { code, reason }); - } - } - }); - } - /** - * Accepts the request, sending a .ready event to the other party - * @returns resolves when the event has been sent. - */ - accept() { - return __awaiter(this, void 0, void 0, function* () { - if (!this.observeOnly && this.phase === exports.PHASE_REQUESTED && !this.initiatedByMe) { - const methods = [...this.verificationMethods.keys()]; - this._accepting = true; - this.emit(VerificationRequestEvent.Change); - yield this.channel.send(exports.READY_TYPE, { methods }); - } - }); - } - /** - * Can be used to listen for state changes until the callback returns true. - * @param fn - callback to evaluate whether the request is in the desired state. - * Takes the request as an argument. - * @returns that resolves once the callback returns true - * @throws Error when the request is cancelled - */ - waitFor(fn) { - return new Promise((resolve, reject) => { - const check = () => { - let handled = false; - if (fn(this)) { - resolve(this); - handled = true; - } - else if (this.cancelled) { - reject(new Error("cancelled")); - handled = true; - } - if (handled) { - this.off(VerificationRequestEvent.Change, check); - } - return handled; - }; - if (!check()) { - this.on(VerificationRequestEvent.Change, check); - } - }); - } - setPhase(phase, notify = true) { - this._phase = phase; - if (notify) { - this.emit(VerificationRequestEvent.Change); - } - } - getEventByEither(type) { - return this.eventsByThem.get(type) || this.eventsByUs.get(type); - } - getEventBy(type, byThem = false) { - if (byThem) { - return this.eventsByThem.get(type); - } - else { - return this.eventsByUs.get(type); - } - } - calculatePhaseTransitions() { - const transitions = [{ phase: exports.PHASE_UNSENT }]; - const phase = () => transitions[transitions.length - 1].phase; - // always pass by .request first to be sure channel.userId has been set - const hasRequestByThem = this.eventsByThem.has(exports.REQUEST_TYPE); - const requestEvent = this.getEventBy(exports.REQUEST_TYPE, hasRequestByThem); - if (requestEvent) { - transitions.push({ phase: exports.PHASE_REQUESTED, event: requestEvent }); - } - const readyEvent = requestEvent && this.getEventBy(exports.READY_TYPE, !hasRequestByThem); - if (readyEvent && phase() === exports.PHASE_REQUESTED) { - transitions.push({ phase: exports.PHASE_READY, event: readyEvent }); - } - let startEvent; - if (readyEvent || !requestEvent) { - const theirStartEvent = this.eventsByThem.get(exports.START_TYPE); - const ourStartEvent = this.eventsByUs.get(exports.START_TYPE); - // any party can send .start after a .ready or unsent - if (theirStartEvent && ourStartEvent) { - startEvent = - theirStartEvent.getSender() < ourStartEvent.getSender() ? theirStartEvent : ourStartEvent; - } - else { - startEvent = theirStartEvent ? theirStartEvent : ourStartEvent; - } - } - else { - startEvent = this.getEventBy(exports.START_TYPE, !hasRequestByThem); - } - if (startEvent) { - const fromRequestPhase = phase() === exports.PHASE_REQUESTED && (requestEvent === null || requestEvent === void 0 ? void 0 : requestEvent.getSender()) !== startEvent.getSender(); - const fromUnsentPhase = phase() === exports.PHASE_UNSENT && this.channel.canCreateRequest(exports.START_TYPE); - if (fromRequestPhase || phase() === exports.PHASE_READY || fromUnsentPhase) { - transitions.push({ phase: exports.PHASE_STARTED, event: startEvent }); - } - } - const ourDoneEvent = this.eventsByUs.get(exports.DONE_TYPE); - if (this.verifierHasFinished || (ourDoneEvent && phase() === exports.PHASE_STARTED)) { - transitions.push({ phase: exports.PHASE_DONE }); - } - const cancelEvent = this.getEventByEither(exports.CANCEL_TYPE); - if ((this._cancelled || cancelEvent) && phase() !== exports.PHASE_DONE) { - transitions.push({ phase: exports.PHASE_CANCELLED, event: cancelEvent }); - return transitions; - } - return transitions; - } - transitionToPhase(transition) { - const { phase, event } = transition; - // get common methods - if (phase === exports.PHASE_REQUESTED || phase === exports.PHASE_READY) { - if (!this.wasSentByOwnDevice(event)) { - const content = event.getContent(); - this.commonMethods = content.methods.filter((m) => this.verificationMethods.has(m)); - } - } - // detect if we're not a party in the request, and we should just observe - if (!this.observeOnly) { - // if requested or accepted by one of my other devices - if (phase === exports.PHASE_REQUESTED || phase === exports.PHASE_STARTED || phase === exports.PHASE_READY) { - if (this.channel.receiveStartFromOtherDevices && - this.wasSentByOwnUser(event) && - !this.wasSentByOwnDevice(event)) { - this._observeOnly = true; - } - } - } - // create verifier - if (phase === exports.PHASE_STARTED) { - const { method } = event.getContent(); - if (!this._verifier && !this.observeOnly) { - this._verifier = this.createVerifier(method, event); - if (!this._verifier) { - this.cancel({ - code: "m.unknown_method", - reason: `Unknown method: ${method}`, - }); - } - else { - this._chosenMethod = method; - } - } - } - } - applyPhaseTransitions() { - const transitions = this.calculatePhaseTransitions(); - const existingIdx = transitions.findIndex((t) => t.phase === this.phase); - // trim off phases we already went through, if any - const newTransitions = transitions.slice(existingIdx + 1); - // transition to all new phases - for (const transition of newTransitions) { - this.transitionToPhase(transition); - } - return newTransitions; - } - isWinningStartRace(newEvent) { - if (newEvent.getType() !== exports.START_TYPE) { - return false; - } - const oldEvent = this._verifier.startEvent; - let oldRaceIdentifier; - if (this.isSelfVerification) { - // if the verifier does not have a startEvent, - // it is because it's still sending and we are on the initator side - // we know we are sending a .start event because we already - // have a verifier (checked in calling method) - if (oldEvent) { - const oldContent = oldEvent.getContent(); - oldRaceIdentifier = oldContent && oldContent.from_device; - } - else { - oldRaceIdentifier = this.client.getDeviceId(); - } - } - else { - if (oldEvent) { - oldRaceIdentifier = oldEvent.getSender(); - } - else { - oldRaceIdentifier = this.client.getUserId(); - } - } - let newRaceIdentifier; - if (this.isSelfVerification) { - const newContent = newEvent.getContent(); - newRaceIdentifier = newContent && newContent.from_device; - } - else { - newRaceIdentifier = newEvent.getSender(); - } - return newRaceIdentifier < oldRaceIdentifier; - } - hasEventId(eventId) { - for (const event of this.eventsByUs.values()) { - if (event.getId() === eventId) { - return true; - } - } - for (const event of this.eventsByThem.values()) { - if (event.getId() === eventId) { - return true; - } - } - return false; - } - /** - * Changes the state of the request and verifier in response to a key verification event. - * @param type - the "symbolic" event type, as returned by the `getEventType` function on the channel. - * @param event - the event to handle. Don't call getType() on it but use the `type` parameter instead. - * @param isLiveEvent - whether this is an even received through sync or not - * @param isRemoteEcho - whether this is the remote echo of an event sent by the same device - * @param isSentByUs - whether this event is sent by a party that can accept and/or observe the request like one of our peers. - * For InRoomChannel this means any device for the syncing user. For ToDeviceChannel, just the syncing device. - * @returns a promise that resolves when any requests as an answer to the passed-in event are sent. - */ - handleEvent(type, event, isLiveEvent, isRemoteEcho, isSentByUs) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - // if reached phase cancelled or done, ignore anything else that comes - if (this.done || this.cancelled) { - return; - } - const wasObserveOnly = this._observeOnly; - this.adjustObserveOnly(event, isLiveEvent); - if (!this.observeOnly && !isRemoteEcho) { - if (yield this.cancelOnError(type, event)) { - return; - } - } - // This assumes verification won't need to send an event with - // the same type for the same party twice. - // This is true for QR and SAS verification, and was - // added here to prevent verification getting cancelled - // when the server duplicates an event (https://github.com/matrix-org/synapse/issues/3365) - const isDuplicateEvent = isSentByUs ? this.eventsByUs.has(type) : this.eventsByThem.has(type); - if (isDuplicateEvent) { - return; - } - const oldPhase = this.phase; - this.addEvent(type, event, isSentByUs); - // this will create if needed the verifier so needs to happen before calling it - const newTransitions = this.applyPhaseTransitions(); - try { - // only pass events from the other side to the verifier, - // no remote echos of our own events - if (this._verifier && !this.observeOnly) { - const newEventWinsRace = this.isWinningStartRace(event); - if (this._verifier.canSwitchStartEvent(event) && newEventWinsRace) { - this._verifier.switchStartEvent(event); - } - else if (!isRemoteEcho) { - if (type === exports.CANCEL_TYPE || ((_a = this._verifier.events) === null || _a === void 0 ? void 0 : _a.includes(type))) { - this._verifier.handleEvent(event); - } - } - } - if (newTransitions.length) { - // create QRCodeData if the other side can scan - // important this happens before emitting a phase change, - // so listeners can rely on it being there already - // We only do this for live events because it is important that - // we sign the keys that were in the QR code, and not the keys - // we happen to have at some later point in time. - if (isLiveEvent && newTransitions.some((t) => t.phase === exports.PHASE_READY)) { - const shouldGenerateQrCode = this.otherPartySupportsMethod(QRCode_1.SCAN_QR_CODE_METHOD, true); - if (shouldGenerateQrCode) { - this._qrCodeData = yield QRCode_1.QRCodeData.create(this, this.client); - } - } - const lastTransition = newTransitions[newTransitions.length - 1]; - const { phase } = lastTransition; - this.setupTimeout(phase); - // set phase as last thing as this emits the "change" event - this.setPhase(phase); - } - else if (this._observeOnly !== wasObserveOnly) { - this.emit(VerificationRequestEvent.Change); - } - } - finally { - // log events we processed so we can see from rageshakes what events were added to a request - logger_1.logger.log(`Verification request ${this.channel.transactionId}: ` + - `${type} event with id:${event.getId()}, ` + - `content:${JSON.stringify(event.getContent())} ` + - `deviceId:${this.channel.deviceId}, ` + - `sender:${event.getSender()}, isSentByUs:${isSentByUs}, ` + - `isLiveEvent:${isLiveEvent}, isRemoteEcho:${isRemoteEcho}, ` + - `phase:${oldPhase}=>${this.phase}, ` + - `observeOnly:${wasObserveOnly}=>${this._observeOnly}`); - } - }); - } - setupTimeout(phase) { - const shouldTimeout = !this.timeoutTimer && !this.observeOnly && phase === exports.PHASE_REQUESTED; - if (shouldTimeout) { - this.timeoutTimer = setTimeout(this.cancelOnTimeout, this.timeout); - } - if (this.timeoutTimer) { - const shouldClear = phase === exports.PHASE_STARTED || phase === exports.PHASE_READY || phase === exports.PHASE_DONE || phase === exports.PHASE_CANCELLED; - if (shouldClear) { - clearTimeout(this.timeoutTimer); - this.timeoutTimer = null; - } - } - } - cancelOnError(type, event) { - return __awaiter(this, void 0, void 0, function* () { - if (type === exports.START_TYPE) { - const method = event.getContent().method; - if (!this.verificationMethods.has(method)) { - yield this.cancel((0, Error_1.errorFromEvent)((0, Error_1.newUnknownMethodError)())); - return true; - } - } - const isUnexpectedRequest = type === exports.REQUEST_TYPE && this.phase !== exports.PHASE_UNSENT; - const isUnexpectedReady = type === exports.READY_TYPE && this.phase !== exports.PHASE_REQUESTED && this.phase !== exports.PHASE_STARTED; - // only if phase has passed from PHASE_UNSENT should we cancel, because events - // are allowed to come in in any order (at least with InRoomChannel). So we only know - // we're dealing with a valid request we should participate in once we've moved to PHASE_REQUESTED. - // Before that, we could be looking at somebody else's verification request and we just - // happen to be in the room - if (this.phase !== exports.PHASE_UNSENT && (isUnexpectedRequest || isUnexpectedReady)) { - logger_1.logger.warn(`Cancelling, unexpected ${type} verification ` + `event from ${event.getSender()}`); - const reason = `Unexpected ${type} event in phase ${this.phase}`; - yield this.cancel((0, Error_1.errorFromEvent)((0, Error_1.newUnexpectedMessageError)({ reason }))); - return true; - } - return false; - }); - } - adjustObserveOnly(event, isLiveEvent = false) { - // don't send out events for historical requests - if (!isLiveEvent) { - this._observeOnly = true; - } - if (this.calculateEventTimeout(event) < VERIFICATION_REQUEST_MARGIN) { - this._observeOnly = true; - } - } - addEvent(type, event, isSentByUs = false) { - if (isSentByUs) { - this.eventsByUs.set(type, event); - } - else { - this.eventsByThem.set(type, event); - } - // once we know the userId of the other party (from the .request event) - // see if any event by anyone else crept into this.eventsByThem - if (type === exports.REQUEST_TYPE) { - for (const [type, event] of this.eventsByThem.entries()) { - if (event.getSender() !== this.otherUserId) { - this.eventsByThem.delete(type); - } - } - // also remember when we received the request event - this.requestReceivedAt = Date.now(); - } - } - createVerifier(method, startEvent = null, targetDevice = null) { - if (!targetDevice) { - targetDevice = this.targetDevice; - } - const { userId, deviceId } = targetDevice; - const VerifierCtor = this.verificationMethods.get(method); - if (!VerifierCtor) { - logger_1.logger.warn("could not find verifier constructor for method", method); - return; - } - return new VerifierCtor(this.channel, this.client, userId, deviceId, startEvent, this); - } - wasSentByOwnUser(event) { - return (event === null || event === void 0 ? void 0 : event.getSender()) === this.client.getUserId(); - } - // only for .request, .ready or .start - wasSentByOwnDevice(event) { - if (!this.wasSentByOwnUser(event)) { - return false; - } - const content = event.getContent(); - if (!content || content.from_device !== this.client.getDeviceId()) { - return false; - } - return true; - } - onVerifierCancelled() { - this._cancelled = true; - // move to cancelled phase - const newTransitions = this.applyPhaseTransitions(); - if (newTransitions.length) { - this.setPhase(newTransitions[newTransitions.length - 1].phase); - } - } - onVerifierFinished() { - this.channel.send(event_1.EventType.KeyVerificationDone, {}); - this.verifierHasFinished = true; - // move to .done phase - const newTransitions = this.applyPhaseTransitions(); - if (newTransitions.length) { - this.setPhase(newTransitions[newTransitions.length - 1].phase); - } - } - getEventFromOtherParty(type) { - return this.eventsByThem.get(type); - } -} -exports.VerificationRequest = VerificationRequest; - -},{"../../../@types/event":306,"../../../logger":374,"../../../models/typed-event-emitter":395,"../Error":350,"../QRCode":352}],358:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __asyncValues = (this && this.__asyncValues) || function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RoomWidgetClient = void 0; -const matrix_widget_api_1 = require("matrix-widget-api"); -const event_1 = require("./models/event"); -const event_2 = require("./@types/event"); -const logger_1 = require("./logger"); -const client_1 = require("./client"); -const sync_1 = require("./sync"); -const sliding_sync_sdk_1 = require("./sliding-sync-sdk"); -const event_3 = require("./models/event"); -const user_1 = require("./models/user"); -const utils_1 = require("./utils"); -/** - * A MatrixClient that routes its requests through the widget API instead of the - * real CS API. - * @experimental This class is considered unstable! - */ -class RoomWidgetClient extends client_1.MatrixClient { - constructor(widgetApi, capabilities, roomId, opts) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; - super(opts); - this.widgetApi = widgetApi; - this.capabilities = capabilities; - this.roomId = roomId; - this.widgetApiReady = new Promise((resolve) => this.widgetApi.once("ready", resolve)); - this.syncState = null; - this.onEvent = (ev) => __awaiter(this, void 0, void 0, function* () { - ev.preventDefault(); - // Verify the room ID matches, since it's possible for the client to - // send us events from other rooms if this widget is always on screen - if (ev.detail.data.room_id === this.roomId) { - const event = new event_3.MatrixEvent(ev.detail.data); - yield this.syncApi.injectRoomEvents(this.room, [], [event]); - this.emit(client_1.ClientEvent.Event, event); - this.setSyncState(sync_1.SyncState.Syncing); - logger_1.logger.info(`Received event ${event.getId()} ${event.getType()} ${event.getStateKey()}`); - } - else { - const { event_id: eventId, room_id: roomId } = ev.detail.data; - logger_1.logger.info(`Received event ${eventId} for a different room ${roomId}; discarding`); - } - yield this.ack(ev); - }); - this.onToDevice = (ev) => __awaiter(this, void 0, void 0, function* () { - ev.preventDefault(); - const event = new event_3.MatrixEvent({ - type: ev.detail.data.type, - sender: ev.detail.data.sender, - content: ev.detail.data.content, - }); - // Mark the event as encrypted if it was, using fake contents and keys since those are unknown to us - if (ev.detail.data.encrypted) - event.makeEncrypted(event_2.EventType.RoomMessageEncrypted, {}, "", ""); - this.emit(client_1.ClientEvent.ToDeviceEvent, event); - this.setSyncState(sync_1.SyncState.Syncing); - yield this.ack(ev); - }); - // Request capabilities for the functionality this client needs to support - if (((_a = capabilities.sendEvent) === null || _a === void 0 ? void 0 : _a.length) || - ((_b = capabilities.receiveEvent) === null || _b === void 0 ? void 0 : _b.length) || - capabilities.sendMessage === true || - (Array.isArray(capabilities.sendMessage) && capabilities.sendMessage.length) || - capabilities.receiveMessage === true || - (Array.isArray(capabilities.receiveMessage) && capabilities.receiveMessage.length) || - ((_c = capabilities.sendState) === null || _c === void 0 ? void 0 : _c.length) || - ((_d = capabilities.receiveState) === null || _d === void 0 ? void 0 : _d.length)) { - widgetApi.requestCapabilityForRoomTimeline(roomId); - } - (_e = capabilities.sendEvent) === null || _e === void 0 ? void 0 : _e.forEach((eventType) => widgetApi.requestCapabilityToSendEvent(eventType)); - (_f = capabilities.receiveEvent) === null || _f === void 0 ? void 0 : _f.forEach((eventType) => widgetApi.requestCapabilityToReceiveEvent(eventType)); - if (capabilities.sendMessage === true) { - widgetApi.requestCapabilityToSendMessage(); - } - else if (Array.isArray(capabilities.sendMessage)) { - capabilities.sendMessage.forEach((msgType) => widgetApi.requestCapabilityToSendMessage(msgType)); - } - if (capabilities.receiveMessage === true) { - widgetApi.requestCapabilityToReceiveMessage(); - } - else if (Array.isArray(capabilities.receiveMessage)) { - capabilities.receiveMessage.forEach((msgType) => widgetApi.requestCapabilityToReceiveMessage(msgType)); - } - (_g = capabilities.sendState) === null || _g === void 0 ? void 0 : _g.forEach(({ eventType, stateKey }) => widgetApi.requestCapabilityToSendState(eventType, stateKey)); - (_h = capabilities.receiveState) === null || _h === void 0 ? void 0 : _h.forEach(({ eventType, stateKey }) => widgetApi.requestCapabilityToReceiveState(eventType, stateKey)); - (_j = capabilities.sendToDevice) === null || _j === void 0 ? void 0 : _j.forEach((eventType) => widgetApi.requestCapabilityToSendToDevice(eventType)); - (_k = capabilities.receiveToDevice) === null || _k === void 0 ? void 0 : _k.forEach((eventType) => widgetApi.requestCapabilityToReceiveToDevice(eventType)); - if (capabilities.turnServers) { - widgetApi.requestCapability(matrix_widget_api_1.MatrixCapabilities.MSC3846TurnServers); - } - widgetApi.on(`action:${matrix_widget_api_1.WidgetApiToWidgetAction.SendEvent}`, this.onEvent); - widgetApi.on(`action:${matrix_widget_api_1.WidgetApiToWidgetAction.SendToDevice}`, this.onToDevice); - // Open communication with the host - widgetApi.start(); - } - startClient(opts = {}) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - this.lifecycle = new AbortController(); - // Create our own user object artificially (instead of waiting for sync) - // so it's always available, even if the user is not in any rooms etc. - const userId = this.getUserId(); - if (userId) { - this.store.storeUser(new user_1.User(userId)); - } - // Even though we have no access token and cannot sync, the sync class - // still has some valuable helper methods that we make use of, so we - // instantiate it anyways - if (opts.slidingSync) { - this.syncApi = new sliding_sync_sdk_1.SlidingSyncSdk(opts.slidingSync, this, opts, this.buildSyncApiOptions()); - } - else { - this.syncApi = new sync_1.SyncApi(this, opts, this.buildSyncApiOptions()); - } - this.room = this.syncApi.createRoom(this.roomId); - this.store.storeRoom(this.room); - yield this.widgetApiReady; - // Backfill the requested events - // We only get the most recent event for every type + state key combo, - // so it doesn't really matter what order we inject them in - yield Promise.all((_b = (_a = this.capabilities.receiveState) === null || _a === void 0 ? void 0 : _a.map(({ eventType, stateKey }) => __awaiter(this, void 0, void 0, function* () { - const rawEvents = yield this.widgetApi.readStateEvents(eventType, undefined, stateKey, [this.roomId]); - const events = rawEvents.map((rawEvent) => new event_3.MatrixEvent(rawEvent)); - yield this.syncApi.injectRoomEvents(this.room, [], events); - events.forEach((event) => { - this.emit(client_1.ClientEvent.Event, event); - logger_1.logger.info(`Backfilled event ${event.getId()} ${event.getType()} ${event.getStateKey()}`); - }); - }))) !== null && _b !== void 0 ? _b : []); - this.setSyncState(sync_1.SyncState.Syncing); - logger_1.logger.info("Finished backfilling events"); - // Watch for TURN servers, if requested - if (this.capabilities.turnServers) - this.watchTurnServers(); - }); - } - stopClient() { - this.widgetApi.off(`action:${matrix_widget_api_1.WidgetApiToWidgetAction.SendEvent}`, this.onEvent); - this.widgetApi.off(`action:${matrix_widget_api_1.WidgetApiToWidgetAction.SendToDevice}`, this.onToDevice); - super.stopClient(); - this.lifecycle.abort(); // Signal to other async tasks that the client has stopped - } - joinRoom(roomIdOrAlias) { - return __awaiter(this, void 0, void 0, function* () { - if (roomIdOrAlias === this.roomId) - return this.room; - throw new Error(`Unknown room: ${roomIdOrAlias}`); - }); - } - encryptAndSendEvent(room, event) { - return __awaiter(this, void 0, void 0, function* () { - let response; - try { - response = yield this.widgetApi.sendRoomEvent(event.getType(), event.getContent(), room.roomId); - } - catch (e) { - this.updatePendingEventStatus(room, event, event_1.EventStatus.NOT_SENT); - throw e; - } - room.updatePendingEvent(event, event_1.EventStatus.SENT, response.event_id); - return { event_id: response.event_id }; - }); - } - sendStateEvent(roomId, eventType, content, stateKey = "") { - return __awaiter(this, void 0, void 0, function* () { - return yield this.widgetApi.sendStateEvent(eventType, stateKey, content, roomId); - }); - } - sendToDevice(eventType, contentMap) { - return __awaiter(this, void 0, void 0, function* () { - yield this.widgetApi.sendToDevice(eventType, false, (0, utils_1.recursiveMapToObject)(contentMap)); - return {}; - }); - } - queueToDevice({ eventType, batch }) { - return __awaiter(this, void 0, void 0, function* () { - // map: user Id → device Id → payload - const contentMap = new utils_1.MapWithDefault(() => new Map()); - for (const { userId, deviceId, payload } of batch) { - contentMap.getOrCreate(userId).set(deviceId, payload); - } - yield this.widgetApi.sendToDevice(eventType, false, (0, utils_1.recursiveMapToObject)(contentMap)); - }); - } - encryptAndSendToDevices(userDeviceInfoArr, payload) { - return __awaiter(this, void 0, void 0, function* () { - // map: user Id → device Id → payload - const contentMap = new utils_1.MapWithDefault(() => new Map()); - for (const { userId, deviceInfo: { deviceId }, } of userDeviceInfoArr) { - contentMap.getOrCreate(userId).set(deviceId, payload); - } - yield this.widgetApi.sendToDevice(payload.type, true, (0, utils_1.recursiveMapToObject)(contentMap)); - }); - } - // Overridden since we get TURN servers automatically over the widget API, - // and this method would otherwise complain about missing an access token - checkTurnServers() { - return __awaiter(this, void 0, void 0, function* () { - return this.turnServers.length > 0; - }); - } - // Overridden since we 'sync' manually without the sync API - getSyncState() { - return this.syncState; - } - setSyncState(state) { - const oldState = this.syncState; - this.syncState = state; - this.emit(client_1.ClientEvent.Sync, state, oldState); - } - ack(ev) { - return __awaiter(this, void 0, void 0, function* () { - yield this.widgetApi.transport.reply(ev.detail, {}); - }); - } - watchTurnServers() { - var _a, e_1, _b, _c; - return __awaiter(this, void 0, void 0, function* () { - const servers = this.widgetApi.getTurnServers(); - const onClientStopped = () => { - servers.return(undefined); - }; - this.lifecycle.signal.addEventListener("abort", onClientStopped); - try { - try { - for (var _d = true, servers_1 = __asyncValues(servers), servers_1_1; servers_1_1 = yield servers_1.next(), _a = servers_1_1.done, !_a;) { - _c = servers_1_1.value; - _d = false; - try { - const server = _c; - this.turnServers = [ - { - urls: server.uris, - username: server.username, - credential: server.password, - }, - ]; - this.emit(client_1.ClientEvent.TurnServers, this.turnServers); - logger_1.logger.log(`Received TURN server: ${server.uris}`); - } - finally { - _d = true; - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (!_d && !_a && (_b = servers_1.return)) yield _b.call(servers_1); - } - finally { if (e_1) throw e_1.error; } - } - } - catch (e) { - logger_1.logger.warn("Error watching TURN servers", e); - } - finally { - this.lifecycle.signal.removeEventListener("abort", onClientStopped); - } - }); - } -} -exports.RoomWidgetClient = RoomWidgetClient; - -},{"./@types/event":306,"./client":321,"./logger":374,"./models/event":383,"./models/user":396,"./sliding-sync-sdk":406,"./sync":414,"./utils":416,"matrix-widget-api":178}],359:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.KeySignatureUploadError = exports.InvalidCryptoStoreError = exports.InvalidCryptoStoreState = exports.InvalidStoreError = exports.InvalidStoreState = void 0; -var InvalidStoreState; -(function (InvalidStoreState) { - InvalidStoreState[InvalidStoreState["ToggledLazyLoading"] = 0] = "ToggledLazyLoading"; -})(InvalidStoreState = exports.InvalidStoreState || (exports.InvalidStoreState = {})); -class InvalidStoreError extends Error { - constructor(reason, value) { - const message = `Store is invalid because ${reason}, ` + - `please stop the client, delete all data and start the client again`; - super(message); - this.reason = reason; - this.value = value; - this.name = "InvalidStoreError"; - } -} -exports.InvalidStoreError = InvalidStoreError; -InvalidStoreError.TOGGLED_LAZY_LOADING = InvalidStoreState.ToggledLazyLoading; -var InvalidCryptoStoreState; -(function (InvalidCryptoStoreState) { - InvalidCryptoStoreState["TooNew"] = "TOO_NEW"; -})(InvalidCryptoStoreState = exports.InvalidCryptoStoreState || (exports.InvalidCryptoStoreState = {})); -class InvalidCryptoStoreError extends Error { - constructor(reason) { - const message = `Crypto store is invalid because ${reason}, ` + - `please stop the client, delete all data and start the client again`; - super(message); - this.reason = reason; - this.name = "InvalidCryptoStoreError"; - } -} -exports.InvalidCryptoStoreError = InvalidCryptoStoreError; -InvalidCryptoStoreError.TOO_NEW = InvalidCryptoStoreState.TooNew; -class KeySignatureUploadError extends Error { - constructor(message, value) { - super(message); - this.value = value; - } -} -exports.KeySignatureUploadError = KeySignatureUploadError; - -},{}],360:[function(require,module,exports){ -"use strict"; -/* -Copyright 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.eventMapperFor = void 0; -const event_1 = require("./models/event"); -const event_2 = require("./@types/event"); -function eventMapperFor(client, options) { - let preventReEmit = Boolean(options.preventReEmit); - const decrypt = options.decrypt !== false; - function mapper(plainOldJsObject) { - if (options.toDevice) { - delete plainOldJsObject.room_id; - } - const room = client.getRoom(plainOldJsObject.room_id); - let event; - // If the event is already known to the room, let's re-use the model rather than duplicating. - // We avoid doing this to state events as they may be forward or backwards looking which tweaks behaviour. - if (room && plainOldJsObject.state_key === undefined) { - event = room.findEventById(plainOldJsObject.event_id); - } - if (!event || event.status) { - event = new event_1.MatrixEvent(plainOldJsObject); - } - else { - // merge the latest unsigned data from the server - event.setUnsigned(Object.assign(Object.assign({}, event.getUnsigned()), plainOldJsObject.unsigned)); - // prevent doubling up re-emitters - preventReEmit = true; - } - // if there is a complete edit bundled alongside the event, perform the replacement. - // (prior to MSC3925, events were automatically replaced on the server-side. MSC3925 proposes that that doesn't - // happen automatically but the server does provide us with the whole content of the edit event.) - const bundledEdit = event.getServerAggregatedRelation(event_2.RelationType.Replace); - if (bundledEdit === null || bundledEdit === void 0 ? void 0 : bundledEdit.content) { - const replacement = mapper(bundledEdit); - // XXX: it's worth noting that the spec says we should only respect encrypted edits if, once decrypted, the - // replacement has a `m.new_content` property. The problem is that we haven't yet decrypted the replacement - // (it should be happening in the background), so we can't enforce this. Possibly we should for decryption - // to complete, but that sounds a bit racy. For now, we just assume it's ok. - event.makeReplaced(replacement); - } - const thread = room === null || room === void 0 ? void 0 : room.findThreadForEvent(event); - if (thread) { - event.setThread(thread); - } - // TODO: once we get rid of the old libolm-backed crypto, we can restrict this to room events (rather than - // to-device events), because the rust implementation decrypts to-device messages at a higher level. - // Generally we probably want to use a different eventMapper implementation for to-device events because - if (event.isEncrypted()) { - if (!preventReEmit) { - client.reEmitter.reEmit(event, [event_1.MatrixEventEvent.Decrypted]); - } - if (decrypt) { - client.decryptEventIfNeeded(event); - } - } - if (!preventReEmit) { - client.reEmitter.reEmit(event, [event_1.MatrixEventEvent.Replaced, event_1.MatrixEventEvent.VisibilityChange]); - room === null || room === void 0 ? void 0 : room.reEmitter.reEmit(event, [event_1.MatrixEventEvent.BeforeRedaction]); - } - return event; - } - return mapper; -} -exports.eventMapperFor = eventMapperFor; - -},{"./@types/event":306,"./models/event":383}],361:[function(require,module,exports){ -"use strict"; -/* -Copyright 2021 - 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isOptionalAString = exports.isProvided = void 0; -/** - * 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 !== undefined; -} -exports.isProvided = isProvided; -/** - * Determines if the given optional string is a defined string. - * @param s - The input string. - * @returns True if the input is a defined string. - */ -function isOptionalAString(s) { - return isProvided(s) && typeof s === "string"; -} -exports.isOptionalAString = isOptionalAString; - -},{}],362:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.buildFeatureSupportMap = exports.Feature = exports.ServerSupport = void 0; -var ServerSupport; -(function (ServerSupport) { - ServerSupport[ServerSupport["Stable"] = 0] = "Stable"; - ServerSupport[ServerSupport["Unstable"] = 1] = "Unstable"; - ServerSupport[ServerSupport["Unsupported"] = 2] = "Unsupported"; -})(ServerSupport = exports.ServerSupport || (exports.ServerSupport = {})); -var Feature; -(function (Feature) { - Feature["Thread"] = "Thread"; - Feature["ThreadUnreadNotifications"] = "ThreadUnreadNotifications"; - Feature["LoginTokenRequest"] = "LoginTokenRequest"; - Feature["RelationBasedRedactions"] = "RelationBasedRedactions"; - Feature["AccountDataDeletion"] = "AccountDataDeletion"; -})(Feature = exports.Feature || (exports.Feature = {})); -const 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"], - }, -}; -function buildFeatureSupportMap(versions) { - var _a, _b, _c, _d; - return __awaiter(this, void 0, void 0, function* () { - const supportMap = new Map(); - for (const [feature, supportCondition] of Object.entries(featureSupportResolver)) { - const supportMatrixVersion = (_b = (_a = versions.versions) === null || _a === void 0 ? void 0 : _a.includes(supportCondition.matrixVersion || "")) !== null && _b !== void 0 ? _b : false; - const supportUnstablePrefixes = (_d = (_c = supportCondition.unstablePrefixes) === null || _c === void 0 ? void 0 : _c.every((unstablePrefix) => { - var _a; - return ((_a = versions.unstable_features) === null || _a === void 0 ? void 0 : _a[unstablePrefix]) === true; - })) !== null && _d !== void 0 ? _d : false; - if (supportMatrixVersion) { - supportMap.set(feature, ServerSupport.Stable); - } - else if (supportUnstablePrefixes) { - supportMap.set(feature, ServerSupport.Unstable); - } - else { - supportMap.set(feature, ServerSupport.Unsupported); - } - } - return supportMap; - }); -} -exports.buildFeatureSupportMap = buildFeatureSupportMap; - -},{}],363:[function(require,module,exports){ -"use strict"; -/* -Copyright 2016 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.FilterComponent = void 0; -const thread_1 = require("./models/thread"); -/** - * 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("*")) { - const typePrefix = filterValue.slice(0, -1); - return actualValue.slice(0, typePrefix.length) === typePrefix; - } - else { - return actualValue === filterValue; - } -} -/* eslint-enable camelcase */ -/** - * 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'. - */ -class FilterComponent { - 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 _a, _b; - const bundledRelationships = ((_a = event.getUnsigned()) === null || _a === void 0 ? void 0 : _a["m.relations"]) || {}; - const relations = Object.keys(bundledRelationships); - // Relation senders allows in theory a look-up of any senders - // however clients can only know about the current user participation status - // as sending a whole list of participants could be proven problematic in terms - // of performance - // This should be improved when bundled relationships solve that problem - const relationSenders = []; - if (this.userId && ((_b = bundledRelationships === null || bundledRelationships === void 0 ? void 0 : bundledRelationships[thread_1.THREAD_RELATION_TYPE.name]) === null || _b === void 0 ? void 0 : _b.current_user_participated)) { - relationSenders.push(this.userId); - } - return this.checkFields(event.getRoomId(), event.getSender(), event.getType(), event.getContent() ? event.getContent().url !== undefined : false, relations, relationSenders); - } - /** - * Converts the filter component into the form expected over the wire - */ - toJSON() { - return { - types: this.filterJson.types || null, - not_types: this.filterJson.not_types || [], - rooms: this.filterJson.rooms || null, - not_rooms: this.filterJson.not_rooms || [], - senders: this.filterJson.senders || null, - not_senders: this.filterJson.not_senders || [], - contains_url: this.filterJson.contains_url || null, - [thread_1.FILTER_RELATED_BY_SENDERS.name]: this.filterJson[thread_1.FILTER_RELATED_BY_SENDERS.name] || [], - [thread_1.FILTER_RELATED_BY_REL_TYPES.name]: this.filterJson[thread_1.FILTER_RELATED_BY_REL_TYPES.name] || [], - }; - } - /** - * 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) { - const literalKeys = { - rooms: function (v) { - return roomId === v; - }, - senders: function (v) { - return sender === v; - }, - types: function (v) { - return matchesWildcard(eventType, v); - }, - }; - for (const name in literalKeys) { - const matchFunc = literalKeys[name]; - const notName = "not_" + name; - const disallowedValues = this.filterJson[notName]; - if (disallowedValues === null || disallowedValues === void 0 ? void 0 : disallowedValues.some(matchFunc)) { - return false; - } - const allowedValues = this.filterJson[name]; - if (allowedValues && !allowedValues.some(matchFunc)) { - return false; - } - } - const containsUrlFilter = this.filterJson.contains_url; - if (containsUrlFilter !== undefined && containsUrlFilter !== containsUrl) { - return false; - } - const relationTypesFilter = this.filterJson[thread_1.FILTER_RELATED_BY_REL_TYPES.name]; - if (relationTypesFilter !== undefined) { - if (!this.arrayMatchesFilter(relationTypesFilter, relationTypes)) { - return false; - } - } - const relationSendersFilter = this.filterJson[thread_1.FILTER_RELATED_BY_SENDERS.name]; - if (relationSendersFilter !== undefined) { - 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 !== undefined ? this.filterJson.limit : 10; - } -} -exports.FilterComponent = FilterComponent; - -},{"./models/thread":394}],364:[function(require,module,exports){ -"use strict"; -/* -Copyright 2015 - 2021 Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Filter = void 0; -const sync_1 = require("./@types/sync"); -const filter_component_1 = require("./filter-component"); -/** - */ -function setProp(obj, keyNesting, val) { - const nestedKeys = keyNesting.split("."); - let currentObj = obj; - for (let i = 0; i < nestedKeys.length - 1; i++) { - if (!currentObj[nestedKeys[i]]) { - currentObj[nestedKeys[i]] = {}; - } - currentObj = currentObj[nestedKeys[i]]; - } - currentObj[nestedKeys[nestedKeys.length - 1]] = val; -} -/* eslint-enable camelcase */ -class Filter { - /** - * Create a filter from existing data. - */ - static fromJson(userId, filterId, jsonObj) { - const 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; - this.definition = {}; - } - /** - * 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; - // This is all ported from synapse's FilterCollection() - // definitions look something like: - // { - // "room": { - // "rooms": ["!abcde:example.com"], - // "not_rooms": ["!123456:example.com"], - // "state": { - // "types": ["m.room.*"], - // "not_rooms": ["!726s6s6q:example.com"], - // "lazy_load_members": true, - // }, - // "timeline": { - // "limit": 10, - // "types": ["m.room.message"], - // "not_rooms": ["!726s6s6q:example.com"], - // "not_senders": ["@spam:example.com"] - // "contains_url": true - // }, - // "ephemeral": { - // "types": ["m.receipt", "m.typing"], - // "not_rooms": ["!726s6s6q:example.com"], - // "not_senders": ["@spam:example.com"] - // } - // }, - // "presence": { - // "types": ["m.presence"], - // "not_senders": ["@alice:example.com"] - // }, - // "event_format": "client", - // "event_fields": ["type", "content", "sender"] - // } - const roomFilterJson = definition.room; - // consider the top level rooms/not_rooms filter - const roomFilterFields = {}; - if (roomFilterJson) { - if (roomFilterJson.rooms) { - roomFilterFields.rooms = roomFilterJson.rooms; - } - if (roomFilterJson.rooms) { - roomFilterFields.not_rooms = roomFilterJson.not_rooms; - } - } - this.roomFilter = new filter_component_1.FilterComponent(roomFilterFields, this.userId); - this.roomTimelineFilter = new filter_component_1.FilterComponent((roomFilterJson === null || roomFilterJson === void 0 ? void 0 : roomFilterJson.timeline) || {}, this.userId); - // don't bother porting this from synapse yet: - // this._room_state_filter = - // new FilterComponent(roomFilterJson.state || {}); - // this._room_ephemeral_filter = - // new FilterComponent(roomFilterJson.ephemeral || {}); - // this._room_account_data_filter = - // new FilterComponent(roomFilterJson.account_data || {}); - // this._presence_filter = - // new FilterComponent(definition.presence || {}); - // this._account_data_filter = - // new FilterComponent(definition.account_data || {}); - } - /** - * 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 _a, _b, _c; - this.definition = Object.assign(Object.assign({}, this.definition), { room: Object.assign(Object.assign({}, (_a = this.definition) === null || _a === void 0 ? void 0 : _a.room), { timeline: Object.assign(Object.assign({}, (_c = (_b = this.definition) === null || _b === void 0 ? void 0 : _b.room) === null || _c === void 0 ? void 0 : _c.timeline), { [sync_1.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); - } -} -exports.Filter = Filter; -Filter.LAZY_LOADING_MESSAGES_FILTER = { - lazy_load_members: true, -}; - -},{"./@types/sync":314,"./filter-component":363}],365:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConnectionError = exports.MatrixError = exports.HTTPError = void 0; -/** - * 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. - */ -class HTTPError extends Error { - constructor(msg, httpStatus) { - super(msg); - this.httpStatus = httpStatus; - } -} -exports.HTTPError = HTTPError; -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 - */ - constructor(errorJson = {}, httpStatus, url, event) { - let message = errorJson.error || "Unknown message"; - if (httpStatus) { - message = `[${httpStatus}] ${message}`; - } - if (url) { - message = `${message} (${url})`; - } - super(`MatrixError: ${message}`, httpStatus); - this.httpStatus = httpStatus; - this.url = url; - this.event = event; - this.errcode = errorJson.errcode; - this.name = errorJson.errcode || "Unknown error code"; - this.data = errorJson; - } -} -exports.MatrixError = MatrixError; -/** - * 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. - */ -class ConnectionError extends Error { - constructor(message, cause) { - super(message + (cause ? `: ${cause.message}` : "")); - } - get name() { - return "ConnectionError"; - } -} -exports.ConnectionError = ConnectionError; - -},{}],366:[function(require,module,exports){ -(function (global){(function (){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.FetchHttpApi = void 0; -/** - * This is an internal module. See {@link MatrixHttpApi} for the public class. - */ -const utils = __importStar(require("../utils")); -const method_1 = require("./method"); -const errors_1 = require("./errors"); -const interface_1 = require("./interface"); -const utils_1 = require("./utils"); -class FetchHttpApi { - constructor(eventEmitter, opts) { - var _a; - this.eventEmitter = eventEmitter; - this.opts = opts; - this.abortController = new AbortController(); - utils.checkObjectHasKeys(opts, ["baseUrl", "prefix"]); - opts.onlyData = !!opts.onlyData; - opts.useAuthorizationHeader = (_a = opts.useAuthorizationHeader) !== null && _a !== void 0 ? _a : true; - } - abort() { - this.abortController.abort(); - this.abortController = new AbortController(); - } - fetch(resource, options) { - if (this.opts.fetchFn) { - return this.opts.fetchFn(resource, options); - } - return global.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"); - } - let queryParams = undefined; - let body = undefined; - if (method === method_1.Method.Get) { - queryParams = params; - } - else { - body = params; - } - const fullUri = this.getUrl(path, queryParams, prefix, this.opts.idBaseUrl); - const opts = { - json: true, - headers: {}, - }; - if (accessToken) { - opts.headers.Authorization = `Bearer ${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 after 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. If a number is specified, - * this is treated as `opts.localTimeoutMs`. - * - * @returns Promise which resolves to - * ``` - * { - * data: {Object}, - * headers: {Object}, - * code: {Number}, - * } - * ``` - * If `onlyData` is set, this will resolve to the `data` object only. - * @returns Rejects with an error if a problem occurred. - * This includes network problems and Matrix-specific error JSON. - */ - authedRequest(method, path, queryParams, body, opts = {}) { - if (!queryParams) - queryParams = {}; - if (this.opts.accessToken) { - if (this.opts.useAuthorizationHeader) { - if (!opts.headers) { - opts.headers = {}; - } - if (!opts.headers.Authorization) { - opts.headers.Authorization = "Bearer " + this.opts.accessToken; - } - if (queryParams.access_token) { - delete queryParams.access_token; - } - } - else if (!queryParams.access_token) { - queryParams.access_token = this.opts.accessToken; - } - } - const requestPromise = this.request(method, path, queryParams, body, opts); - requestPromise.catch((err) => { - if (err.errcode == "M_UNKNOWN_TOKEN" && !(opts === null || opts === void 0 ? void 0 : opts.inhibitLogoutEmit)) { - this.eventEmitter.emit(interface_1.HttpApiEvent.SessionLoggedOut, err); - } - else if (err.errcode == "M_CONSENT_NOT_GIVEN") { - this.eventEmitter.emit(interface_1.HttpApiEvent.NoConsent, err.message, err.data.consent_uri); - } - }); - // return the original promise, otherwise tests break due to it having to - // go around the event loop one more time to process the result of the request - return requestPromise; - } - /** - * Perform a request to the homeserver without any credentials. - * @param method - The HTTP method e.g. "GET". - * @param path - The HTTP path after 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 Promise which resolves to - * ``` - * { - * data: {Object}, - * headers: {Object}, - * code: {Number}, - * } - * ``` - * If `onlyData is set, this will resolve to the data` - * object only. - * @returns Rejects with an error if a problem - * occurred. This includes network problems and Matrix-specific error JSON. - */ - request(method, path, queryParams, body, opts) { - const 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 Promise which resolves to data unless `onlyData` is specified as false, - * where the resolved value will be a fetch Response object. - * @returns Rejects with an error if a problem - * occurred. This includes network problems and Matrix-specific error JSON. - */ - requestOtherUrl(method, url, body, opts = {}) { - var _a, _b, _c, _d; - return __awaiter(this, void 0, void 0, function* () { - const headers = Object.assign({}, opts.headers || {}); - const json = (_a = opts.json) !== null && _a !== void 0 ? _a : true; - // We can't use getPrototypeOf here as objects made in other contexts e.g. over postMessage won't have same ref - const jsonBody = json && ((_b = body === null || body === void 0 ? void 0 : body.constructor) === null || _b === void 0 ? void 0 : _b.name) === Object.name; - if (json) { - if (jsonBody && !headers["Content-Type"]) { - headers["Content-Type"] = "application/json"; - } - if (!headers["Accept"]) { - headers["Accept"] = "application/json"; - } - } - const timeout = (_c = opts.localTimeoutMs) !== null && _c !== void 0 ? _c : this.opts.localTimeoutMs; - const keepAlive = (_d = opts.keepAlive) !== null && _d !== void 0 ? _d : false; - const signals = [this.abortController.signal]; - if (timeout !== undefined) { - signals.push((0, utils_1.timeoutSignal)(timeout)); - } - if (opts.abortSignal) { - signals.push(opts.abortSignal); - } - let data; - if (jsonBody) { - data = JSON.stringify(body); - } - else { - data = body; - } - const { signal, cleanup } = (0, utils_1.anySignal)(signals); - let res; - try { - res = yield this.fetch(url, { - signal, - method, - body: data, - headers, - mode: "cors", - redirect: "follow", - referrer: "", - referrerPolicy: "no-referrer", - cache: "no-cache", - credentials: "omit", - keepalive: keepAlive, - }); - } - catch (e) { - if (e.name === "AbortError") { - throw e; - } - throw new errors_1.ConnectionError("fetch failed", e); - } - finally { - cleanup(); - } - if (!res.ok) { - throw (0, utils_1.parseErrorResponse)(res, yield res.text()); - } - if (this.opts.onlyData) { - return json ? res.json() : res.text(); - } - return res; - }); - } - /** - * Form and return a homeserver request URL based on the given path params and prefix. - * @param path - The HTTP path after 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) { - const url = new URL((baseUrl !== null && baseUrl !== void 0 ? baseUrl : this.opts.baseUrl) + (prefix !== null && prefix !== void 0 ? prefix : this.opts.prefix) + path); - if (queryParams) { - utils.encodeParams(queryParams, url.searchParams); - } - return url; - } -} -exports.FetchHttpApi = FetchHttpApi; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"../utils":416,"./errors":365,"./interface":368,"./method":369,"./utils":371}],367:[function(require,module,exports){ -(function (global){(function (){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MatrixHttpApi = void 0; -const fetch_1 = require("./fetch"); -const prefix_1 = require("./prefix"); -const utils = __importStar(require("../utils")); -const callbacks = __importStar(require("../realtime-callbacks")); -const method_1 = require("./method"); -const errors_1 = require("./errors"); -const utils_1 = require("./utils"); -__exportStar(require("./interface"), exports); -__exportStar(require("./prefix"), exports); -__exportStar(require("./errors"), exports); -__exportStar(require("./method"), exports); -__exportStar(require("./utils"), exports); -class MatrixHttpApi extends fetch_1.FetchHttpApi { - constructor() { - super(...arguments); - 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, as - * determined by this.opts.onlyData, opts.rawResponse, and - * opts.onlyContentUri. Rejects with an error (usually a MatrixError). - */ - uploadContent(file, opts = {}) { - var _a, _b, _c, _d, _e; - const includeFilename = (_a = opts.includeFilename) !== null && _a !== void 0 ? _a : true; - const abortController = (_b = opts.abortController) !== null && _b !== void 0 ? _b : new AbortController(); - // If the file doesn't have a mime type, use a default since the HS errors if we don't supply one. - const contentType = (_d = (_c = opts.type) !== null && _c !== void 0 ? _c : file.type) !== null && _d !== void 0 ? _d : "application/octet-stream"; - const fileName = (_e = opts.name) !== null && _e !== void 0 ? _e : file.name; - const upload = { - loaded: 0, - total: 0, - abortController, - }; - const defer = utils.defer(); - if (global.XMLHttpRequest) { - const xhr = new global.XMLHttpRequest(); - const timeoutFn = function () { - xhr.abort(); - defer.reject(new Error("Timeout")); - }; - // set an initial timeout of 30s; we'll advance it each time we get a progress notification - let timeoutTimer = callbacks.setTimeout(timeoutFn, 30000); - xhr.onreadystatechange = function () { - switch (xhr.readyState) { - case global.XMLHttpRequest.DONE: - callbacks.clearTimeout(timeoutTimer); - try { - if (xhr.status === 0) { - throw new DOMException(xhr.statusText, "AbortError"); // mimic fetch API - } - if (!xhr.responseText) { - throw new Error("No response body."); - } - if (xhr.status >= 400) { - defer.reject((0, utils_1.parseErrorResponse)(xhr, xhr.responseText)); - } - else { - defer.resolve(JSON.parse(xhr.responseText)); - } - } - catch (err) { - if (err.name === "AbortError") { - defer.reject(err); - return; - } - defer.reject(new errors_1.ConnectionError("request failed", err)); - } - break; - } - }; - xhr.upload.onprogress = (ev) => { - var _a; - callbacks.clearTimeout(timeoutTimer); - upload.loaded = ev.loaded; - upload.total = ev.total; - timeoutTimer = callbacks.setTimeout(timeoutFn, 30000); - (_a = opts.progressHandler) === null || _a === void 0 ? void 0 : _a.call(opts, { - loaded: ev.loaded, - total: ev.total, - }); - }; - const url = this.getUrl("/upload", undefined, prefix_1.MediaPrefix.R0); - 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_1.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 { - const queryParams = {}; - if (includeFilename && fileName) { - queryParams.filename = fileName; - } - const headers = { "Content-Type": contentType }; - this.authedRequest(method_1.Method.Post, "/upload", queryParams, file, { - prefix: prefix_1.MediaPrefix.R0, - headers, - abortSignal: abortController.signal, - }) - .then((response) => { - return this.opts.onlyData ? response : response.json(); - }) - .then(defer.resolve, defer.reject); - } - // remove the upload from the list on completion - upload.promise = defer.promise.finally(() => { - utils.removeElement(this.uploads, (elem) => elem === upload); - }); - abortController.signal.addEventListener("abort", () => { - utils.removeElement(this.uploads, (elem) => elem === upload); - defer.reject(new DOMException("Aborted", "AbortError")); - }); - this.uploads.push(upload); - return upload.promise; - } - cancelUpload(promise) { - const 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: prefix_1.MediaPrefix.R0 + "/upload", - params: { - access_token: this.opts.accessToken, - }, - }; - } -} -exports.MatrixHttpApi = MatrixHttpApi; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"../realtime-callbacks":399,"../utils":416,"./errors":365,"./fetch":366,"./interface":368,"./method":369,"./prefix":370,"./utils":371}],368:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.HttpApiEvent = void 0; -var HttpApiEvent; -(function (HttpApiEvent) { - HttpApiEvent["SessionLoggedOut"] = "Session.logged_out"; - HttpApiEvent["NoConsent"] = "no_consent"; -})(HttpApiEvent = exports.HttpApiEvent || (exports.HttpApiEvent = {})); - -},{}],369:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Method = void 0; -var Method; -(function (Method) { - Method["Get"] = "GET"; - Method["Put"] = "PUT"; - Method["Post"] = "POST"; - Method["Delete"] = "DELETE"; -})(Method = exports.Method || (exports.Method = {})); - -},{}],370:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MediaPrefix = exports.IdentityPrefix = exports.ClientPrefix = void 0; -var ClientPrefix; -(function (ClientPrefix) { - /** - * A constant representing the URI path for release 0 of the Client-Server HTTP API. - */ - ClientPrefix["R0"] = "/_matrix/client/r0"; - /** - * A constant representing the URI path for the legacy release v1 of the Client-Server HTTP API. - */ - 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"; -})(ClientPrefix = exports.ClientPrefix || (exports.ClientPrefix = {})); -var IdentityPrefix; -(function (IdentityPrefix) { - /** - * URI path for the v2 identity API - */ - IdentityPrefix["V2"] = "/_matrix/identity/v2"; -})(IdentityPrefix = exports.IdentityPrefix || (exports.IdentityPrefix = {})); -var MediaPrefix; -(function (MediaPrefix) { - /** - * URI path for the media repo API - */ - MediaPrefix["R0"] = "/_matrix/media/r0"; -})(MediaPrefix = exports.MediaPrefix || (exports.MediaPrefix = {})); - -},{}],371:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.retryNetworkOperation = exports.parseErrorResponse = exports.anySignal = exports.timeoutSignal = void 0; -const content_type_1 = require("content-type"); -const logger_1 = require("../logger"); -const utils_1 = require("../utils"); -const errors_1 = require("./errors"); -// Ponyfill for https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout -function timeoutSignal(ms) { - const controller = new AbortController(); - setTimeout(() => { - controller.abort(); - }, ms); - return controller.signal; -} -exports.timeoutSignal = timeoutSignal; -function anySignal(signals) { - const controller = new AbortController(); - function cleanup() { - for (const signal of signals) { - signal.removeEventListener("abort", onAbort); - } - } - function onAbort() { - controller.abort(); - cleanup(); - } - for (const signal of signals) { - if (signal.aborted) { - onAbort(); - break; - } - signal.addEventListener("abort", onAbort); - } - return { - signal: controller.signal, - cleanup, - }; -} -exports.anySignal = anySignal; -/** - * 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) { - let contentType; - try { - contentType = getResponseContentType(response); - } - catch (e) { - return e; - } - if ((contentType === null || contentType === void 0 ? void 0 : contentType.type) === "application/json" && body) { - return new errors_1.MatrixError(JSON.parse(body), response.status, isXhr(response) ? response.responseURL : response.url); - } - if ((contentType === null || contentType === void 0 ? void 0 : contentType.type) === "text/plain") { - return new errors_1.HTTPError(`Server returned ${response.status} error: ${body}`, response.status); - } - return new errors_1.HTTPError(`Server returned ${response.status} error`, response.status); -} -exports.parseErrorResponse = parseErrorResponse; -function isXhr(response) { - return "getResponseHeader" in response; -} -/** - * extract the Content-Type header from the response object, 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(response) { - let contentType; - if (isXhr(response)) { - contentType = response.getResponseHeader("Content-Type"); - } - else { - contentType = response.headers.get("Content-Type"); - } - if (!contentType) - return null; - try { - return (0, content_type_1.parse)(contentType); - } - catch (e) { - throw new Error(`Error parsing Content-Type '${contentType}': ${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(maxAttempts, callback) { - return __awaiter(this, void 0, void 0, function* () { - let attempts = 0; - let lastConnectionError = null; - while (attempts < maxAttempts) { - try { - if (attempts > 0) { - const timeout = 1000 * Math.pow(2, attempts); - logger_1.logger.log(`network operation failed ${attempts} times, retrying in ${timeout}ms...`); - yield (0, utils_1.sleep)(timeout); - } - return yield callback(); - } - catch (err) { - if (err instanceof errors_1.ConnectionError) { - attempts += 1; - lastConnectionError = err; - } - else { - throw err; - } - } - } - throw lastConnectionError; - }); -} -exports.retryNetworkOperation = retryNetworkOperation; - -},{"../logger":374,"../utils":416,"./errors":365,"content-type":72}],372:[function(require,module,exports){ -"use strict"; -/* -Copyright 2019 New Vector Ltd - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.exists = void 0; -/** - * 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) => { - let exists = true; - const req = indexedDB.open(dbName); - req.onupgradeneeded = () => { - // Since we did not provide an explicit version when opening, this event - // should only fire if the DB did not exist before at any version. - exists = false; - }; - req.onblocked = () => reject(req.error); - req.onsuccess = () => { - const db = req.result; - db.close(); - if (!exists) { - // The DB did not exist before, but has been created as part of this - // existence check. Delete it now to restore previous state. Delete can - // actually take a while to complete in some browsers, so don't wait for - // it. This won't block future open calls that a store might issue next to - // properly set up the DB. - indexedDB.deleteDatabase(dbName); - } - resolve(exists); - }; - req.onerror = () => reject(req.error); - }); -} -exports.exists = exists; - -},{}],373:[function(require,module,exports){ -"use strict"; -/* -Copyright 2016 OpenMarket Ltd -Copyright 2017 Vector Creations Ltd -Copyright 2019 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.InteractiveAuth = exports.AuthType = void 0; -const logger_1 = require("./logger"); -const utils_1 = require("./utils"); -const EMAIL_STAGE_TYPE = "m.login.email.identity"; -const MSISDN_STAGE_TYPE = "m.login.msisdn"; -var AuthType; -(function (AuthType) { - AuthType["Password"] = "m.login.password"; - AuthType["Recaptcha"] = "m.login.recaptcha"; - AuthType["Terms"] = "m.login.terms"; - AuthType["Email"] = "m.login.email.identity"; - AuthType["Msisdn"] = "m.login.msisdn"; - AuthType["Sso"] = "m.login.sso"; - AuthType["SsoUnstable"] = "org.matrix.login.sso"; - AuthType["Dummy"] = "m.login.dummy"; - AuthType["RegistrationToken"] = "m.login.registration_token"; - // For backwards compatability with servers that have not yet updated to - // use the stable "m.login.registration_token" type. - // The authentication flow is the same in both cases. - AuthType["UnstableRegistrationToken"] = "org.matrix.msc3231.login.registration_token"; -})(AuthType = exports.AuthType || (exports.AuthType = {})); -class NoAuthFlowFoundError extends Error { - // eslint-disable-next-line @typescript-eslint/naming-convention, camelcase - constructor(m, required_stages, flows) { - super(m); - this.required_stages = required_stages; - this.flows = flows; - this.name = "NoAuthFlowFoundError"; - } -} -/** - * Abstracts the logic used to drive the interactive auth process. - * - *

Components implementing an interactive auth flow should instantiate one of - * these, passing in the necessary callbacks to the constructor. They should - * then call attemptAuth, which will return a promise which will resolve or - * reject when the interactive-auth process completes. - * - *

Meanwhile, calls will be made to the startAuthStage and doRequest - * callbacks, and information gathered from the user can be submitted with - * submitAuthDict. - * - * @param opts - options object - */ -class InteractiveAuth { - constructor(opts) { - this.requestingEmailToken = false; - this.attemptAuthDeferred = null; - this.chosenFlow = null; - this.currentStage = null; - this.emailAttempt = 1; - // if we are currently trying to submit an auth dict (which includes polling) - // the promise the will resolve/reject when it completes - this.submitPromise = null; - /** - * Requests a new email token and sets the email sid for the validation session - */ - this.requestEmailToken = () => __awaiter(this, void 0, void 0, function* () { - if (!this.requestingEmailToken) { - logger_1.logger.trace("Requesting email token. Attempt: " + this.emailAttempt); - // If we've picked a flow with email auth, we send the email - // now because we want the request to fail as soon as possible - // if the email address is not valid (ie. already taken or not - // registered, depending on what the operation is). - this.requestingEmailToken = true; - try { - const requestTokenResult = yield this.requestEmailTokenCallback(this.inputs.emailAddress, this.clientSecret, this.emailAttempt++, this.data.session); - this.emailSid = requestTokenResult.sid; - logger_1.logger.trace("Email token request succeeded"); - } - finally { - this.requestingEmailToken = false; - } - } - else { - logger_1.logger.warn("Could not request email token: Already requesting"); - } - }); - this.matrixClient = opts.matrixClient; - this.data = opts.authData || {}; - this.requestCallback = opts.doRequest; - this.busyChangedCallback = opts.busyChanged; - // startAuthStage included for backwards compat - this.stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage; - this.requestEmailTokenCallback = opts.requestEmailToken; - this.inputs = opts.inputs || {}; - if (opts.sessionId) - this.data.session = opts.sessionId; - this.clientSecret = opts.clientSecret || this.matrixClient.generateClientSecret(); - this.emailSid = opts.emailSid; - } - /** - * begin the authentication process. - * - * @returns which resolves to the response on success, - * or rejects with the error on failure. Rejects with NoAuthFlowFoundError if - * no suitable authentication flow can be found - */ - attemptAuth() { - var _a, _b; - // This promise will be quite long-lived and will resolve when the - // request is authenticated and completes successfully. - this.attemptAuthDeferred = (0, utils_1.defer)(); - // pluck the promise out now, as doRequest may clear before we return - const promise = this.attemptAuthDeferred.promise; - // if we have no flows, try a request to acquire the flows - if (!((_a = this.data) === null || _a === void 0 ? void 0 : _a.flows)) { - (_b = this.busyChangedCallback) === null || _b === void 0 ? void 0 : _b.call(this, true); - // use the existing sessionId, if one is present. - const auth = this.data.session ? { session: this.data.session } : null; - this.doRequest(auth).finally(() => { - var _a; - (_a = this.busyChangedCallback) === null || _a === void 0 ? void 0 : _a.call(this, false); - }); - } - else { - this.startNextAuthStage(); - } - return promise; - } - /** - * Poll to check if the auth session or current stage has been - * completed out-of-band. If so, the attemptAuth promise will - * be resolved. - */ - poll() { - return __awaiter(this, void 0, void 0, function* () { - if (!this.data.session) - return; - // likewise don't poll if there is no auth session in progress - if (!this.attemptAuthDeferred) - return; - // if we currently have a request in flight, there's no point making - // another just to check what the status is - if (this.submitPromise) - return; - let authDict = {}; - if (this.currentStage == EMAIL_STAGE_TYPE) { - // The email can be validated out-of-band, but we need to provide the - // creds so the HS can go & check it. - if (this.emailSid) { - const creds = { - sid: this.emailSid, - client_secret: this.clientSecret, - }; - if (yield this.matrixClient.doesServerRequireIdServerParam()) { - const idServerParsedUrl = new URL(this.matrixClient.getIdentityServerUrl()); - creds.id_server = idServerParsedUrl.host; - } - authDict = { - type: EMAIL_STAGE_TYPE, - // TODO: Remove `threepid_creds` once servers support proper UIA - // See https://github.com/matrix-org/synapse/issues/5665 - // See https://github.com/matrix-org/matrix-doc/issues/2220 - threepid_creds: creds, - threepidCreds: creds, - }; - } - } - this.submitAuthDict(authDict, true); - }); - } - /** - * get the auth session ID - * - * @returns session id - */ - getSessionId() { - var _a; - return (_a = this.data) === null || _a === void 0 ? void 0 : _a.session; - } - /** - * get the client secret used for validation sessions - * with the identity server. - * - * @returns client secret - */ - getClientSecret() { - return this.clientSecret; - } - /** - * get the server params for a given stage - * - * @param loginType - login type for the stage - * @returns any parameters from the server for this stage - */ - getStageParams(loginType) { - var _a; - return (_a = this.data.params) === null || _a === void 0 ? void 0 : _a[loginType]; - } - getChosenFlow() { - return this.chosenFlow; - } - /** - * submit a new auth dict and fire off the request. This will either - * make attemptAuth resolve/reject, or cause the startAuthStage callback - * to be called for a new stage. - * - * @param authData - new auth dict to send to the server. Should - * include a `type` property denoting the login type, as well as any - * other params for that stage. - * @param background - If true, this request failing will not result - * in the attemptAuth promise being rejected. This can be set to true - * for requests that just poll to see if auth has been completed elsewhere. - */ - submitAuthDict(authData, background = false) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - if (!this.attemptAuthDeferred) { - throw new Error("submitAuthDict() called before attemptAuth()"); - } - if (!background) { - (_a = this.busyChangedCallback) === null || _a === void 0 ? void 0 : _a.call(this, true); - } - // if we're currently trying a request, wait for it to finish - // as otherwise we can get multiple 200 responses which can mean - // things like multiple logins for register requests. - // (but discard any exceptions as we only care when its done, - // not whether it worked or not) - while (this.submitPromise) { - try { - yield this.submitPromise; - } - catch (e) { } - } - // use the sessionid from the last request, if one is present. - let auth; - if (this.data.session) { - auth = { - session: this.data.session, - }; - Object.assign(auth, authData); - } - else { - auth = authData; - } - try { - // NB. the 'background' flag is deprecated by the busyChanged - // callback and is here for backwards compat - this.submitPromise = this.doRequest(auth, background); - yield this.submitPromise; - } - finally { - this.submitPromise = null; - if (!background) { - (_b = this.busyChangedCallback) === null || _b === void 0 ? void 0 : _b.call(this, false); - } - } - }); - } - /** - * Gets the sid for the email validation session - * Specific to m.login.email.identity - * - * @returns The sid of the email auth session - */ - getEmailSid() { - return this.emailSid; - } - /** - * Sets the sid for the email validation session - * This must be set in order to successfully poll for completion - * of the email validation. - * Specific to m.login.email.identity - * - * @param sid - The sid for the email validation session - */ - setEmailSid(sid) { - this.emailSid = sid; - } - /** - * Fire off a request, and either resolve the promise, or call - * startAuthStage. - * - * @internal - * @param auth - new auth dict, including session id - * @param background - If true, this request is a background poll, so it - * failing will not result in the attemptAuth promise being rejected. - * This can be set to true for requests that just poll to see if auth has - * been completed elsewhere. - */ - doRequest(auth, background = false) { - var _a, _b, _c, _d; - return __awaiter(this, void 0, void 0, function* () { - try { - const result = yield this.requestCallback(auth, background); - this.attemptAuthDeferred.resolve(result); - this.attemptAuthDeferred = null; - } - catch (error) { - // sometimes UI auth errors don't come with flows - const errorFlows = (_b = (_a = error.data) === null || _a === void 0 ? void 0 : _a.flows) !== null && _b !== void 0 ? _b : null; - const haveFlows = this.data.flows || Boolean(errorFlows); - if (error.httpStatus !== 401 || !error.data || !haveFlows) { - // doesn't look like an interactive-auth failure. - if (!background) { - (_c = this.attemptAuthDeferred) === null || _c === void 0 ? void 0 : _c.reject(error); - } - else { - // We ignore all failures here (even non-UI auth related ones) - // since we don't want to suddenly fail if the internet connection - // had a blip whilst we were polling - logger_1.logger.log("Background poll request failed doing UI auth: ignoring", error); - } - } - if (!error.data) { - error.data = {}; - } - // if the error didn't come with flows, completed flows or session ID, - // copy over the ones we have. Synapse sometimes sends responses without - // any UI auth data (eg. when polling for email validation, if the email - // has not yet been validated). This appears to be a Synapse bug, which - // we workaround here. - if (!error.data.flows && - !error.data.completed && - !error.data.session) { - error.data.flows = this.data.flows; - error.data.completed = this.data.completed; - error.data.session = this.data.session; - } - this.data = error.data; - try { - this.startNextAuthStage(); - } - catch (e) { - this.attemptAuthDeferred.reject(e); - this.attemptAuthDeferred = null; - return; - } - if (!this.emailSid && ((_d = this.chosenFlow) === null || _d === void 0 ? void 0 : _d.stages.includes(AuthType.Email))) { - try { - yield this.requestEmailToken(); - // NB. promise is not resolved here - at some point, doRequest - // will be called again and if the user has jumped through all - // the hoops correctly, auth will be complete and the request - // will succeed. - // Also, we should expose the fact that this request has compledted - // so clients can know that the email has actually been sent. - } - catch (e) { - // we failed to request an email token, so fail the request. - // This could be due to the email already beeing registered - // (or not being registered, depending on what we're trying - // to do) or it could be a network failure. Either way, pass - // the failure up as the user can't complete auth if we can't - // send the email, for whatever reason. - this.attemptAuthDeferred.reject(e); - this.attemptAuthDeferred = null; - } - } - } - }); - } - /** - * Pick the next stage and call the callback - * - * @internal - * @throws {@link NoAuthFlowFoundError} If no suitable authentication flow can be found - */ - startNextAuthStage() { - var _a, _b, _c, _d; - const nextStage = this.chooseStage(); - if (!nextStage) { - throw new Error("No incomplete flows from the server"); - } - this.currentStage = nextStage; - if (nextStage === AuthType.Dummy) { - this.submitAuthDict({ - type: "m.login.dummy", - }); - return; - } - if (((_a = this.data) === null || _a === void 0 ? void 0 : _a.errcode) || ((_b = this.data) === null || _b === void 0 ? void 0 : _b.error)) { - this.stateUpdatedCallback(nextStage, { - errcode: ((_c = this.data) === null || _c === void 0 ? void 0 : _c.errcode) || "", - error: ((_d = this.data) === null || _d === void 0 ? void 0 : _d.error) || "", - }); - return; - } - this.stateUpdatedCallback(nextStage, nextStage === EMAIL_STAGE_TYPE ? { emailSid: this.emailSid } : {}); - } - /** - * Pick the next auth stage - * - * @internal - * @returns login type - * @throws {@link NoAuthFlowFoundError} If no suitable authentication flow can be found - */ - chooseStage() { - if (this.chosenFlow === null) { - this.chosenFlow = this.chooseFlow(); - } - logger_1.logger.log("Active flow => %s", JSON.stringify(this.chosenFlow)); - const nextStage = this.firstUncompletedStage(this.chosenFlow); - logger_1.logger.log("Next stage: %s", nextStage); - return nextStage; - } - /** - * Pick one of the flows from the returned list - * If a flow using all of the inputs is found, it will - * be returned, otherwise, null will be returned. - * - * Only flows using all given inputs are chosen because it - * is likely to be surprising if the user provides a - * credential and it is not used. For example, for registration, - * this could result in the email not being used which would leave - * the account with no means to reset a password. - * - * @internal - * @returns flow - * @throws {@link NoAuthFlowFoundError} If no suitable authentication flow can be found - */ - chooseFlow() { - const flows = this.data.flows || []; - // we've been given an email or we've already done an email part - const haveEmail = Boolean(this.inputs.emailAddress) || Boolean(this.emailSid); - const haveMsisdn = Boolean(this.inputs.phoneCountry) && Boolean(this.inputs.phoneNumber); - for (const flow of flows) { - let flowHasEmail = false; - let flowHasMsisdn = false; - for (const stage of flow.stages) { - if (stage === EMAIL_STAGE_TYPE) { - flowHasEmail = true; - } - else if (stage == MSISDN_STAGE_TYPE) { - flowHasMsisdn = true; - } - } - if (flowHasEmail == haveEmail && flowHasMsisdn == haveMsisdn) { - return flow; - } - } - const requiredStages = []; - if (haveEmail) - requiredStages.push(EMAIL_STAGE_TYPE); - if (haveMsisdn) - requiredStages.push(MSISDN_STAGE_TYPE); - // Throw an error with a fairly generic description, but with more - // information such that the app can give a better one if so desired. - throw new NoAuthFlowFoundError("No appropriate authentication flow found", requiredStages, flows); - } - /** - * Get the first uncompleted stage in the given flow - * - * @internal - * @returns login type - */ - firstUncompletedStage(flow) { - const completed = this.data.completed || []; - return flow.stages.find((stageType) => !completed.includes(stageType)); - } -} -exports.InteractiveAuth = InteractiveAuth; - -},{"./logger":374,"./utils":416}],374:[function(require,module,exports){ -"use strict"; -/* -Copyright 2018 André Jaenisch -Copyright 2019, 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.logger = void 0; -const loglevel_1 = __importDefault(require("loglevel")); -// This is to demonstrate, that you can use any namespace you want. -// Namespaces allow you to turn on/off the logging for specific parts of the -// application. -// An idea would be to control this via an environment variable (on Node.js). -// See https://www.npmjs.com/package/debug to see how this could be implemented -// Part of #332 is introducing a logging library in the first place. -const DEFAULT_NAMESPACE = "matrix"; -// because rageshakes in react-sdk hijack the console log, also at module load time, -// initializing the logger here races with the initialization of rageshakes. -// to avoid the issue, we override the methodFactory of loglevel that binds to the -// console methods at initialization time by a factory that looks up the console methods -// when logging so we always get the current value of console methods. -loglevel_1.default.methodFactory = function (methodName, logLevel, loggerName) { - return function (...args) { - /* eslint-disable @typescript-eslint/no-invalid-this */ - if (this.prefix) { - args.unshift(this.prefix); - } - /* eslint-enable @typescript-eslint/no-invalid-this */ - const supportedByConsole = methodName === "error" || methodName === "warn" || methodName === "trace" || methodName === "info"; - /* eslint-disable no-console */ - if (supportedByConsole) { - return console[methodName](...args); - } - else { - return console.log(...args); - } - /* eslint-enable no-console */ - }; -}; -/** - * Drop-in replacement for `console` using {@link https://www.npmjs.com/package/loglevel|loglevel}. - * Can be tailored down to specific use cases if needed. - */ -exports.logger = loglevel_1.default.getLogger(DEFAULT_NAMESPACE); -exports.logger.setLevel(loglevel_1.default.levels.DEBUG, false); -function extendLogger(logger) { - logger.withPrefix = function (prefix) { - const existingPrefix = this.prefix || ""; - return getPrefixedLogger(existingPrefix + prefix); - }; -} -extendLogger(exports.logger); -function getPrefixedLogger(prefix) { - const prefixLogger = loglevel_1.default.getLogger(`${DEFAULT_NAMESPACE}-${prefix}`); - if (prefixLogger.prefix !== prefix) { - // Only do this setup work the first time through, as loggers are saved by name. - extendLogger(prefixLogger); - prefixLogger.prefix = prefix; - prefixLogger.setLevel(loglevel_1.default.levels.DEBUG, false); - } - return prefixLogger; -} - -},{"loglevel":151}],375:[function(require,module,exports){ -(function (global){(function (){ -"use strict"; -/* -Copyright 2015-2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createRoomWidgetClient = exports.createClient = exports.setCryptoStoreFactory = exports.GroupCallType = exports.GroupCallState = exports.GroupCallIntent = exports.GroupCallEvent = exports.createNewMatrixCall = exports.SecretStorage = exports.ContentHelpers = void 0; -const memory_crypto_store_1 = require("./crypto/store/memory-crypto-store"); -const memory_1 = require("./store/memory"); -const scheduler_1 = require("./scheduler"); -const client_1 = require("./client"); -const embedded_1 = require("./embedded"); -__exportStar(require("./client"), exports); -__exportStar(require("./embedded"), exports); -__exportStar(require("./http-api"), exports); -__exportStar(require("./autodiscovery"), exports); -__exportStar(require("./sync-accumulator"), exports); -__exportStar(require("./errors"), exports); -__exportStar(require("./models/beacon"), exports); -__exportStar(require("./models/event"), exports); -__exportStar(require("./models/room"), exports); -__exportStar(require("./models/event-timeline"), exports); -__exportStar(require("./models/event-timeline-set"), exports); -__exportStar(require("./models/poll"), exports); -__exportStar(require("./models/room-member"), exports); -__exportStar(require("./models/room-state"), exports); -__exportStar(require("./models/user"), exports); -__exportStar(require("./scheduler"), exports); -__exportStar(require("./filter"), exports); -__exportStar(require("./timeline-window"), exports); -__exportStar(require("./interactive-auth"), exports); -__exportStar(require("./service-types"), exports); -__exportStar(require("./store/memory"), exports); -__exportStar(require("./store/indexeddb"), exports); -__exportStar(require("./crypto/store/memory-crypto-store"), exports); -__exportStar(require("./crypto/store/indexeddb-crypto-store"), exports); -__exportStar(require("./content-repo"), exports); -__exportStar(require("./@types/event"), exports); -__exportStar(require("./@types/PushRules"), exports); -__exportStar(require("./@types/partials"), exports); -__exportStar(require("./@types/requests"), exports); -__exportStar(require("./@types/search"), exports); -__exportStar(require("./models/room-summary"), exports); -exports.ContentHelpers = __importStar(require("./content-helpers")); -exports.SecretStorage = __importStar(require("./secret-storage")); -var call_1 = require("./webrtc/call"); -Object.defineProperty(exports, "createNewMatrixCall", { enumerable: true, get: function () { return call_1.createNewMatrixCall; } }); -var groupCall_1 = require("./webrtc/groupCall"); -Object.defineProperty(exports, "GroupCallEvent", { enumerable: true, get: function () { return groupCall_1.GroupCallEvent; } }); -Object.defineProperty(exports, "GroupCallIntent", { enumerable: true, get: function () { return groupCall_1.GroupCallIntent; } }); -Object.defineProperty(exports, "GroupCallState", { enumerable: true, get: function () { return groupCall_1.GroupCallState; } }); -Object.defineProperty(exports, "GroupCallType", { enumerable: true, get: function () { return groupCall_1.GroupCallType; } }); -let cryptoStoreFactory = () => new memory_crypto_store_1.MemoryCryptoStore(); -/** - * Configure a different factory to be used for creating crypto stores - * - * @param fac - a function which will return a new {@link CryptoStore} - */ -function setCryptoStoreFactory(fac) { - cryptoStoreFactory = fac; -} -exports.setCryptoStoreFactory = setCryptoStoreFactory; -function amendClientOpts(opts) { - var _a, _b, _c; - opts.store = - (_a = opts.store) !== null && _a !== void 0 ? _a : new memory_1.MemoryStore({ - localStorage: global.localStorage, - }); - opts.scheduler = (_b = opts.scheduler) !== null && _b !== void 0 ? _b : new scheduler_1.MatrixScheduler(); - opts.cryptoStore = (_c = opts.cryptoStore) !== null && _c !== void 0 ? _c : cryptoStoreFactory(); - return opts; -} -/** - * Construct a Matrix Client. Similar to {@link MatrixClient} - * except that the 'request', 'store' and 'scheduler' dependencies are satisfied. - * @param opts - The configuration options for this client. These configuration - * options will be passed directly to {@link MatrixClient}. - * - * @returns A new matrix client. - * @see {@link MatrixClient} for the full list of options for - * `opts`. - */ -function createClient(opts) { - return new client_1.MatrixClient(amendClientOpts(opts)); -} -exports.createClient = createClient; -function createRoomWidgetClient(widgetApi, capabilities, roomId, opts) { - return new embedded_1.RoomWidgetClient(widgetApi, capabilities, roomId, amendClientOpts(opts)); -} -exports.createRoomWidgetClient = createRoomWidgetClient; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"./@types/PushRules":304,"./@types/event":306,"./@types/partials":309,"./@types/requests":312,"./@types/search":313,"./autodiscovery":319,"./client":321,"./content-helpers":322,"./content-repo":323,"./crypto/store/indexeddb-crypto-store":346,"./crypto/store/memory-crypto-store":348,"./embedded":358,"./errors":359,"./filter":364,"./http-api":367,"./interactive-auth":373,"./models/beacon":378,"./models/event":383,"./models/event-timeline":382,"./models/event-timeline-set":381,"./models/poll":385,"./models/room":392,"./models/room-member":389,"./models/room-state":390,"./models/room-summary":391,"./models/user":396,"./scheduler":403,"./secret-storage":404,"./service-types":405,"./store/indexeddb":410,"./store/memory":411,"./sync-accumulator":413,"./timeline-window":415,"./webrtc/call":418,"./webrtc/groupCall":422}],376:[function(require,module,exports){ -"use strict"; -/* -Copyright 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MSC3089Branch = void 0; -const event_1 = require("../@types/event"); -const event_timeline_1 = require("./event-timeline"); -/** - * 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. - */ -class MSC3089Branch { - constructor(client, indexEvent, directory) { - this.client = client; - this.indexEvent = indexEvent; - this.directory = directory; - // Nothing to do - } - /** - * The file ID. - */ - get id() { - const 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 _a; - return (_a = this.indexEvent.getContent()["version"]) !== null && _a !== void 0 ? _a : 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() { - return __awaiter(this, void 0, void 0, function* () { - yield this.client.sendStateEvent(this.roomId, event_1.UNSTABLE_MSC3089_BRANCH.name, {}, this.id); - yield this.client.redactEvent(this.roomId, this.id); - const nextVersion = (yield this.getVersionHistory())[1]; // [0] will be us - if (nextVersion) - yield nextVersion.delete(); // implicit recursion - }); - } - /** - * 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) { - return __awaiter(this, void 0, void 0, function* () { - yield this.client.sendStateEvent(this.roomId, event_1.UNSTABLE_MSC3089_BRANCH.name, Object.assign(Object.assign({}, this.indexEvent.getContent()), { name: name }), this.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) { - return __awaiter(this, void 0, void 0, function* () { - yield this.client.sendStateEvent(this.roomId, event_1.UNSTABLE_MSC3089_BRANCH.name, Object.assign(Object.assign({}, this.indexEvent.getContent()), { locked: locked }), this.id); - }); - } - /** - * Gets information about the file needed to download it. - * @returns Information about the file. - */ - getFileInfo() { - return __awaiter(this, void 0, void 0, function* () { - const event = yield this.getFileEvent(); - const file = event.getOriginalContent()["file"]; - const httpUrl = this.client.mxcUrlToHttp(file["url"]); - if (!httpUrl) { - throw new Error(`No HTTP URL available for ${file["url"]}`); - } - return { info: file, httpUrl: httpUrl }; - }); - } - /** - * Gets the event the file points to. - * @returns Promise which resolves to the file's event. - */ - getFileEvent() { - return __awaiter(this, void 0, void 0, function* () { - const room = this.client.getRoom(this.roomId); - if (!room) - throw new Error("Unknown room"); - let event = room.getUnfilteredTimelineSet().findEventById(this.id); - // keep scrolling back if needed until we find the event or reach the start of the room: - while (!event && room.getLiveTimeline().getState(event_timeline_1.EventTimeline.BACKWARDS).paginationToken) { - yield this.client.scrollback(room, 100); - event = room.getUnfilteredTimelineSet().findEventById(this.id); - } - if (!event) - throw new Error("Failed to find event"); - // Sometimes the event isn't decrypted for us, so do that. We specifically set `emit: true` - // to ensure that the relations system in the sdk will function. - yield this.client.decryptEventIfNeeded(event, { emit: true, isRetry: true }); - 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) { - return __awaiter(this, void 0, void 0, function* () { - const fileEventResponse = yield this.directory.createFile(name, encryptedContents, info, Object.assign(Object.assign({}, (additionalContent !== null && additionalContent !== void 0 ? additionalContent : {})), { "m.new_content": true, "m.relates_to": { - rel_type: event_1.RelationType.Replace, - event_id: this.id, - } })); - // Update the version of the new event - yield this.client.sendStateEvent(this.roomId, event_1.UNSTABLE_MSC3089_BRANCH.name, { - active: true, - name: name, - version: this.version + 1, - }, fileEventResponse["event_id"]); - // Deprecate ourselves - yield this.client.sendStateEvent(this.roomId, event_1.UNSTABLE_MSC3089_BRANCH.name, Object.assign(Object.assign({}, this.indexEvent.getContent()), { active: false }), this.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() { - return __awaiter(this, void 0, void 0, function* () { - const fileHistory = []; - fileHistory.push(this); // start with ourselves - const room = this.client.getRoom(this.roomId); - if (!room) - throw new Error("Invalid or unknown room"); - // Clone the timeline to reverse it, getting most-recent-first ordering, hopefully - // shortening the awful loop below. Without the clone, we can unintentionally mutate - // the timeline. - const timelineEvents = [...room.getLiveTimeline().getEvents()].reverse(); - // XXX: This is a very inefficient search, but it's the best we can do with the - // relations structure we have in the SDK. As of writing, it is not worth the - // investment in improving the structure. - let childEvent; - let parentEvent = yield this.getFileEvent(); - do { - childEvent = timelineEvents.find((e) => e.replacingEventId() === parentEvent.getId()); - if (childEvent) { - const branch = this.directory.getFile(childEvent.getId()); - if (branch) { - fileHistory.push(branch); - parentEvent = childEvent; - } - else { - break; // prevent infinite loop - } - } - } while (childEvent); - return fileHistory; - }); - } -} -exports.MSC3089Branch = MSC3089Branch; - -},{"../@types/event":306,"./event-timeline":382}],377:[function(require,module,exports){ -"use strict"; -/* -Copyright 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MSC3089TreeSpace = exports.TreePermissions = exports.DEFAULT_TREE_POWER_LEVELS_TEMPLATE = void 0; -const p_retry_1 = __importDefault(require("p-retry")); -const event_1 = require("../@types/event"); -const logger_1 = require("../logger"); -const utils_1 = require("../utils"); -const MSC3089Branch_1 = require("./MSC3089Branch"); -const megolm_1 = require("../crypto/algorithms/megolm"); -/** - * The recommended defaults for a tree space's power levels. Note that this - * is UNSTABLE and subject to breaking changes without notice. - */ -exports.DEFAULT_TREE_POWER_LEVELS_TEMPLATE = { - // Owner - invite: 100, - kick: 100, - ban: 100, - // Editor - redact: 50, - state_default: 50, - events_default: 50, - // Viewer - users_default: 0, - // Mixed - events: { - [event_1.EventType.RoomPowerLevels]: 100, - [event_1.EventType.RoomHistoryVisibility]: 100, - [event_1.EventType.RoomTombstone]: 100, - [event_1.EventType.RoomEncryption]: 100, - [event_1.EventType.RoomName]: 50, - [event_1.EventType.RoomMessage]: 50, - [event_1.EventType.RoomMessageEncrypted]: 50, - [event_1.EventType.Sticker]: 50, - }, - users: {}, // defined by calling code -}; -/** - * 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; -(function (TreePermissions) { - TreePermissions["Viewer"] = "viewer"; - TreePermissions["Editor"] = "editor"; - TreePermissions["Owner"] = "owner"; -})(TreePermissions = exports.TreePermissions || (exports.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. - */ -class MSC3089TreeSpace { - constructor(client, roomId) { - this.client = client; - this.roomId = roomId; - 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() { - // XXX: This is absolutely not how you find out if the space is top level - // but is safe for a managed usecase like we offer in the SDK. - const parentEvents = this.room.currentState.getStateEvents(event_1.EventType.SpaceParent); - if (!(parentEvents === null || parentEvents === void 0 ? void 0 : parentEvents.length)) - return true; - return parentEvents.every((e) => { var _a; return !((_a = e.getContent()) === null || _a === void 0 ? void 0 : _a["via"]); }); - } - /** - * Sets the name of the tree space. - * @param name - The new name for the space. - * @returns Promise which resolves when complete. - */ - setName(name) { - return __awaiter(this, void 0, void 0, function* () { - yield this.client.sendStateEvent(this.roomId, event_1.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. - * @param shareHistoryKeys - True (default) to share encryption keys - * with the invited user. This will allow them to decrypt the events (files) - * in the tree. Keys will not be shared if the room is lacking appropriate - * history visibility (by default, history visibility is "shared" in trees, - * which is an appropriate visibility for these purposes). - * @returns Promise which resolves when complete. - */ - invite(userId, andSubspaces = true, shareHistoryKeys = true) { - return __awaiter(this, void 0, void 0, function* () { - const promises = [this.retryInvite(userId)]; - if (andSubspaces) { - promises.push(...this.getDirectories().map((d) => d.invite(userId, andSubspaces, shareHistoryKeys))); - } - return Promise.all(promises).then(() => { - // Note: key sharing is default on because for file trees it is relatively important that the invite - // target can actually decrypt the files. The implied use case is that by inviting a user to the tree - // it means the sender would like the receiver to view/download the files contained within, much like - // sharing a folder in other circles. - if (shareHistoryKeys && (0, megolm_1.isRoomSharedHistory)(this.room)) { - // noinspection JSIgnoredPromiseFromCall - we aren't concerned as much if this fails. - this.client.sendSharedHistoryKeys(this.roomId, [userId]); - } - }); - }); - } - retryInvite(userId) { - return (0, utils_1.simpleRetryOperation)(() => __awaiter(this, void 0, void 0, function* () { - yield this.client.invite(this.roomId, userId).catch((e) => { - // We don't want to retry permission errors forever... - if ((e === null || e === void 0 ? void 0 : e.errcode) === "M_FORBIDDEN") { - throw new p_retry_1.default.AbortError(e); - } - throw e; - }); - })); - } - /** - * 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 _a; - return __awaiter(this, void 0, void 0, function* () { - const currentPls = this.room.currentState.getStateEvents(event_1.EventType.RoomPowerLevels, ""); - if (Array.isArray(currentPls)) - throw new Error("Unexpected return type for power levels"); - const pls = (currentPls === null || currentPls === void 0 ? void 0 : currentPls.getContent()) || {}; - const viewLevel = pls["users_default"] || 0; - const editLevel = pls["events_default"] || 50; - const adminLevel = ((_a = pls["events"]) === null || _a === void 0 ? void 0 : _a[event_1.EventType.RoomPowerLevels]) || 100; - const 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 this.client.sendStateEvent(this.roomId, event_1.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 _a, _b; - const currentPls = this.room.currentState.getStateEvents(event_1.EventType.RoomPowerLevels, ""); - if (Array.isArray(currentPls)) - throw new Error("Unexpected return type for power levels"); - const pls = (currentPls === null || currentPls === void 0 ? void 0 : currentPls.getContent()) || {}; - const viewLevel = pls["users_default"] || 0; - const editLevel = pls["events_default"] || 50; - const adminLevel = ((_a = pls["events"]) === null || _a === void 0 ? void 0 : _a[event_1.EventType.RoomPowerLevels]) || 100; - const userLevel = ((_b = pls["users"]) === null || _b === void 0 ? void 0 : _b[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) { - return __awaiter(this, void 0, void 0, function* () { - const directory = yield this.client.unstableCreateFileTree(name); - yield this.client.sendStateEvent(this.roomId, event_1.EventType.SpaceChild, { - via: [this.client.getDomain()], - }, directory.roomId); - yield this.client.sendStateEvent(directory.roomId, event_1.EventType.SpaceParent, { - via: [this.client.getDomain()], - }, this.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() { - const trees = []; - const children = this.room.currentState.getStateEvents(event_1.EventType.SpaceChild); - for (const child of children) { - try { - const stateKey = child.getStateKey(); - if (stateKey) { - const tree = this.client.unstableGetFileTreeSpace(stateKey); - if (tree) - trees.push(tree); - } - } - catch (e) { - logger_1.logger.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() { - return __awaiter(this, void 0, void 0, function* () { - const subdirectories = this.getDirectories(); - for (const dir of subdirectories) { - yield dir.delete(); - } - const kickMemberships = ["invite", "knock", "join"]; - const members = this.room.currentState.getStateEvents(event_1.EventType.RoomMember); - for (const member of members) { - const isNotUs = member.getStateKey() !== this.client.getUserId(); - if (isNotUs && kickMemberships.includes(member.getContent().membership)) { - const stateKey = member.getStateKey(); - if (!stateKey) { - throw new Error("State key not found for branch"); - } - yield this.client.kick(this.roomId, stateKey, "Room deleted"); - } - } - yield this.client.leave(this.roomId); - }); - } - getOrderedChildren(children) { - const ordered = children - .map((c) => ({ roomId: c.getStateKey(), order: c.getContent()["order"] })) - .filter((c) => c.roomId); - ordered.sort((a, b) => { - var _a, _b, _c, _d; - if (a.order && !b.order) { - return -1; - } - else if (!a.order && b.order) { - return 1; - } - else if (!a.order && !b.order) { - const roomA = this.client.getRoom(a.roomId); - const roomB = this.client.getRoom(b.roomId); - if (!roomA || !roomB) { - // just don't bother trying to do more partial sorting - return (0, utils_1.lexicographicCompare)(a.roomId, b.roomId); - } - const createTsA = (_b = (_a = roomA.currentState.getStateEvents(event_1.EventType.RoomCreate, "")) === null || _a === void 0 ? void 0 : _a.getTs()) !== null && _b !== void 0 ? _b : 0; - const createTsB = (_d = (_c = roomB.currentState.getStateEvents(event_1.EventType.RoomCreate, "")) === null || _c === void 0 ? void 0 : _c.getTs()) !== null && _d !== void 0 ? _d : 0; - if (createTsA === createTsB) { - return (0, utils_1.lexicographicCompare)(a.roomId, b.roomId); - } - return createTsA - createTsB; - } - else { - // both not-null orders - return (0, utils_1.lexicographicCompare)(a.order, b.order); - } - }); - return ordered; - } - getParentRoom() { - const parents = this.room.currentState.getStateEvents(event_1.EventType.SpaceParent); - const parent = parents[0]; // XXX: Wild assumption - if (!parent) - throw new Error("Expected to have a parent in a non-top level space"); - // XXX: We are assuming the parent is a valid tree space. - // We probably don't need to validate the parent room state for this usecase though. - const stateKey = parent.getStateKey(); - if (!stateKey) - throw new Error("No state key found for parent"); - const 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; - const parentRoom = this.getParentRoom(); - const children = parentRoom.currentState.getStateEvents(event_1.EventType.SpaceChild); - const ordered = this.getOrderedChildren(children); - return ordered.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 _a, _b; - return __awaiter(this, void 0, void 0, function* () { - if (this.isTopLevel) - throw new Error("Cannot set order of top level spaces currently"); - const parentRoom = this.getParentRoom(); - const children = parentRoom.currentState.getStateEvents(event_1.EventType.SpaceChild); - const ordered = this.getOrderedChildren(children); - index = Math.max(Math.min(index, ordered.length - 1), 0); - const currentIndex = this.getOrder(); - const movingUp = currentIndex < index; - if (movingUp && index === ordered.length - 1) { - index--; - } - else if (!movingUp && index === 0) { - index++; - } - const prev = ordered[movingUp ? index : index - 1]; - const next = ordered[movingUp ? index + 1 : index]; - let newOrder = utils_1.DEFAULT_ALPHABET[0]; - let ensureBeforeIsSane = false; - if (!prev) { - // Move to front - if (next === null || next === void 0 ? void 0 : next.order) { - newOrder = (0, utils_1.prevString)(next.order); - } - } - else if (index === ordered.length - 1) { - // Move to back - if (next === null || next === void 0 ? void 0 : next.order) { - newOrder = (0, utils_1.nextString)(next.order); - } - } - else { - // Move somewhere in the middle - const startOrder = prev === null || prev === void 0 ? void 0 : prev.order; - const endOrder = next === null || next === void 0 ? void 0 : next.order; - if (startOrder && endOrder) { - if (startOrder === endOrder) { - // Error case: just move +1 to break out of awful math - newOrder = (0, utils_1.nextString)(startOrder); - } - else { - newOrder = (0, utils_1.averageBetweenStrings)(startOrder, endOrder); - } - } - else { - if (startOrder) { - // We're at the end (endOrder is null, so no explicit order) - newOrder = (0, utils_1.nextString)(startOrder); - } - else if (endOrder) { - // We're at the start (startOrder is null, so nothing before us) - newOrder = (0, utils_1.prevString)(endOrder); - } - else { - // Both points are unknown. We're likely in a range where all the children - // don't have particular order values, so we may need to update them too. - // The other possibility is there's only us as a child, but we should have - // shown up in the other states. - ensureBeforeIsSane = true; - } - } - } - if (ensureBeforeIsSane) { - // We were asked by the order algorithm to prepare the moving space for a landing - // in the undefined order part of the order array, which means we need to update the - // spaces that come before it with a stable order value. - let lastOrder; - for (let i = 0; i <= index; i++) { - const target = ordered[i]; - if (i === 0) { - lastOrder = target.order; - } - if (!target.order) { - // XXX: We should be creating gaps to avoid conflicts - lastOrder = lastOrder ? (0, utils_1.nextString)(lastOrder) : utils_1.DEFAULT_ALPHABET[0]; - const currentChild = parentRoom.currentState.getStateEvents(event_1.EventType.SpaceChild, target.roomId); - const content = (_a = currentChild === null || currentChild === void 0 ? void 0 : currentChild.getContent()) !== null && _a !== void 0 ? _a : { via: [this.client.getDomain()] }; - yield this.client.sendStateEvent(parentRoom.roomId, event_1.EventType.SpaceChild, Object.assign(Object.assign({}, content), { order: lastOrder }), target.roomId); - } - else { - lastOrder = target.order; - } - } - if (lastOrder) { - newOrder = (0, utils_1.nextString)(lastOrder); - } - } - // TODO: Deal with order conflicts by reordering - // Now we can finally update our own order state - const currentChild = parentRoom.currentState.getStateEvents(event_1.EventType.SpaceChild, this.roomId); - const content = (_b = currentChild === null || currentChild === void 0 ? void 0 : currentChild.getContent()) !== null && _b !== void 0 ? _b : { via: [this.client.getDomain()] }; - yield this.client.sendStateEvent(parentRoom.roomId, event_1.EventType.SpaceChild, Object.assign(Object.assign({}, content), { - // TODO: Safely constrain to 50 character limit required by spaces. - order: newOrder }), this.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) { - return __awaiter(this, void 0, void 0, function* () { - const { content_uri: mxc } = yield this.client.uploadContent(encryptedContents, { - includeFilename: false, - }); - info.url = mxc; - const fileContent = { - msgtype: event_1.MsgType.File, - body: name, - url: mxc, - file: info, - }; - additionalContent = additionalContent !== null && additionalContent !== void 0 ? additionalContent : {}; - if (additionalContent["m.new_content"]) { - // We do the right thing according to the spec, but due to how relations are - // handled we also end up duplicating this information to the regular `content` - // as well. - additionalContent["m.new_content"] = fileContent; - } - const res = yield this.client.sendMessage(this.roomId, Object.assign(Object.assign(Object.assign({}, additionalContent), fileContent), { [event_1.UNSTABLE_MSC3089_LEAF.name]: {} })); - yield this.client.sendStateEvent(this.roomId, event_1.UNSTABLE_MSC3089_BRANCH.name, { - active: true, - name: 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) { - const branch = this.room.currentState.getStateEvents(event_1.UNSTABLE_MSC3089_BRANCH.name, fileEventId); - return branch ? new MSC3089Branch_1.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 _a; - const branches = (_a = this.room.currentState.getStateEvents(event_1.UNSTABLE_MSC3089_BRANCH.name)) !== null && _a !== void 0 ? _a : []; - return branches.map((e) => new MSC3089Branch_1.MSC3089Branch(this.client, e, this)); - } -} -exports.MSC3089TreeSpace = MSC3089TreeSpace; - -},{"../@types/event":306,"../crypto/algorithms/megolm":334,"../logger":374,"../utils":416,"./MSC3089Branch":376,"p-retry":225}],378:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Beacon = exports.getBeaconInfoIdentifier = exports.isTimestampInDuration = exports.BeaconEvent = void 0; -const content_helpers_1 = require("../content-helpers"); -const utils_1 = require("../utils"); -const typed_event_emitter_1 = require("./typed-event-emitter"); -var BeaconEvent; -(function (BeaconEvent) { - BeaconEvent["New"] = "Beacon.new"; - BeaconEvent["Update"] = "Beacon.update"; - BeaconEvent["LivenessChange"] = "Beacon.LivenessChange"; - BeaconEvent["Destroy"] = "Beacon.Destroy"; - BeaconEvent["LocationUpdate"] = "Beacon.LocationUpdate"; -})(BeaconEvent = exports.BeaconEvent || (exports.BeaconEvent = {})); -const isTimestampInDuration = (startTimestamp, durationMs, timestamp) => timestamp >= startTimestamp && startTimestamp + durationMs >= timestamp; -exports.isTimestampInDuration = isTimestampInDuration; -const getBeaconInfoIdentifier = (event) => `${event.getRoomId()}_${event.getStateKey()}`; -exports.getBeaconInfoIdentifier = getBeaconInfoIdentifier; -// https://github.com/matrix-org/matrix-spec-proposals/pull/3672 -class Beacon extends typed_event_emitter_1.TypedEventEmitter { - constructor(rootEvent) { - super(); - this.rootEvent = rootEvent; - this.clearLatestLocation = () => { - this._latestLocationEvent = undefined; - this.emit(BeaconEvent.LocationUpdate, this.latestLocationState); - }; - this.roomId = this.rootEvent.getRoomId(); - this.setBeaconInfo(this.rootEvent); - } - get isLive() { - return !!this._isLive; - } - get identifier() { - return (0, exports.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 && (0, content_helpers_1.parseBeaconContent)(this._latestLocationEvent.getContent()); - } - get latestLocationEvent() { - return this._latestLocationEvent; - } - update(beaconInfoEvent) { - if ((0, exports.getBeaconInfoIdentifier)(beaconInfoEvent) !== this.identifier) { - throw new Error("Invalid updating event"); - } - // don't update beacon with an older 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) { - const 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()) { - // beacon start timestamp is in the future - // check liveness again then - this.livenessWatchTimeout = setTimeout(() => { - this.monitorLiveness(); - }, this.beaconInfo.timestamp - Date.now()); - } - } - /** - * Process Beacon locations - * Emits BeaconEvent.LocationUpdate - */ - addLocations(beaconLocationEvents) { - var _a; - // discard locations for beacons that are not live - if (!this.isLive) { - return; - } - const validLocationEvents = beaconLocationEvents.filter((event) => { - const content = event.getContent(); - const parsed = (0, content_helpers_1.parseBeaconContent)(content); - if (!parsed.uri || !parsed.timestamp) - return false; // we won't be able to process these - const { timestamp } = parsed; - return (this._beaconInfo.timestamp && - // only include positions that were taken inside the beacon's live period - (0, exports.isTimestampInDuration)(this._beaconInfo.timestamp, this._beaconInfo.timeout, timestamp) && - // ignore positions older than our current latest location - (!this.latestLocationState || timestamp > this.latestLocationState.timestamp)); - }); - const latestLocationEvent = (_a = validLocationEvents.sort(utils_1.sortEventsByLatestContentTimestamp)) === null || _a === void 0 ? void 0 : _a[0]; - if (latestLocationEvent) { - this._latestLocationEvent = latestLocationEvent; - this.emit(BeaconEvent.LocationUpdate, this.latestLocationState); - } - } - setBeaconInfo(event) { - this._beaconInfo = (0, content_helpers_1.parseBeaconInfoContent)(event.getContent()); - this.checkLiveness(); - } - checkLiveness() { - const prevLiveness = this.isLive; - // element web sets a beacon's start timestamp to the senders local current time - // when Alice's system clock deviates slightly from Bob's a beacon Alice intended to be live - // may have a start timestamp in the future from Bob's POV - // handle this by adding 6min of leniency to the start timestamp when it is in the future - if (!this.beaconInfo) - return; - const startTimestamp = this.beaconInfo.timestamp > Date.now() - ? this.beaconInfo.timestamp - 360000 /* 6min */ - : this.beaconInfo.timestamp; - this._isLive = - !!this._beaconInfo.live && - !!startTimestamp && - (0, exports.isTimestampInDuration)(startTimestamp, this._beaconInfo.timeout, Date.now()); - if (prevLiveness !== this.isLive) { - this.emit(BeaconEvent.LivenessChange, this.isLive, this); - } - } -} -exports.Beacon = Beacon; - -},{"../content-helpers":322,"../utils":416,"./typed-event-emitter":395}],379:[function(require,module,exports){ -"use strict"; -/* -Copyright 2015 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.EventContext = void 0; -const event_timeline_1 = require("./event-timeline"); -class EventContext { - /** - * 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; - this.ourEventIndex = 0; - this.paginateTokens = { - [event_timeline_1.Direction.Backward]: null, - [event_timeline_1.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(backwards = false) { - return this.paginateTokens[backwards ? event_timeline_1.Direction.Backward : event_timeline_1.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, backwards = false) { - this.paginateTokens[backwards ? event_timeline_1.Direction.Backward : event_timeline_1.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, atStart = false) { - // TODO: should we share logic with Room.addEventsToTimeline? - // Should Room even use EventContext? - if (atStart) { - this.timeline = events.concat(this.timeline); - this.ourEventIndex += events.length; - } - else { - this.timeline = this.timeline.concat(events); - } - } -} -exports.EventContext = EventContext; - -},{"./event-timeline":382}],380:[function(require,module,exports){ -"use strict"; -/* -Copyright 2015 - 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.EventStatus = void 0; -/** - * Enum for event statuses. - * @readonly - */ -var EventStatus; -(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"; -})(EventStatus = exports.EventStatus || (exports.EventStatus = {})); - -},{}],381:[function(require,module,exports){ -"use strict"; -/* -Copyright 2016 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.EventTimelineSet = exports.DuplicateStrategy = void 0; -const event_timeline_1 = require("./event-timeline"); -const logger_1 = require("../logger"); -const room_1 = require("./room"); -const typed_event_emitter_1 = require("./typed-event-emitter"); -const relations_container_1 = require("./relations-container"); -const DEBUG = true; -/* istanbul ignore next */ -let debuglog; -if (DEBUG) { - // using bind means that we get to keep useful line numbers in the console - debuglog = logger_1.logger.log.bind(logger_1.logger); -} -else { - /* istanbul ignore next */ - debuglog = function () { }; -} -var DuplicateStrategy; -(function (DuplicateStrategy) { - DuplicateStrategy["Ignore"] = "ignore"; - DuplicateStrategy["Replace"] = "replace"; -})(DuplicateStrategy = exports.DuplicateStrategy || (exports.DuplicateStrategy = {})); -class EventTimelineSet extends typed_event_emitter_1.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. - * - *

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. - * - *

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. - * - *

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 isThreadTimeline - Whether this timeline set relates to a thread list timeline - * (e.g., All threads or My threads) - */ - constructor(room, opts = {}, client, thread, threadListType = null) { - var _a, _b, _c; - super(); - this.room = room; - this.thread = thread; - this.threadListType = threadListType; - this._eventIdToTimeline = new Map(); - this.timelineSupport = Boolean(opts.timelineSupport); - this.liveTimeline = new event_timeline_1.EventTimeline(this); - this.displayPendingEvents = opts.pendingEvents !== false; - // just a list - *not* ordered. - this.timelines = [this.liveTimeline]; - this._eventIdToTimeline = new Map(); - this.filter = opts.filter; - this.relations = (_b = (_a = this.room) === null || _a === void 0 ? void 0 : _a.relations) !== null && _b !== void 0 ? _b : new relations_container_1.RelationsContainer((_c = room === null || room === void 0 ? void 0 : room.client) !== null && _c !== void 0 ? _c : 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) { - const 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. - * - *

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) { - // Each EventTimeline has RoomState objects tracking the state at the start - // and end of that timeline. The copies at the end of the live timeline are - // special because they will have listeners attached to monitor changes to - // the current room state, so we move this RoomState from the end of the - // current live timeline to the end of the new one and, if necessary, - // replace it with a newly created one. We also make a copy for the start - // of the new timeline. - // if timeline support is disabled, forget about the old timelines - const resetAllTimelines = !this.timelineSupport || !forwardPaginationToken; - const oldTimeline = this.liveTimeline; - const newTimeline = resetAllTimelines - ? oldTimeline.forkLive(event_timeline_1.EventTimeline.FORWARDS) - : oldTimeline.fork(event_timeline_1.EventTimeline.FORWARDS); - if (resetAllTimelines) { - this.timelines = [newTimeline]; - this._eventIdToTimeline = new Map(); - } - else { - this.timelines.push(newTimeline); - } - if (forwardPaginationToken) { - // Now set the forward pagination token on the old live timeline - // so it can be forward-paginated. - oldTimeline.setPaginationToken(forwardPaginationToken, event_timeline_1.EventTimeline.FORWARDS); - } - // make sure we set the pagination token before firing timelineReset, - // otherwise clients which start back-paginating will fail, and then get - // stuck without realising that they *can* back-paginate. - newTimeline.setPaginationToken(backPaginationToken !== null && backPaginationToken !== void 0 ? backPaginationToken : null, event_timeline_1.EventTimeline.BACKWARDS); - // Now we can swap the live timeline to the new one. - this.liveTimeline = newTimeline; - this.emit(room_1.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 === undefined) { - return null; - } - const res = this._eventIdToTimeline.get(eventId); - return res === undefined ? 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) { - const tl = this.getTimelineForEvent(eventId); - if (!tl) { - return undefined; - } - 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."); - } - const timeline = new event_timeline_1.EventTimeline(this); - this.timelines.push(timeline); - return timeline; - } - /** - * Add events to a timeline - * - *

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 last 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, 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; - } - } - const direction = toStartOfTimeline ? event_timeline_1.EventTimeline.BACKWARDS : event_timeline_1.EventTimeline.FORWARDS; - const inverseDirection = toStartOfTimeline ? event_timeline_1.EventTimeline.FORWARDS : event_timeline_1.EventTimeline.BACKWARDS; - // Adding events to timelines can be quite complicated. The following - // illustrates some of the corner-cases. - // - // Let's say we start by knowing about four timelines. timeline3 and - // timeline4 are neighbours: - // - // timeline1 timeline2 timeline3 timeline4 - // [M] [P] [S] <------> [T] - // - // Now we paginate timeline1, and get the following events from the server: - // [M, N, P, R, S, T, U]. - // - // 1. First, we ignore event M, since we already know about it. - // - // 2. Next, we append N to timeline 1. - // - // 3. Next, we don't add event P, since we already know about it, - // but we do link together the timelines. We now have: - // - // timeline1 timeline2 timeline3 timeline4 - // [M, N] <---> [P] [S] <------> [T] - // - // 4. Now we add event R to timeline2: - // - // timeline1 timeline2 timeline3 timeline4 - // [M, N] <---> [P, R] [S] <------> [T] - // - // Note that we have switched the timeline we are working on from - // timeline1 to timeline2. - // - // 5. We ignore event S, but again join the timelines: - // - // timeline1 timeline2 timeline3 timeline4 - // [M, N] <---> [P, R] <---> [S] <------> [T] - // - // 6. We ignore event T, and the timelines are already joined, so there - // is nothing to do. - // - // 7. Finally, we add event U to timeline4: - // - // timeline1 timeline2 timeline3 timeline4 - // [M, N] <---> [P, R] <---> [S] <------> [T, U] - // - // The important thing to note in the above is what happened when we - // already knew about a given event: - // - // - if it was appropriate, we joined up the timelines (steps 3, 5). - // - in any case, we started adding further events to the timeline which - // contained the event we knew about (steps 3, 5, 6). - // - // - // So much for adding events to the timeline. But what do we want to do - // with the pagination token? - // - // In the case above, we will be given a pagination token which tells us how to - // get events beyond 'U' - in this case, it makes sense to store this - // against timeline4. But what if timeline4 already had 'U' and beyond? in - // that case, our best bet is to throw away the pagination token we were - // given and stick with whatever token timeline4 had previously. In short, - // we want to only store the pagination token if the last event we receive - // is one we didn't previously know about. - // - // We make an exception for this if it turns out that we already knew about - // *all* of the events, and we weren't able to join up any timelines. When - // that happens, it means our existing pagination token is faulty, since it - // is only telling us what we already know. Rather than repeatedly - // paginating with the same token, we might as well use the new pagination - // token in the hope that we eventually work our way out of the mess. - let didUpdate = false; - let lastEventWasNew = false; - for (const event of events) { - const eventId = event.getId(); - const existingTimeline = this._eventIdToTimeline.get(eventId); - if (!existingTimeline) { - // we don't know about this event yet. Just add it to the timeline. - this.addEventToTimeline(event, timeline, { - toStartOfTimeline, - }); - lastEventWasNew = true; - didUpdate = true; - continue; - } - lastEventWasNew = false; - if (existingTimeline == timeline) { - debuglog("Event " + eventId + " already in timeline " + timeline); - continue; - } - const neighbour = timeline.getNeighbouringTimeline(direction); - if (neighbour) { - // this timeline already has a neighbour in the relevant direction; - // let's assume the timelines are already correctly linked up, and - // skip over to it. - // - // there's probably some edge-case here where we end up with an - // event which is in a timeline a way down the chain, and there is - // a break in the chain somewhere. But I can't really imagine how - // that would happen, so I'm going to ignore it for now. - // - if (existingTimeline == neighbour) { - debuglog("Event " + eventId + " in neighbouring timeline - " + "switching to " + existingTimeline); - } - else { - debuglog("Event " + eventId + " already in a different " + "timeline " + existingTimeline); - } - timeline = existingTimeline; - continue; - } - // time to join the timelines. - logger_1.logger.info("Already have timeline for " + eventId + " - joining timeline " + timeline + " to " + existingTimeline); - // Variables to keep the line length limited below. - const existingIsLive = existingTimeline === this.liveTimeline; - const timelineIsLive = timeline === this.liveTimeline; - const backwardsIsLive = direction === event_timeline_1.EventTimeline.BACKWARDS && existingIsLive; - const forwardsIsLive = direction === event_timeline_1.EventTimeline.FORWARDS && timelineIsLive; - if (backwardsIsLive || forwardsIsLive) { - // The live timeline should never be spliced into a non-live position. - // We use independent logging to better discover the problem at a glance. - if (backwardsIsLive) { - logger_1.logger.warn("Refusing to set a preceding existingTimeLine on our " + - "timeline as the existingTimeLine is live (" + - existingTimeline + - ")"); - } - if (forwardsIsLive) { - logger_1.logger.warn("Refusing to set our preceding timeline on a existingTimeLine " + - "as our timeline is live (" + - timeline + - ")"); - } - continue; // abort splicing - try next event - } - timeline.setNeighbouringTimeline(existingTimeline, direction); - existingTimeline.setNeighbouringTimeline(timeline, inverseDirection); - timeline = existingTimeline; - didUpdate = true; - } - // see above - if the last event was new to us, or if we didn't find any - // new information, we update the pagination token for whatever - // timeline we ended up on. - if (lastEventWasNew || !didUpdate) { - if (direction === event_timeline_1.EventTimeline.FORWARDS && timeline === this.liveTimeline) { - logger_1.logger.warn({ lastEventWasNew, didUpdate }); // for debugging - logger_1.logger.warn(`Refusing to set forwards pagination token of live timeline ` + `${timeline} to ${paginationToken}`); - return; - } - timeline.setPaginationToken(paginationToken !== null && paginationToken !== void 0 ? paginationToken : null, direction); - } - } - addLiveEvent(event, duplicateStrategyOrOpts, fromCache = false, roomState) { - let duplicateStrategy = duplicateStrategyOrOpts || DuplicateStrategy.Ignore; - let timelineWasEmpty; - if (typeof duplicateStrategyOrOpts === "object") { - ({ - duplicateStrategy = DuplicateStrategy.Ignore, - fromCache = false, - roomState, - timelineWasEmpty, - } = duplicateStrategyOrOpts); - } - else if (duplicateStrategyOrOpts !== undefined) { - // Deprecation warning - // FIXME: Remove after 2023-06-01 (technical debt) - logger_1.logger.warn("Overload deprecated: " + - "`EventTimelineSet.addLiveEvent(event, duplicateStrategy?, fromCache?, roomState?)` " + - "is deprecated in favor of the overload with " + - "`EventTimelineSet.addLiveEvent(event, IAddLiveEventOptions)`"); - } - if (this.filter) { - const events = this.filter.filterRoomTimeline([event]); - if (!events.length) { - return; - } - } - const timeline = this._eventIdToTimeline.get(event.getId()); - if (timeline) { - if (duplicateStrategy === DuplicateStrategy.Replace) { - debuglog("EventTimelineSet.addLiveEvent: replacing duplicate event " + event.getId()); - const tlEvents = timeline.getEvents(); - for (let j = 0; j < tlEvents.length; j++) { - if (tlEvents[j].getId() === event.getId()) { - // still need to set the right metadata on this event - if (!roomState) { - roomState = timeline.getState(event_timeline_1.EventTimeline.FORWARDS); - } - event_timeline_1.EventTimeline.setEventMetadata(event, roomState, false); - tlEvents[j] = event; - // XXX: we need to fire an event when this happens. - break; - } - } - } - else { - debuglog("EventTimelineSet.addLiveEvent: ignoring duplicate event " + event.getId()); - } - return; - } - this.addEventToTimeline(event, this.liveTimeline, { - toStartOfTimeline: false, - fromCache, - roomState, - timelineWasEmpty, - }); - } - addEventToTimeline(event, timeline, toStartOfTimelineOrOpts, fromCache = false, roomState) { - var _a, _b; - let toStartOfTimeline = !!toStartOfTimelineOrOpts; - let timelineWasEmpty; - if (typeof toStartOfTimelineOrOpts === "object") { - ({ toStartOfTimeline, fromCache = false, roomState, timelineWasEmpty } = toStartOfTimelineOrOpts); - } - else if (toStartOfTimelineOrOpts !== undefined) { - // Deprecation warning - // FIXME: Remove after 2023-06-01 (technical debt) - logger_1.logger.warn("Overload deprecated: " + - "`EventTimelineSet.addEventToTimeline(event, timeline, toStartOfTimeline, fromCache?, roomState?)` " + - "is deprecated in favor of the overload with " + - "`EventTimelineSet.addEventToTimeline(event, timeline, IAddEventToTimelineOptions)`"); - } - if (timeline.getTimelineSet() !== this) { - throw new Error(`EventTimelineSet.addEventToTimeline: Timeline=${timeline.toString()} does not belong " + - "in timelineSet(threadId=${(_a = this.thread) === null || _a === void 0 ? void 0 : _a.id})`); - } - // Make sure events don't get mixed in timelines they shouldn't be in (e.g. a - // threaded message should not be in the main timeline). - // - // We can only run this check for timelines with a `room` because `canContain` - // requires it - if (this.room && !this.canContain(event)) { - let eventDebugString = `event=${event.getId()}`; - if (event.threadRootId) { - eventDebugString += `(belongs to thread=${event.threadRootId})`; - } - logger_1.logger.warn(`EventTimelineSet.addEventToTimeline: Ignoring ${eventDebugString} that does not belong ` + - `in timeline=${timeline.toString()} timelineSet(threadId=${(_b = this.thread) === null || _b === void 0 ? void 0 : _b.id})`); - return; - } - const eventId = event.getId(); - timeline.addEvent(event, { - toStartOfTimeline, - roomState, - timelineWasEmpty, - }); - this._eventIdToTimeline.set(eventId, timeline); - this.relations.aggregateParentEvent(event); - this.relations.aggregateChildEvent(event, this); - const data = { - timeline: timeline, - liveEvent: !toStartOfTimeline && timeline == this.liveTimeline && !fromCache, - }; - this.emit(room_1.RoomEvent.Timeline, event, this.room, Boolean(toStartOfTimeline), 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) { - // XXX: why don't we infer newEventId from localEvent? - const 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, - }); - } - } - /** - * 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) { - const timeline = this._eventIdToTimeline.get(eventId); - if (!timeline) { - return null; - } - const removed = timeline.removeEvent(eventId); - if (removed) { - this._eventIdToTimeline.delete(eventId); - const data = { - timeline: timeline, - }; - this.emit(room_1.RoomEvent.Timeline, removed, this.room, undefined, 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 a number less than zero if eventId1 precedes eventId2, and - * greater than zero if eventId1 succeeds eventId2. zero 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) { - // optimise this case - return 0; - } - const timeline1 = this._eventIdToTimeline.get(eventId1); - const timeline2 = this._eventIdToTimeline.get(eventId2); - if (timeline1 === undefined) { - return null; - } - if (timeline2 === undefined) { - return null; - } - if (timeline1 === timeline2) { - // both events are in the same timeline - figure out their relative indices - let idx1 = undefined; - let idx2 = undefined; - const events = timeline1.getEvents(); - for (let idx = 0; idx < events.length && (idx1 === undefined || idx2 === undefined); idx++) { - const evId = events[idx].getId(); - if (evId == eventId1) { - idx1 = idx; - } - if (evId == eventId2) { - idx2 = idx; - } - } - return idx1 - idx2; - } - // the events are in different timelines. Iterate through the - // linkedlist to see which comes first. - // first work forwards from timeline1 - let tl = timeline1; - while (tl) { - if (tl === timeline2) { - // timeline1 is before timeline2 - return -1; - } - tl = tl.getNeighbouringTimeline(event_timeline_1.EventTimeline.FORWARDS); - } - // now try backwards from timeline1 - tl = timeline1; - while (tl) { - if (tl === timeline2) { - // timeline2 is before timeline1 - return 1; - } - tl = tl.getNeighbouringTimeline(event_timeline_1.EventTimeline.BACKWARDS); - } - // the timelines are not contiguous. - 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."); - } - const { threadId, shouldLiveInRoom } = this.room.eventShouldLiveIn(event); - if (this.thread) { - return this.thread.id === threadId; - } - return shouldLiveInRoom; - } -} -exports.EventTimelineSet = EventTimelineSet; - -},{"../logger":374,"./event-timeline":382,"./relations-container":387,"./room":392,"./typed-event-emitter":395}],382:[function(require,module,exports){ -"use strict"; -/* -Copyright 2016 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.EventTimeline = exports.Direction = void 0; -const logger_1 = require("../logger"); -const room_state_1 = require("./room-state"); -const event_1 = require("../@types/event"); -var Direction; -(function (Direction) { - Direction["Backward"] = "b"; - Direction["Forward"] = "f"; -})(Direction = exports.Direction || (exports.Direction = {})); -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) { - var _a, _b, _c, _d; - // When we try to generate a sentinel member before we have that member - // in the members object, we still generate a sentinel but it doesn't - // have a membership event, so test to see if events.member is set. We - // check this to avoid overriding non-sentinel members by sentinel ones - // when adding the event to a filtered timeline - if (!((_b = (_a = event.sender) === null || _a === void 0 ? void 0 : _a.events) === null || _b === void 0 ? void 0 : _b.member)) { - event.sender = stateContext.getSentinelMember(event.getSender()); - } - if (!((_d = (_c = event.target) === null || _c === void 0 ? void 0 : _c.events) === null || _d === void 0 ? void 0 : _d.member) && event.getType() === event_1.EventType.RoomMember) { - event.target = stateContext.getSentinelMember(event.getStateKey()); - } - if (event.isState()) { - // room state has no concept of 'old' or 'current', but we want the - // room state to regress back to previous values if toStartOfTimeline - // is set, which means inspecting prev_content if it exists. This - // is done by toggling the forwardLooking flag. - if (toStartOfTimeline) { - event.forwardLooking = false; - } - } - } - /** - * Construct a new EventTimeline - * - *

An EventTimeline represents a contiguous sequence of events in a room. - * - *

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. - * - *

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. - * - *

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 _a, _b; - this.eventTimelineSet = eventTimelineSet; - this.events = []; - this.baseIndex = 0; - // If we have a roomId then we delegate pagination token storage to the room state objects `startState` and - // `endState`, but for things like the notification timeline which mix multiple rooms we store the tokens ourselves. - this.startToken = null; - this.endToken = null; - this.prevTimeline = null; - this.nextTimeline = null; - this.paginationRequests = { - [Direction.Backward]: null, - [Direction.Forward]: null, - }; - this.roomId = (_b = (_a = eventTimelineSet.room) === null || _a === void 0 ? void 0 : _a.roomId) !== null && _b !== void 0 ? _b : null; - if (this.roomId) { - this.startState = new room_state_1.RoomState(this.roomId); - this.endState = new room_state_1.RoomState(this.roomId); - } - // this is used by client.js - this.paginationRequests = { b: null, f: null }; - this.name = this.roomId + ":" + new Date().toISOString(); - } - /** - * Initialise the start and end state with the given events - * - *

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, { timelineWasEmpty } = {}) { - var _a, _b; - if (this.events.length > 0) { - throw new Error("Cannot initialise state after events are added"); - } - (_a = this.startState) === null || _a === void 0 ? void 0 : _a.setStateEvents(stateEvents, { timelineWasEmpty }); - (_b = this.endState) === null || _b === void 0 ? void 0 : _b.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) { - const forkState = this.getState(direction); - const timeline = new EventTimeline(this.eventTimelineSet); - timeline.startState = forkState === null || forkState === void 0 ? void 0 : forkState.clone(); - // Now clobber the end state of the new live timeline with that from the - // previous live timeline. It will be identical except that we'll keep - // using the same RoomMember objects for the 'live' set of members with any - // listeners still attached - timeline.endState = forkState; - // Firstly, we just stole the current timeline's end state, so it needs a new one. - // Make an immutable copy of the state so back pagination will get the correct sentinels. - 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) { - const forkState = this.getState(direction); - const 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. - * - *

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 + "'"); - } - // make sure we don't try to paginate this timeline - this.setPaginationToken(null, direction); - } - addEvent(event, toStartOfTimelineOrOpts, roomState) { - let toStartOfTimeline = !!toStartOfTimelineOrOpts; - let timelineWasEmpty; - if (typeof toStartOfTimelineOrOpts === "object") { - ({ toStartOfTimeline, roomState, timelineWasEmpty } = toStartOfTimelineOrOpts); - } - else if (toStartOfTimelineOrOpts !== undefined) { - // Deprecation warning - // FIXME: Remove after 2023-06-01 (technical debt) - logger_1.logger.warn("Overload deprecated: " + - "`EventTimeline.addEvent(event, toStartOfTimeline, roomState?)` " + - "is deprecated in favor of the overload with `EventTimeline.addEvent(event, IAddEventOptions)`"); - } - if (!roomState) { - roomState = toStartOfTimeline ? this.startState : this.endState; - } - const timelineSet = this.getTimelineSet(); - if (timelineSet.room) { - EventTimeline.setEventMetadata(event, roomState, toStartOfTimeline); - // modify state but only on unfiltered timelineSets - if (event.isState() && timelineSet.room.getUnfilteredTimelineSet() === timelineSet) { - roomState === null || roomState === void 0 ? void 0 : roomState.setStateEvents([event], { timelineWasEmpty }); - // it is possible that the act of setting the state event means we - // can set more metadata (specifically sender/target props), so try - // it again if the prop wasn't previously set. It may also mean that - // the sender/target is updated (if the event set was a room member event) - // so we want to use the *updated* member (new avatar/name) instead. - // - // However, we do NOT want to do this on member events if we're going - // back in time, else we'll set the .sender value for BEFORE the given - // member event, whereas we want to set the .sender value for the ACTUAL - // member event itself. - if (!event.sender || (event.getType() === event_1.EventType.RoomMember && !toStartOfTimeline)) { - EventTimeline.setEventMetadata(event, roomState, toStartOfTimeline); - } - } - } - let insertIndex; - if (toStartOfTimeline) { - insertIndex = 0; - } - else { - insertIndex = this.events.length; - } - this.events.splice(insertIndex, 0, event); // insert element - if (toStartOfTimeline) { - this.baseIndex++; - } - } - /** - * 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 (let i = this.events.length - 1; i >= 0; i--) { - const 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; - } -} -exports.EventTimeline = EventTimeline; -/** - * Symbolic constant for methods which take a 'direction' argument: - * refers to the start of the timeline, or backwards in time. - */ -EventTimeline.BACKWARDS = Direction.Backward; -/** - * Symbolic constant for methods which take a 'direction' argument: - * refers to the end of the timeline, or forwards in time. - */ -EventTimeline.FORWARDS = Direction.Forward; - -},{"../@types/event":306,"../logger":374,"./room-state":390}],383:[function(require,module,exports){ -"use strict"; -/* -Copyright 2015 - 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MatrixEvent = exports.MatrixEventEvent = exports.EventStatus = void 0; -/** - * This is an internal module. See {@link MatrixEvent} and {@link RoomEvent} for - * the public classes. - */ -const matrix_events_sdk_1 = require("matrix-events-sdk"); -const logger_1 = require("../logger"); -const event_1 = require("../@types/event"); -const utils_1 = require("../utils"); -const thread_1 = require("./thread"); -const ReEmitter_1 = require("../ReEmitter"); -const typed_event_emitter_1 = require("./typed-event-emitter"); -const algorithms_1 = require("../crypto/algorithms"); -const OlmDevice_1 = require("../crypto/OlmDevice"); -var event_status_1 = require("./event-status"); -Object.defineProperty(exports, "EventStatus", { enumerable: true, get: function () { return event_status_1.EventStatus; } }); -// A singleton implementing `IMessageVisibilityVisible`. -const MESSAGE_VISIBLE = Object.freeze({ visible: true }); -var MatrixEventEvent; -(function (MatrixEventEvent) { - 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 = exports.MatrixEventEvent || (exports.MatrixEventEvent = {})); -class MatrixEvent extends typed_event_emitter_1.TypedEventEmitter { - /** - * Construct a Matrix Event object - * - * @param event - The raw (possibly encrypted) event. Do not access - * this property 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(event = {}) { - var _a; - super(); - this.event = event; - this.pushActions = null; - this._replacingEvent = null; - this._localRedactionEvent = null; - this._isCancelled = false; - /* Message hiding, as specified by https://github.com/matrix-org/matrix-doc/pull/3531. - - Note: We're returning this object, so any value stored here MUST be frozen. - */ - this.visibility = MESSAGE_VISIBLE; - // Not all events will be extensible-event compatible, so cache a flag in - // addition to a falsy cached event value. We check the flag later on in - // a public getter to decide if the cache is valid. - this._hasCachedExtEv = false; - this._cachedExtEv = undefined; - /* curve25519 key which we believe belongs to the sender of the event. See - * getSenderKey() - */ - this.senderCurve25519Key = null; - /* ed25519 key which the sender of this event (for olm) or the creator of - * the megolm session (for megolm) claims to own. See getClaimedEd25519Key() - */ - this.claimedEd25519Key = null; - /* curve25519 keys of devices involved in telling us about the - * senderCurve25519Key and claimedEd25519Key. - * See getForwardingCurve25519KeyChain(). - */ - this.forwardingCurve25519KeyChain = []; - /* where the decryption key is untrusted - */ - this.untrusted = null; - /* if we have a process decrypting this event, a Promise which resolves - * when it is finished. Normally null. - */ - this.decryptionPromise = null; - /* flag to indicate if we should retry decrypting this event after the - * first attempt (eg, we have received new data which means that a second - * attempt may succeed) - */ - this.retryDecryption = false; - /* - * True if this event is an encrypted event which we failed to decrypt, the receiver's device is unverified and - * the sender has disabled encrypting to unverified devices. - */ - this.encryptedDisabledForUnverifiedDevices = false; - /** - * 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 - */ - 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 - */ - this.target = null; - /** - * The sending status of the event. - * @privateRemarks - * Should be read-only - */ - this.status = null; - /** - * most recent error associated with sending the event, if any - * @privateRemarks - * Should be read-only - */ - 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. This property is experimental and may change. - * @privateRemarks - * Should be read-only - */ - this.forwardLooking = true; - // intern the values of matrix events to force share strings and reduce the - // amount of needless string duplication. This can save moderate amounts of - // memory (~10% on a 350MB heap). - // 'membership' at the event level (rather than the content level) is a legacy - // field that Element never otherwise looks at, but it will still take up a lot - // of space if we don't intern it. - ["state_key", "type", "sender", "room_id", "membership"].forEach((prop) => { - if (typeof event[prop] !== "string") - return; - event[prop] = (0, utils_1.internaliseString)(event[prop]); - }); - ["membership", "avatar_url", "displayname"].forEach((prop) => { - var _a; - if (typeof ((_a = event.content) === null || _a === void 0 ? void 0 : _a[prop]) !== "string") - return; - event.content[prop] = (0, utils_1.internaliseString)(event.content[prop]); - }); - ["rel_type"].forEach((prop) => { - var _a, _b; - if (typeof ((_b = (_a = event.content) === null || _a === void 0 ? void 0 : _a["m.relates_to"]) === null || _b === void 0 ? void 0 : _b[prop]) !== "string") - return; - event.content["m.relates_to"][prop] = (0, utils_1.internaliseString)(event.content["m.relates_to"][prop]); - }); - this.txnId = event.txn_id; - this.localTimestamp = Date.now() - ((_a = this.getAge()) !== null && _a !== void 0 ? _a : 0); - this.reEmitter = new ReEmitter_1.TypedReEmitter(this); - } - /** - * 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) { - this._cachedExtEv = matrix_events_sdk_1.ExtensibleEvents.parse(this.getEffectiveEvent()); - } - return this._cachedExtEv; - } - invalidateExtensibleEvent() { - // just reset the flag - that'll trick the getter into parsing a new event - this._hasCachedExtEv = false; - } - /** - * Gets the event as though it would appear unencrypted. If the event is already not - * encrypted, it is simply returned as-is. - * @returns The event in wire format. - */ - getEffectiveEvent() { - const content = Object.assign({}, this.getContent()); // clone for mutation - if (this.getWireType() === event_1.EventType.RoomMessageEncrypted) { - // Encrypted events sometimes aren't symmetrical on the `content` so we'll copy - // that over too, but only for missing properties. We don't copy over mismatches - // between the plain and decrypted copies of `content` because we assume that the - // app is relying on the decrypted version, so we want to expose that as a source - // of truth here too. - for (const [key, value] of Object.entries(this.getWireContent())) { - // Skip fields from the encrypted event schema though - we don't want to leak - // these. - if (["algorithm", "ciphertext", "device_id", "sender_key", "session_id"].includes(key)) { - continue; - } - if (content[key] === undefined) - content[key] = value; - } - } - // clearEvent doesn't have all the fields, so we'll copy what we can from this.event. - // We also copy over our "fixed" content key. - return Object.assign({}, this.event, this.clearEvent, { content }); - } - /** - * Get the event_id for this event. - * @returns The event ID, e.g. $143350589368169JsLZx:localhost - * - */ - 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 || this.event.user_id; // v2 / v1 - } - /** - * 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. !cURbafjkfsMDVwdRDQ:matrix.org - * - */ - 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() { - let details = `id=${this.getId()} type=${this.getWireType()} sender=${this.getSender()}`; - const room = this.getRoomId(); - if (room) { - details += ` room=${room}`; - } - const date = this.getDate(); - if (date) { - details += ` ts=${date.toISOString()}`; - } - return details; - } - /** - * 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() { - if (this._localRedactionEvent) { - return {}; - } - if (this.clearEvent) { - return (this.clearEvent.content || {}); - } - return (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) { - return this._replacingEvent.getContent()["m.new_content"] || {}; - } - 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 _a, _b; - const relatesTo = (_a = this.getWireContent()) === null || _a === void 0 ? void 0 : _a["m.relates_to"]; - if ((relatesTo === null || relatesTo === void 0 ? void 0 : relatesTo.rel_type) === thread_1.THREAD_RELATION_TYPE.name) { - return relatesTo.event_id; - } - else { - return ((_b = this.getThread()) === null || _b === void 0 ? void 0 : _b.id) || this.threadId; - } - } - /** - * A helper to check if an event is a thread's head or not - */ - get isThreadRoot() { - var _a; - const threadDetails = this.getServerAggregatedRelation(thread_1.THREAD_RELATION_TYPE.name); - // Bundled relationships only returned when the sync response is limited - // hence us having to check both bundled relation and inspect the thread - // model - return !!threadDetails || ((_a = this.getThread()) === null || _a === void 0 ? void 0 : _a.id) === this.getId(); - } - get replyEventId() { - var _a, _b; - return (_b = (_a = this.getWireContent()["m.relates_to"]) === null || _a === void 0 ? void 0 : _a["m.in_reply_to"]) === null || _b === void 0 ? void 0 : _b.event_id; - } - get relationEventId() { - var _a, _b; - return (_b = (_a = this.getWireContent()) === null || _a === void 0 ? void 0 : _a["m.relates_to"]) === null || _b === void 0 ? void 0 : _b.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() { - // v2 then v1 then default - return this.getUnsigned().prev_content || this.event.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) - * This method is experimental and may change. - * @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 || this.event.age; // v2 / v1 - } - /** - * 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. This will return undefined - * for message events. - * @returns The event's `state_key`. - */ - getStateKey() { - 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 !== undefined; - } - /** - * 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 - * "m.room.encrypted" - * - * @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) { - // keep the plain-text data for 'view source' - this.clearEvent = { - type: this.event.type, - content: this.event.content, - }; - this.event.type = cryptoType; - this.event.content = cryptoContent; - this.senderCurve25519Key = senderCurve25519Key; - this.claimedEd25519Key = claimedEd25519Key; - } - /** - * 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() { - var _a, _b; - return ((_b = (_a = this.clearEvent) === null || _a === void 0 ? void 0 : _a.content) === null || _b === void 0 ? void 0 : _b.msgtype) === "m.bad.encrypted"; - } - /* - * True if this event is an encrypted event which we failed to decrypt, the receiver's device is unverified and - * the sender has disabled encrypting to unverified devices. - */ - get isEncryptedDisabledForUnverifiedDevices() { - return this.isDecryptionFailure() && this.encryptedDisabledForUnverifiedDevices; - } - 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, options = {}) { - return __awaiter(this, void 0, void 0, function* () { - // start with a couple of sanity checks. - if (!this.isEncrypted()) { - throw new Error("Attempt to decrypt event which isn't encrypted"); - } - const alreadyDecrypted = this.clearEvent && !this.isDecryptionFailure(); - const forceRedecrypt = options.forceRedecryptIfUntrusted && this.isKeySourceUntrusted(); - if (alreadyDecrypted && !forceRedecrypt) { - // we may want to just ignore this? let's start with rejecting it. - throw new Error("Attempt to decrypt event which has already been decrypted"); - } - // if we already have a decryption attempt in progress, then it may - // fail because it was using outdated info. We now have reason to - // succeed where it failed before, but we don't want to have multiple - // attempts going at the same time, so just set a flag that says we have - // new info. - // - if (this.decryptionPromise) { - logger_1.logger.log(`Event ${this.getId()} already being decrypted; queueing a retry`); - this.retryDecryption = true; - return this.decryptionPromise; - } - this.decryptionPromise = this.decryptionLoop(crypto, options); - return this.decryptionPromise; - }); - } - /** - * Cancel any room key request for this event and resend another. - * - * @param crypto - crypto module - * @param userId - the user who received this event - * - * @returns a promise that resolves when the request is queued - */ - cancelAndResendKeyRequest(crypto, userId) { - const wireContent = this.getWireContent(); - return crypto.requestRoomKey({ - algorithm: wireContent.algorithm, - room_id: this.getRoomId(), - session_id: wireContent.session_id, - sender_key: wireContent.sender_key, - }, this.getKeyRequestRecipients(userId), true); - } - /** - * Calculate the recipients for keyshare requests. - * - * @param userId - the user who received this event. - * - * @returns array of recipients - */ - getKeyRequestRecipients(userId) { - // send the request to all of our own devices - const recipients = [ - { - userId, - deviceId: "*", - }, - ]; - return recipients; - } - decryptionLoop(crypto, options = {}) { - return __awaiter(this, void 0, void 0, function* () { - // make sure that this method never runs completely synchronously. - // (doing so would mean that we would clear decryptionPromise *before* - // it is set in attemptDecryption - and hence end up with a stuck - // `decryptionPromise`). - yield Promise.resolve(); - // eslint-disable-next-line no-constant-condition - while (true) { - this.retryDecryption = false; - let res; - let err = undefined; - try { - if (!crypto) { - res = this.badEncryptedMessage("Encryption not enabled"); - } - else { - res = yield crypto.decryptEvent(this); - if (options.isRetry === true) { - logger_1.logger.info(`Decrypted event on retry (${this.getDetails()})`); - } - } - } - catch (e) { - const detailedError = e instanceof algorithms_1.DecryptionError ? e.detailedString : String(e); - err = e; - // see if we have a retry queued. - // - // NB: make sure to keep this check in the same tick of the - // event loop as `decryptionPromise = null` below - otherwise we - // risk a race: - // - // * A: we check retryDecryption here and see that it is - // false - // * B: we get a second call to attemptDecryption, which sees - // that decryptionPromise is set so sets - // retryDecryption - // * A: we continue below, clear decryptionPromise, and - // never do the retry. - // - if (this.retryDecryption) { - // decryption error, but we have a retry queued. - logger_1.logger.log(`Error decrypting event (${this.getDetails()}), but retrying: ${detailedError}`); - continue; - } - // decryption error, no retries queued. Warn about the error and - // set it to m.bad.encrypted. - // - // the detailedString already includes the name and message of the error, and the stack isn't much use, - // so we don't bother to log `e` separately. - logger_1.logger.warn(`Error decrypting event (${this.getDetails()}): ${detailedError}`); - res = this.badEncryptedMessage(String(e)); - } - // at this point, we've either successfully decrypted the event, or have given up - // (and set res to a 'badEncryptedMessage'). Either way, we can now set the - // cleartext of the event and raise Event.decrypted. - // - // make sure we clear 'decryptionPromise' before sending the 'Event.decrypted' event, - // otherwise the app will be confused to see `isBeingDecrypted` still set when - // there isn't an `Event.decrypted` on the way. - // - // see also notes on retryDecryption above. - // - this.decryptionPromise = null; - this.retryDecryption = false; - this.setClearData(res); - // Before we emit the event, clear the push actions so that they can be recalculated - // by relevant code. We do this because the clear event has now changed, making it - // so that existing rules can be re-run over the applicable properties. Stuff like - // highlighting when the user's name is mentioned rely on this happening. We also want - // to set the push actions before emitting so that any notification listeners don't - // pick up the wrong contents. - this.setPushActions(null); - if (options.emit !== false) { - this.emit(MatrixEventEvent.Decrypted, this, err); - } - return; - } - }); - } - badEncryptedMessage(reason) { - return { - clearEvent: { - type: event_1.EventType.RoomMessage, - content: { - msgtype: "m.bad.encrypted", - body: "** Unable to decrypt: " + reason + " **", - }, - }, - encryptedDisabledForUnverifiedDevices: reason === `DecryptionError: ${OlmDevice_1.WITHHELD_MESSAGES["m.unverified"]}`, - }; - } - /** - * 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 - * - * @remarks - * Fires {@link MatrixEventEvent.Decrypted} - */ - setClearData(decryptionResult) { - var _a, _b; - this.clearEvent = decryptionResult.clearEvent; - this.senderCurve25519Key = (_a = decryptionResult.senderCurve25519Key) !== null && _a !== void 0 ? _a : null; - this.claimedEd25519Key = (_b = decryptionResult.claimedEd25519Key) !== null && _b !== void 0 ? _b : null; - this.forwardingCurve25519KeyChain = decryptionResult.forwardingCurve25519KeyChain || []; - this.untrusted = decryptionResult.untrusted || false; - this.encryptedDisabledForUnverifiedDevices = decryptionResult.encryptedDisabledForUnverifiedDevices || false; - 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.isState() && this.event.type === event_1.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 MatrixClient.getEventSenderDeviceInfo. - */ - getClaimedEd25519Key() { - return this.claimedEd25519Key; - } - /** - * Get the curve25519 keys of the devices which were involved in telling us - * about the claimedEd25519Key and sender curve25519 key. - * - * Normally this will be empty, but in the case of a forwarded megolm - * session, the sender keys are sent to us by another device (the forwarding - * device), which we need to trust to do this. In that case, the result will - * be a list consisting of one entry. - * - * If the device that sent us the key (A) got it from another device which - * it wasn't prepared to vouch for (B), the result will be [A, B]. And so on. - * - * @returns base64-encoded curve25519 keys, from oldest to newest. - */ - getForwardingCurve25519KeyChain() { - return this.forwardingCurve25519KeyChain; - } - /** - * Whether the decryption key was obtained from an untrusted source. If so, - * we cannot verify the authenticity of the message. - */ - isKeySourceUntrusted() { - return !!this.untrusted; - } - getUnsigned() { - return this.event.unsigned || {}; - } - setUnsigned(unsigned) { - this.event.unsigned = unsigned; - } - unmarkLocallyRedacted() { - const value = this._localRedactionEvent; - this._localRedactionEvent = null; - if (this.event.unsigned) { - this.event.unsigned.redacted_because = undefined; - } - 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 _a, _b; - const visible = (_a = visibilityChange === null || visibilityChange === void 0 ? void 0 : visibilityChange.visible) !== null && _a !== void 0 ? _a : true; - const reason = (_b = visibilityChange === null || visibilityChange === void 0 ? void 0 : visibilityChange.reason) !== null && _b !== void 0 ? _b : null; - let 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() { - // Note: We may return `this.visibility` without fear, as - // this is a shallow frozen object. - 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 - */ - makeRedacted(redactionEvent) { - // quick sanity-check - if (!redactionEvent.event) { - throw new Error("invalid redactionEvent in makeRedacted"); - } - this._localRedactionEvent = null; - this.emit(MatrixEventEvent.BeforeRedaction, this, redactionEvent); - this._replacingEvent = null; - // we attempt to replicate what we would see from the server if - // the event had been redacted before we saw it. - // - // The server removes (most of) the content of the event, and adds a - // "redacted_because" key to the unsigned section containing the - // redacted event. - if (!this.event.unsigned) { - this.event.unsigned = {}; - } - this.event.unsigned.redacted_because = redactionEvent.event; - for (const key in this.event) { - if (this.event.hasOwnProperty(key) && !REDACT_KEEP_KEYS.has(key)) { - delete this.event[key]; - } - } - // If the event is encrypted prune the decrypted bits - if (this.isEncrypted()) { - this.clearEvent = undefined; - } - const keeps = this.getType() in REDACT_KEEP_CONTENT_MAP - ? REDACT_KEEP_CONTENT_MAP[this.getType()] - : {}; - const content = this.getContent(); - for (const key in content) { - if (content.hasOwnProperty(key) && !keeps[key]) { - delete content[key]; - } - } - this.invalidateExtensibleEvent(); - } - /** - * 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() === event_1.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_1.EVENT_VISIBILITY_CHANGE_TYPE.matches(this.getType())) { - // Not a visibility change event. - return null; - } - const relation = this.getRelation(); - if (!relation || relation.rel_type != "m.reference") { - // Ill-formed, ignore this event. - return null; - } - const eventId = relation.event_id; - if (!eventId) { - // Ill-formed, ignore this event. - return null; - } - const content = this.getWireContent(); - const visible = !!content.visible; - const reason = content.reason; - if (reason && typeof reason != "string") { - // Ill-formed, ignore this event. - return null; - } - // Well-formed visibility change event. - 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_1.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 _a, _b, _c, _d; - if (!this.isRedacted()) - return null; - if ((_a = this.clearEvent) === null || _a === void 0 ? void 0 : _a.unsigned) { - return (_c = (_b = this.clearEvent) === null || _b === void 0 ? void 0 : _b.unsigned.redacted_because) !== null && _c !== void 0 ? _c : null; - } - else if ((_d = this.event.unsigned) === null || _d === void 0 ? void 0 : _d.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.pushActions; - } - /** - * Set the push actions for this event. - * - * @param pushActions - push actions - */ - setPushActions(pushActions) { - this.pushActions = pushActions; - } - /** - * Replace the `event` property and recalculate any properties based on it. - * @param event - the object to assign to the `event` property - */ - handleRemoteEcho(event) { - const oldUnsigned = this.getUnsigned(); - const oldId = this.getId(); - this.event = event; - // if this event was redacted before it was sent, it's locally marked as redacted. - // At this point, we've received the remote echo for the event, but not yet for - // the redaction that we are sending ourselves. Preserve the locally redacted - // state by copying over redacted_because so we don't get a flash of - // redacted, not-redacted, redacted as remote echos come in - if (oldUnsigned.redacted_because) { - if (!this.event.unsigned) { - this.event.unsigned = {}; - } - this.event.unsigned.redacted_because = oldUnsigned.redacted_because; - } - // successfully sent. - this.setStatus(null); - if (this.getId() !== oldId) { - // emit the event if it changed - this.emit(MatrixEventEvent.LocalEventIdReplaced, this); - } - this.localTimestamp = Date.now() - this.getAge(); - } - /** - * 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 _a; - // Relation info is lifted out of the encrypted content when sent to - // encrypted rooms, so we have to check `getWireContent` for this. - const relation = (_a = this.getWireContent()) === null || _a === void 0 ? void 0 : _a["m.relates_to"]; - if (this.isState() && (relation === null || relation === void 0 ? void 0 : relation.rel_type) === event_1.RelationType.Replace) { - // State events cannot be m.replace relations - return false; - } - return !!((relation === null || relation === void 0 ? void 0 : relation.rel_type) && relation.event_id && (relType ? relation.rel_type === relType : true)); - } - /** - * Get relation info for the event, if any. - */ - getRelation() { - var _a; - if (!this.isRelation()) { - return null; - } - return (_a = this.getWireContent()["m.relates_to"]) !== null && _a !== void 0 ? _a : 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) { - // don't allow redacted events to be replaced. - // if newEvent is null we allow to go through though, - // as with local redaction, the replacing event might get - // cancelled, which should be reflected on the target event. - if (this.isRedacted() && newEvent) { - return; - } - // don't allow state events to be replaced using this mechanism as per MSC2676 - 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 _a; - return (_a = this.getUnsigned()["m.relations"]) === null || _a === void 0 ? void 0 : _a[relType]; - } - /** - * Returns the event ID of the event replacing the content of this event, if any. - */ - replacingEventId() { - const replaceRelation = this.getServerAggregatedRelation(event_1.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 _a; - const replaceRelation = this.getServerAggregatedRelation(event_1.RelationType.Replace); - if (replaceRelation) { - const ts = replaceRelation.origin_server_ts; - if (Number.isFinite(ts)) { - return new Date(ts); - } - } - else if (this._replacingEvent) { - return (_a = this._replacingEvent.getDate()) !== null && _a !== void 0 ? _a : undefined; - } - } - /** - * 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() { - const 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`. - * @deprecated use hasAssociation instead. - */ - hasAssocation() { - return !!this.getAssociatedId(); - } - /** - * 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) { - const 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(cancelled = true) { - this._isCancelled = cancelled; - } - /** - * 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() { - const ev = new MatrixEvent(JSON.parse(JSON.stringify(this.event))); - for (const [p, v] of Object.entries(this)) { - if (p !== "event") { - // exclude the thing we just cloned - // @ts-ignore - XXX: this is just nasty - 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; - const myProps = (0, utils_1.deepSortedObjectEntries)(this.event); - const theirProps = (0, utils_1.deepSortedObjectEntries)(otherEvent.event); - return JSON.stringify(myProps) === JSON.stringify(theirProps); - } - /** - * Summarise the event as JSON. This is currently used by React SDK's view - * event source feature and Seshat's event indexing, so take care when - * adjusting the output here. - * - * 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. - */ - toJSON() { - const event = this.getEffectiveEvent(); - if (!this.isEncrypted()) { - return event; - } - return { - decrypted: event, - encrypted: this.event, - }; - } - setVerificationRequest(request) { - this.verificationRequest = request; - } - 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.thread) { - this.reEmitter.stopReEmitting(this.thread, [thread_1.ThreadEvent.Update]); - } - this.thread = thread; - this.setThreadId(thread === null || thread === void 0 ? void 0 : thread.id); - if (thread) { - this.reEmitter.reEmit(thread, [thread_1.ThreadEvent.Update]); - } - } - /** - * Get the instance of the thread associated with the current event - */ - getThread() { - return this.thread; - } - setThreadId(threadId) { - this.threadId = threadId; - } -} -exports.MatrixEvent = MatrixEvent; -/* REDACT_KEEP_KEYS gives the keys we keep when an event is redacted - * - * This is specified here: - * http://matrix.org/speculator/spec/HEAD/client_server/latest.html#redactions - * - * Also: - * - We keep 'unsigned' since that is created by the local server - * - We keep user_id for backwards-compat with v1 - */ -const REDACT_KEEP_KEYS = new Set([ - "event_id", - "type", - "room_id", - "user_id", - "sender", - "state_key", - "prev_state", - "content", - "unsigned", - "origin_server_ts", -]); -// a map from state event type to the .content keys we keep when an event is redacted -const REDACT_KEEP_CONTENT_MAP = { - [event_1.EventType.RoomMember]: { membership: 1 }, - [event_1.EventType.RoomCreate]: { creator: 1 }, - [event_1.EventType.RoomJoinRules]: { join_rule: 1 }, - [event_1.EventType.RoomPowerLevels]: { - ban: 1, - events: 1, - events_default: 1, - kick: 1, - redact: 1, - state_default: 1, - users: 1, - users_default: 1, - }, -}; - -},{"../@types/event":306,"../ReEmitter":317,"../crypto/OlmDevice":327,"../crypto/algorithms":333,"../logger":374,"../utils":416,"./event-status":380,"./thread":394,"./typed-event-emitter":395,"matrix-events-sdk":167}],384:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.IgnoredInvites = exports.PolicyScope = exports.IGNORE_INVITES_ACCOUNT_EVENT_KEY = exports.POLICIES_ACCOUNT_EVENT_TYPE = void 0; -const matrix_events_sdk_1 = require("matrix-events-sdk"); -const event_timeline_1 = require("./event-timeline"); -const partials_1 = require("../@types/partials"); -const utils_1 = require("../utils"); -/// The event type storing the user's individual policies. -/// -/// Exported for testing purposes. -exports.POLICIES_ACCOUNT_EVENT_TYPE = new matrix_events_sdk_1.UnstableValue("m.policies", "org.matrix.msc3847.policies"); -/// The key within the user's individual policies storing the user's ignored invites. -/// -/// Exported for testing purposes. -exports.IGNORE_INVITES_ACCOUNT_EVENT_KEY = new matrix_events_sdk_1.UnstableValue("m.ignore.invites", "org.matrix.msc3847.ignore.invites"); -/// The types of recommendations understood. -var PolicyRecommendation; -(function (PolicyRecommendation) { - PolicyRecommendation["Ban"] = "m.ban"; -})(PolicyRecommendation || (PolicyRecommendation = {})); -/** - * The various scopes for policies. - */ -var PolicyScope; -(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"; -})(PolicyScope = exports.PolicyScope || (exports.PolicyScope = {})); -/** - * 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. - */ -class IgnoredInvites { - 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) { - return __awaiter(this, void 0, void 0, function* () { - const target = yield this.getOrCreateTargetRoom(); - const response = yield this.client.sendStateEvent(target.roomId, scope, { - entity, - reason, - recommendation: PolicyRecommendation.Ban, - }); - return response.event_id; - }); - } - /** - * Remove a rule. - */ - removeRule(event) { - return __awaiter(this, void 0, void 0, function* () { - yield this.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) { - return __awaiter(this, void 0, void 0, function* () { - // We attempt to join the room *before* calling - // `await this.getOrCreateSourceRooms()` to decrease the duration - // of the racy section. - yield this.client.joinRoom(roomId); - // Race starts. - const sources = (yield this.getOrCreateSourceRooms()).map((room) => room.roomId); - if (sources.includes(roomId)) { - return false; - } - sources.push(roomId); - yield this.withIgnoreInvitesPolicies((ignoreInvitesPolicies) => { - ignoreInvitesPolicies.sources = sources; - }); - // Race ends. - return true; - }); - } - /** - * Find out whether an invite should be ignored. - * - * @param sender - The user id for the user who issued the invite. - * @param roomId - The room to which the user is invited. - * @returns A rule matching the entity, if any was found, `null` otherwise. - */ - getRuleForInvite({ sender, roomId, }) { - return __awaiter(this, void 0, void 0, function* () { - // In this implementation, we perform a very naive lookup: - // - search in each policy room; - // - turn each (potentially glob) rule entity into a regexp. - // - // Real-world testing will tell us whether this is performant enough. - // In the (unfortunately likely) case it isn't, there are several manners - // in which we could optimize this: - // - match several entities per go; - // - pre-compile each rule entity into a regexp; - // - pre-compile entire rooms into a single regexp. - const policyRooms = yield this.getOrCreateSourceRooms(); - const senderServer = sender.split(":")[1]; - const roomServer = roomId.split(":")[1]; - for (const room of policyRooms) { - const state = room.getUnfilteredTimelineSet().getLiveTimeline().getState(event_timeline_1.EventTimeline.FORWARDS); - for (const { scope, entities } of [ - { scope: PolicyScope.Room, entities: [roomId] }, - { scope: PolicyScope.User, entities: [sender] }, - { scope: PolicyScope.Server, entities: [senderServer, roomServer] }, - ]) { - const events = state.getStateEvents(scope); - for (const event of events) { - const content = event.getContent(); - if ((content === null || content === void 0 ? void 0 : content.recommendation) != PolicyRecommendation.Ban) { - // Ignoring invites only looks at `m.ban` recommendations. - continue; - } - const glob = content === null || content === void 0 ? void 0 : content.entity; - if (!glob) { - // Invalid event. - continue; - } - let regexp; - try { - regexp = new RegExp((0, utils_1.globToRegexp)(glob, false)); - } - catch (ex) { - // Assume invalid event. - continue; - } - for (const entity of entities) { - if (entity && regexp.test(entity)) { - return event; - } - } - // No match. - } - } - } - 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() { - return __awaiter(this, void 0, void 0, function* () { - const ignoreInvitesPolicies = this.getIgnoreInvitesPolicies(); - let target = ignoreInvitesPolicies.target; - // Validate `target`. If it is invalid, trash out the current `target` - // and create a new room. - if (typeof target !== "string") { - target = null; - } - if (target) { - // Check that the room exists and is valid. - const room = this.client.getRoom(target); - if (room) { - return room; - } - else { - target = null; - } - } - // We need to create our own policy room for ignoring invites. - target = (yield this.client.createRoom({ - name: "Individual Policy Room", - preset: partials_1.Preset.PrivateChat, - })).room_id; - yield this.withIgnoreInvitesPolicies((ignoreInvitesPolicies) => { - ignoreInvitesPolicies.target = target; - }); - // Since we have just called `createRoom`, `getRoom` should not be `null`. - return this.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() { - return __awaiter(this, void 0, void 0, function* () { - const ignoreInvitesPolicies = this.getIgnoreInvitesPolicies(); - let sources = ignoreInvitesPolicies.sources; - // Validate `sources`. If it is invalid, trash out the current `sources` - // and create a new list of sources from `target`. - let hasChanges = false; - if (!Array.isArray(sources)) { - // `sources` could not be an array. - hasChanges = true; - sources = []; - } - let sourceRooms = sources - // `sources` could contain non-string / invalid room ids - .filter((roomId) => typeof roomId === "string") - .map((roomId) => this.client.getRoom(roomId)) - .filter((room) => !!room); - if (sourceRooms.length != sources.length) { - hasChanges = true; - } - if (sourceRooms.length == 0) { - // `sources` could be empty (possibly because we've removed - // invalid content) - const target = yield this.getOrCreateTargetRoom(); - hasChanges = true; - sourceRooms = [target]; - } - if (hasChanges) { - // Reload `policies`/`ignoreInvitesPolicies` in case it has been changed - // during or by our call to `this.getTargetRoom()`. - yield this.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) { - return __awaiter(this, void 0, void 0, function* () { - const { policies, ignoreInvitesPolicies } = this.getPoliciesAndIgnoreInvitesPolicies(); - cb(ignoreInvitesPolicies); - policies[exports.IGNORE_INVITES_ACCOUNT_EVENT_KEY.name] = ignoreInvitesPolicies; - yield this.client.setAccountData(exports.POLICIES_ACCOUNT_EVENT_TYPE.name, policies); - }); - } - /** - * As `getIgnoreInvitesPolicies` but also return the `POLICIES_ACCOUNT_EVENT_TYPE` - * object. - */ - getPoliciesAndIgnoreInvitesPolicies() { - var _a; - let policies = {}; - for (const key of [exports.POLICIES_ACCOUNT_EVENT_TYPE.name, exports.POLICIES_ACCOUNT_EVENT_TYPE.altName]) { - if (!key) { - continue; - } - const value = (_a = this.client.getAccountData(key)) === null || _a === void 0 ? void 0 : _a.getContent(); - if (value) { - policies = value; - break; - } - } - let ignoreInvitesPolicies = {}; - let hasIgnoreInvitesPolicies = false; - for (const key of [exports.IGNORE_INVITES_ACCOUNT_EVENT_KEY.name, exports.IGNORE_INVITES_ACCOUNT_EVENT_KEY.altName]) { - if (!key) { - continue; - } - const value = policies[key]; - if (value && typeof value == "object") { - ignoreInvitesPolicies = value; - hasIgnoreInvitesPolicies = true; - break; - } - } - if (!hasIgnoreInvitesPolicies) { - policies[exports.IGNORE_INVITES_ACCOUNT_EVENT_KEY.name] = ignoreInvitesPolicies; - } - return { policies, ignoreInvitesPolicies }; - } -} -exports.IgnoredInvites = IgnoredInvites; - -},{"../@types/partials":309,"../utils":416,"./event-timeline":382,"matrix-events-sdk":167}],385:[function(require,module,exports){ -"use strict"; -/* -Copyright 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Poll = exports.PollEvent = void 0; -const polls_1 = require("../@types/polls"); -const relations_1 = require("./relations"); -const typed_event_emitter_1 = require("./typed-event-emitter"); -var PollEvent; -(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"; -})(PollEvent = exports.PollEvent || (exports.PollEvent = {})); -const filterResponseRelations = (relationEvents, pollEndTimestamp) => { - const responseEvents = relationEvents.filter((event) => { - if (event.isDecryptionFailure()) { - return; - } - return (polls_1.M_POLL_RESPONSE.matches(event.getType()) && - // From MSC3381: - // "Votes sent on or before the end event's timestamp are valid votes" - event.getTs() <= pollEndTimestamp); - }); - return { responseEvents }; -}; -class Poll extends typed_event_emitter_1.TypedEventEmitter { - constructor(rootEvent, matrixClient, room) { - super(); - this.rootEvent = rootEvent; - this.matrixClient = matrixClient; - this.room = room; - this._isFetchingResponses = false; - this.responses = null; - /** - * Keep track of undecryptable relations - * As incomplete result sets affect poll results - */ - this.undecryptableRelationEventIds = new Set(); - this.countUndecryptableEvents = (events) => { - const undecryptableEventIds = events - .filter((event) => event.isDecryptionFailure()) - .map((event) => event.getId()); - const 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 _a; - return (_a = this.endEvent) === null || _a === void 0 ? void 0 : _a.getId(); - } - get isEnded() { - return !!this.endEvent; - } - get isFetchingResponses() { - return this._isFetchingResponses; - } - get undecryptableRelationsCount() { - return this.undecryptableRelationEventIds.size; - } - getResponses() { - return __awaiter(this, void 0, void 0, function* () { - // if we have already fetched some responses - // just return them - if (this.responses) { - return this.responses; - } - // if there is no fetching in progress - // start fetching - if (!this.isFetchingResponses) { - yield this.fetchResponses(); - } - // return whatever responses we got from the first page - return this.responses; - }); - } - /** - * - * @param event - event with a relation to the rootEvent - * @returns void - */ - onNewRelation(event) { - var _a; - if (polls_1.M_POLL_END.matches(event.getType()) && this.validateEndEvent(event)) { - this.endEvent = event; - this.refilterResponsesOnEnd(); - this.emit(PollEvent.End); - } - // wait for poll responses to be initialised - if (!this.responses) { - return; - } - const pollEndTimestamp = ((_a = this.endEvent) === null || _a === void 0 ? void 0 : _a.getTs()) || Number.MAX_SAFE_INTEGER; - const { 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 _a, _b; - return __awaiter(this, void 0, void 0, function* () { - this._isFetchingResponses = true; - // we want: - // - stable and unstable M_POLL_RESPONSE - // - stable and unstable M_POLL_END - // so make one api call and filter by event type client side - const allRelations = yield this.matrixClient.relations(this.roomId, this.rootEvent.getId(), "m.reference", undefined, { - from: this.relationsNextBatch || undefined, - }); - yield Promise.all(allRelations.events.map((event) => this.matrixClient.decryptEventIfNeeded(event))); - const responses = this.responses || - new relations_1.Relations("m.reference", polls_1.M_POLL_RESPONSE.name, this.matrixClient, [polls_1.M_POLL_RESPONSE.altName]); - const pollEndEvent = allRelations.events.find((event) => polls_1.M_POLL_END.matches(event.getType())); - if (this.validateEndEvent(pollEndEvent)) { - this.endEvent = pollEndEvent; - this.refilterResponsesOnEnd(); - this.emit(PollEvent.End); - } - const pollCloseTimestamp = ((_a = this.endEvent) === null || _a === void 0 ? void 0 : _a.getTs()) || Number.MAX_SAFE_INTEGER; - const { responseEvents } = filterResponseRelations(allRelations.events, pollCloseTimestamp); - responseEvents.forEach((event) => { - responses.addEvent(event); - }); - this.relationsNextBatch = (_b = allRelations.nextBatch) !== null && _b !== void 0 ? _b : undefined; - this.responses = responses; - this.countUndecryptableEvents(allRelations.events); - // while there are more pages of relations - // fetch them - if (this.relationsNextBatch) { - // don't await - // we want to return the first page as soon as possible - this.fetchResponses(); - } - else { - // no more pages - this._isFetchingResponses = false; - } - // emit after updating _isFetchingResponses state - this.emit(PollEvent.Responses, this.responses); - }); - } - /** - * Only responses made before the poll ended are valid - * Refilter after an end event is recieved - * To ensure responses are valid - */ - refilterResponsesOnEnd() { - var _a; - if (!this.responses) { - return; - } - const pollEndTimestamp = ((_a = this.endEvent) === null || _a === void 0 ? void 0 : _a.getTs()) || Number.MAX_SAFE_INTEGER; - this.responses.getRelations().forEach((event) => { - var _a; - if (event.getTs() > pollEndTimestamp) { - (_a = this.responses) === null || _a === void 0 ? void 0 : _a.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. - */ - const roomCurrentState = this.room.currentState; - const endEventSender = endEvent.getSender(); - return (!!endEventSender && - (endEventSender === this.rootEvent.getSender() || - roomCurrentState.maySendRedactionForEvent(this.rootEvent, endEventSender))); - } -} -exports.Poll = Poll; - -},{"../@types/polls":310,"./relations":388,"./typed-event-emitter":395}],386:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ReadReceipt = exports.synthesizeReceipt = void 0; -const read_receipts_1 = require("../@types/read_receipts"); -const typed_event_emitter_1 = require("./typed-event-emitter"); -const utils = __importStar(require("../utils")); -const event_1 = require("./event"); -const event_2 = require("../@types/event"); -const utils_1 = require("../utils"); -const room_1 = require("./room"); -function synthesizeReceipt(userId, event, receiptType) { - var _a; - return new event_1.MatrixEvent({ - content: { - [event.getId()]: { - [receiptType]: { - [userId]: { - ts: event.getTs(), - thread_id: (_a = event.threadRootId) !== null && _a !== void 0 ? _a : read_receipts_1.MAIN_ROOM_TIMELINE, - }, - }, - }, - }, - type: event_2.EventType.Receipt, - room_id: event.getRoomId(), - }); -} -exports.synthesizeReceipt = synthesizeReceipt; -const ReceiptPairRealIndex = 0; -const ReceiptPairSyntheticIndex = 1; -class ReadReceipt extends typed_event_emitter_1.TypedEventEmitter { - constructor() { - super(...arguments); - // receipts should clobber based on receipt_type and user_id pairs hence - // the form of this structure. This is sub-optimal for the exposed APIs - // which pass in an event ID and get back some receipts, so we also store - // a pre-cached list for this purpose. - // Map: receipt type → user Id → receipt - this.receipts = new utils_1.MapWithDefault(() => new Map()); - this.receiptCacheByEventId = 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, ignoreSynthesized = false, receiptType = read_receipts_1.ReceiptType.Read) { - var _a, _b; - const [realReceipt, syntheticReceipt] = (_b = (_a = this.receipts.get(receiptType)) === null || _a === void 0 ? void 0 : _a.get(userId)) !== null && _b !== void 0 ? _b : [null, null]; - if (ignoreSynthesized) { - return realReceipt; - } - return syntheticReceipt !== null && syntheticReceipt !== void 0 ? syntheticReceipt : realReceipt; - } - /** - * Get the ID of the event that a given user has read up to, or null if we - * have received no read receipts 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 = false) { - // XXX: This is very very ugly and I hope I won't have to ever add a new - // receipt type here again. IMHO this should be done by the server in - // some more intelligent manner or the client should just use timestamps - var _a, _b, _c, _d, _e, _f, _g; - const timelineSet = this.getUnfilteredTimelineSet(); - const publicReadReceipt = this.getReadReceiptForUserId(userId, ignoreSynthesized, read_receipts_1.ReceiptType.Read); - const privateReadReceipt = this.getReadReceiptForUserId(userId, ignoreSynthesized, read_receipts_1.ReceiptType.ReadPrivate); - // If we have both, compare them - let comparison; - if ((publicReadReceipt === null || publicReadReceipt === void 0 ? void 0 : publicReadReceipt.eventId) && (privateReadReceipt === null || privateReadReceipt === void 0 ? void 0 : privateReadReceipt.eventId)) { - comparison = timelineSet.compareEventOrdering(publicReadReceipt === null || publicReadReceipt === void 0 ? void 0 : publicReadReceipt.eventId, privateReadReceipt === null || privateReadReceipt === void 0 ? void 0 : privateReadReceipt.eventId); - } - // If we didn't get a comparison try to compare the ts of the receipts - if (!comparison && ((_a = publicReadReceipt === null || publicReadReceipt === void 0 ? void 0 : publicReadReceipt.data) === null || _a === void 0 ? void 0 : _a.ts) && ((_b = privateReadReceipt === null || privateReadReceipt === void 0 ? void 0 : privateReadReceipt.data) === null || _b === void 0 ? void 0 : _b.ts)) { - comparison = ((_c = publicReadReceipt === null || publicReadReceipt === void 0 ? void 0 : publicReadReceipt.data) === null || _c === void 0 ? void 0 : _c.ts) - ((_d = privateReadReceipt === null || privateReadReceipt === void 0 ? void 0 : privateReadReceipt.data) === null || _d === void 0 ? void 0 : _d.ts); - } - // The public receipt is more likely to drift out of date so the private - // one has precedence - if (!comparison) - return (_f = (_e = privateReadReceipt === null || privateReadReceipt === void 0 ? void 0 : privateReadReceipt.eventId) !== null && _e !== void 0 ? _e : publicReadReceipt === null || publicReadReceipt === void 0 ? void 0 : publicReadReceipt.eventId) !== null && _f !== void 0 ? _f : null; - // If public read receipt is older, return the private one - return (_g = (comparison < 0 ? privateReadReceipt === null || privateReadReceipt === void 0 ? void 0 : privateReadReceipt.eventId : publicReadReceipt === null || publicReadReceipt === void 0 ? void 0 : publicReadReceipt.eventId)) !== null && _g !== void 0 ? _g : null; - } - addReceiptToStructure(eventId, receiptType, userId, receipt, synthetic) { - var _a, _b, _c; - const receiptTypesMap = this.receipts.getOrCreate(receiptType); - let pair = receiptTypesMap.get(userId); - if (!pair) { - pair = [null, null]; - receiptTypesMap.set(userId, pair); - } - let existingReceipt = pair[ReceiptPairRealIndex]; - if (synthetic) { - existingReceipt = (_a = pair[ReceiptPairSyntheticIndex]) !== null && _a !== void 0 ? _a : pair[ReceiptPairRealIndex]; - } - if (existingReceipt) { - // we only want to add this receipt if we think it is later than the one we already have. - // This is managed server-side, but because we synthesize RRs locally we have to do it here too. - const ordering = this.getUnfilteredTimelineSet().compareEventOrdering(existingReceipt.eventId, eventId); - if (ordering !== null && ordering >= 0) { - return; - } - } - const wrappedReceipt = { - eventId, - data: receipt, - }; - const realReceipt = synthetic ? pair[ReceiptPairRealIndex] : wrappedReceipt; - const syntheticReceipt = synthetic ? wrappedReceipt : pair[ReceiptPairSyntheticIndex]; - let ordering = null; - if (realReceipt && syntheticReceipt) { - ordering = this.getUnfilteredTimelineSet().compareEventOrdering(realReceipt.eventId, syntheticReceipt.eventId); - } - const preferSynthetic = ordering === null || ordering < 0; - // we don't bother caching just real receipts by event ID as there's nothing that would read it. - // Take the current cached receipt before we overwrite the pair elements. - const cachedReceipt = (_b = pair[ReceiptPairSyntheticIndex]) !== null && _b !== void 0 ? _b : pair[ReceiptPairRealIndex]; - if (synthetic && preferSynthetic) { - pair[ReceiptPairSyntheticIndex] = wrappedReceipt; - } - else if (!synthetic) { - pair[ReceiptPairRealIndex] = wrappedReceipt; - if (!preferSynthetic) { - pair[ReceiptPairSyntheticIndex] = null; - } - } - const newCachedReceipt = (_c = pair[ReceiptPairSyntheticIndex]) !== null && _c !== void 0 ? _c : pair[ReceiptPairRealIndex]; - if (cachedReceipt === newCachedReceipt) - return; - // clean up any previous cache entry - if (cachedReceipt && this.receiptCacheByEventId.get(cachedReceipt.eventId)) { - const previousEventId = cachedReceipt.eventId; - // Remove the receipt we're about to clobber out of existence from the cache - 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); // clean up the cache keys - } - } - // cache the new one - if (!this.receiptCacheByEventId.get(eventId)) { - this.receiptCacheByEventId.set(eventId, []); - } - this.receiptCacheByEventId.get(eventId).push({ - userId: 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()) || []; - } - /** - * 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) { - const receipt = this.getReadReceiptForUserId(userId, false); - const 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(room_1.NotificationCountType.Total, 0); - this.setUnread(room_1.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 - */ - addLocalEchoReceipt(userId, e, receiptType) { - this.addReceipt(synthesizeReceipt(userId, e, receiptType), true); - } - /** - * Get a list of user IDs who have read up to 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 utils.isSupportedReceiptType(receipt.type); - }) - .map(function (receipt) { - return receipt.userId; - }); - } - /** - * 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) { - var _a, _b; - const readUpToId = this.getEventReadUpTo(userId, false); - if (readUpToId === eventId) - return true; - if (((_a = this.timeline) === null || _a === void 0 ? void 0 : _a.length) && - this.timeline[this.timeline.length - 1].getSender() && - this.timeline[this.timeline.length - 1].getSender() === userId) { - // It doesn't matter where the event is in the timeline, the user has read - // it because they've sent the latest event. - return true; - } - for (let i = ((_b = this.timeline) === null || _b === void 0 ? void 0 : _b.length) - 1; i >= 0; --i) { - const ev = this.timeline[i]; - // If we encounter the target event first, the user hasn't read it - // however if we encounter the readUpToId first then the user has read - // it. These rules apply because we're iterating bottom-up. - if (ev.getId() === eventId) - return false; - if (ev.getId() === readUpToId) - return true; - } - // We don't know if the user has read it, so assume not. - return false; - } -} -exports.ReadReceipt = ReadReceipt; - -},{"../@types/event":306,"../@types/read_receipts":311,"../utils":416,"./event":383,"./room":392,"./typed-event-emitter":395}],387:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RelationsContainer = void 0; -const relations_1 = require("./relations"); -const event_1 = require("./event"); -class RelationsContainer { - constructor(client, room) { - this.client = client; - this.room = room; - // A tree of objects to access a set of related children for an event, as in: - // this.relations.get(parentEventId).get(relationType).get(relationEventType) - this.relations = 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, relationType or 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 _a, _b; - return (_b = (_a = this.relations.get(eventId)) === null || _a === void 0 ? void 0 : _a.get(relationType)) === null || _b === void 0 ? void 0 : _b.get(eventType); - } - getAllChildEventsForEvent(parentEventId) { - var _a; - const relationsForEvent = (_a = this.relations.get(parentEventId)) !== null && _a !== void 0 ? _a : new Map(); - const events = []; - for (const relationsRecord of relationsForEvent.values()) { - for (const 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) { - const relationsForEvent = this.relations.get(event.getId()); - if (!relationsForEvent) - return; - for (const relationsWithRelType of relationsForEvent.values()) { - for (const 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) { - var _a, _b, _c; - if (event.isRedacted() || event.status === event_1.EventStatus.CANCELLED) { - return; - } - const relation = event.getRelation(); - if (!relation) - return; - const onEventDecrypted = () => { - if (event.isDecryptionFailure()) { - // This could for example happen if the encryption keys are not yet available. - // The event may still be decrypted later. Register the listener again. - event.once(event_1.MatrixEventEvent.Decrypted, onEventDecrypted); - return; - } - this.aggregateChildEvent(event, timelineSet); - }; - // If the event is currently encrypted, wait until it has been decrypted. - if (event.isBeingDecrypted() || event.shouldAttemptDecryption()) { - event.once(event_1.MatrixEventEvent.Decrypted, onEventDecrypted); - return; - } - const { event_id: relatesToEventId, rel_type: relationType } = relation; - const eventType = event.getType(); - let relationsForEvent = this.relations.get(relatesToEventId); - if (!relationsForEvent) { - relationsForEvent = new Map(); - this.relations.set(relatesToEventId, relationsForEvent); - } - let relationsWithRelType = relationsForEvent.get(relationType); - if (!relationsWithRelType) { - relationsWithRelType = new Map(); - relationsForEvent.set(relationType, relationsWithRelType); - } - let relationsWithEventType = relationsWithRelType.get(eventType); - if (!relationsWithEventType) { - relationsWithEventType = new relations_1.Relations(relationType, eventType, this.client); - relationsWithRelType.set(eventType, relationsWithEventType); - const room = (_a = this.room) !== null && _a !== void 0 ? _a : timelineSet === null || timelineSet === void 0 ? void 0 : timelineSet.room; - const relatesToEvent = (_c = (_b = timelineSet === null || timelineSet === void 0 ? void 0 : timelineSet.findEventById(relatesToEventId)) !== null && _b !== void 0 ? _b : room === null || room === void 0 ? void 0 : room.findEventById(relatesToEventId)) !== null && _c !== void 0 ? _c : room === null || room === void 0 ? void 0 : room.getPendingEvent(relatesToEventId); - if (relatesToEvent) { - relationsWithEventType.setTargetEvent(relatesToEvent); - } - } - relationsWithEventType.addEvent(event); - } -} -exports.RelationsContainer = RelationsContainer; - -},{"./event":383,"./relations":388}],388:[function(require,module,exports){ -"use strict"; -/* -Copyright 2019, 2021, 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Relations = exports.RelationsEvent = void 0; -const event_1 = require("./event"); -const logger_1 = require("../logger"); -const event_2 = require("../@types/event"); -const typed_event_emitter_1 = require("./typed-event-emitter"); -const room_1 = require("./room"); -var RelationsEvent; -(function (RelationsEvent) { - RelationsEvent["Add"] = "Relations.add"; - RelationsEvent["Remove"] = "Relations.remove"; - RelationsEvent["Redaction"] = "Relations.redaction"; -})(RelationsEvent = exports.RelationsEvent || (exports.RelationsEvent = {})); -const matchesEventType = (eventType, targetEventType, altTargetEventTypes = []) => [targetEventType, ...altTargetEventTypes].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. - */ -class Relations extends typed_event_emitter_1.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) { - super(); - this.relationType = relationType; - this.eventType = eventType; - this.altEventTypes = altEventTypes; - this.relationEventIds = new Set(); - this.relations = new Set(); - this.annotationsByKey = {}; - this.annotationsBySender = {}; - this.sortedAnnotationsByKey = []; - this.targetEvent = null; - this.creationEmitted = false; - /** - * Listens for event status changes to remove cancelled events. - * - * @param event - The event whose status has changed - * @param status - The new status - */ - this.onEventStatus = (event, status) => { - if (!event.isSending()) { - // Sending is done, so we don't need to listen anymore - event.removeListener(event_1.MatrixEventEvent.Status, this.onEventStatus); - return; - } - if (status !== event_1.EventStatus.CANCELLED) { - return; - } - // Event was cancelled, remove from the collection - event.removeListener(event_1.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. - */ - this.onBeforeRedaction = (redactedEvent) => __awaiter(this, void 0, void 0, function* () { - if (!this.relations.has(redactedEvent)) { - return; - } - this.relations.delete(redactedEvent); - if (this.relationType === event_2.RelationType.Annotation) { - // Remove the redacted annotation from aggregation by key - this.removeAnnotationFromAggregation(redactedEvent); - } - else if (this.relationType === event_2.RelationType.Replace && this.targetEvent && !this.targetEvent.isState()) { - const lastReplacement = yield this.getLastReplacement(); - this.targetEvent.makeReplaced(lastReplacement); - } - redactedEvent.removeListener(event_1.MatrixEventEvent.BeforeRedaction, this.onBeforeRedaction); - this.emit(RelationsEvent.Redaction, redactedEvent); - }); - this.client = client instanceof room_1.Room ? client.client : client; - } - /** - * Add relation events to this collection. - * - * @param event - The new relation event to be added. - */ - addEvent(event) { - return __awaiter(this, void 0, void 0, function* () { - if (this.relationEventIds.has(event.getId())) { - return; - } - const relation = event.getRelation(); - if (!relation) { - logger_1.logger.error("Event must have relation info"); - return; - } - const relationType = relation.rel_type; - const eventType = event.getType(); - if (this.relationType !== relationType || !matchesEventType(eventType, this.eventType, this.altEventTypes)) { - logger_1.logger.error("Event relation info doesn't match this container"); - return; - } - // If the event is in the process of being sent, listen for cancellation - // so we can remove the event from the collection. - if (event.isSending()) { - event.on(event_1.MatrixEventEvent.Status, this.onEventStatus); - } - this.relations.add(event); - this.relationEventIds.add(event.getId()); - if (this.relationType === event_2.RelationType.Annotation) { - this.addAnnotationToAggregation(event); - } - else if (this.relationType === event_2.RelationType.Replace && this.targetEvent && !this.targetEvent.isState()) { - const lastReplacement = yield this.getLastReplacement(); - this.targetEvent.makeReplaced(lastReplacement); - } - event.on(event_1.MatrixEventEvent.BeforeRedaction, this.onBeforeRedaction); - this.emit(RelationsEvent.Add, event); - this.maybeEmitCreated(); - }); - } - /** - * Remove relation event from this collection. - * - * @param event - The relation event to remove. - */ - removeEvent(event) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.relations.has(event)) { - return; - } - this.relations.delete(event); - if (this.relationType === event_2.RelationType.Annotation) { - this.removeAnnotationFromAggregation(event); - } - else if (this.relationType === event_2.RelationType.Replace && this.targetEvent && !this.targetEvent.isState()) { - const lastReplacement = yield this.getLastReplacement(); - this.targetEvent.makeReplaced(lastReplacement); - } - this.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 _a; - const { key } = (_a = event.getRelation()) !== null && _a !== void 0 ? _a : {}; - if (!key) - return; - let eventsForKey = this.annotationsByKey[key]; - if (!eventsForKey) { - eventsForKey = this.annotationsByKey[key] = new Set(); - this.sortedAnnotationsByKey.push([key, eventsForKey]); - } - // Add the new event to the set for this key - eventsForKey.add(event); - // Re-sort the [key, events] pairs in descending order of event count - this.sortedAnnotationsByKey.sort((a, b) => { - const aEvents = a[1]; - const bEvents = b[1]; - return bEvents.size - aEvents.size; - }); - const sender = event.getSender(); - let eventsFromSender = this.annotationsBySender[sender]; - if (!eventsFromSender) { - eventsFromSender = this.annotationsBySender[sender] = new Set(); - } - // Add the new event to the set for this sender - eventsFromSender.add(event); - } - removeAnnotationFromAggregation(event) { - var _a; - const { key } = (_a = event.getRelation()) !== null && _a !== void 0 ? _a : {}; - if (!key) - return; - const eventsForKey = this.annotationsByKey[key]; - if (eventsForKey) { - eventsForKey.delete(event); - // Re-sort the [key, events] pairs in descending order of event count - this.sortedAnnotationsByKey.sort((a, b) => { - const aEvents = a[1]; - const bEvents = b[1]; - return bEvents.size - aEvents.size; - }); - } - const sender = event.getSender(); - const 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 !== event_2.RelationType.Annotation) { - // Other relation types are not grouped currently. - 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 !== event_2.RelationType.Annotation) { - // Other relation types are not grouped currently. - 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() { - return __awaiter(this, void 0, void 0, function* () { - if (this.relationType !== event_2.RelationType.Replace) { - // Aggregating on last only makes sense for this relation type - return null; - } - if (!this.targetEvent) { - // Don't know which replacements to accept yet. - // This method shouldn't be called before the original - // event is known anyway. - return null; - } - // the all-knowning server tells us that the event at some point had - // this timestamp for its replacement, so any following replacement should definitely not be less - const replaceRelation = this.targetEvent.getServerAggregatedRelation(event_2.RelationType.Replace); - const minTs = replaceRelation === null || replaceRelation === void 0 ? void 0 : replaceRelation.origin_server_ts; - const lastReplacement = this.getRelations().reduce((last, event) => { - if (event.getSender() !== this.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 ? void 0 : lastReplacement.shouldAttemptDecryption()) && this.client.isCryptoEnabled()) { - yield lastReplacement.attemptDecryption(this.client.crypto); - } - else if (lastReplacement === null || lastReplacement === void 0 ? void 0 : lastReplacement.isBeingDecrypted()) { - yield lastReplacement.getDecryptionPromise(); - } - return lastReplacement; - }); - } - /* - * @param targetEvent - the event the relations are related to. - */ - setTargetEvent(event) { - return __awaiter(this, void 0, void 0, function* () { - if (this.targetEvent) { - return; - } - this.targetEvent = event; - if (this.relationType === event_2.RelationType.Replace && !this.targetEvent.isState()) { - const replacement = yield this.getLastReplacement(); - // this is the initial update, so only call it if we already have something - // to not emit Event.replaced needlessly - if (replacement) { - this.targetEvent.makeReplaced(replacement); - } - } - this.maybeEmitCreated(); - }); - } - maybeEmitCreated() { - if (this.creationEmitted) { - return; - } - // Only emit we're "created" once we have a target event instance _and_ - // at least one related event. - if (!this.targetEvent || !this.relations.size) { - return; - } - this.creationEmitted = true; - this.targetEvent.emit(event_1.MatrixEventEvent.RelationsCreated, this.relationType, this.eventType); - } -} -exports.Relations = Relations; - -},{"../@types/event":306,"../logger":374,"./event":383,"./room":392,"./typed-event-emitter":395}],389:[function(require,module,exports){ -"use strict"; -/* -Copyright 2015 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RoomMember = exports.RoomMemberEvent = void 0; -const content_repo_1 = require("../content-repo"); -const utils = __importStar(require("../utils")); -const logger_1 = require("../logger"); -const typed_event_emitter_1 = require("./typed-event-emitter"); -const event_1 = require("../@types/event"); -var RoomMemberEvent; -(function (RoomMemberEvent) { - RoomMemberEvent["Membership"] = "RoomMember.membership"; - RoomMemberEvent["Name"] = "RoomMember.name"; - RoomMemberEvent["PowerLevel"] = "RoomMember.powerLevel"; - RoomMemberEvent["Typing"] = "RoomMember.typing"; -})(RoomMemberEvent = exports.RoomMemberEvent || (exports.RoomMemberEvent = {})); -class RoomMember extends typed_event_emitter_1.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; - this._isOutOfBand = false; - this.modified = -1; - this.requestedProfileInfo = false; // used by sync.ts - // XXX these should be read-only - /** - * True if the room member is currently typing. - */ - this.typing = false; - /** - * The power level for this room member. - */ - this.powerLevel = 0; - /** - * The normalised power level (0-100) for this room member. - */ - this.powerLevelNorm = 0; - /** - * True if the member's name is disambiguated. - */ - this.disambiguate = false; - /** - * The events describing this RoomMember. - */ - 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 _a, _b; - const displayName = (_a = event.getDirectionalContent().displayname) !== null && _a !== void 0 ? _a : ""; - if (event.getType() !== event_1.EventType.RoomMember) { - return; - } - this._isOutOfBand = false; - this.events.member = event; - const oldMembership = this.membership; - this.membership = event.getDirectionalContent().membership; - if (this.membership === undefined) { - // logging to diagnose https://github.com/vector-im/element-web/issues/20962 - // (logs event content, although only of membership events) - logger_1.logger.trace(`membership event with membership undefined (forwardLooking: ${event.forwardLooking})!`, event.getContent(), `prevcontent is `, event.getPrevContent()); - } - this.disambiguate = shouldDisambiguate(this.userId, displayName, roomState); - const oldName = this.name; - this.name = calculateDisplayName(this.userId, displayName, this.disambiguate); - // not quite raw: we strip direction override chars so it can safely be inserted into - // blocks of text without breaking the text direction - this.rawDisplayName = utils.removeDirectionOverrideChars((_b = event.getDirectionalContent().displayname) !== null && _b !== void 0 ? _b : ""); - if (!this.rawDisplayName || !utils.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); - } - } - /** - * Update this room member's power level event. May fire - * "RoomMember.powerLevel" if this event updates this member's power levels. - * @param powerLevelEvent - The `m.room.power_levels` event - * - * @remarks - * Fires {@link RoomMemberEvent.PowerLevel} - */ - setPowerLevelEvent(powerLevelEvent) { - if (powerLevelEvent.getType() !== event_1.EventType.RoomPowerLevels || powerLevelEvent.getStateKey() !== "") { - return; - } - const evContent = powerLevelEvent.getDirectionalContent(); - let maxLevel = evContent.users_default || 0; - const users = evContent.users || {}; - Object.values(users).forEach((lvl) => { - maxLevel = Math.max(maxLevel, lvl); - }); - const oldPowerLevel = this.powerLevel; - const oldPowerLevelNorm = this.powerLevelNorm; - if (users[this.userId] !== undefined && Number.isInteger(users[this.userId])) { - this.powerLevel = users[this.userId]; - } - else if (evContent.users_default !== undefined) { - this.powerLevel = evContent.users_default; - } - else { - this.powerLevel = 0; - } - this.powerLevelNorm = 0; - if (maxLevel > 0) { - this.powerLevelNorm = (this.powerLevel * 100) / maxLevel; - } - // emit for changes in powerLevelNorm as well (since the app will need to - // redraw everyone's level if the max has changed) - if (oldPowerLevel !== this.powerLevel || oldPowerLevelNorm !== this.powerLevelNorm) { - 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; - } - const oldTyping = this.typing; - this.typing = false; - const typingList = event.getContent().user_ids; - if (!Array.isArray(typingList)) { - // malformed event :/ bail early. TODO: whine? - 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 before firing events. - * @returns The timestamp - */ - getLastModifiedTime() { - return this.modified; - } - isKicked() { - return (this.membership === "leave" && - this.events.member !== undefined && - 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() { - // when not available because that room state hasn't been loaded in, - // we don't really know, but more likely to not be a direct chat - if (this.events.member) { - // TODO: persist the is_direct flag on the member as more member events - // come in caused by displayName changes. - // the is_direct flag is set on the invite member event. - // This is copied on the prev_content section of the join member event - // when the invite is accepted. - const memberEvent = this.events.member; - let memberContent = memberEvent.getContent(); - let inviteSender = memberEvent.getSender(); - if (memberContent.membership === "join") { - memberContent = memberEvent.getPrevContent(); - inviteSender = memberEvent.getUnsigned().prev_sender; - } - if (memberContent.membership === "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. - * @returns the avatar URL or null. - */ - getAvatarUrl(baseUrl, width, height, resizeMethod, allowDefault = true, allowDirectLinks) { - const rawUrl = this.getMxcAvatarUrl(); - if (!rawUrl && !allowDefault) { - return null; - } - const httpUrl = (0, content_repo_1.getHttpUriForMxc)(baseUrl, rawUrl, width, height, resizeMethod, allowDirectLinks); - 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; - } - } -} -exports.RoomMember = RoomMember; -const MXID_PATTERN = /@.+:.+/; -const LTR_RTL_PATTERN = /[\u200E\u200F\u202A-\u202F]/; -function shouldDisambiguate(selfUserId, displayName, roomState) { - if (!displayName || displayName === selfUserId) - return false; - // First check if the displayname is something we consider truthy - // after stripping it of zero width characters and padding spaces - if (!utils.removeHiddenChars(displayName)) - return false; - if (!roomState) - return false; - // Next check if the name contains something that look like a mxid - // If it does, it may be someone trying to impersonate someone else - // Show full mxid in this case - if (MXID_PATTERN.test(displayName)) - return true; - // Also show mxid if the display name contains any LTR/RTL characters as these - // make it very difficult for us to find similar *looking* display names - // E.g "Mark" could be cloned by writing "kraM" but in RTL. - if (LTR_RTL_PATTERN.test(displayName)) - return true; - // Also show mxid if there are other people with the same or similar - // displayname, after hidden character removal. - const userIds = roomState.getUserIdsWithDisplayName(displayName); - if (userIds.some((u) => u !== selfUserId)) - return true; - return false; -} -function calculateDisplayName(selfUserId, displayName, disambiguate) { - if (!displayName || displayName === selfUserId) - return selfUserId; - if (disambiguate) - return utils.removeDirectionOverrideChars(displayName) + " (" + selfUserId + ")"; - // First check if the displayname is something we consider truthy - // after stripping it of zero width characters and padding spaces - if (!utils.removeHiddenChars(displayName)) - return selfUserId; - // We always strip the direction override characters (LRO and RLO). - // These override the text direction for all subsequent characters - // in the paragraph so if display names contained these, they'd - // need to be wrapped in something to prevent this from leaking out - // (which we can do in HTML but not text) or we'd need to add - // control characters to the string to reset any overrides (eg. - // adding PDF characters at the end). As far as we can see, - // there should be no reason these would be necessary - rtl display - // names should flip into the correct direction automatically based on - // the characters, and you can still embed rtl in ltr or vice versa - // with the embed chars or marker chars. - return utils.removeDirectionOverrideChars(displayName); -} - -},{"../@types/event":306,"../content-repo":323,"../logger":374,"../utils":416,"./typed-event-emitter":395}],390:[function(require,module,exports){ -"use strict"; -/* -Copyright 2015 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RoomState = exports.RoomStateEvent = void 0; -const room_member_1 = require("./room-member"); -const logger_1 = require("../logger"); -const utils = __importStar(require("../utils")); -const event_1 = require("../@types/event"); -const event_2 = require("./event"); -const partials_1 = require("../@types/partials"); -const typed_event_emitter_1 = require("./typed-event-emitter"); -const beacon_1 = require("./beacon"); -const ReEmitter_1 = require("../ReEmitter"); -const beacon_2 = require("../@types/beacon"); -// possible statuses for out-of-band member loading -var OobStatus; -(function (OobStatus) { - OobStatus[OobStatus["NotStarted"] = 0] = "NotStarted"; - OobStatus[OobStatus["InProgress"] = 1] = "InProgress"; - OobStatus[OobStatus["Finished"] = 2] = "Finished"; -})(OobStatus || (OobStatus = {})); -var RoomStateEvent; -(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"; -})(RoomStateEvent = exports.RoomStateEvent || (exports.RoomStateEvent = {})); -class RoomState extends typed_event_emitter_1.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, oobMemberFlags = { status: OobStatus.NotStarted }) { - super(); - this.roomId = roomId; - this.oobMemberFlags = oobMemberFlags; - this.reEmitter = new ReEmitter_1.TypedReEmitter(this); - this.sentinels = {}; // userId: RoomMember - // stores fuzzy matches to a list of userIDs (applies utils.removeHiddenChars to keys) - this.displayNameToUserIds = new Map(); - this.userIdsToDisplayNames = {}; - this.tokenToInvite = {}; // 3pid invite state_key to m.room.member invite - this.joinedMemberCount = null; // cache of the number of joined members - // joined members count from summary api - // once set, we know the server supports the summary api - // and we should only trust that - // we could also only trust that before OOB members - // are loaded but doesn't seem worth the hassle atm - this.summaryJoinedMemberCount = null; - // same for invited member count - this.invitedMemberCount = null; - this.summaryInvitedMemberCount = null; - this.modified = -1; - // XXX: Should be read-only - // The room member dictionary, keyed on the user's ID. - this.members = {}; // userId: RoomMember - // The state events dictionary, keyed on the event type and then the state_key value. - this.events = new Map(); // Map> - // The pagination token for this state. - this.paginationToken = null; - this.beacons = new Map(); - this._liveBeaconIds = []; - this.updateModifiedTime(); - } - /** - * 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 === "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 === "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; - let sentinel = this.sentinels[userId]; - if (sentinel === undefined) { - sentinel = new room_member_1.RoomMember(this.roomId, userId); - const member = this.members[userId]; - if (member === null || member === void 0 ? void 0 : member.events.member) { - sentinel.setMembershipEvent(member.events.member, this); - } - this.sentinels[userId] = sentinel; - } - return sentinel; - } - getStateEvents(eventType, stateKey) { - if (!this.events.has(eventType)) { - // no match - return stateKey === undefined ? [] : null; - } - if (stateKey === undefined) { - // return all values - return Array.from(this.events.get(eventType).values()); - } - const event = this.events.get(eventType).get(stateKey); - return event ? event : null; - } - get hasLiveBeacons() { - var _a; - return !!((_a = this.liveBeaconIds) === null || _a === void 0 ? void 0 : _a.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() { - const copy = new RoomState(this.roomId, this.oobMemberFlags); - // Ugly hack: because setStateEvents will mark - // members as susperseding future out of bound members - // if loading is in progress (through oobMemberFlags) - // since these are not new members, we're merely copying them - // set the status to not started - // after copying, we set back the status - const status = this.oobMemberFlags.status; - this.oobMemberFlags.status = OobStatus.NotStarted; - Array.from(this.events.values()).forEach((eventsByStateKey) => { - copy.setStateEvents(Array.from(eventsByStateKey.values())); - }); - // Ugly hack: see above - this.oobMemberFlags.status = status; - if (this.summaryInvitedMemberCount !== null) { - copy.setInvitedMemberCount(this.getInvitedMemberCount()); - } - if (this.summaryJoinedMemberCount !== null) { - copy.setJoinedMemberCount(this.getJoinedMemberCount()); - } - // copy out of band flags if needed - if (this.oobMemberFlags.status == OobStatus.Finished) { - // copy markOutOfBand flags - this.getMembers().forEach((member) => { - var _a; - if (member.isOutOfBand()) { - (_a = copy.getMember(member.userId)) === null || _a === void 0 ? void 0 : _a.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) { - const 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(); - // update the core event dict - stateEvents.forEach((event) => { - var _a; - if (event.getRoomId() !== this.roomId || !event.isState()) - return; - if (beacon_2.M_BEACON_INFO.matches(event.getType())) { - this.setBeacon(event); - } - const lastStateEvent = this.getStateEventMatching(event); - this.setStateEvent(event); - if (event.getType() === event_1.EventType.RoomMember) { - this.updateDisplayNameCache(event.getStateKey(), (_a = event.getContent().displayname) !== null && _a !== void 0 ? _a : ""); - this.updateThirdPartyTokenCache(event); - } - this.emit(RoomStateEvent.Events, event, this, lastStateEvent); - }); - this.onBeaconLivenessChange(); - // update higher level data structures. This needs to be done AFTER the - // core event dict as these structures may depend on other state events in - // the given array (e.g. disambiguating display names in one go to do both - // clashing names rather than progressively which only catches 1 of them). - stateEvents.forEach((event) => { - if (event.getRoomId() !== this.roomId || !event.isState()) - return; - if (event.getType() === event_1.EventType.RoomMember) { - const userId = event.getStateKey(); - // leave events apparently elide the displayname or avatar_url, - // so let's fake one up so that we don't leak user ids - // into the timeline - if (event.getContent().membership === "leave" || event.getContent().membership === "ban") { - event.getContent().avatar_url = event.getContent().avatar_url || event.getPrevContent().avatar_url; - event.getContent().displayname = - event.getContent().displayname || event.getPrevContent().displayname; - } - const member = this.getOrCreateMember(userId, event); - member.setMembershipEvent(event, this); - this.updateMember(member); - this.emit(RoomStateEvent.Members, event, this, member); - } - else if (event.getType() === event_1.EventType.RoomPowerLevels) { - // events with unknown state keys should be ignored - // and should not aggregate onto members power levels - if (event.getStateKey() !== "") { - return; - } - const members = Object.values(this.members); - members.forEach((member) => { - // We only propagate `RoomState.members` event if the - // power levels has been changed - // large room suffer from large re-rendering especially when not needed - const oldLastModified = member.getLastModifiedTime(); - member.setPowerLevelEvent(event); - if (oldLastModified !== member.getLastModifiedTime()) { - this.emit(RoomStateEvent.Members, event, this, member); - } - }); - // assume all our sentinels are now out-of-date - this.sentinels = {}; - } - else if (event_1.UNSTABLE_MSC2716_MARKER.matches(event.getType())) { - this.emit(RoomStateEvent.Marker, event, markerFoundOptions); - } - }); - this.emit(RoomStateEvent.Update, this); - } - processBeaconEvents(events, matrixClient) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - if (!events.length || - // discard locations if we have no beacons - !this.beacons.size) { - return; - } - const beaconByEventIdDict = [...this.beacons.values()].reduce((dict, beacon) => { - dict[beacon.beaconInfoId] = beacon; - return dict; - }, {}); - const processBeaconRelation = (beaconInfoEventId, event) => { - if (!beacon_2.M_BEACON.matches(event.getType())) { - return; - } - const beacon = beaconByEventIdDict[beaconInfoEventId]; - if (beacon) { - beacon.addLocations([event]); - } - }; - for (const event of events) { - const relatedToEventId = (_a = event.getRelation()) === null || _a === void 0 ? void 0 : _a.event_id; - // not related to a beacon we know about; discard - if (!relatedToEventId || !beaconByEventIdDict[relatedToEventId]) - return; - if (!beacon_2.M_BEACON.matches(event.getType()) && !event.isEncrypted()) - return; - try { - yield matrixClient.decryptEventIfNeeded(event); - processBeaconRelation(relatedToEventId, event); - } - catch (_b) { - if (event.isDecryptionFailure()) { - // add an event listener for once the event is decrypted. - event.once(event_2.MatrixEventEvent.Decrypted, () => __awaiter(this, void 0, void 0, function* () { - processBeaconRelation(relatedToEventId, event); - })); - } - } - } - }); - } - /** - * 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) { - let member = this.members[userId]; - if (!member) { - member = new room_member_1.RoomMember(this.roomId, userId); - // add member to members before emitting any events, - // as event handlers often lookup the member - 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(), new Map()); - } - this.events.get(event.getType()).set(event.getStateKey(), event); - } - /** - * @experimental - */ - setBeacon(event) { - var _a; - const beaconIdentifier = (0, beacon_1.getBeaconInfoIdentifier)(event); - if (this.beacons.has(beaconIdentifier)) { - const beacon = this.beacons.get(beaconIdentifier); - if (event.isRedacted()) { - if (beacon.beaconInfoId === ((_a = event.getRedactionEvent()) === null || _a === void 0 ? void 0 : _a.redacts)) { - beacon.destroy(); - this.beacons.delete(beaconIdentifier); - } - return; - } - return beacon.update(event); - } - if (event.isRedacted()) { - return; - } - const beacon = new beacon_1.Beacon(event); - this.reEmitter.reEmit(beacon, [ - beacon_1.BeaconEvent.New, - beacon_1.BeaconEvent.Update, - beacon_1.BeaconEvent.Destroy, - beacon_1.BeaconEvent.LivenessChange, - ]); - this.emit(beacon_1.BeaconEvent.New, event, beacon); - beacon.on(beacon_1.BeaconEvent.LivenessChange, this.onBeaconLivenessChange.bind(this)); - beacon.on(beacon_1.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 _a, _b; - return (_b = (_a = this.events.get(event.getType())) === null || _a === void 0 ? void 0 : _a.get(event.getStateKey())) !== null && _b !== void 0 ? _b : null; - } - updateMember(member) { - // this member may have a power level already, so set it. - const pwrLvlEvent = this.getStateEvents(event_1.EventType.RoomPowerLevels, ""); - if (pwrLvlEvent) { - member.setPowerLevelEvent(pwrLvlEvent); - } - // blow away the sentinel which is now outdated - 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() { - let count = 0; - Object.keys(this.members).forEach((userId) => { - const member = this.members[userId]; - if (member.isOutOfBand()) { - ++count; - delete this.members[userId]; - } - }); - logger_1.logger.log(`LL: RoomState removed ${count} members...`); - this.oobMemberFlags.status = OobStatus.NotStarted; - } - /** - * Sets the loaded out-of-band members. - * @param stateEvents - array of membership state events - */ - setOutOfBandMembers(stateEvents) { - logger_1.logger.log(`LL: RoomState about to set ${stateEvents.length} OOB members ...`); - if (this.oobMemberFlags.status !== OobStatus.InProgress) { - return; - } - logger_1.logger.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() !== event_1.EventType.RoomMember) { - return; - } - const userId = stateEvent.getStateKey(); - const existingMember = this.getMember(userId); - // never replace members received as part of the sync - if (existingMember && !existingMember.isOutOfBand()) { - return; - } - const member = this.getOrCreateMember(userId, stateEvent); - member.setMembershipEvent(stateEvent, this); - // needed to know which members need to be stored seperately - // as they are not part of the sync accumulator - // this is cleared by setMembershipEvent so when it's updated through /sync - 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 _a; - return (_a = this.displayNameToUserIds.get(utils.removeHiddenChars(displayName))) !== null && _a !== void 0 ? _a : []; - } - /** - * 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) { - const member = this.getMember(userId); - if (!member || member.membership === "leave") - return false; - if (mxEvent.status || mxEvent.isRedacted()) - return false; - // The user may have been the sender, but they can't redact their own message - // if redactions are blocked. - const canRedact = this.maySendEvent(event_1.EventType.RoomRedaction, userId); - if (mxEvent.getSender() === userId) - return canRedact; - 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) { - const powerLevelsEvent = this.getStateEvents(event_1.EventType.RoomPowerLevels, ""); - let powerLevels = {}; - if (powerLevelsEvent) { - powerLevels = powerLevelsEvent.getContent(); - } - let requiredLevel = 50; - if (utils.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(event_1.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) { - const powerLevelsEvent = this.getStateEvents(event_1.EventType.RoomPowerLevels, ""); - let powerLevels; - let eventsLevels = {}; - let stateDefault = 0; - let eventsDefault = 0; - let powerLevel = 0; - if (powerLevelsEvent) { - powerLevels = powerLevelsEvent.getContent(); - eventsLevels = powerLevels.events || {}; - if (Number.isSafeInteger(powerLevels.state_default)) { - stateDefault = powerLevels.state_default; - } - else { - stateDefault = 50; - } - const userPowerLevel = powerLevels.users && powerLevels.users[userId]; - if (Number.isSafeInteger(userPowerLevel)) { - powerLevel = userPowerLevel; - } - else if (Number.isSafeInteger(powerLevels.users_default)) { - powerLevel = powerLevels.users_default; - } - if (Number.isSafeInteger(powerLevels.events_default)) { - eventsDefault = powerLevels.events_default; - } - } - let requiredLevel = state ? stateDefault : eventsDefault; - if (Number.isSafeInteger(eventsLevels[eventType])) { - requiredLevel = eventsLevels[eventType]; - } - return powerLevel >= 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) { - const member = this.getMember(userId); - if (!member) { - return false; - } - const powerLevelsEvent = this.getStateEvents(event_1.EventType.RoomPowerLevels, ""); - let notifLevel = 50; - if (powerLevelsEvent && - powerLevelsEvent.getContent() && - powerLevelsEvent.getContent().notifications && - utils.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 _a; - const joinRuleEvent = this.getStateEvents(event_1.EventType.RoomJoinRules, ""); - const joinRuleContent = (_a = joinRuleEvent === null || joinRuleEvent === void 0 ? void 0 : joinRuleEvent.getContent()) !== null && _a !== void 0 ? _a : {}; - return joinRuleContent["join_rule"] || partials_1.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 _a; - const historyVisibilityEvent = this.getStateEvents(event_1.EventType.RoomHistoryVisibility, ""); - const historyVisibilityContent = (_a = historyVisibilityEvent === null || historyVisibilityEvent === void 0 ? void 0 : historyVisibilityEvent.getContent()) !== null && _a !== void 0 ? _a : {}; - return historyVisibilityContent["history_visibility"] || partials_1.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 _a; - const guestAccessEvent = this.getStateEvents(event_1.EventType.RoomGuestAccess, ""); - const guestAccessContent = (_a = guestAccessEvent === null || guestAccessEvent === void 0 ? void 0 : guestAccessEvent.getContent()) !== null && _a !== void 0 ? _a : {}; - return guestAccessContent["guest_access"] || partials_1.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(msc3946ProcessDynamicPredecessor = false) { - // Note: the tests for this function are against Room.findPredecessor, - // which just calls through to here. - if (msc3946ProcessDynamicPredecessor) { - const predecessorEvent = this.getStateEvents(event_1.EventType.RoomPredecessor, ""); - if (predecessorEvent) { - const content = predecessorEvent.getContent(); - const roomId = content.predecessor_room_id; - let eventId = content.last_known_event_id; - if (typeof eventId !== "string") { - eventId = undefined; - } - let viaServers = content.via_servers; - if (!Array.isArray(viaServers)) { - viaServers = undefined; - } - if (typeof roomId === "string") { - return { roomId, eventId, viaServers }; - } - } - } - const createEvent = this.getStateEvents(event_1.EventType.RoomCreate, ""); - if (createEvent) { - const predecessor = createEvent.getContent()["predecessor"]; - if (predecessor) { - const roomId = predecessor["room_id"]; - if (typeof roomId === "string") { - let eventId = predecessor["event_id"]; - if (typeof eventId !== "string" || eventId === "") { - eventId = undefined; - } - return { roomId, eventId }; - } - } - } - return null; - } - updateThirdPartyTokenCache(memberEvent) { - if (!memberEvent.getContent().third_party_invite) { - return; - } - const token = (memberEvent.getContent().third_party_invite.signed || {}).token; - if (!token) { - return; - } - const threePidInvite = this.getStateEvents(event_1.EventType.RoomThirdPartyInvite, token); - if (!threePidInvite) { - return; - } - this.tokenToInvite[token] = memberEvent; - } - updateDisplayNameCache(userId, displayName) { - var _a; - const oldName = this.userIdsToDisplayNames[userId]; - delete this.userIdsToDisplayNames[userId]; - if (oldName) { - // Remove the old name from the cache. - // We clobber the user_id > name lookup but the name -> [user_id] lookup - // means we need to remove that user ID from that array rather than nuking - // the lot. - const strippedOldName = utils.removeHiddenChars(oldName); - const existingUserIds = this.displayNameToUserIds.get(strippedOldName); - if (existingUserIds) { - // remove this user ID from this array - const filteredUserIDs = existingUserIds.filter((id) => id !== userId); - this.displayNameToUserIds.set(strippedOldName, filteredUserIDs); - } - } - this.userIdsToDisplayNames[userId] = displayName; - const strippedDisplayname = displayName && utils.removeHiddenChars(displayName); - // an empty stripped displayname (undefined/'') will be set to MXID in room-member.js - if (strippedDisplayname) { - const arr = (_a = this.displayNameToUserIds.get(strippedDisplayname)) !== null && _a !== void 0 ? _a : []; - arr.push(userId); - this.displayNameToUserIds.set(strippedDisplayname, arr); - } - } -} -exports.RoomState = RoomState; - -},{"../@types/beacon":305,"../@types/event":306,"../@types/partials":309,"../ReEmitter":317,"../logger":374,"../utils":416,"./beacon":378,"./event":383,"./room-member":389,"./typed-event-emitter":395}],391:[function(require,module,exports){ -"use strict"; -/* -Copyright 2015 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RoomSummary = void 0; -/** - * 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. - */ -class RoomSummary { - constructor(roomId, info) { - this.roomId = roomId; - } -} -exports.RoomSummary = RoomSummary; - -},{}],392:[function(require,module,exports){ -"use strict"; -/* -Copyright 2015 - 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RoomNameType = exports.Room = exports.RoomEvent = exports.NotificationCountType = exports.KNOWN_SAFE_ROOM_VERSION = void 0; -const matrix_events_sdk_1 = require("matrix-events-sdk"); -const event_timeline_set_1 = require("./event-timeline-set"); -const event_timeline_1 = require("./event-timeline"); -const content_repo_1 = require("../content-repo"); -const utils = __importStar(require("../utils")); -const utils_1 = require("../utils"); -const event_1 = require("./event"); -const event_status_1 = require("./event-status"); -const room_member_1 = require("./room-member"); -const room_summary_1 = require("./room-summary"); -const logger_1 = require("../logger"); -const ReEmitter_1 = require("../ReEmitter"); -const event_2 = require("../@types/event"); -const client_1 = require("../client"); -const filter_1 = require("../filter"); -const room_state_1 = require("./room-state"); -const beacon_1 = require("./beacon"); -const thread_1 = require("./thread"); -const read_receipts_1 = require("../@types/read_receipts"); -const relations_container_1 = require("./relations-container"); -const read_receipt_1 = require("./read-receipt"); -const poll_1 = require("./poll"); -// These constants are used as sane defaults when the homeserver doesn't support -// the m.room_versions capability. In practice, KNOWN_SAFE_ROOM_VERSION should be -// the same as the common default room version whereas SAFE_ROOM_VERSIONS are the -// room versions which are considered okay for people to run without being asked -// to upgrade (ie: "stable"). Eventually, we should remove these when all homeservers -// return an m.room_versions capability. -exports.KNOWN_SAFE_ROOM_VERSION = "9"; -const SAFE_ROOM_VERSIONS = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]; -// When inserting a visibility event affecting event `eventId`, we -// need to scan through existing visibility events for `eventId`. -// In theory, this could take an unlimited amount of time if: -// -// - the visibility event was sent by a moderator; and -// - `eventId` already has many visibility changes (usually, it should -// be 2 or less); and -// - for some reason, the visibility changes are received out of order -// (usually, this shouldn't happen at all). -// -// For this reason, we limit the number of events to scan through, -// expecting that a broken visibility change for a single event in -// an extremely uncommon case (possibly a DoS) is a small -// price to pay to keep matrix-js-sdk responsive. -const MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH = 30; -var NotificationCountType; -(function (NotificationCountType) { - NotificationCountType["Highlight"] = "highlight"; - NotificationCountType["Total"] = "total"; -})(NotificationCountType = exports.NotificationCountType || (exports.NotificationCountType = {})); -var RoomEvent; -(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 = exports.RoomEvent || (exports.RoomEvent = {})); -class Room extends read_receipt_1.ReadReceipt { - /** - * Construct a new Room. - * - *

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. - * - *

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. - * - *

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, opts = {}) { - super(); - this.roomId = roomId; - this.client = client; - this.myUserId = myUserId; - this.opts = opts; - this.txnToEvent = new Map(); // Pending in-flight requests { string: MatrixEvent } - this.notificationCounts = {}; - this.threadNotifications = new Map(); - this.cachedThreadReadReceipts = new Map(); - // Useful to know at what point the current user has started using threads in this room - 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 - */ - this.unthreadedReceipts = new Map(); - this.polls = new Map(); - this.threadsTimelineSets = []; - // any filtered timeline sets we're maintaining for this room - this.filteredTimelineSets = {}; // filter_id: timelineSet - this.timelineNeedsRefresh = false; - this.summaryHeroes = null; - // flags to stop logspam about missing m.room.create events - this.getTypeWarning = false; - this.getVersionWarning = false; - /** - * 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 } }` - */ - this.tags = {}; // $tagName: { $metadata: $value } - /** - * accountData Dict of per-room account_data events; the keys are the - * event type and the values are the events. - */ - this.accountData = new Map(); // $eventType: $event - /** - * The room summary. - */ - this.summary = null; - this.relations = new relations_container_1.RelationsContainer(this.client, this); - /** - * A collection of events known by the client - * This is not a comprehensive list of the threads that exist in this room - */ - this.threads = 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 - */ - this.visibilityEvents = new Map(); - this.threadTimelineSetsPromise = null; - this.threadsReady = false; - this.updateThreadRootEvents = (thread, toStartOfTimeline, recreateEvent) => { - var _a, _b; - if (thread.length) { - this.updateThreadRootEvent((_a = this.threadsTimelineSets) === null || _a === void 0 ? void 0 : _a[0], thread, toStartOfTimeline, recreateEvent); - if (thread.hasCurrentUserParticipated) { - this.updateThreadRootEvent((_b = this.threadsTimelineSets) === null || _b === void 0 ? void 0 : _b[1], thread, toStartOfTimeline, recreateEvent); - } - } - }; - this.updateThreadRootEvent = (timelineSet, thread, toStartOfTimeline, recreateEvent) => { - if (timelineSet && thread.rootEvent) { - if (recreateEvent) { - timelineSet.removeEvent(thread.id); - } - if (thread_1.Thread.hasServerSideSupport) { - timelineSet.addLiveEvent(thread.rootEvent, { - duplicateStrategy: event_timeline_set_1.DuplicateStrategy.Replace, - fromCache: false, - roomState: this.currentState, - }); - } - else { - timelineSet.addEventToTimeline(thread.rootEvent, timelineSet.getLiveTimeline(), { toStartOfTimeline }); - } - } - }; - this.applyRedaction = (event) => { - if (event.isRedaction()) { - const redactId = event.event.redacts; - // if we know about this event, redact its contents now. - const redactedEvent = redactId ? this.findEventById(redactId) : undefined; - if (redactedEvent) { - redactedEvent.makeRedacted(event); - // If this is in the current state, replace it with the redacted version - if (redactedEvent.isState()) { - const 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, event, this); - // TODO: we stash user displaynames (among other things) in - // RoomMember objects which are then attached to other events - // (in the sender and target fields). We should get those - // RoomMember objects to update themselves when the events that - // they are based on are changed. - // Remove any visibility change on this event. - this.visibilityEvents.delete(redactId); - // If this event is a visibility change event, remove it from the - // list of visibility changes and update any event affected by it. - if (redactedEvent.isVisibilityEvent()) { - this.redactVisibilityChangeEvent(event); - } - } - // FIXME: apply redactions to notification list - // NB: We continue to add the redaction event to the timeline so - // clients can say "so and so redacted an event" if they wish to. Also - // this may be needed to trigger an update. - } - }; - // In some cases, we add listeners for every displayed Matrix event, so it's - // common to have quite a few more than the default limit. - this.setMaxListeners(100); - this.reEmitter = new ReEmitter_1.TypedReEmitter(this); - opts.pendingEventOrdering = opts.pendingEventOrdering || client_1.PendingEventOrdering.Chronological; - this.name = roomId; - this.normalizedName = roomId; - // all our per-room timeline sets. the first one is the unfiltered ones; - // the subsequent ones are the filtered ones in no particular order. - this.timelineSets = [new event_timeline_set_1.EventTimelineSet(this, opts)]; - this.reEmitter.reEmit(this.getUnfilteredTimelineSet(), [RoomEvent.Timeline, RoomEvent.TimelineReset]); - this.fixUpLegacyTimelineFields(); - if (this.opts.pendingEventOrdering === client_1.PendingEventOrdering.Detached) { - this.pendingEventList = []; - this.client.store.getPendingEvents(this.roomId).then((events) => { - const mapper = this.client.getEventMapper({ - toDevice: false, - decrypt: false, - }); - events.forEach((serializedEvent) => __awaiter(this, void 0, void 0, function* () { - const event = mapper(serializedEvent); - yield client.decryptEventIfNeeded(event); - event.setStatus(event_status_1.EventStatus.NOT_SENT); - this.addPendingEvent(event, event.getTxnId()); - })); - }); - } - // awaited by getEncryptionTargetMembers while room members are loading - if (!this.opts.lazyLoadMembers) { - this.membersPromise = Promise.resolve(false); - } - else { - this.membersPromise = undefined; - } - } - createThreadsTimelineSets() { - var _a; - return __awaiter(this, void 0, void 0, function* () { - if (this.threadTimelineSetsPromise) { - return this.threadTimelineSetsPromise; - } - if ((_a = this.client) === null || _a === void 0 ? void 0 : _a.supportsThreads()) { - try { - this.threadTimelineSetsPromise = Promise.all([ - this.createThreadTimelineSet(), - this.createThreadTimelineSet(thread_1.ThreadFilterType.My), - ]); - const timelineSets = yield this.threadTimelineSetsPromise; - this.threadsTimelineSets.push(...timelineSets); - return timelineSets; - } - catch (e) { - this.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() { - return __awaiter(this, void 0, void 0, function* () { - if (!this.client.isCryptoEnabled()) - return; - const readReceiptEventId = this.getEventReadUpTo(this.client.getUserId(), true); - const events = this.getLiveTimeline().getEvents(); - const readReceiptTimelineIndex = events.findIndex((matrixEvent) => { - return matrixEvent.event.event_id === readReceiptEventId; - }); - const decryptionPromises = events - .slice(readReceiptTimelineIndex) - .reverse() - .map((event) => this.client.decryptEventIfNeeded(event, { isRetry: true })); - yield Promise.allSettled(decryptionPromises); - }); - } - /** - * Bulk decrypt events in a room - * - * @returns Signals when all events have been decrypted - */ - decryptAllEvents() { - return __awaiter(this, void 0, void 0, function* () { - if (!this.client.isCryptoEnabled()) - return; - const decryptionPromises = this.getUnfilteredTimelineSet() - .getLiveTimeline() - .getEvents() - .slice(0) // copy before reversing - .reverse() - .map((event) => this.client.decryptEventIfNeeded(event, { isRetry: true })); - 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 _a; - const createEvent = this.currentState.getStateEvents(event_2.EventType.RoomCreate, ""); - return (_a = createEvent === null || createEvent === void 0 ? void 0 : createEvent.getContent()["creator"]) !== null && _a !== void 0 ? _a : null; - } - /** - * Gets the version of the room - * @returns The version of the room, or null if it could not be determined - */ - getVersion() { - var _a; - const createEvent = this.currentState.getStateEvents(event_2.EventType.RoomCreate, ""); - if (!createEvent) { - if (!this.getVersionWarning) { - logger_1.logger.warn("[getVersion] Room " + this.roomId + " does not have an m.room.create event"); - this.getVersionWarning = true; - } - return "1"; - } - return (_a = createEvent.getContent()["room_version"]) !== null && _a !== void 0 ? _a : "1"; - } - /** - * Determines whether this room needs to be upgraded to a new version - * @returns What version the room should be upgraded to, or null if - * the room does not require upgrading at this time. - * @deprecated Use #getRecommendedVersion() instead - */ - shouldUpgradeToVersion() { - // TODO: Remove this function. - // This makes assumptions about which versions are safe, and can easily - // be wrong. Instead, people are encouraged to use getRecommendedVersion - // which determines a safer value. This function doesn't use that function - // because this is not async-capable, and to avoid breaking the contract - // we're deprecating this. - if (!SAFE_ROOM_VERSIONS.includes(this.getVersion())) { - return exports.KNOWN_SAFE_ROOM_VERSION; - } - return null; - } - /** - * 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() { - return __awaiter(this, void 0, void 0, function* () { - const capabilities = yield this.client.getCapabilities(); - let versionCap = capabilities["m.room_versions"]; - if (!versionCap) { - versionCap = { - default: exports.KNOWN_SAFE_ROOM_VERSION, - available: {}, - }; - for (const safeVer of SAFE_ROOM_VERSIONS) { - versionCap.available[safeVer] = client_1.RoomVersionStability.Stable; - } - } - let result = this.checkVersionAgainstCapability(versionCap); - if (result.urgent && result.needsUpgrade) { - // Something doesn't feel right: we shouldn't need to update - // because the version we're on should be in the protocol's - // namespace. This usually means that the server was updated - // before the client was, making us think the newest possible - // room version is not stable. As a solution, we'll refresh - // the capability we're using to determine this. - logger_1.logger.warn("Refreshing room version capability because the server looks " + - "to be supporting a newer room version we don't know about."); - const caps = yield this.client.getCapabilities(true); - versionCap = caps["m.room_versions"]; - if (!versionCap) { - logger_1.logger.warn("No room version capability - assuming upgrade required."); - return result; - } - else { - result = this.checkVersionAgainstCapability(versionCap); - } - } - return result; - }); - } - checkVersionAgainstCapability(versionCap) { - const currentVersion = this.getVersion(); - logger_1.logger.log(`[${this.roomId}] Current version: ${currentVersion}`); - logger_1.logger.log(`[${this.roomId}] Version capability: `, versionCap); - const result = { - version: currentVersion, - needsUpgrade: false, - urgent: false, - }; - // If the room is on the default version then nothing needs to change - if (currentVersion === versionCap.default) - return result; - const stableVersions = Object.keys(versionCap.available).filter((v) => versionCap.available[v] === "stable"); - // Check if the room is on an unstable version. We determine urgency based - // off the version being in the Matrix spec namespace or not (if the version - // is in the current namespace and unstable, the room is probably vulnerable). - if (!stableVersions.includes(currentVersion)) { - result.version = versionCap.default; - result.needsUpgrade = true; - result.urgent = !!this.getVersion().match(/^[0-9]+[0-9.]*$/g); - if (result.urgent) { - logger_1.logger.warn(`URGENT upgrade required on ${this.roomId}`); - } - else { - logger_1.logger.warn(`Non-urgent upgrade required on ${this.roomId}`); - } - return result; - } - // The room is on a stable, but non-default, version by this point. - // No upgrade needed. - 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(event_2.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); - } - const removed = utils.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 _a, _b; - return (_b = (_a = this.pendingEventList) === null || _a === void 0 ? void 0 : _a.some((event) => event.getId() === eventId)) !== null && _b !== void 0 ? _b : 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 _a, _b; - return (_b = (_a = this.pendingEventList) === null || _a === void 0 ? void 0 : _a.find((event) => event.getId() === eventId)) !== null && _b !== void 0 ? _b : null; - } - /** - * Get the live unfiltered timeline for this room. - * - * @returns live timeline - */ - getLiveTimeline() { - return this.getUnfilteredTimelineSet().getLiveTimeline(); - } - /** - * Get the timestamp of the last message in the room - * - * @returns the timestamp of the last message in the room - */ - getLastActiveTimestamp() { - const timeline = this.getLiveTimeline(); - const events = timeline.getEvents(); - if (events.length) { - const lastEvent = events[events.length - 1]; - return lastEvent.getTs(); - } - else { - return Number.MIN_SAFE_INTEGER; - } - } - /** - * @returns the membership type (join | leave | invite) for the logged in user - */ - getMyMembership() { - var _a; - return (_a = this.selfMembership) !== null && _a !== void 0 ? _a : "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 _a; - const me = this.getMember(this.myUserId); - if (me) { - return me.getDMInviter(); - } - if (this.selfMembership === "invite") { - // fall back to summary information - const memberCount = this.getInvitedAndJoinedMemberCount(); - if (memberCount === 2) { - return (_a = this.summaryHeroes) === null || _a === void 0 ? void 0 : _a[0]; - } - } - } - /** - * 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() { - const me = this.getMember(this.myUserId); - if (me) { - const inviterId = me.getDMInviter(); - if (inviterId) { - return inviterId; - } - } - // Remember, we're assuming this room is a DM, so returning the first member we find should be fine - if (Array.isArray(this.summaryHeroes) && this.summaryHeroes.length) { - return this.summaryHeroes[0]; - } - const members = this.currentState.getMembers(); - const anyMember = members.find((m) => m.userId !== this.myUserId); - if (anyMember) { - return anyMember.userId; - } - // it really seems like I'm the only user in the room - // so I probably created a room with just me in it - // and marked it as a DM. Ok then - return this.myUserId; - } - getAvatarFallbackMember() { - const memberCount = this.getInvitedAndJoinedMemberCount(); - if (memberCount > 2) { - return; - } - const hasHeroes = Array.isArray(this.summaryHeroes) && this.summaryHeroes.length; - if (hasHeroes) { - const availableMember = this.summaryHeroes.map((userId) => { - return this.getMember(userId); - }).find((member) => !!member); - if (availableMember) { - return availableMember; - } - } - const members = this.currentState.getMembers(); - // could be different than memberCount - // as this includes left members - if (members.length <= 2) { - const availableMember = members.find((m) => { - return m.userId !== this.myUserId; - }); - if (availableMember) { - return availableMember; - } - } - // if all else fails, try falling back to a user, - // and create a one-off member for it - if (hasHeroes) { - const availableUser = this.summaryHeroes.map((userId) => { - return this.client.getUser(userId); - }).find((user) => !!user); - if (availableUser) { - const member = new room_member_1.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) { - const prevMembership = this.selfMembership; - this.selfMembership = membership; - if (prevMembership !== membership) { - if (membership === "leave") { - this.cleanupAfterLeaving(); - } - this.emit(RoomEvent.MyMembership, this, membership, prevMembership); - } - } - loadMembersFromServer() { - return __awaiter(this, void 0, void 0, function* () { - const lastSyncToken = this.client.store.getSyncToken(); - const response = yield this.client.members(this.roomId, undefined, "leave", lastSyncToken !== null && lastSyncToken !== void 0 ? lastSyncToken : undefined); - return response.chunk; - }); - } - loadMembers() { - return __awaiter(this, void 0, void 0, function* () { - // were the members loaded from the server? - let fromServer = false; - let rawMembersEvents = yield this.client.store.getOutOfBandMembers(this.roomId); - // If the room is encrypted, we always fetch members from the server at - // least once, in case the latest state wasn't persisted properly. Note - // that this function is only called once (unless loading the members - // fails), since loadMembersIfNeeded always returns this.membersPromise - // if set, which will be the result of the first (successful) call. - if (rawMembersEvents === null || (this.client.isCryptoEnabled() && this.client.isRoomEncrypted(this.roomId))) { - fromServer = true; - rawMembersEvents = yield this.loadMembersFromServer(); - logger_1.logger.log(`LL: got ${rawMembersEvents.length} ` + `members from server for room ${this.roomId}`); - } - const memberEvents = rawMembersEvents.filter(utils_1.noUnsafeEventProps).map(this.client.getEventMapper()); - return { memberEvents, 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; - } - // mark the state so that incoming messages while - // the request is in flight get marked as superseding - // the OOB members - this.currentState.markOutOfBandMembersStarted(); - const inMemoryUpdate = this.loadMembers() - .then((result) => { - this.currentState.setOutOfBandMembers(result.memberEvents); - return result.fromServer; - }) - .catch((err) => { - // allow retries on fail - this.membersPromise = undefined; - this.currentState.markOutOfBandMembersFailed(); - throw err; - }); - // update members in storage, but don't wait for it - inMemoryUpdate - .then((fromServer) => { - if (fromServer) { - const oobMembers = this.currentState - .getMembers() - .filter((m) => m.isOutOfBand()) - .map((m) => { var _a; return (_a = m.events.member) === null || _a === void 0 ? void 0 : _a.event; }); - logger_1.logger.log(`LL: telling store to write ${oobMembers.length}` + ` members for room ${this.roomId}`); - const store = this.client.store; - return (store - .setOutOfBandMembers(this.roomId, oobMembers) - // swallow any IDB error as we don't want to fail - // because of this - .catch((err) => { - logger_1.logger.log("LL: storing OOB room members failed, oh well", err); - })); - } - }) - .catch((err) => { - // as this is not awaited anywhere, - // at least show the error in the console - logger_1.logger.error(err); - }); - this.membersPromise = inMemoryUpdate; - return this.membersPromise; - } - /** - * Removes the lazily loaded members from storage if needed - */ - clearLoadedMembersIfNeeded() { - return __awaiter(this, void 0, void 0, function* () { - if (this.opts.lazyLoadMembers && this.membersPromise) { - yield this.loadMembersIfNeeded(); - yield this.client.store.clearOutOfBandMembers(this.roomId); - this.currentState.clearOutOfBandMembers(); - this.membersPromise = undefined; - } - }); - } - /** - * 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_1.logger.error(`error after clearing loaded members from ` + `room ${this.roomId} after leaving`); - logger_1.logger.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() { - return __awaiter(this, void 0, void 0, function* () { - const liveTimelineBefore = this.getLiveTimeline(); - const forwardPaginationToken = liveTimelineBefore.getPaginationToken(event_timeline_1.EventTimeline.FORWARDS); - const backwardPaginationToken = liveTimelineBefore.getPaginationToken(event_timeline_1.EventTimeline.BACKWARDS); - const eventsBefore = liveTimelineBefore.getEvents(); - const mostRecentEventInTimeline = eventsBefore[eventsBefore.length - 1]; - logger_1.logger.log(`[refreshLiveTimeline for ${this.roomId}] at ` + - `mostRecentEventInTimeline=${mostRecentEventInTimeline && mostRecentEventInTimeline.getId()} ` + - `liveTimelineBefore=${liveTimelineBefore.toString()} ` + - `forwardPaginationToken=${forwardPaginationToken} ` + - `backwardPaginationToken=${backwardPaginationToken}`); - // Get the main TimelineSet - const timelineSet = this.getUnfilteredTimelineSet(); - let newTimeline; - // If there isn't any event in the timeline, let's go fetch the latest - // event and construct a timeline from it. - // - // This should only really happen if the user ran into an error - // with refreshing the timeline before which left them in a blank - // timeline from `resetLiveTimeline`. - if (!mostRecentEventInTimeline) { - newTimeline = yield this.client.getLatestTimeline(timelineSet); - } - else { - // Empty out all of `this.timelineSets`. But we also need to keep the - // same `timelineSet` references around so the React code updates - // properly and doesn't ignore the room events we emit because it checks - // that the `timelineSet` references are the same. We need the - // `timelineSet` empty so that the `client.getEventTimeline(...)` call - // later, will call `/context` and create a new timeline instead of - // returning the same one. - this.resetLiveTimeline(null, null); - // Make the UI timeline show the new blank live timeline we just - // reset so that if the network fails below it's showing the - // accurate state of what we're working with instead of the - // disconnected one in the TimelineWindow which is just hanging - // around by reference. - this.emit(RoomEvent.TimelineRefresh, this, timelineSet); - // Use `client.getEventTimeline(...)` to construct a new timeline from a - // `/context` response state and events for the most recent event before - // we reset everything. The `timelineSet` we pass in needs to be empty - // in order for this function to call `/context` and generate a new - // timeline. - newTimeline = yield this.client.getEventTimeline(timelineSet, mostRecentEventInTimeline.getId()); - } - // If a racing `/sync` beat us to creating a new timeline, use that - // instead because it's the latest in the room and any new messages in - // the scrollback will include the history. - const liveTimeline = timelineSet.getLiveTimeline(); - if (!liveTimeline || - (liveTimeline.getPaginationToken(event_timeline_1.Direction.Forward) === null && - liveTimeline.getPaginationToken(event_timeline_1.Direction.Backward) === null && - liveTimeline.getEvents().length === 0)) { - logger_1.logger.log(`[refreshLiveTimeline for ${this.roomId}] using our new live timeline`); - // Set the pagination token back to the live sync token (`null`) instead - // of using the `/context` historical token (ex. `t12-13_0_0_0_0_0_0_0_0`) - // so that it matches the next response from `/sync` and we can properly - // continue the timeline. - newTimeline.setPaginationToken(forwardPaginationToken, event_timeline_1.EventTimeline.FORWARDS); - // Set our new fresh timeline as the live timeline to continue syncing - // forwards and back paginating from. - timelineSet.setLiveTimeline(newTimeline); - // Fixup `this.oldstate` so that `scrollback` has the pagination tokens - // available - this.fixUpLegacyTimelineFields(); - } - else { - logger_1.logger.log(`[refreshLiveTimeline for ${this.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.`); - } - // The timeline has now been refreshed ✅ - this.setTimelineNeedsRefresh(false); - // Emit an event which clients can react to and re-load the timeline - // from the SDK - this.emit(RoomEvent.TimelineRefresh, this, timelineSet); - }); - } - /** - * Reset the live timeline of all timelineSets, and start new ones. - * - *

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 (const timelineSet of this.timelineSets) { - timelineSet.resetLiveTimeline(backPaginationToken !== null && backPaginationToken !== void 0 ? backPaginationToken : undefined, forwardPaginationToken !== null && forwardPaginationToken !== void 0 ? forwardPaginationToken : undefined); - } - for (const thread of this.threads.values()) { - thread.resetLiveTimeline(backPaginationToken, forwardPaginationToken); - } - this.fixUpLegacyTimelineFields(); - } - /** - * Fix up this.timeline, this.oldState and this.currentState - * - * @internal - */ - fixUpLegacyTimelineFields() { - const previousOldState = this.oldState; - const previousCurrentState = this.currentState; - // maintain this.timeline as a reference to the live timeline, - // and this.oldState and this.currentState as references to the - // state at the start and end of that timeline. These are more - // for backwards-compatibility than anything else. - this.timeline = this.getLiveTimeline().getEvents(); - this.oldState = this.getLiveTimeline().getState(event_timeline_1.EventTimeline.BACKWARDS); - this.currentState = this.getLiveTimeline().getState(event_timeline_1.EventTimeline.FORWARDS); - // Let people know to register new listeners for the new state - // references. The reference won't necessarily change every time so only - // emit when we see a change. - if (previousOldState !== this.oldState) { - this.emit(RoomEvent.OldStateUpdated, this, previousOldState, this.oldState); - } - if (previousCurrentState !== this.currentState) { - this.emit(RoomEvent.CurrentStateUpdated, this, previousCurrentState, this.currentState); - // Re-emit various events on the current room state - // TODO: If currentState really only exists for backwards - // compatibility, shouldn't we be doing this some other way? - this.reEmitter.stopReEmitting(previousCurrentState, [ - room_state_1.RoomStateEvent.Events, - room_state_1.RoomStateEvent.Members, - room_state_1.RoomStateEvent.NewMember, - room_state_1.RoomStateEvent.Update, - room_state_1.RoomStateEvent.Marker, - beacon_1.BeaconEvent.New, - beacon_1.BeaconEvent.Update, - beacon_1.BeaconEvent.Destroy, - beacon_1.BeaconEvent.LivenessChange, - ]); - this.reEmitter.reEmit(this.currentState, [ - room_state_1.RoomStateEvent.Events, - room_state_1.RoomStateEvent.Members, - room_state_1.RoomStateEvent.NewMember, - room_state_1.RoomStateEvent.Update, - room_state_1.RoomStateEvent.Marker, - beacon_1.BeaconEvent.New, - beacon_1.BeaconEvent.Update, - beacon_1.BeaconEvent.Destroy, - beacon_1.BeaconEvent.LivenessChange, - ]); - } - } - /** - * Returns whether there are any devices in the room that are unverified - * - * Note: Callers should first check if crypto is enabled on this device. If it is - * disabled, then we aren't tracking room devices at all, so we can't answer this, and an - * error will be thrown. - * - * @returns the result - */ - hasUnverifiedDevices() { - return __awaiter(this, void 0, void 0, function* () { - if (!this.client.isRoomEncrypted(this.roomId)) { - return false; - } - const e2eMembers = yield this.getEncryptionTargetMembers(); - for (const member of e2eMembers) { - const devices = this.client.getStoredDevicesForUser(member.userId); - if (devices.some((device) => device.isUnverified())) { - return true; - } - } - return false; - }); - } - /** - * 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) { - const event = this.findEventById(eventId); - const 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) { - let event = this.getUnfilteredTimelineSet().findEventById(eventId); - if (!event) { - const threads = this.getThreads(); - for (let i = 0; i < threads.length; i++) { - const thread = threads[i]; - event = thread.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(type = NotificationCountType.Total) { - var _a; - let count = this.getRoomUnreadNotificationCount(type); - for (const threadNotification of this.threadNotifications.values()) { - count += (_a = threadNotification[type]) !== null && _a !== void 0 ? _a : 0; - } - return count; - } - /** - * Get the notification for the event context (room or thread timeline) - */ - getUnreadCountForEventContext(type = NotificationCountType.Total, event) { - var _a; - const isThreadEvent = !!event.threadRootId && !event.isThreadRoot; - return ((_a = (isThreadEvent - ? this.getThreadUnreadNotificationCount(event.threadRootId, type) - : this.getRoomUnreadNotificationCount(type))) !== null && _a !== void 0 ? _a : 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(type = NotificationCountType.Total) { - var _a; - return (_a = this.notificationCounts[type]) !== null && _a !== void 0 ? _a : 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, type = NotificationCountType.Total) { - var _a, _b; - return (_b = (_a = this.threadNotifications.get(threadId)) === null || _a === void 0 ? void 0 : _a[type]) !== null && _b !== void 0 ? _b : 0; - } - /** - * Checks if the current room has unread thread notifications - * @returns - */ - hasThreadUnreadNotification() { - var _a, _b; - for (const notification of this.threadNotifications.values()) { - if (((_a = notification.highlight) !== null && _a !== void 0 ? _a : 0) > 0 || ((_b = notification.total) !== null && _b !== void 0 ? _b : 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 _a, _b; - const notification = Object.assign({ highlight: (_a = this.threadNotifications.get(threadId)) === null || _a === void 0 ? void 0 : _a.highlight, total: (_b = this.threadNotifications.get(threadId)) === null || _b === void 0 ? void 0 : _b.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 _a, _b; - let type = null; - for (const threadNotification of this.threadNotifications.values()) { - if (((_a = threadNotification.highlight) !== null && _a !== void 0 ? _a : 0) > 0) { - return NotificationCountType.Highlight; - } - else if (((_b = threadNotification.total) !== null && _b !== void 0 ? _b : 0) > 0 && !type) { - type = NotificationCountType.Total; - } - } - return type; - } - /** - * Resets the thread notifications for this room - */ - resetThreadUnreadNotificationCount(notificationsToKeep) { - if (notificationsToKeep) { - for (const [threadId] of this.threadNotifications) { - if (!notificationsToKeep.includes(threadId)) { - this.threadNotifications.delete(threadId); - } - } - } - else { - this.threadNotifications.clear(); - } - this.emit(RoomEvent.UnreadNotifications); - } - /** - * 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); - } - setSummary(summary) { - const heroes = summary["m.heroes"]; - const joinedCount = summary["m.joined_member_count"]; - const 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)) { - // be cautious about trusting server values, - // and make sure heroes doesn't contain our own id - // just to be sure - this.summaryHeroes = heroes.filter((userId) => { - return userId !== this.myUserId; - }); - } - } - /** - * 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 === undefined) - 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) - * @returns the avatar URL or null. - */ - getAvatarUrl(baseUrl, width, height, resizeMethod, allowDefault = true) { - const roomAvatarEvent = this.currentState.getStateEvents(event_2.EventType.RoomAvatar, ""); - if (!roomAvatarEvent && !allowDefault) { - return null; - } - const mainUrl = roomAvatarEvent ? roomAvatarEvent.getContent().url : null; - if (mainUrl) { - return (0, content_repo_1.getHttpUriForMxc)(baseUrl, mainUrl, width, height, resizeMethod); - } - return null; - } - /** - * Get the mxc avatar url for the room, if one was set. - * @returns the mxc avatar url or falsy - */ - getMxcAvatarUrl() { - var _a, _b; - return ((_b = (_a = this.currentState.getStateEvents(event_2.EventType.RoomAvatar, "")) === null || _a === void 0 ? void 0 : _a.getContent()) === null || _b === void 0 ? void 0 : _b.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() { - const canonicalAlias = this.currentState.getStateEvents(event_2.EventType.RoomCanonicalAlias, ""); - if (canonicalAlias) { - return canonicalAlias.getContent().alias || null; - } - return null; - } - /** - * Get this room's alternative aliases - * @returns The room's alternative aliases, or an empty array - */ - getAltAliases() { - const canonicalAlias = this.currentState.getStateEvents(event_2.EventType.RoomCanonicalAlias, ""); - if (canonicalAlias) { - return canonicalAlias.getContent().alt_aliases || []; - } - return []; - } - /** - * Add events to a timeline - * - *

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 last 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, timeline, paginationToken) { - timeline.getTimelineSet().addEventsToTimeline(events, toStartOfTimeline, 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 _a; - return (_a = this.threads.get(eventId)) !== null && _a !== void 0 ? _a : 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("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() { - return __awaiter(this, void 0, void 0, function* () { - yield this.loadMembersIfNeeded(); - let members = this.getMembersWithMembership("join"); - if (this.shouldEncryptForInvitedMembers()) { - members = members.concat(this.getMembersWithMembership("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 _a; - const ev = this.currentState.getStateEvents(event_2.EventType.RoomHistoryVisibility, ""); - return ((_a = ev === null || ev === void 0 ? void 0 : ev.getContent()) === null || _a === void 0 ? void 0 : _a.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) { - const 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, { prepopulateTimeline = true, useSyncEvents = true, pendingEvents = true } = {}) { - if (this.filteredTimelineSets[filter.filterId]) { - return this.filteredTimelineSets[filter.filterId]; - } - const opts = Object.assign({ filter, pendingEvents }, this.opts); - const timelineSet = new event_timeline_set_1.EventTimelineSet(this, opts); - this.reEmitter.reEmit(timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]); - if (useSyncEvents) { - this.filteredTimelineSets[filter.filterId] = timelineSet; - this.timelineSets.push(timelineSet); - } - const unfilteredLiveTimeline = this.getLiveTimeline(); - // Not all filter are possible to replicate client-side only - // When that's the case we do not want to prepopulate from the live timeline - // as we would get incorrect results compared to what the server would send back - if (prepopulateTimeline) { - // populate up the new timelineSet with filtered events from our live - // unfiltered timeline. - // - // XXX: This is risky as our timeline - // may have grown huge and so take a long time to filter. - // see https://github.com/vector-im/vector-web/issues/2109 - unfilteredLiveTimeline.getEvents().forEach(function (event) { - timelineSet.addLiveEvent(event); - }); - // find the earliest unfiltered timeline - let timeline = unfilteredLiveTimeline; - while (timeline.getNeighbouringTimeline(event_timeline_1.EventTimeline.BACKWARDS)) { - timeline = timeline.getNeighbouringTimeline(event_timeline_1.EventTimeline.BACKWARDS); - } - timelineSet - .getLiveTimeline() - .setPaginationToken(timeline.getPaginationToken(event_timeline_1.EventTimeline.BACKWARDS), event_timeline_1.EventTimeline.BACKWARDS); - } - else if (useSyncEvents) { - const livePaginationToken = unfilteredLiveTimeline.getPaginationToken(event_timeline_1.Direction.Forward); - timelineSet.getLiveTimeline().setPaginationToken(livePaginationToken, event_timeline_1.Direction.Backward); - } - // alternatively, we could try to do something like this to try and re-paginate - // in the filtered events from nothing, but Mark says it's an abuse of the API - // to do so: - // - // timelineSet.resetLiveTimeline( - // unfilteredLiveTimeline.getPaginationToken(EventTimeline.FORWARDS) - // ); - return timelineSet; - } - getThreadListFilter(filterType = thread_1.ThreadFilterType.All) { - return __awaiter(this, void 0, void 0, function* () { - const myUserId = this.client.getUserId(); - const filter = new filter_1.Filter(myUserId); - const definition = { - room: { - timeline: { - [thread_1.FILTER_RELATED_BY_REL_TYPES.name]: [thread_1.THREAD_RELATION_TYPE.name], - }, - }, - }; - if (filterType === thread_1.ThreadFilterType.My) { - definition.room.timeline[thread_1.FILTER_RELATED_BY_SENDERS.name] = [myUserId]; - } - filter.setDefinition(definition); - const filterId = yield this.client.getOrCreateFilter(`THREAD_PANEL_${this.roomId}_${filterType}`, filter); - filter.filterId = filterId; - return filter; - }); - } - createThreadTimelineSet(filterType) { - return __awaiter(this, void 0, void 0, function* () { - let timelineSet; - if (thread_1.Thread.hasServerSideListSupport) { - timelineSet = new event_timeline_set_1.EventTimelineSet(this, Object.assign(Object.assign({}, this.opts), { pendingEvents: false }), undefined, undefined, filterType !== null && filterType !== void 0 ? filterType : thread_1.ThreadFilterType.All); - this.reEmitter.reEmit(timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]); - } - else if (thread_1.Thread.hasServerSideSupport) { - const filter = yield this.getThreadListFilter(filterType); - timelineSet = this.getOrCreateFilteredTimelineSet(filter, { - prepopulateTimeline: false, - useSyncEvents: false, - pendingEvents: false, - }); - } - else { - timelineSet = new event_timeline_set_1.EventTimelineSet(this, { - pendingEvents: false, - }); - Array.from(this.threads).forEach(([, thread]) => { - if (thread.length === 0) - return; - const currentUserParticipated = thread.timeline.some((event) => { - return event.getSender() === this.client.getUserId(); - }); - if (filterType !== thread_1.ThreadFilterType.My || currentUserParticipated) { - timelineSet.getLiveTimeline().addEvent(thread.rootEvent, { - toStartOfTimeline: false, - }); - } - }); - } - return timelineSet; - }); - } - /** - * Takes the given thread root events and creates threads for them. - */ - processThreadRoots(events, toStartOfTimeline) { - for (const rootEvent of events) { - event_timeline_1.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 _a, _b; - return __awaiter(this, void 0, void 0, function* () { - if (this.threadsReady || !this.client.supportsThreads()) { - return; - } - if (thread_1.Thread.hasServerSideListSupport) { - yield Promise.all([ - this.fetchRoomThreadList(thread_1.ThreadFilterType.All), - this.fetchRoomThreadList(thread_1.ThreadFilterType.My), - ]); - } - else { - const allThreadsFilter = yield this.getThreadListFilter(); - const { chunk: events } = yield this.client.createMessagesRequest(this.roomId, "", Number.MAX_SAFE_INTEGER, event_timeline_1.Direction.Backward, allThreadsFilter); - if (!events.length) - return; - // Sorted by last_reply origin_server_ts - const threadRoots = events.map(this.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 - */ - const threadAMetadata = eventA.getServerAggregatedRelation(thread_1.THREAD_RELATION_TYPE.name); - const threadBMetadata = eventB.getServerAggregatedRelation(thread_1.THREAD_RELATION_TYPE.name); - return threadAMetadata.latest_event.origin_server_ts - threadBMetadata.latest_event.origin_server_ts; - }); - let latestMyThreadsRootEvent; - const roomState = this.getLiveTimeline().getState(event_timeline_1.EventTimeline.FORWARDS); - for (const rootEvent of threadRoots) { - const opts = { - duplicateStrategy: event_timeline_set_1.DuplicateStrategy.Ignore, - fromCache: false, - roomState, - }; - (_a = this.threadsTimelineSets[0]) === null || _a === void 0 ? void 0 : _a.addLiveEvent(rootEvent, opts); - const threadRelationship = rootEvent.getServerAggregatedRelation(thread_1.THREAD_RELATION_TYPE.name); - if (threadRelationship === null || threadRelationship === void 0 ? void 0 : threadRelationship.current_user_participated) { - (_b = this.threadsTimelineSets[1]) === null || _b === void 0 ? void 0 : _b.addLiveEvent(rootEvent, opts); - latestMyThreadsRootEvent = rootEvent; - } - } - this.processThreadRoots(threadRoots, true); - this.client.decryptEventIfNeeded(threadRoots[threadRoots.length - 1]); - if (latestMyThreadsRootEvent) { - this.client.decryptEventIfNeeded(latestMyThreadsRootEvent); - } - } - this.on(thread_1.ThreadEvent.NewReply, this.onThreadNewReply); - this.on(thread_1.ThreadEvent.Delete, this.onThreadDelete); - this.threadsReady = true; - }); - } - processPollEvents(events) { - return __awaiter(this, void 0, void 0, function* () { - const processPollStartEvent = (event) => { - if (!matrix_events_sdk_1.M_POLL_START.matches(event.getType())) - return; - try { - const poll = new poll_1.Poll(event, this.client, this); - this.polls.set(event.getId(), poll); - this.emit(poll_1.PollEvent.New, poll); - } - catch (_a) { } - // poll creation can fail for malformed poll start events - }; - const processPollRelationEvent = (event) => { - const relationEventId = event.relationEventId; - if (relationEventId && this.polls.has(relationEventId)) { - const poll = this.polls.get(relationEventId); - poll === null || poll === void 0 ? void 0 : poll.onNewRelation(event); - } - }; - const processPollEvent = (event) => { - processPollStartEvent(event); - processPollRelationEvent(event); - }; - for (const event of events) { - try { - yield this.client.decryptEventIfNeeded(event); - processPollEvent(event); - } - catch (_a) { } - } - }); - } - /** - * Fetch a single page of threadlist messages for the specific thread filter - * @internal - */ - fetchRoomThreadList(filter) { - return __awaiter(this, void 0, void 0, function* () { - const timelineSet = filter === thread_1.ThreadFilterType.My ? this.threadsTimelineSets[1] : this.threadsTimelineSets[0]; - const { chunk: events, end } = yield this.client.createThreadListMessagesRequest(this.roomId, null, undefined, event_timeline_1.Direction.Backward, timelineSet.threadListType, timelineSet.getFilter()); - timelineSet.getLiveTimeline().setPaginationToken(end !== null && end !== void 0 ? end : null, event_timeline_1.Direction.Backward); - if (!events.length) - return; - const matrixEvents = events.map(this.client.getEventMapper()); - this.processThreadRoots(matrixEvents, true); - const roomState = this.getLiveTimeline().getState(event_timeline_1.EventTimeline.FORWARDS); - for (const rootEvent of matrixEvents) { - timelineSet.addLiveEvent(rootEvent, { - duplicateStrategy: event_timeline_set_1.DuplicateStrategy.Replace, - fromCache: false, - roomState, - }); - } - }); - } - onThreadNewReply(thread) { - this.updateThreadRootEvents(thread, false, true); - } - onThreadDelete(thread) { - var _a; - this.threads.delete(thread.id); - const timeline = this.getTimelineForEvent(thread.id); - const roomEvent = (_a = timeline === null || timeline === void 0 ? void 0 : timeline.getEvents()) === null || _a === void 0 ? void 0 : _a.find((it) => it.getId() === thread.id); - if (roomEvent) { - thread.clearEventMetadata(roomEvent); - } - else { - logger_1.logger.debug("onThreadDelete: Could not find root event in room timeline"); - } - for (const 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) { - const timelineSet = this.filteredTimelineSets[filter.filterId]; - delete this.filteredTimelineSets[filter.filterId]; - const i = this.timelineSets.indexOf(timelineSet); - if (i > -1) { - this.timelineSets.splice(i, 1); - } - } - eventShouldLiveIn(event, events, roots) { - var _a, _b; - if (!((_a = this.client) === null || _a === void 0 ? void 0 : _a.supportsThreads())) { - return { - shouldLiveInRoom: true, - shouldLiveInThread: false, - }; - } - // A thread root is always shown in both timelines - if (event.isThreadRoot || (roots === null || roots === void 0 ? void 0 : roots.has(event.getId()))) { - return { - shouldLiveInRoom: true, - shouldLiveInThread: true, - threadId: event.getId(), - }; - } - // A thread relation is always only shown in a thread - if (event.isRelation(thread_1.THREAD_RELATION_TYPE.name)) { - return { - shouldLiveInRoom: false, - shouldLiveInThread: true, - threadId: event.threadRootId, - }; - } - const parentEventId = event.getAssociatedId(); - let parentEvent; - if (parentEventId) { - parentEvent = (_b = this.findEventById(parentEventId)) !== null && _b !== void 0 ? _b : events === null || events === void 0 ? void 0 : events.find((e) => e.getId() === parentEventId); - } - // Treat relations and redactions as extensions of their parents so evaluate parentEvent instead - if (parentEvent && (event.isRelation() || event.isRedaction())) { - return this.eventShouldLiveIn(parentEvent, events, roots); - } - // Edge case where we know the event is a relation but don't have the parentEvent - if (roots === null || roots === void 0 ? void 0 : roots.has(event.relationEventId)) { - return { - shouldLiveInRoom: true, - shouldLiveInThread: true, - threadId: event.relationEventId, - }; - } - // We've exhausted all scenarios, can safely assume that this event should live in the room timeline only - return { - shouldLiveInRoom: true, - shouldLiveInThread: false, - }; - } - findThreadForEvent(event) { - if (!event) - return null; - const { threadId } = this.eventShouldLiveIn(event); - return threadId ? this.getThread(threadId) : null; - } - addThreadedEvents(threadId, events, toStartOfTimeline = false) { - var _a; - let thread = this.getThread(threadId); - if (!thread) { - const rootEvent = (_a = this.findEventById(threadId)) !== null && _a !== void 0 ? _a : events.find((e) => e.getId() === threadId); - thread = this.createThread(threadId, rootEvent, events, toStartOfTimeline); - } - thread.addEvents(events, toStartOfTimeline); - } - /** - * Adds events to a thread's timeline. Will fire "Thread.update" - */ - processThreadedEvents(events, toStartOfTimeline) { - var _a; - events.forEach(this.applyRedaction); - const eventsByThread = {}; - for (const event of events) { - const { threadId, shouldLiveInThread } = this.eventShouldLiveIn(event); - if (shouldLiveInThread && !eventsByThread[threadId]) { - eventsByThread[threadId] = []; - } - (_a = eventsByThread[threadId]) === null || _a === void 0 ? void 0 : _a.push(event); - } - Object.entries(eventsByThread).map(([threadId, threadEvents]) => this.addThreadedEvents(threadId, threadEvents, toStartOfTimeline)); - } - createThread(threadId, rootEvent, events = [], toStartOfTimeline) { - var _a, _b, _c; - if (this.threads.has(threadId)) { - return this.threads.get(threadId); - } - if (rootEvent) { - const relatedEvents = this.relations.getAllChildEventsForEvent(rootEvent.getId()); - if (relatedEvents === null || relatedEvents === void 0 ? void 0 : relatedEvents.length) { - // Include all relations of the root event, given it'll be visible in both timelines, - // except `m.replace` as that will already be applied atop the event using `MatrixEvent::makeReplaced` - events = events.concat(relatedEvents.filter((e) => !e.isRelation(event_2.RelationType.Replace))); - } - } - const thread = new thread_1.Thread(threadId, rootEvent, { - room: this, - client: this.client, - pendingEventOrdering: this.opts.pendingEventOrdering, - receipts: (_a = this.cachedThreadReadReceipts.get(threadId)) !== null && _a !== void 0 ? _a : [], - }); - // All read receipts should now come down from sync, we do not need to keep - // a reference to the cached receipts anymore. - this.cachedThreadReadReceipts.delete(threadId); - // If we managed to create a thread and figure out its `id` then we can use it - // This has to happen before thread.addEvents, because that adds events to the eventtimeline, and the - // eventtimeline sometimes looks up thread information via the room. - this.threads.set(thread.id, thread); - // This is necessary to be able to jump to events in threads: - // If we jump to an event in a thread where neither the event, nor the root, - // nor any thread event are loaded yet, we'll load the event as well as the thread root, create the thread, - // and pass the event through this. - thread.addEvents(events, false); - this.reEmitter.reEmit(thread, [ - thread_1.ThreadEvent.Delete, - thread_1.ThreadEvent.Update, - thread_1.ThreadEvent.NewReply, - RoomEvent.Timeline, - RoomEvent.TimelineReset, - ]); - const isNewer = ((_b = this.lastThread) === null || _b === void 0 ? void 0 : _b.rootEvent) && - (rootEvent === null || rootEvent === void 0 ? void 0 : rootEvent.localTimestamp) && - ((_c = this.lastThread.rootEvent) === null || _c === void 0 ? void 0 : _c.localTimestamp) < (rootEvent === null || rootEvent === void 0 ? void 0 : rootEvent.localTimestamp); - if (!this.lastThread || isNewer) { - this.lastThread = thread; - } - if (this.threadsReady) { - this.updateThreadRootEvents(thread, toStartOfTimeline, false); - } - this.emit(thread_1.ThreadEvent.New, thread, toStartOfTimeline); - return thread; - } - processLiveEvent(event) { - this.applyRedaction(event); - // Implement MSC3531: hiding messages. - if (event.isVisibilityEvent()) { - // This event changes the visibility of another event, record - // the visibility change, inform clients if necessary. - this.applyNewVisibilityEvent(event); - } - // If any pending visibility change is waiting for this (older) event, - this.applyPendingVisibilityEvents(event); - // Sliding Sync modifications: - // The proxy cannot guarantee every sent event will have a transaction_id field, so we need - // to check the event ID against the list of pending events if there is no transaction ID - // field. Only do this for events sent by us though as it's potentially expensive to loop - // the pending events map. - const txnId = event.getUnsigned().transaction_id; - if (!txnId && event.getSender() === this.myUserId) { - // check the txn map for a matching event ID - for (const [tid, localEvent] of this.txnToEvent) { - if (localEvent.getId() === event.getId()) { - logger_1.logger.debug("processLiveEvent: found sent event without txn ID: ", tid, event.getId()); - // update the unsigned field so we can re-use the same codepaths - const 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) { - const { duplicateStrategy, timelineWasEmpty, fromCache } = addLiveEventOptions; - // add to our timeline sets - for (const timelineSet of this.timelineSets) { - timelineSet.addLiveEvent(event, { - duplicateStrategy, - fromCache, - timelineWasEmpty, - }); - } - // synthesize and inject implicit read receipts - // Done after adding the event because otherwise the app would get a read receipt - // pointing to an event that wasn't yet in the timeline - // Don't synthesize RR for m.room.redaction as this causes the RR to go missing. - if (event.sender && event.getType() !== event_2.EventType.RoomRedaction) { - this.addReceipt((0, read_receipt_1.synthesizeReceipt)(event.sender.userId, event, read_receipts_1.ReceiptType.Read), true); - // Any live events from a user could be taken as implicit - // presence information: evidence that they are currently active. - // ...except in a world where we use 'user.currentlyActive' to reduce - // presence spam, this isn't very useful - we'll get a transition when - // they are no longer currently active anyway. So don't bother to - // reset the lastActiveAgo and lastPresenceTs from the RoomState's user. - } - } - /** - * Add a pending outgoing event to this room. - * - *

The event is added to either the pendingEventList, or the live timeline, - * depending on the setting of opts.pendingEventOrdering. - * - *

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 !== event_status_1.EventStatus.SENDING && event.status !== event_status_1.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); - } - // call setEventMetadata to set up event.sender etc - // as event is shared over all timelineSets, we set up its metadata based - // on the unfiltered timelineSet. - event_timeline_1.EventTimeline.setEventMetadata(event, this.getLiveTimeline().getState(event_timeline_1.EventTimeline.FORWARDS), false); - this.txnToEvent.set(txnId, event); - if (this.pendingEventList) { - if (this.pendingEventList.some((e) => e.status === event_status_1.EventStatus.NOT_SENT)) { - logger_1.logger.warn("Setting event as NOT_SENT due to messages in the same state"); - event.setStatus(event_status_1.EventStatus.NOT_SENT); - } - this.pendingEventList.push(event); - this.savePendingEvents(); - if (event.isRelation()) { - // For pending events, add them to the relations collection immediately. - // (The alternate case below already covers this as part of adding to - // the timeline set.) - this.aggregateNonLiveRelation(event); - } - if (event.isRedaction()) { - const redactId = event.event.redacts; - let 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); - } - } - } - else { - for (const timelineSet of this.timelineSets) { - if (timelineSet.getFilter()) { - if (timelineSet.getFilter().filterRoomTimeline([event]).length) { - timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), { - toStartOfTimeline: false, - }); - } - } - else { - timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), { - toStartOfTimeline: 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) { - const pendingEvents = this.pendingEventList - .map((event) => { - return Object.assign(Object.assign({}, event.event), { txn_id: event.getTxnId() }); - }) - .filter((event) => { - // Filter out the unencrypted messages if the room is encrypted - const isEventEncrypted = event.type === event_2.EventType.RoomMessageEncrypted; - const isRoomEncrypted = this.client.isRoomEncrypted(this.roomId); - 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. - * - *

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) { - const oldEventId = localEvent.getId(); - const newEventId = remoteEvent.getId(); - const oldStatus = localEvent.status; - logger_1.logger.debug(`Got remote echo for event ${oldEventId} -> ${newEventId} old status ${oldStatus}`); - // no longer pending - this.txnToEvent.delete(remoteEvent.getUnsigned().transaction_id); - // if it's in the pending list, remove it - if (this.pendingEventList) { - this.removePendingEvent(oldEventId); - } - // replace the event source (this will preserve the plaintext payload if - // any, which is good, because we don't want to try decoding it again). - localEvent.handleRemoteEcho(remoteEvent.event); - const { shouldLiveInRoom, threadId } = this.eventShouldLiveIn(remoteEvent); - const thread = threadId ? this.getThread(threadId) : null; - thread === null || thread === void 0 ? void 0 : thread.setEventMetadata(localEvent); - thread === null || thread === void 0 ? void 0 : thread.timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId); - if (shouldLiveInRoom) { - for (const timelineSet of this.timelineSets) { - // if it's already in the timeline, update the timeline map. If it's not, add it. - 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. - * - *

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_1.logger.log(`setting pendingEvent status to ${newStatus} in ${event.getRoomId()} ` + - `event ID ${event.getId()} -> ${newEventId}`); - // if the message was sent, we expect an event id - if (newStatus == event_status_1.EventStatus.SENT && !newEventId) { - throw new Error("updatePendingEvent called with status=SENT, but no new event id"); - } - // SENT races against /sync, so we have to special-case it. - if (newStatus == event_status_1.EventStatus.SENT) { - const timeline = this.getTimelineForEvent(newEventId); - if (timeline) { - // we've already received the event via the event stream. - // nothing more to do here, assuming the transaction ID was correctly matched. - // Let's check that. - const remoteEvent = this.findEventById(newEventId); - const remoteTxnId = remoteEvent === null || remoteEvent === void 0 ? void 0 : remoteEvent.getUnsigned().transaction_id; - if (!remoteTxnId && remoteEvent) { - // This code path is mostly relevant for the Sliding Sync proxy. - // The remote event did not contain a transaction ID, so we did not handle - // the remote echo yet. Handle it now. - const unsigned = remoteEvent.getUnsigned(); - unsigned.transaction_id = event.getTxnId(); - remoteEvent.setUnsigned(unsigned); - // the remote event is _already_ in the timeline, so we need to remove it so - // we can convert the local event into the final event. - this.removeEvent(remoteEvent.getId()); - this.handleRemoteEcho(remoteEvent, event); - } - return; - } - } - const oldStatus = event.status; - const oldEventId = event.getId(); - if (!oldStatus) { - throw new Error("updatePendingEventStatus called on an event which is not a local echo."); - } - const allowed = ALLOWED_TRANSITIONS[oldStatus]; - if (!(allowed === null || allowed === void 0 ? void 0 : allowed.includes(newStatus))) { - throw new Error(`Invalid EventStatus transition ${oldStatus}->${newStatus}`); - } - event.setStatus(newStatus); - if (newStatus == event_status_1.EventStatus.SENT) { - // update the event id - event.replaceLocalEventId(newEventId); - const { shouldLiveInRoom, threadId } = this.eventShouldLiveIn(event); - const thread = threadId ? this.getThread(threadId) : undefined; - thread === null || thread === void 0 ? void 0 : thread.setEventMetadata(event); - thread === null || thread === void 0 ? void 0 : thread.timelineSet.replaceEventId(oldEventId, newEventId); - if (shouldLiveInRoom) { - // if the event was already in the timeline (which will be the case if - // opts.pendingEventOrdering==chronological), we need to update the - // timeline map. - for (const timelineSet of this.timelineSets) { - timelineSet.replaceEventId(oldEventId, newEventId); - } - } - } - else if (newStatus == event_status_1.EventStatus.CANCELLED) { - // remove it from the pending event list, or the timeline. - if (this.pendingEventList) { - const removedEvent = this.getPendingEvent(oldEventId); - this.removePendingEvent(oldEventId); - if (removedEvent === null || removedEvent === void 0 ? void 0 : removedEvent.isRedaction()) { - this.revertRedactionLocalEcho(removedEvent); - } - } - this.removeEvent(oldEventId); - } - this.savePendingEvents(); - this.emit(RoomEvent.LocalEchoUpdated, event, this, oldEventId, oldStatus); - } - revertRedactionLocalEcho(redactionEvent) { - const redactId = redactionEvent.event.redacts; - if (!redactId) { - return; - } - const redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId); - if (redactedEvent) { - redactedEvent.unmarkLocallyRedacted(); - // re-render after undoing redaction - this.emit(RoomEvent.RedactionCancelled, redactionEvent, this); - // reapply relation now redaction failed - if (redactedEvent.isRelation()) { - this.aggregateNonLiveRelation(redactedEvent); - } - } - } - addLiveEvents(events, duplicateStrategyOrOpts, fromCache = false) { - var _a; - let duplicateStrategy = duplicateStrategyOrOpts; - let timelineWasEmpty = false; - if (typeof duplicateStrategyOrOpts === "object") { - ({ - duplicateStrategy, - fromCache = false, - /* roomState, (not used here) */ - timelineWasEmpty, - } = duplicateStrategyOrOpts); - } - else if (duplicateStrategyOrOpts !== undefined) { - // Deprecation warning - // FIXME: Remove after 2023-06-01 (technical debt) - logger_1.logger.warn("Overload deprecated: " + - "`Room.addLiveEvents(events, duplicateStrategy?, fromCache?)` " + - "is deprecated in favor of the overload with `Room.addLiveEvents(events, IAddLiveEventOptions)`"); - } - if (duplicateStrategy && ["replace", "ignore"].indexOf(duplicateStrategy) === -1) { - throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'"); - } - // sanity check that the live timeline is still live - for (let i = 0; i < this.timelineSets.length; i++) { - const liveTimeline = this.timelineSets[i].getLiveTimeline(); - if (liveTimeline.getPaginationToken(event_timeline_1.EventTimeline.FORWARDS)) { - throw new Error("live timeline " + - i + - " is no longer live - it has a pagination token " + - "(" + - liveTimeline.getPaginationToken(event_timeline_1.EventTimeline.FORWARDS) + - ")"); - } - if (liveTimeline.getNeighbouringTimeline(event_timeline_1.EventTimeline.FORWARDS)) { - throw new Error(`live timeline ${i} is no longer live - it has a neighbouring timeline`); - } - } - const threadRoots = this.findThreadRoots(events); - const eventsByThread = {}; - const options = { - duplicateStrategy, - fromCache, - timelineWasEmpty, - }; - for (const event of events) { - // TODO: We should have a filter to say "only add state event types X Y Z to the timeline". - this.processLiveEvent(event); - if (event.getUnsigned().transaction_id) { - const existingEvent = this.txnToEvent.get(event.getUnsigned().transaction_id); - if (existingEvent) { - // remote echo of an event we sent earlier - this.handleRemoteEcho(event, existingEvent); - continue; // we can skip adding the event to the timeline sets, it is already there - } - } - const { shouldLiveInRoom, shouldLiveInThread, threadId } = this.eventShouldLiveIn(event, events, threadRoots); - if (shouldLiveInThread && !eventsByThread[threadId !== null && threadId !== void 0 ? threadId : ""]) { - eventsByThread[threadId !== null && threadId !== void 0 ? threadId : ""] = []; - } - (_a = eventsByThread[threadId !== null && threadId !== void 0 ? threadId : ""]) === null || _a === void 0 ? void 0 : _a.push(event); - if (shouldLiveInRoom) { - this.addLiveEvent(event, options); - } - } - Object.entries(eventsByThread).forEach(([threadId, threadEvents]) => { - this.addThreadedEvents(threadId, threadEvents, false); - }); - } - partitionThreadedEvents(events) { - // Indices to the events array, for readability - const ROOM = 0; - const THREAD = 1; - if (this.client.supportsThreads()) { - const threadRoots = this.findThreadRoots(events); - return events.reduce((memo, event) => { - const { 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); - } - return memo; - }, [[], []]); - } - else { - // When `experimentalThreadSupport` is disabled treat all events as timelineEvents - return [events, []]; - } - } - /** - * Given some events, find the IDs of all the thread roots that are referred to by them. - */ - findThreadRoots(events) { - var _a; - const threadRoots = new Set(); - for (const event of events) { - if (event.isRelation(thread_1.THREAD_RELATION_TYPE.name)) { - threadRoots.add((_a = event.relationEventId) !== null && _a !== void 0 ? _a : ""); - } - } - 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, synthetic = false) { - const content = event.getContent(); - Object.keys(content).forEach((eventId) => { - Object.keys(content[eventId]).forEach((receiptType) => { - Object.keys(content[eventId][receiptType]).forEach((userId) => { - var _a, _b, _c, _d; - const receipt = content[eventId][receiptType][userId]; - const receiptForMainTimeline = !receipt.thread_id || receipt.thread_id === read_receipts_1.MAIN_ROOM_TIMELINE; - const receiptDestination = receiptForMainTimeline - ? this - : this.threads.get((_a = receipt.thread_id) !== null && _a !== void 0 ? _a : ""); - if (receiptDestination) { - receiptDestination.addReceiptToStructure(eventId, receiptType, userId, receipt, synthetic); - // If the read receipt sent for the logged in user matches - // the last event of the live timeline, then we know for a fact - // that the user has read that message. - // We can mark the room as read and not wait for the local echo - // from synapse - // This needs to be done after the initial sync as we do not want this - // logic to run whilst the room is being initialised - if (this.client.isInitialSyncComplete() && userId === this.client.getUserId()) { - const 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 { - // The thread does not exist locally, keep the read receipt - // in a cache locally, and re-apply the `addReceipt` logic - // when the thread is created - this.cachedThreadReadReceipts.set(receipt.thread_id, [ - ...((_b = this.cachedThreadReadReceipts.get(receipt.thread_id)) !== null && _b !== void 0 ? _b : []), - { eventId, receiptType, userId, receipt, synthetic }, - ]); - } - const me = this.client.getUserId(); - // Track the time of the current user's oldest threaded receipt in the room. - if (userId === me && !receiptForMainTimeline && receipt.ts < this.oldestThreadedReceiptTs) { - this.oldestThreadedReceiptTs = receipt.ts; - } - // Track each user's unthreaded read receipt. - if (!receipt.thread_id && receipt.ts > ((_d = (_c = this.unthreadedReceipts.get(userId)) === null || _c === void 0 ? void 0 : _c.ts) !== null && _d !== void 0 ? _d : 0)) { - this.unthreadedReceipts.set(userId, receipt); - } - }); - }); - }); - // send events after we've regenerated the structure & cache, otherwise things that - // listened for the event would read stale data. - 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 (const event of events) { - if (event.getType() === event_2.EventType.Typing) { - this.currentState.setTypingEvent(event); - } - else if (event.getType() === event_2.EventType.Receipt) { - this.addReceipt(event); - } // else ignore - life is too short for us to care about these events - } - } - /** - * Removes events from this room. - * @param eventIds - A list of eventIds to remove. - */ - removeEvents(eventIds) { - for (const 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) { - let removedAny = false; - for (const timelineSet of this.timelineSets) { - const 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() { - // set fake stripped state events if this is an invite room so logic remains - // consistent elsewhere. - const membershipEvent = this.currentState.getStateEvents(event_2.EventType.RoomMember, this.myUserId); - if (membershipEvent) { - const membership = membershipEvent.getContent().membership; - this.updateMyMembership(membership); - if (membership === "invite") { - const strippedStateEvents = membershipEvent.getUnsigned().invite_room_state || []; - strippedStateEvents.forEach((strippedEvent) => { - const existingEvent = this.currentState.getStateEvents(strippedEvent.type, strippedEvent.state_key); - if (!existingEvent) { - // set the fake stripped event instead - this.currentState.setStateEvents([ - new event_1.MatrixEvent({ - type: strippedEvent.type, - state_key: strippedEvent.state_key, - content: strippedEvent.content, - event_id: "$fake" + Date.now(), - room_id: this.roomId, - user_id: this.myUserId, // technically a lie - }), - ]); - } - }); - } - } - const oldName = this.name; - this.name = this.calculateRoomName(this.myUserId); - this.normalizedName = (0, utils_1.normalize)(this.name); - this.summary = new room_summary_1.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) { - // event content looks like: - // content: { - // tags: { - // $tagName: { $metadata: $value }, - // $tagName: { $metadata: $value }, - // } - // } - // XXX: do we need to deep copy here? - this.tags = event.getContent().tags || {}; - // XXX: we could do a deep-comparison to see if the tags have really - // changed - but do we want to bother? - 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 (const event of events) { - if (event.getType() === "m.tag") { - this.addTags(event); - } - const eventType = event.getType(); - const 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); - } - /** - * 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() === "join" && - (this.client.isRoomEncrypted(this.roomId) - ? this.currentState.maySendEvent(event_2.EventType.RoomMessageEncrypted, this.myUserId) - : this.currentState.maySendEvent(event_2.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) { - let canInvite = this.getMyMembership() === "join"; - const powerLevelsEvent = this.currentState.getStateEvents(event_2.EventType.RoomPowerLevels, ""); - const powerLevels = powerLevelsEvent && powerLevelsEvent.getContent(); - const 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() { - const createEvent = this.currentState.getStateEvents(event_2.EventType.RoomCreate, ""); - if (!createEvent) { - if (!this.getTypeWarning) { - logger_1.logger.warn("[getType] Room " + this.roomId + " does not have an m.room.create event"); - this.getTypeWarning = true; - } - return undefined; - } - return createEvent.getContent()[event_2.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() === event_2.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() === event_2.RoomType.UnstableCall; - } - /** - * Returns whether the room is a video room. - * @returns true if the room's type is RoomType.ElementVideo - */ - isElementVideoRoom() { - return this.getType() === event_2.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(msc3946ProcessDynamicPredecessor = false) { - const currentState = this.getLiveTimeline().getState(event_timeline_1.EventTimeline.FORWARDS); - if (!currentState) { - return null; - } - return currentState.findPredecessor(msc3946ProcessDynamicPredecessor); - } - roomNameGenerator(state) { - if (this.client.roomNameGenerator) { - const 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 ${memberNamesToRoomName(state.names, state.count)}`; - default: - return memberNamesToRoomName(state.names, state.count); - } - case RoomNameType.EmptyRoom: - if (state.oldName) { - return `Empty room (was ${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, ignoreRoomNameEvent = false) { - if (!ignoreRoomNameEvent) { - // check for an alias, if any. for now, assume first alias is the - // official one. - const mRoomName = this.currentState.getStateEvents(event_2.EventType.RoomName, ""); - if (mRoomName === null || mRoomName === void 0 ? void 0 : mRoomName.getContent().name) { - return this.roomNameGenerator({ - type: RoomNameType.Actual, - name: mRoomName.getContent().name, - }); - } - } - const alias = this.getCanonicalAlias(); - if (alias) { - return this.roomNameGenerator({ - type: RoomNameType.Actual, - name: alias, - }); - } - const joinedMemberCount = this.currentState.getJoinedMemberCount(); - const invitedMemberCount = this.currentState.getInvitedMemberCount(); - // -1 because these numbers include the syncing user - let inviteJoinCount = joinedMemberCount + invitedMemberCount - 1; - // get service members (e.g. helper bots) for exclusion - let excludedUserIds = []; - const mFunctionalMembers = this.currentState.getStateEvents(event_2.UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name, ""); - if (Array.isArray(mFunctionalMembers === null || mFunctionalMembers === void 0 ? void 0 : mFunctionalMembers.getContent().service_members)) { - excludedUserIds = mFunctionalMembers.getContent().service_members; - } - // get members that are NOT ourselves and are actually in the room. - let otherNames = []; - if (this.summaryHeroes) { - // if we have a summary, the member state events should be in the room state - this.summaryHeroes.forEach((userId) => { - // filter service members - if (excludedUserIds.includes(userId)) { - inviteJoinCount--; - return; - } - const member = this.getMember(userId); - otherNames.push(member ? member.name : userId); - }); - } - else { - let otherMembers = this.currentState.getMembers().filter((m) => { - return m.userId !== userId && (m.membership === "invite" || m.membership === "join"); - }); - otherMembers = otherMembers.filter(({ userId }) => { - // filter service members - if (excludedUserIds.includes(userId)) { - inviteJoinCount--; - return false; - } - return true; - }); - // make sure members have stable order - otherMembers.sort((a, b) => utils.compare(a.userId, b.userId)); - // only 5 first members, immitate summaryHeroes - otherMembers = otherMembers.slice(0, 5); - otherNames = otherMembers.map((m) => m.name); - } - if (inviteJoinCount) { - return this.roomNameGenerator({ - type: RoomNameType.Generated, - names: otherNames, - count: inviteJoinCount, - }); - } - const myMembership = this.getMyMembership(); - // if I have created a room and invited people through - // 3rd party invites - if (myMembership == "join") { - const thirdPartyInvites = this.currentState.getStateEvents(event_2.EventType.RoomThirdPartyInvite); - if (thirdPartyInvites === null || thirdPartyInvites === void 0 ? void 0 : thirdPartyInvites.length) { - const thirdPartyNames = thirdPartyInvites.map((i) => { - return i.getContent().display_name; - }); - return this.roomNameGenerator({ - type: RoomNameType.Generated, - subtype: "Inviting", - names: thirdPartyNames, - count: thirdPartyNames.length + 1, - }); - } - } - // let's try to figure out who was here before - let leftNames = otherNames; - // if we didn't have heroes, try finding them in the room state - if (!leftNames.length) { - leftNames = this.currentState - .getMembers() - .filter((m) => { - return m.userId !== userId && m.membership !== "invite" && m.membership !== "join"; - }) - .map((m) => m.name); - } - let 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) { - const visibilityChange = event.asVisibilityChange(); - if (!visibilityChange) { - // The event is ill-formed. - return; - } - // Ignore visibility change events that are not emitted by moderators. - const userId = event.getSender(); - if (!userId) { - return; - } - const isPowerSufficient = (event_2.EVENT_VISIBILITY_CHANGE_TYPE.name && - this.currentState.maySendStateEvent(event_2.EVENT_VISIBILITY_CHANGE_TYPE.name, userId)) || - (event_2.EVENT_VISIBILITY_CHANGE_TYPE.altName && - this.currentState.maySendStateEvent(event_2.EVENT_VISIBILITY_CHANGE_TYPE.altName, userId)); - if (!isPowerSufficient) { - // Powerlevel is insufficient. - return; - } - // Record this change in visibility. - // If the event is not in our timeline and we only receive it later, - // we may need to apply the visibility change at a later date. - const visibilityEventsOnOriginalEvent = this.visibilityEvents.get(visibilityChange.eventId); - if (visibilityEventsOnOriginalEvent) { - // It would be tempting to simply erase the latest visibility change - // but we need to record all of the changes in case the latest change - // is ever redacted. - // - // In practice, linear scans through `visibilityEvents` should be fast. - // However, to protect against a potential DoS attack, we limit the - // number of iterations in this loop. - let index = visibilityEventsOnOriginalEvent.length - 1; - const min = Math.max(0, visibilityEventsOnOriginalEvent.length - MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH); - for (; index >= min; --index) { - const target = visibilityEventsOnOriginalEvent[index]; - if (target.getTs() < event.getTs()) { - break; - } - } - if (index === -1) { - visibilityEventsOnOriginalEvent.unshift(event); - } - else { - visibilityEventsOnOriginalEvent.splice(index + 1, 0, event); - } - } - else { - this.visibilityEvents.set(visibilityChange.eventId, [event]); - } - // Finally, let's check if the event is already in our timeline. - // If so, we need to patch it and inform listeners. - const originalEvent = this.findEventById(visibilityChange.eventId); - if (!originalEvent) { - return; - } - originalEvent.applyVisibilityEvent(visibilityChange); - } - redactVisibilityChangeEvent(event) { - // Sanity checks. - if (!event.isVisibilityEvent) { - throw new Error("expected a visibility change event"); - } - const relation = event.getRelation(); - const originalEventId = relation === null || relation === void 0 ? void 0 : relation.event_id; - const visibilityEventsOnOriginalEvent = this.visibilityEvents.get(originalEventId); - if (!visibilityEventsOnOriginalEvent) { - // No visibility changes on the original event. - // In particular, this change event was not recorded, - // most likely because it was ill-formed. - return; - } - const index = visibilityEventsOnOriginalEvent.findIndex((change) => change.getId() === event.getId()); - if (index === -1) { - // This change event was not recorded, most likely because - // it was ill-formed. - return; - } - // Remove visibility change. - visibilityEventsOnOriginalEvent.splice(index, 1); - // If we removed the latest visibility change event, propagate changes. - if (index === visibilityEventsOnOriginalEvent.length) { - const originalEvent = this.findEventById(originalEventId); - if (!originalEvent) { - return; - } - if (index === 0) { - // We have just removed the only visibility change event. - this.visibilityEvents.delete(originalEventId); - originalEvent.applyVisibilityEvent(); - } - else { - const newEvent = visibilityEventsOnOriginalEvent[visibilityEventsOnOriginalEvent.length - 1]; - const newVisibility = newEvent.asVisibilityChange(); - if (!newVisibility) { - // Event is ill-formed. - // This breaks our invariant. - 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) { - const visibilityEvents = this.visibilityEvents.get(event.getId()); - if (!visibilityEvents || visibilityEvents.length == 0) { - // No pending visibility change in store. - return; - } - const visibilityEvent = visibilityEvents[visibilityEvents.length - 1]; - const visibilityChange = visibilityEvent.asVisibilityChange(); - if (!visibilityChange) { - return; - } - if (visibilityChange.visible) { - // Events are visible by default, no need to apply a visibility change. - // Note that we need to keep the visibility changes in `visibilityEvents`, - // in case we later fetch an older visibility change event that is superseded - // by `visibilityChange`. - } - if (visibilityEvent.getTs() < event.getTs()) { - // Something is wrong, the visibility change cannot happen before the - // event. Presumably an ill-formed event. - 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; - } - /** - * 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); - const unreadThreads = this.getThreads().filter((thread) => this.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Total) > 0); - for (const thread of unreadThreads) { - thread.fixupNotifications(userId); - } - } -} -exports.Room = Room; -// a map from current event status to a list of allowed next statuses -const ALLOWED_TRANSITIONS = { - [event_status_1.EventStatus.ENCRYPTING]: [event_status_1.EventStatus.SENDING, event_status_1.EventStatus.NOT_SENT, event_status_1.EventStatus.CANCELLED], - [event_status_1.EventStatus.SENDING]: [event_status_1.EventStatus.ENCRYPTING, event_status_1.EventStatus.QUEUED, event_status_1.EventStatus.NOT_SENT, event_status_1.EventStatus.SENT], - [event_status_1.EventStatus.QUEUED]: [event_status_1.EventStatus.SENDING, event_status_1.EventStatus.NOT_SENT, event_status_1.EventStatus.CANCELLED], - [event_status_1.EventStatus.SENT]: [], - [event_status_1.EventStatus.NOT_SENT]: [event_status_1.EventStatus.SENDING, event_status_1.EventStatus.QUEUED, event_status_1.EventStatus.CANCELLED], - [event_status_1.EventStatus.CANCELLED]: [], -}; -var RoomNameType; -(function (RoomNameType) { - RoomNameType[RoomNameType["EmptyRoom"] = 0] = "EmptyRoom"; - RoomNameType[RoomNameType["Generated"] = 1] = "Generated"; - RoomNameType[RoomNameType["Actual"] = 2] = "Actual"; -})(RoomNameType = exports.RoomNameType || (exports.RoomNameType = {})); -// Can be overriden by IMatrixClientCreateOpts::memberNamesToRoomNameFn -function memberNamesToRoomName(names, count) { - const 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 `${names[0]} and ${names[1]}`; - } - else { - const plural = countWithoutMe > 1; - if (plural) { - return `${names[0]} and ${countWithoutMe} others`; - } - else { - return `${names[0]} and 1 other`; - } - } -} - -},{"../@types/event":306,"../@types/read_receipts":311,"../ReEmitter":317,"../client":321,"../content-repo":323,"../filter":364,"../logger":374,"../utils":416,"./beacon":378,"./event":383,"./event-status":380,"./event-timeline":382,"./event-timeline-set":381,"./poll":385,"./read-receipt":386,"./relations-container":387,"./room-member":389,"./room-state":390,"./room-summary":391,"./thread":394,"matrix-events-sdk":167}],393:[function(require,module,exports){ -"use strict"; -/* -Copyright 2015 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SearchResult = void 0; -const event_context_1 = require("./event-context"); -class SearchResult { - /** - * Create a SearchResponse from the response to /search - */ - static fromJson(jsonObj, eventMapper) { - const jsonContext = jsonObj.context || {}; - let eventsBefore = (jsonContext.events_before || []).map(eventMapper); - let eventsAfter = (jsonContext.events_after || []).map(eventMapper); - const context = new event_context_1.EventContext(eventMapper(jsonObj.result)); - // Filter out any contextual events which do not correspond to the same timeline (thread or room) - const 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; - } -} -exports.SearchResult = SearchResult; - -},{"./event-context":379}],394:[function(require,module,exports){ -"use strict"; -/* -Copyright 2021 - 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.threadFilterTypeToFilter = exports.ThreadFilterType = exports.THREAD_RELATION_TYPE = exports.FILTER_RELATED_BY_REL_TYPES = exports.FILTER_RELATED_BY_SENDERS = exports.Thread = exports.determineFeatureSupport = exports.FeatureSupport = exports.ThreadEvent = void 0; -const client_1 = require("../client"); -const ReEmitter_1 = require("../ReEmitter"); -const event_1 = require("../@types/event"); -const event_2 = require("./event"); -const event_timeline_1 = require("./event-timeline"); -const event_timeline_set_1 = require("./event-timeline-set"); -const room_1 = require("./room"); -const NamespacedValue_1 = require("../NamespacedValue"); -const logger_1 = require("../logger"); -const read_receipt_1 = require("./read-receipt"); -const read_receipts_1 = require("../@types/read_receipts"); -var ThreadEvent; -(function (ThreadEvent) { - ThreadEvent["New"] = "Thread.new"; - ThreadEvent["Update"] = "Thread.update"; - ThreadEvent["NewReply"] = "Thread.newReply"; - ThreadEvent["ViewThread"] = "Thread.viewThread"; - ThreadEvent["Delete"] = "Thread.delete"; -})(ThreadEvent = exports.ThreadEvent || (exports.ThreadEvent = {})); -var FeatureSupport; -(function (FeatureSupport) { - FeatureSupport[FeatureSupport["None"] = 0] = "None"; - FeatureSupport[FeatureSupport["Experimental"] = 1] = "Experimental"; - FeatureSupport[FeatureSupport["Stable"] = 2] = "Stable"; -})(FeatureSupport = exports.FeatureSupport || (exports.FeatureSupport = {})); -function determineFeatureSupport(stable, unstable) { - if (stable) { - return FeatureSupport.Stable; - } - else if (unstable) { - return FeatureSupport.Experimental; - } - else { - return FeatureSupport.None; - } -} -exports.determineFeatureSupport = determineFeatureSupport; -class Thread extends read_receipt_1.ReadReceipt { - constructor(id, rootEvent, opts) { - var _a; - super(); - this.id = id; - this.rootEvent = rootEvent; - this.timeline = []; - this._currentUserParticipated = false; - this.replyCount = 0; - this.pendingReplyCount = 0; - this.initialEventsFetched = !Thread.hasServerSideSupport; - /** - * An array of events to add to the timeline once the thread has been initialised - * with server suppport. - */ - this.replayEvents = []; - this.onBeforeRedaction = (event, redaction) => { - if ((event === null || event === void 0 ? void 0 : event.isRelation(exports.THREAD_RELATION_TYPE.name)) && - this.room.eventShouldLiveIn(event).threadId === this.id && - event.getId() !== this.id && // the root event isn't counted in the length so ignore this redaction - !redaction.status // only respect it when it succeeds - ) { - this.replyCount--; - this.updatePendingReplyCount(); - this.emit(ThreadEvent.Update, this); - } - }; - this.onRedaction = (event) => __awaiter(this, void 0, void 0, function* () { - if (event.threadRootId !== this.id) - return; // ignore redactions for other timelines - if (this.replyCount <= 0) { - for (const threadEvent of this.timeline) { - this.clearEventMetadata(threadEvent); - } - this.lastEvent = this.rootEvent; - this._currentUserParticipated = false; - this.emit(ThreadEvent.Delete, this); - } - else { - yield this.updateThreadMetadata(); - } - }); - this.onTimelineEvent = (event, room, toStartOfTimeline) => { - // Add a synthesized receipt when paginating forward in the timeline - if (!toStartOfTimeline) { - room.addLocalEchoReceipt(event.getSender(), event, read_receipts_1.ReceiptType.Read); - } - this.onEcho(event, toStartOfTimeline !== null && toStartOfTimeline !== void 0 ? toStartOfTimeline : false); - }; - this.onLocalEcho = (event) => { - this.onEcho(event, false); - }; - this.onEcho = (event, toStartOfTimeline) => __awaiter(this, void 0, void 0, function* () { - if (event.threadRootId !== this.id) - return; // ignore echoes for other timelines - if (this.lastEvent === event) - return; // ignore duplicate events - yield this.updateThreadMetadata(); - if (!event.isRelation(exports.THREAD_RELATION_TYPE.name)) - return; // don't send a new reply event for reactions or edits - if (toStartOfTimeline) - return; // ignore messages added to the start of the timeline - this.emit(ThreadEvent.NewReply, this, event); - }); - if (!(opts === null || opts === void 0 ? void 0 : opts.room)) { - // Logging/debugging for https://github.com/vector-im/element-web/issues/22141 - // Hope is that we end up with a more obvious stack trace. - 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 = (_a = opts.pendingEventOrdering) !== null && _a !== void 0 ? _a : client_1.PendingEventOrdering.Chronological; - this.timelineSet = new event_timeline_set_1.EventTimelineSet(this.room, { - timelineSupport: true, - pendingEvents: true, - }, this.client, this); - this.reEmitter = new ReEmitter_1.TypedReEmitter(this); - this.reEmitter.reEmit(this.timelineSet, [room_1.RoomEvent.Timeline, room_1.RoomEvent.TimelineReset]); - this.room.on(event_2.MatrixEventEvent.BeforeRedaction, this.onBeforeRedaction); - this.room.on(room_1.RoomEvent.Redaction, this.onRedaction); - this.room.on(room_1.RoomEvent.LocalEchoUpdated, this.onLocalEcho); - this.timelineSet.on(room_1.RoomEvent.Timeline, this.onTimelineEvent); - this.processReceipts(opts.receipts); - // even if this thread is thought to be originating from this client, we initialise it as we may be in a - // gappy sync and a thread around this event may already exist. - this.updateThreadMetadata(); - this.setEventMetadata(this.rootEvent); - } - fetchRootEvent() { - return __awaiter(this, void 0, void 0, function* () { - this.rootEvent = this.room.findEventById(this.id); - // If the rootEvent does not exist in the local stores, then fetch it from the server. - try { - const eventData = yield this.client.fetchRoomEvent(this.roomId, this.id); - const mapper = this.client.getEventMapper(); - this.rootEvent = mapper(eventData); // will merge with existing event object if such is known - } - catch (e) { - logger_1.logger.error("Failed to fetch thread root to construct thread with", e); - } - yield this.processEvent(this.rootEvent); - }); - } - static setServerSideSupport(status) { - Thread.hasServerSideSupport = status; - if (status !== FeatureSupport.Stable) { - exports.FILTER_RELATED_BY_SENDERS.setPreferUnstable(true); - exports.FILTER_RELATED_BY_REL_TYPES.setPreferUnstable(true); - exports.THREAD_RELATION_TYPE.setPreferUnstable(true); - } - } - static setServerSideListSupport(status) { - Thread.hasServerSideListSupport = status; - } - static setServerSideFwdPaginationSupport(status) { - Thread.hasServerSideFwdPaginationSupport = status; - } - get roomState() { - return this.room.getLiveTimeline().getState(event_timeline_1.EventTimeline.FORWARDS); - } - addEventToTimeline(event, toStartOfTimeline) { - if (!this.findEventById(event.getId())) { - this.timelineSet.addEventToTimeline(event, this.liveTimeline, { - toStartOfTimeline, - fromCache: false, - roomState: this.roomState, - }); - this.timeline = this.events; - } - } - 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, emit = true) { - var _a, _b, _c; - return __awaiter(this, void 0, void 0, function* () { - this.setEventMetadata(event); - const lastReply = this.lastReply(); - const isNewestReply = !lastReply || event.localTimestamp >= lastReply.localTimestamp; - // Add all incoming events to the thread's timeline set when there's no server support - if (!Thread.hasServerSideSupport) { - // all the relevant membership info to hydrate events with a sender - // is held in the main room timeline - // We want to fetch the room state from there and pass it down to this thread - // timeline set to let it reconcile an event with its relevant RoomMember - this.addEventToTimeline(event, toStartOfTimeline); - this.client.decryptEventIfNeeded(event, {}); - } - else if (!toStartOfTimeline && this.initialEventsFetched && isNewestReply) { - this.addEventToTimeline(event, false); - this.fetchEditsWhereNeeded(event); - } - else if (event.isRelation(event_1.RelationType.Annotation) || event.isRelation(event_1.RelationType.Replace)) { - if (!this.initialEventsFetched) { - /** - * 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. - */ - (_a = this.replayEvents) === null || _a === void 0 ? void 0 : _a.push(event); - } - else { - this.addEventToTimeline(event, toStartOfTimeline); - } - // Apply annotations and replace relations to the relations of the timeline only - (_b = this.timelineSet.relations) === null || _b === void 0 ? void 0 : _b.aggregateParentEvent(event); - (_c = this.timelineSet.relations) === null || _c === void 0 ? void 0 : _c.aggregateChildEvent(event, this.timelineSet); - return; - } - // If no thread support exists we want to count all thread relation - // added as a reply. We can't rely on the bundled relationships count - if ((!Thread.hasServerSideSupport || !this.rootEvent) && event.isRelation(exports.THREAD_RELATION_TYPE.name)) { - this.replyCount++; - } - if (emit) { - this.emit(ThreadEvent.NewReply, this, event); - this.updateThreadMetadata(); - } - }); - } - processEvent(event) { - return __awaiter(this, void 0, void 0, function* () { - if (event) { - this.setEventMetadata(event); - yield this.fetchEditsWhereNeeded(event); - } - this.timeline = this.events; - }); - } - /** - * 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(receipts = []) { - for (const { eventId, receiptType, userId, receipt, synthetic } of receipts) { - this.addReceiptToStructure(eventId, receiptType, userId, receipt, synthetic); - } - } - getRootEventBundledRelationship(rootEvent = this.rootEvent) { - return rootEvent === null || rootEvent === void 0 ? void 0 : rootEvent.getServerAggregatedRelation(exports.THREAD_RELATION_TYPE.name); - } - processRootEvent() { - return __awaiter(this, void 0, void 0, function* () { - const bundledRelationship = this.getRootEventBundledRelationship(); - if (Thread.hasServerSideSupport && bundledRelationship) { - this.replyCount = bundledRelationship.count; - this._currentUserParticipated = !!bundledRelationship.current_user_participated; - const mapper = this.client.getEventMapper(); - // re-insert roomId - this.lastEvent = mapper(Object.assign(Object.assign({}, bundledRelationship.latest_event), { room_id: this.roomId })); - this.updatePendingReplyCount(); - yield this.processEvent(this.lastEvent); - } - }); - } - updatePendingReplyCount() { - const unfilteredPendingEvents = this.pendingEventOrdering === client_1.PendingEventOrdering.Detached ? this.room.getPendingEvents() : this.events; - const pendingEvents = unfilteredPendingEvents.filter((ev) => { - var _a; - return ev.threadRootId === this.id && - ev.isRelation(exports.THREAD_RELATION_TYPE.name) && - ev.status !== null && - ev.getId() !== ((_a = this.lastEvent) === null || _a === void 0 ? void 0 : _a.getId()); - }); - this.lastPendingEvent = pendingEvents.length ? pendingEvents[pendingEvents.length - 1] : undefined; - this.pendingReplyCount = pendingEvents.length; - } - /** - * Reset the live timeline of all timelineSets, and start new ones. - * - *

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) { - return __awaiter(this, void 0, void 0, function* () { - const oldLive = this.liveTimeline; - this.timelineSet.resetLiveTimeline(backPaginationToken !== null && backPaginationToken !== void 0 ? backPaginationToken : undefined, forwardPaginationToken !== null && forwardPaginationToken !== void 0 ? forwardPaginationToken : undefined); - const newLive = this.liveTimeline; - // FIXME: Remove the following as soon as https://github.com/matrix-org/synapse/issues/14830 is resolved. - // - // The pagination API for thread timelines currently can't handle the type of pagination tokens returned by sync - // - // To make this work anyway, we'll have to transform them into one of the types that the API can handle. - // One option is passing the tokens to /messages, which can handle sync tokens, and returns the right format. - // /messages does not return new tokens on requests with a limit of 0. - // This means our timelines might overlap a slight bit, but that's not an issue, as we deduplicate messages - // anyway. - let newBackward; - let oldForward; - if (backPaginationToken) { - const res = yield this.client.createMessagesRequest(this.roomId, backPaginationToken, 1, event_timeline_1.Direction.Forward); - newBackward = res.end; - } - if (forwardPaginationToken) { - const res = yield this.client.createMessagesRequest(this.roomId, forwardPaginationToken, 1, event_timeline_1.Direction.Backward); - oldForward = res.start; - } - // Only replace the token if we don't have paginated away from this position already. This situation doesn't - // occur today, but if the above issue is resolved, we'd have to go down this path. - if (forwardPaginationToken && oldLive.getPaginationToken(event_timeline_1.Direction.Forward) === forwardPaginationToken) { - oldLive.setPaginationToken(oldForward !== null && oldForward !== void 0 ? oldForward : null, event_timeline_1.Direction.Forward); - } - if (backPaginationToken && newLive.getPaginationToken(event_timeline_1.Direction.Backward) === backPaginationToken) { - newLive.setPaginationToken(newBackward !== null && newBackward !== void 0 ? newBackward : null, event_timeline_1.Direction.Backward); - } - }); - } - updateThreadMetadata() { - return __awaiter(this, void 0, void 0, function* () { - this.updatePendingReplyCount(); - if (Thread.hasServerSideSupport) { - // Ensure we show *something* as soon as possible, we'll update it as soon as we get better data, but we - // don't want the thread preview to be empty if we can avoid it - if (!this.initialEventsFetched) { - yield this.processRootEvent(); - } - yield this.fetchRootEvent(); - } - yield this.processRootEvent(); - if (!this.initialEventsFetched) { - this.initialEventsFetched = true; - // fetch initial event to allow proper pagination - try { - // if the thread has regular events, this will just load the last reply. - // if the thread is newly created, this will load the root event. - if (this.replyCount === 0 && this.rootEvent) { - this.timelineSet.addEventsToTimeline([this.rootEvent], true, this.liveTimeline, null); - this.liveTimeline.setPaginationToken(null, event_timeline_1.Direction.Backward); - } - else { - yield this.client.paginateEventTimeline(this.liveTimeline, { - backwards: true, - limit: Math.max(1, this.length), - }); - } - for (const event of this.replayEvents) { - this.addEvent(event, false); - } - this.replayEvents = null; - // just to make sure that, if we've created a timeline window for this thread before the thread itself - // existed (e.g. when creating a new thread), we'll make sure the panel is force refreshed correctly. - this.emit(room_1.RoomEvent.TimelineReset, this.room, this.timelineSet, true); - } - catch (e) { - logger_1.logger.error("Failed to load start of newly created thread: ", e); - this.initialEventsFetched = false; - } - } - this.emit(ThreadEvent.Update, this); - }); - } - // XXX: Workaround for https://github.com/matrix-org/matrix-spec-proposals/pull/2676/files#r827240084 - fetchEditsWhereNeeded(...events) { - return __awaiter(this, void 0, void 0, function* () { - return Promise.all(events - .filter((e) => e.isEncrypted()) - .map((event) => { - if (event.isRelation()) - return; // skip - relations don't get edits - return this.client - .relations(this.roomId, event.getId(), event_1.RelationType.Replace, event.getType(), { - limit: 1, - }) - .then((relations) => { - if (relations.events.length) { - event.makeReplaced(relations.events[0]); - } - }) - .catch((e) => { - logger_1.logger.error("Failed to load edits for encrypted thread event", e); - }); - })); - }); - } - setEventMetadata(event) { - if (event) { - event_timeline_1.EventTimeline.setEventMetadata(event, this.roomState, false); - event.setThread(this); - } - } - clearEventMetadata(event) { - var _a, _b, _c; - if (event) { - event.setThread(undefined); - (_c = (_b = (_a = event.event) === null || _a === void 0 ? void 0 : _a.unsigned) === null || _b === void 0 ? void 0 : _b["m.relations"]) === null || _c === void 0 ? true : delete _c[exports.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(matches = () => true) { - for (let i = this.timeline.length - 1; i >= 0; i--) { - const 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 _a, _b; - return (_b = (_a = this.lastPendingEvent) !== null && _a !== void 0 ? _a : this.lastEvent) !== null && _b !== void 0 ? _b : this.lastReply(); - } - get events() { - return this.liveTimeline.getEvents(); - } - has(eventId) { - return this.timelineSet.findEventById(eventId) instanceof event_2.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 _a, _b; - const isCurrentUser = userId === this.client.getUserId(); - const lastReply = this.timeline[this.timeline.length - 1]; - if (isCurrentUser && lastReply) { - // If the last activity in a thread is prior to the first threaded read receipt - // sent in the room (suggesting that it was sent before the user started - // using a client that supported threaded read receipts), we want to - // consider this thread as read. - const beforeFirstThreadedReceipt = lastReply.getTs() < this.room.getOldestThreadedReceiptTs(); - const lastReplyId = lastReply.getId(); - // Some unsent events do not have an ID, we do not want to consider them read - if (beforeFirstThreadedReceipt && lastReplyId) { - return lastReplyId; - } - } - const readUpToId = super.getEventReadUpTo(userId, ignoreSynthesized); - // Check whether the unthreaded read receipt for that user is more recent - // than the read receipt inside that thread. - if (lastReply) { - const unthreadedReceipt = this.room.getLastUnthreadedReceiptFor(userId); - if (!unthreadedReceipt) { - return readUpToId; - } - for (let i = ((_a = this.timeline) === null || _a === void 0 ? void 0 : _a.length) - 1; i >= 0; --i) { - const ev = this.timeline[i]; - // If we encounter the `readUpToId` we do not need to look further - // there is no "more recent" unthreaded read receipt - if (ev.getId() === readUpToId) - return readUpToId; - // Inspecting events from most recent to oldest, we're checking - // whether an unthreaded read receipt is more recent that the current event. - // We usually prefer relying on the order of the DAG but in this scenario - // it is not possible and we have to rely on timestamp - if (ev.getTs() < unthreadedReceipt.ts) - return (_b = ev.getId()) !== null && _b !== void 0 ? _b : 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) { - var _a, _b, _c, _d, _e, _f; - if (userId === this.client.getUserId()) { - // Consider an event read if it's part of a thread that is before the - // first threaded receipt sent in that room. It is likely that it is - // part of a thread that was created before MSC3771 was implemented. - // Or before the last unthreaded receipt for the logged in user - const beforeFirstThreadedReceipt = ((_b = (_a = this.lastReply()) === null || _a === void 0 ? void 0 : _a.getTs()) !== null && _b !== void 0 ? _b : 0) < this.room.getOldestThreadedReceiptTs(); - const unthreadedReceiptTs = (_d = (_c = this.room.getLastUnthreadedReceiptFor(userId)) === null || _c === void 0 ? void 0 : _c.ts) !== null && _d !== void 0 ? _d : 0; - const beforeLastUnthreadedReceipt = ((_f = (_e = this === null || this === void 0 ? void 0 : this.lastReply()) === null || _e === void 0 ? void 0 : _e.getTs()) !== null && _f !== void 0 ? _f : 0) < unthreadedReceiptTs; - if (beforeFirstThreadedReceipt || beforeLastUnthreadedReceipt) { - return true; - } - } - return super.hasUserReadEvent(userId, eventId); - } - setUnread(type, count) { - return this.room.setThreadUnreadNotificationCount(this.id, type, count); - } -} -exports.Thread = Thread; -Thread.hasServerSideSupport = FeatureSupport.None; -Thread.hasServerSideListSupport = FeatureSupport.None; -Thread.hasServerSideFwdPaginationSupport = FeatureSupport.None; -exports.FILTER_RELATED_BY_SENDERS = new NamespacedValue_1.ServerControlledNamespacedValue("related_by_senders", "io.element.relation_senders"); -exports.FILTER_RELATED_BY_REL_TYPES = new NamespacedValue_1.ServerControlledNamespacedValue("related_by_rel_types", "io.element.relation_types"); -exports.THREAD_RELATION_TYPE = new NamespacedValue_1.ServerControlledNamespacedValue("m.thread", "io.element.thread"); -var ThreadFilterType; -(function (ThreadFilterType) { - ThreadFilterType[ThreadFilterType["My"] = 0] = "My"; - ThreadFilterType[ThreadFilterType["All"] = 1] = "All"; -})(ThreadFilterType = exports.ThreadFilterType || (exports.ThreadFilterType = {})); -function threadFilterTypeToFilter(type) { - switch (type) { - case ThreadFilterType.My: - return "participated"; - default: - return "all"; - } -} -exports.threadFilterTypeToFilter = threadFilterTypeToFilter; - -},{"../@types/event":306,"../@types/read_receipts":311,"../NamespacedValue":316,"../ReEmitter":317,"../client":321,"../logger":374,"./event":383,"./event-timeline":382,"./event-timeline-set":381,"./read-receipt":386,"./room":392}],395:[function(require,module,exports){ -"use strict"; -/* -Copyright 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TypedEventEmitter = exports.EventEmitterEvents = void 0; -// eslint-disable-next-line no-restricted-imports -const events_1 = require("events"); -var EventEmitterEvents; -(function (EventEmitterEvents) { - EventEmitterEvents["NewListener"] = "newListener"; - EventEmitterEvents["RemoveListener"] = "removeListener"; - EventEmitterEvents["Error"] = "error"; -})(EventEmitterEvents = exports.EventEmitterEvents || (exports.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. - */ -class TypedEventEmitter extends events_1.EventEmitter { - addListener(event, listener) { - return super.addListener(event, listener); - } - emit(event, ...args) { - return super.emit(event, ...args); - } - eventNames() { - return super.eventNames(); - } - listenerCount(event) { - return super.listenerCount(event); - } - listeners(event) { - return super.listeners(event); - } - off(event, listener) { - return super.off(event, listener); - } - on(event, listener) { - return super.on(event, listener); - } - once(event, listener) { - return super.once(event, listener); - } - prependListener(event, listener) { - return super.prependListener(event, listener); - } - prependOnceListener(event, listener) { - return super.prependOnceListener(event, listener); - } - removeAllListeners(event) { - return super.removeAllListeners(event); - } - removeListener(event, listener) { - return super.removeListener(event, listener); - } - rawListeners(event) { - return super.rawListeners(event); - } -} -exports.TypedEventEmitter = TypedEventEmitter; - -},{"events":105}],396:[function(require,module,exports){ -"use strict"; -/* -Copyright 2015 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.User = exports.UserEvent = void 0; -const typed_event_emitter_1 = require("./typed-event-emitter"); -var UserEvent; -(function (UserEvent) { - UserEvent["DisplayName"] = "User.displayName"; - UserEvent["AvatarUrl"] = "User.avatarUrl"; - UserEvent["Presence"] = "User.presence"; - UserEvent["CurrentlyActive"] = "User.currentlyActive"; - UserEvent["LastPresenceTs"] = "User.lastPresenceTs"; -})(UserEvent = exports.UserEvent || (exports.UserEvent = {})); -class User extends typed_event_emitter_1.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. - */ - constructor(userId) { - super(); - this.userId = userId; - this.modified = -1; - /** - * The presence enum if known. - * @privateRemarks - * Should be read-only - */ - 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 - */ - 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 - */ - 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 - */ - this.currentlyActive = false; - /** - * The events describing this user. - * @privateRemarks - * Should be read-only - */ - this.events = {}; - this.displayName = userId; - this.rawDisplayName = userId; - this.updateModifiedTime(); - } - /** - * 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; - } - const firstFire = this.events.presence === null; - this.events.presence = event; - const 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 !== undefined && - 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 (const 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) { - const 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) { - const 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 before 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; - } -} -exports.User = User; - -},{"./typed-event-emitter":395}],397:[function(require,module,exports){ -"use strict"; -/* -Copyright 2015 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PushProcessor = void 0; -const utils_1 = require("./utils"); -const logger_1 = require("./logger"); -const PushRules_1 = require("./@types/PushRules"); -const event_1 = require("./@types/event"); -const RULEKINDS_IN_ORDER = [ - PushRules_1.PushRuleKind.Override, - PushRules_1.PushRuleKind.ContentSpecific, - PushRules_1.PushRuleKind.RoomSpecific, - PushRules_1.PushRuleKind.SenderSpecific, - PushRules_1.PushRuleKind.Underride, -]; -// The default override rules to apply to the push rules that arrive from the server. -// We do this for two reasons: -// 1. Synapse is unlikely to send us the push rule in an incremental sync - see -// https://github.com/matrix-org/synapse/pull/4867#issuecomment-481446072 for -// more details. -// 2. We often want to start using push rules ahead of the server supporting them, -// and so we can put them here. -const DEFAULT_OVERRIDE_RULES = [ - { - // For homeservers which don't support MSC2153 yet - rule_id: ".m.rule.reaction", - default: true, - enabled: true, - conditions: [ - { - kind: PushRules_1.ConditionKind.EventMatch, - key: "type", - pattern: "m.reaction", - }, - ], - actions: [PushRules_1.PushRuleActionName.DontNotify], - }, - { - rule_id: PushRules_1.RuleId.IsUserMention, - default: true, - enabled: true, - conditions: [ - { - kind: PushRules_1.ConditionKind.EventPropertyContains, - key: "content.org\\.matrix\\.msc3952\\.mentions.user_ids", - value: "", // The user ID is dynamically added in rewriteDefaultRules. - }, - ], - actions: [PushRules_1.PushRuleActionName.Notify, { set_tweak: PushRules_1.TweakName.Highlight }], - }, - { - rule_id: PushRules_1.RuleId.IsRoomMention, - default: true, - enabled: true, - conditions: [ - { - kind: PushRules_1.ConditionKind.EventPropertyIs, - key: "content.org\\.matrix\\.msc3952\\.mentions.room", - value: true, - }, - { - kind: PushRules_1.ConditionKind.SenderNotificationPermission, - key: "room", - }, - ], - actions: [PushRules_1.PushRuleActionName.Notify, { set_tweak: PushRules_1.TweakName.Highlight }], - }, - { - // For homeservers which don't support MSC3786 yet - rule_id: ".org.matrix.msc3786.rule.room.server_acl", - default: true, - enabled: true, - conditions: [ - { - kind: PushRules_1.ConditionKind.EventMatch, - key: "type", - pattern: event_1.EventType.RoomServerAcl, - }, - { - kind: PushRules_1.ConditionKind.EventMatch, - key: "state_key", - pattern: "", - }, - ], - actions: [], - }, -]; -const DEFAULT_UNDERRIDE_RULES = [ - { - // For homeservers which don't support MSC3914 yet - rule_id: ".org.matrix.msc3914.rule.room.call", - default: true, - enabled: true, - conditions: [ - { - kind: PushRules_1.ConditionKind.EventMatch, - key: "type", - pattern: "org.matrix.msc3401.call", - }, - { - kind: PushRules_1.ConditionKind.CallStarted, - }, - ], - actions: [PushRules_1.PushRuleActionName.Notify, { set_tweak: PushRules_1.TweakName.Sound, value: "default" }], - }, -]; -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. - */ - this.parsedKeys = 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) { - const actionObj = { notify: false, tweaks: {} }; - for (const action of actionList) { - if (action === PushRules_1.PushRuleActionName.Notify) { - actionObj.notify = true; - } - else if (typeof action === "object") { - if (action.value === undefined) { - 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 incomingRules - The client's existing push rules - * @param userId - The Matrix ID of the client. - * @returns The rewritten rules - */ - static rewriteDefaultRules(incomingRules, userId = undefined) { - var _a; - let newRules = JSON.parse(JSON.stringify(incomingRules)); // deep clone - // These lines are mostly to make the tests happy. We shouldn't run into these - // properties missing in practice. - if (!newRules) - newRules = {}; - if (!newRules.global) - newRules.global = {}; - if (!newRules.global.override) - newRules.global.override = []; - if (!newRules.global.underride) - newRules.global.underride = []; - // Merge the client-level defaults with the ones from the server - const globalOverrides = newRules.global.override; - for (const originalOverride of DEFAULT_OVERRIDE_RULES) { - const existingRule = globalOverrides.find((r) => r.rule_id === originalOverride.rule_id); - // Dynamically add the user ID as the value for the is_user_mention rule. - let override; - if (originalOverride.rule_id === PushRules_1.RuleId.IsUserMention) { - // If the user ID wasn't provided, skip the rule. - if (!userId) { - continue; - } - override = JSON.parse(JSON.stringify(originalOverride)); // deep clone - override.conditions[0].value = userId; - } - else { - override = originalOverride; - } - if (existingRule) { - // Copy over the actions, default, and conditions. Don't touch the user's preference. - existingRule.default = override.default; - existingRule.conditions = override.conditions; - existingRule.actions = override.actions; - } - else { - // Add the rule - const ruleId = override.rule_id; - logger_1.logger.warn(`Adding default global override for ${ruleId}`); - globalOverrides.push(override); - } - } - const globalUnderrides = (_a = newRules.global.underride) !== null && _a !== void 0 ? _a : []; - for (const underride of DEFAULT_UNDERRIDE_RULES) { - const existingRule = globalUnderrides.find((r) => r.rule_id === underride.rule_id); - if (existingRule) { - // Copy over the actions, default, and conditions. Don't touch the user's preference. - existingRule.default = underride.default; - existingRule.conditions = underride.conditions; - existingRule.actions = underride.actions; - } - else { - // Add the rule - const ruleId = underride.rule_id; - logger_1.logger.warn(`Adding default global underride for ${ruleId}`); - globalUnderrides.push(underride); - } - } - return newRules; - } - /** - * 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) { - // These lines are mostly to make the tests happy. We shouldn't run into these - // properties missing in practice. - 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 = []; - // Process the 'key' property on event_match conditions pre-cache the - // values and clean-out any unused values. - const toRemoveKeys = new Set(this.parsedKeys.keys()); - for (const ruleset of [ - newRules.global.override, - newRules.global.room, - newRules.global.sender, - newRules.global.underride, - ]) { - for (const rule of ruleset) { - if (!rule.conditions) { - continue; - } - for (const condition of rule.conditions) { - if (condition.kind !== PushRules_1.ConditionKind.EventMatch) { - continue; - } - // Ensure we keep this key. - toRemoveKeys.delete(condition.key); - // Pre-process the key. - this.parsedKeys.set(condition.key, PushProcessor.partsForDottedKey(condition.key)); - } - } - } - // Any keys that were previously cached, but are no longer needed should - // be removed. - toRemoveKeys.forEach((k) => this.parsedKeys.delete(k)); - } - matchingRuleFromKindSet(ev, kindset) { - for (const kind of RULEKINDS_IN_ORDER) { - const ruleset = kindset[kind]; - if (!ruleset) { - continue; - } - for (const rule of ruleset) { - if (!rule.enabled) { - continue; - } - const rawrule = this.templateRuleToRaw(kind, rule); - if (!rawrule) { - continue; - } - if (this.ruleMatchesEvent(rawrule, ev)) { - return Object.assign(Object.assign({}, rule), { kind }); - } - } - } - return null; - } - templateRuleToRaw(kind, tprule) { - const rawrule = { - rule_id: tprule.rule_id, - actions: tprule.actions, - conditions: [], - }; - switch (kind) { - case PushRules_1.PushRuleKind.Underride: - case PushRules_1.PushRuleKind.Override: - rawrule.conditions = tprule.conditions; - break; - case PushRules_1.PushRuleKind.RoomSpecific: - if (!tprule.rule_id) { - return null; - } - rawrule.conditions.push({ - kind: PushRules_1.ConditionKind.EventMatch, - key: "room_id", - value: tprule.rule_id, - }); - break; - case PushRules_1.PushRuleKind.SenderSpecific: - if (!tprule.rule_id) { - return null; - } - rawrule.conditions.push({ - kind: PushRules_1.ConditionKind.EventMatch, - key: "user_id", - value: tprule.rule_id, - }); - break; - case PushRules_1.PushRuleKind.ContentSpecific: - if (!tprule.pattern) { - return null; - } - rawrule.conditions.push({ - kind: PushRules_1.ConditionKind.EventMatch, - key: "content.body", - pattern: tprule.pattern, - }); - break; - } - return rawrule; - } - eventFulfillsCondition(cond, ev) { - switch (cond.kind) { - case PushRules_1.ConditionKind.EventMatch: - return this.eventFulfillsEventMatchCondition(cond, ev); - case PushRules_1.ConditionKind.EventPropertyIs: - return this.eventFulfillsEventPropertyIsCondition(cond, ev); - case PushRules_1.ConditionKind.EventPropertyContains: - return this.eventFulfillsEventPropertyContains(cond, ev); - case PushRules_1.ConditionKind.ContainsDisplayName: - return this.eventFulfillsDisplayNameCondition(cond, ev); - case PushRules_1.ConditionKind.RoomMemberCount: - return this.eventFulfillsRoomMemberCountCondition(cond, ev); - case PushRules_1.ConditionKind.SenderNotificationPermission: - return this.eventFulfillsSenderNotifPermCondition(cond, ev); - case PushRules_1.ConditionKind.CallStarted: - case PushRules_1.ConditionKind.CallStartedPrefix: - return this.eventFulfillsCallStartedCondition(cond, ev); - } - // unknown conditions: we previously matched all unknown conditions, - // but given that rules can be added to the base rules on a server, - // it's probably better to not match unknown conditions. - return false; - } - eventFulfillsSenderNotifPermCondition(cond, ev) { - const notifLevelKey = cond["key"]; - if (!notifLevelKey) { - return false; - } - const room = this.client.getRoom(ev.getRoomId()); - if (!(room === null || room === void 0 ? void 0 : room.currentState)) { - return false; - } - // Note that this should not be the current state of the room but the state at - // the point the event is in the DAG. Unfortunately the js-sdk does not store - // this. - return room.currentState.mayTriggerNotifOfType(notifLevelKey, ev.getSender()); - } - eventFulfillsRoomMemberCountCondition(cond, ev) { - if (!cond.is) { - return false; - } - const room = this.client.getRoom(ev.getRoomId()); - if (!room || !room.currentState || !room.currentState.members) { - return false; - } - const memberCount = room.currentState.getJoinedMemberCount(); - const m = cond.is.match(/^([=<>]*)(\d*)$/); - if (!m) { - return false; - } - const ineq = m[1]; - const 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 _a; - let content = ev.getContent(); - if (ev.isEncrypted() && ev.getClearContent()) { - content = ev.getClearContent(); - } - if (!content || !content.body || typeof content.body != "string") { - return false; - } - const room = this.client.getRoom(ev.getRoomId()); - const member = (_a = room === null || room === void 0 ? void 0 : room.currentState) === null || _a === void 0 ? void 0 : _a.getMember(this.client.credentials.userId); - if (!member) { - return false; - } - const displayName = member.name; - // N.B. we can't use \b as it chokes on unicode. however \W seems to be okay - // as shorthand for [^0-9A-Za-z_]. - const pat = new RegExp("(^|\\W)" + (0, utils_1.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; - } - const val = this.valueForDottedKey(cond.key, ev); - if (typeof val !== "string") { - return false; - } - // XXX This does not match in a case-insensitive manner. - // - // See https://spec.matrix.org/v1.5/client-server-api/#conditions-1 - if (cond.value) { - return cond.value === val; - } - if (typeof cond.pattern !== "string") { - return false; - } - const regex = cond.key === "content.body" - ? this.createCachedRegex("(^|\\W)", cond.pattern, "(\\W|$)") - : this.createCachedRegex("^", cond.pattern, "$"); - 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 === undefined) { - 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 === undefined) { - return false; - } - const val = this.valueForDottedKey(cond.key, ev); - if (!Array.isArray(val)) { - return false; - } - return val.includes(cond.value); - } - eventFulfillsCallStartedCondition(_cond, ev) { - // Since servers don't support properly sending push notification - // about MSC3401 call events, we do the handling ourselves - return (["m.ring", "m.prompt"].includes(ev.getContent()["m.intent"]) && - !("m.terminated" in ev.getContent()) && - (ev.getPrevContent()["m.terminated"] !== ev.getContent()["m.terminated"] || - (0, utils_1.deepCompare)(ev.getPrevContent(), {}))); - } - createCachedRegex(prefix, glob, suffix) { - if (PushProcessor.cachedGlobToRegex[glob]) { - return PushProcessor.cachedGlobToRegex[glob]; - } - PushProcessor.cachedGlobToRegex[glob] = new RegExp(prefix + (0, utils_1.globToRegexp)(glob) + suffix, "i"); - return PushProcessor.cachedGlobToRegex[glob]; - } - /** - * 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) { - const result = []; - // The current field and whether the previous character was the escape - // character (a backslash). - let part = ""; - let escaped = false; - // Iterate over each character, and decide whether to append to the current - // part (following the escape rules) or to start a new part (based on the - // field separator). - for (const c of str) { - // If the previous character was the escape character (a backslash) - // then decide what to append to the current part. - if (escaped) { - if (c === "\\" || c === ".") { - // An escaped backslash or dot just gets added. - part += c; - } - else { - // A character that shouldn't be escaped gets the backslash prepended. - part += "\\" + c; - } - // This always resets being escaped. - escaped = false; - continue; - } - if (c == ".") { - // The field separator creates a new part. - result.push(part); - part = ""; - } - else if (c == "\\") { - // A backslash adds no characters, but starts an escape sequence. - escaped = true; - } - else { - // Otherwise, just add the current character. - part += c; - } - } - // Ensure the final part is included. If there's an open escape sequence - // it should be included. - 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) { - // The key should already have been parsed via updateCachedPushRuleKeys, - // but if it hasn't (maybe via an old consumer of the SDK which hasn't - // been updated?) then lazily calculate it here. - let parts = this.parsedKeys.get(key); - if (parts === undefined) { - parts = PushProcessor.partsForDottedKey(key); - this.parsedKeys.set(key, parts); - } - let val; - // special-case the first component to deal with encrypted messages - const firstPart = parts[0]; - let currentIndex = 0; - if (firstPart === "content") { - val = ev.getContent(); - ++currentIndex; - } - else if (firstPart === "type") { - val = ev.getType(); - ++currentIndex; - } - else { - // use the raw event for any other fields - val = ev.event; - } - for (; currentIndex < parts.length; ++currentIndex) { - // The previous iteration resulted in null or undefined, bail (and - // avoid the type error of attempting to retrieve a property). - if ((0, utils_1.isNullOrUndefined)(val)) { - return undefined; - } - const thisPart = parts[currentIndex]; - val = val[thisPart]; - } - return val; - } - matchingRuleForEventWithRulesets(ev, rulesets) { - if (!rulesets) { - return null; - } - if (ev.getSender() === this.client.credentials.userId) { - return null; - } - return this.matchingRuleFromKindSet(ev, rulesets.global); - } - pushActionsForEventAndRulesets(ev, rulesets) { - const rule = this.matchingRuleForEventWithRulesets(ev, rulesets); - if (!rule) { - return {}; - } - const actionObj = PushProcessor.actionListToActionsObject(rule.actions); - // Some actions are implicit in some situations: we add those here - if (actionObj.tweaks.highlight === undefined) { - // if it isn't specified, highlight if it's a content - // rule but otherwise not - actionObj.tweaks.highlight = rule.kind == PushRules_1.PushRuleKind.ContentSpecific; - } - return actionObj; - } - ruleMatchesEvent(rule, ev) { - var _a; - // Disable the deprecated mentions push rules if the new mentions property exists. - if (this.client.supportsIntentionalMentions() && - ev.getContent()["org.matrix.msc3952.mentions"] !== undefined && - (rule.rule_id === PushRules_1.RuleId.ContainsUserName || - rule.rule_id === PushRules_1.RuleId.ContainsDisplayName || - rule.rule_id === PushRules_1.RuleId.AtRoomNotification)) { - return false; - } - return !((_a = rule.conditions) === null || _a === void 0 ? void 0 : _a.some((cond) => !this.eventFulfillsCondition(cond, ev))); - } - /** - * Get the user's push actions for the given event - */ - actionsForEvent(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 _a; - const result = this.getPushRuleAndKindById(ruleId); - return (_a = result === null || result === void 0 ? void 0 : result.rule) !== null && _a !== void 0 ? _a : 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) { - var _a; - for (const scope of ["global"]) { - if (((_a = this.client.pushRules) === null || _a === void 0 ? void 0 : _a[scope]) === undefined) - continue; - for (const kind of RULEKINDS_IN_ORDER) { - if (this.client.pushRules[scope][kind] === undefined) - continue; - for (const rule of this.client.pushRules[scope][kind]) { - if (rule.rule_id === ruleId) - return { rule, kind }; - } - } - } - return null; - } -} -exports.PushProcessor = PushProcessor; -PushProcessor.cachedGlobToRegex = {}; // $glob: RegExp - -},{"./@types/PushRules":304,"./@types/event":306,"./logger":374,"./utils":416}],398:[function(require,module,exports){ -"use strict"; -/* -Copyright 2018 New Vector Ltd -Copyright 2019 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.randomUppercaseString = exports.randomLowercaseString = exports.randomString = void 0; -const LOWERCASE = "abcdefghijklmnopqrstuvwxyz"; -const UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; -const DIGITS = "0123456789"; -function randomString(len) { - return randomStringFrom(len, UPPERCASE + LOWERCASE + DIGITS); -} -exports.randomString = randomString; -function randomLowercaseString(len) { - return randomStringFrom(len, LOWERCASE); -} -exports.randomLowercaseString = randomLowercaseString; -function randomUppercaseString(len) { - return randomStringFrom(len, UPPERCASE); -} -exports.randomUppercaseString = randomUppercaseString; -function randomStringFrom(len, chars) { - let ret = ""; - for (let i = 0; i < len; ++i) { - ret += chars.charAt(Math.floor(Math.random() * chars.length)); - } - return ret; -} - -},{}],399:[function(require,module,exports){ -(function (global){(function (){ -"use strict"; -/* -Copyright 2016 OpenMarket Ltd -Copyright 2019 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.clearTimeout = exports.setTimeout = void 0; -/* A re-implementation of the javascript callback functions (setTimeout, - * clearTimeout; setInterval and clearInterval are not yet implemented) which - * try to improve handling of large clock jumps (as seen when - * suspending/resuming the system). - * - * In particular, if a timeout would have fired while the system was suspended, - * it will instead fire as soon as possible after resume. - */ -const logger_1 = require("./logger"); -// we schedule a callback at least this often, to check if we've missed out on -// some wall-clock time due to being suspended. -const TIMER_CHECK_PERIOD_MS = 1000; -// counter, for making up ids to return from setTimeout -let count = 0; -// the key for our callback with the real global.setTimeout -let realCallbackKey; -// a sorted list of the callbacks to be run. -// each is an object with keys [runAt, func, params, key]. -const callbackList = []; -// var debuglog = logger.log.bind(logger); -/* istanbul ignore next */ -const debuglog = function (...params) { }; -/** - * 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(func, delayMs, ...params) { - delayMs = delayMs || 0; - if (delayMs < 0) { - delayMs = 0; - } - const runAt = Date.now() + delayMs; - const key = count++; - debuglog("setTimeout: scheduling cb", key, "at", runAt, "(delay", delayMs, ")"); - const data = { - runAt: runAt, - func: func, - params: params, - key: key, - }; - // figure out where it goes in the list - const idx = binarySearch(callbackList, function (el) { - return el.runAt - runAt; - }); - callbackList.splice(idx, 0, data); - scheduleRealCallback(); - return key; -} -exports.setTimeout = setTimeout; -/** - * reimplementation of window.clearTimeout, which mirrors setTimeout - * - * @param key - result from an earlier setTimeout call - */ -function clearTimeout(key) { - if (callbackList.length === 0) { - return; - } - // remove the element from the list - let i; - for (i = 0; i < callbackList.length; i++) { - const cb = callbackList[i]; - if (cb.key == key) { - callbackList.splice(i, 1); - break; - } - } - // iff it was the first one in the list, reschedule our callback. - if (i === 0) { - scheduleRealCallback(); - } -} -exports.clearTimeout = clearTimeout; -// use the real global.setTimeout to schedule a callback to runCallbacks. -function scheduleRealCallback() { - if (realCallbackKey) { - global.clearTimeout(realCallbackKey); - } - const first = callbackList[0]; - if (!first) { - debuglog("scheduleRealCallback: no more callbacks, not rescheduling"); - return; - } - const timestamp = Date.now(); - const delayMs = Math.min(first.runAt - timestamp, TIMER_CHECK_PERIOD_MS); - debuglog("scheduleRealCallback: now:", timestamp, "delay:", delayMs); - realCallbackKey = global.setTimeout(runCallbacks, delayMs); -} -function runCallbacks() { - const timestamp = Date.now(); - debuglog("runCallbacks: now:", timestamp); - // get the list of things to call - const callbacksToRun = []; - // eslint-disable-next-line - while (true) { - const first = callbackList[0]; - if (!first || first.runAt > timestamp) { - break; - } - const cb = callbackList.shift(); - debuglog("runCallbacks: popping", cb.key); - callbacksToRun.push(cb); - } - // reschedule the real callback before running our functions, to - // keep the codepaths the same whether or not our functions - // register their own setTimeouts. - scheduleRealCallback(); - for (const cb of callbacksToRun) { - try { - cb.func.apply(global, cb.params); - } - catch (e) { - logger_1.logger.error("Uncaught exception in callback function", e); - } - } -} -/* search in a sorted array. - * - * returns the index of the last element for which func returns - * greater than zero, or array.length if no such element exists. - */ -function binarySearch(array, func) { - // min is inclusive, max exclusive. - let min = 0; - let max = array.length; - while (min < max) { - const mid = (min + max) >> 1; - const res = func(array[mid]); - if (res > 0) { - // the element at 'mid' is too big; set it as the new max. - max = mid; - } - else { - // the element at 'mid' is too small. 'min' is inclusive, so +1. - min = mid + 1; - } - } - // presumably, min==max now. - return min; -} - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"./logger":374}],400:[function(require,module,exports){ -"use strict"; -/* -Copyright 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.initRustCrypto = void 0; -function initRustCrypto(_http, _userId, _deviceId) { - return __awaiter(this, void 0, void 0, function* () { - throw new Error("Rust crypto is not supported under browserify."); - }); -} -exports.initRustCrypto = initRustCrypto; - -},{}],401:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RUST_SDK_STORE_PREFIX = void 0; -/** The prefix used on indexeddbs created by rust-crypto */ -exports.RUST_SDK_STORE_PREFIX = "matrix-js-sdk"; - -},{}],402:[function(require,module,exports){ -module.exports = require('/home/runner/work/matrix-js-sdk/matrix-js-sdk/src/rust-crypto/browserify-index.ts'); -},{"/home/runner/work/matrix-js-sdk/matrix-js-sdk/src/rust-crypto/browserify-index.ts":400}],403:[function(require,module,exports){ -"use strict"; -/* -Copyright 2015 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MatrixScheduler = void 0; -/** - * This is an internal module which manages queuing, scheduling and retrying - * of requests. - */ -const utils = __importStar(require("./utils")); -const logger_1 = require("./logger"); -const event_1 = require("./@types/event"); -const http_api_1 = require("./http-api"); -const DEBUG = false; // set true to enable console logging. -// eslint-disable-next-line camelcase -class MatrixScheduler { - /** - * Retries events up to 4 times using exponential backoff. 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 - * waited before being retried. - * @param attempts - Number of attempts that have been made, including the one that just failed (ie. starting at 1) - * @see retryAlgorithm - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - static RETRY_BACKOFF_RATELIMIT(event, attempts, err) { - if (err.httpStatus === 400 || err.httpStatus === 403 || err.httpStatus === 401) { - // client error; no amount of retrying with save you now. - return -1; - } - if (err instanceof http_api_1.ConnectionError) { - return -1; - } - // if event that we are trying to send is too large in any way then retrying won't help - if (err.name === "M_TOO_LARGE") { - return -1; - } - if (err.name === "M_LIMIT_EXCEEDED") { - const waitTime = err.data.retry_after_ms; - if (waitTime > 0) { - return waitTime; - } - } - if (attempts > 4) { - return -1; // give up - } - return 1000 * Math.pow(2, attempts); - } - /** - * Queues `m.room.message` events and lets other events continue - * concurrently. - * @see queueAlgorithm - */ - // eslint-disable-next-line @typescript-eslint/naming-convention - static QUEUE_MESSAGES(event) { - // enqueue messages or events that associate with another event (redactions and relations) - if (event.getType() === event_1.EventType.RoomMessage || event.hasAssociation()) { - // put these events in the 'message' queue. - return "message"; - } - // allow all other events continue concurrently. - 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( - /** - * The retry algorithm to apply when retrying events. To stop retrying, return - * `-1`. If this event was part of a queue, it will be removed from - * the queue. - * @param event - The event being retried. - * @param attempts - The number of failed attempts. This will always be \>= 1. - * @param err - The most recent error message received when trying - * to send this event. - * @returns The number of milliseconds to wait before trying again. If - * this is 0, the request will be immediately retried. If this is - * `-1`, the event will be marked as - * {@link EventStatus.NOT_SENT} and will not be retried. - */ - retryAlgorithm = MatrixScheduler.RETRY_BACKOFF_RATELIMIT, - /** - * The queuing algorithm to apply to events. This function must be idempotent as - * it may be called multiple times with the same event. All queues created are - * serviced in a FIFO manner. To send the event ASAP, return `null` - * which will not put this event in a queue. Events that fail to send that form - * part of a queue will be removed from the queue and the next event in the - * queue will be sent. - * @param event - The event to be sent. - * @returns The name of the queue to put the event into. If a queue with - * this name does not exist, it will be created. If this is `null`, - * the event is not put into a queue and will be sent concurrently. - */ - queueAlgorithm = MatrixScheduler.QUEUE_MESSAGES) { - this.retryAlgorithm = retryAlgorithm; - this.queueAlgorithm = queueAlgorithm; - // queueName: [{ - // event: MatrixEvent, // event to send - // defer: Deferred, // defer to resolve/reject at the END of the retries - // attempts: Number // number of times we've called processFn - // }, ...] - this.queues = {}; - this.activeQueues = []; - this.procFn = null; - this.processQueue = (queueName) => { - // get head of queue - const obj = this.peekNextEvent(queueName); - if (!obj) { - this.disableQueue(queueName); - return; - } - debuglog("Queue '%s' has %s pending events", queueName, this.queues[queueName].length); - // fire the process function and if it resolves, resolve the deferred. Else - // invoke the retry algorithm. - // First wait for a resolved promise, so the resolve handlers for - // the deferred of the previously sent event can run. - // This way enqueued relations/redactions to enqueued events can receive - // the remove id of their target before being sent. - Promise.resolve() - .then(() => { - return this.procFn(obj.event); - }) - .then((res) => { - // remove this from the queue - this.removeNextEvent(queueName); - debuglog("Queue '%s' sent event %s", queueName, obj.event.getId()); - obj.defer.resolve(res); - // keep processing - this.processQueue(queueName); - }, (err) => { - obj.attempts += 1; - // ask the retry algorithm when/if we should try again - const 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) { - // give up (you quitter!) - debuglog("Queue '%s' giving up on event %s", queueName, obj.event.getId()); - // remove this from the queue - 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 will modify the underlying event in the queue. - * @see MatrixScheduler.removeEventFromQueue To remove an event from the queue. - */ - getQueueForEvent(event) { - const 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) { - const name = this.queueAlgorithm(event); - if (!name || !this.queues[name]) { - return false; - } - let removed = false; - utils.removeElement(this.queues[name], (element) => { - if (element.event.getId() === event.getId()) { - // XXX we should probably reject the promise? - // https://github.com/matrix-org/matrix-js-sdk/issues/496 - 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) { - const queueName = this.queueAlgorithm(event); - if (!queueName) { - return null; - } - // add the event to the queue and make a deferred for it. - if (!this.queues[queueName]) { - this.queues[queueName] = []; - } - const defer = utils.defer(); - this.queues[queueName].push({ - event: event, - defer: defer, - attempts: 0, - }); - debuglog("Queue algorithm dumped event %s into queue '%s'", event.getId(), queueName); - this.startProcessingQueues(); - return defer.promise; - } - startProcessingQueues() { - if (!this.procFn) - return; - // for each inactive queue with events in them - Object.keys(this.queues) - .filter((queueName) => { - return this.activeQueues.indexOf(queueName) === -1 && this.queues[queueName].length > 0; - }) - .forEach((queueName) => { - // mark the queue as active - this.activeQueues.push(queueName); - // begin processing the head of the queue - debuglog("Spinning up queue: '%s'", queueName); - this.processQueue(queueName); - }); - } - disableQueue(queueName) { - // queue is empty. Mark as inactive and stop recursing. - const index = this.activeQueues.indexOf(queueName); - if (index >= 0) { - this.activeQueues.splice(index, 1); - } - debuglog("Stopping queue '%s' as it is now empty", queueName); - } - clearQueue(queueName, err) { - debuglog("clearing queue '%s'", queueName); - let obj; - while ((obj = this.removeNextEvent(queueName))) { - obj.defer.reject(err); - } - this.disableQueue(queueName); - } - peekNextEvent(queueName) { - const queue = this.queues[queueName]; - if (!Array.isArray(queue)) { - return undefined; - } - return queue[0]; - } - removeNextEvent(queueName) { - const queue = this.queues[queueName]; - if (!Array.isArray(queue)) { - return undefined; - } - return queue.shift(); - } -} -exports.MatrixScheduler = MatrixScheduler; -/* istanbul ignore next */ -function debuglog(...args) { - if (DEBUG) { - logger_1.logger.log(...args); - } -} - -},{"./@types/event":306,"./http-api":367,"./logger":374,"./utils":416}],404:[function(require,module,exports){ -"use strict"; -/* -Copyright 2021-2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); - -},{}],405:[function(require,module,exports){ -"use strict"; -/* -Copyright 2019 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SERVICE_TYPES = void 0; -var SERVICE_TYPES; -(function (SERVICE_TYPES) { - SERVICE_TYPES["IS"] = "SERVICE_TYPE_IS"; - SERVICE_TYPES["IM"] = "SERVICE_TYPE_IM"; -})(SERVICE_TYPES = exports.SERVICE_TYPES || (exports.SERVICE_TYPES = {})); - -},{}],406:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SlidingSyncSdk = void 0; -const room_1 = require("./models/room"); -const logger_1 = require("./logger"); -const utils = __importStar(require("./utils")); -const event_timeline_1 = require("./models/event-timeline"); -const client_1 = require("./client"); -const sync_1 = require("./sync"); -const http_api_1 = require("./http-api"); -const sliding_sync_1 = require("./sliding-sync"); -const event_1 = require("./@types/event"); -const room_state_1 = require("./models/room-state"); -const room_member_1 = require("./models/room-member"); -// Number of consecutive failed syncs that will lead to a syncState of ERROR as opposed -// to RECONNECTING. This is needed to inform the client of server issues when the -// keepAlive is successful but the server /sync fails. -const FAILED_SYNC_ERROR_THRESHOLD = 3; -class ExtensionE2EE { - constructor(crypto) { - this.crypto = crypto; - } - name() { - return "e2ee"; - } - when() { - return sliding_sync_1.ExtensionState.PreProcess; - } - onRequest(isInitial) { - if (!isInitial) { - return undefined; - } - return { - enabled: true, // this is sticky so only send it on the initial request - }; - } - onResponse(data) { - return __awaiter(this, void 0, void 0, function* () { - // Handle device list updates - if (data["device_lists"]) { - yield this.crypto.handleDeviceListChanges({ - oldSyncToken: "yep", // XXX need to do this so the device list changes get processed :( - }, data["device_lists"]); - } - // Handle one_time_keys_count - if (data["device_one_time_keys_count"]) { - const currentCount = data["device_one_time_keys_count"].signed_curve25519 || 0; - this.crypto.updateOneTimeKeyCount(currentCount); - } - if (data["device_unused_fallback_key_types"] || data["org.matrix.msc2732.device_unused_fallback_key_types"]) { - // The presence of device_unused_fallback_key_types indicates that the - // server supports fallback keys. If there's no unused - // signed_curve25519 fallback key we need a new one. - const unusedFallbackKeys = data["device_unused_fallback_key_types"] || data["org.matrix.msc2732.device_unused_fallback_key_types"]; - this.crypto.setNeedsNewFallback(Array.isArray(unusedFallbackKeys) && !unusedFallbackKeys.includes("signed_curve25519")); - } - this.crypto.onSyncCompleted({}); - }); - } -} -class ExtensionToDevice { - constructor(client, cryptoCallbacks) { - this.client = client; - this.cryptoCallbacks = cryptoCallbacks; - this.nextBatch = null; - } - name() { - return "to_device"; - } - when() { - return sliding_sync_1.ExtensionState.PreProcess; - } - onRequest(isInitial) { - const extReq = { - since: this.nextBatch !== null ? this.nextBatch : undefined, - }; - if (isInitial) { - extReq["limit"] = 100; - extReq["enabled"] = true; - } - return extReq; - } - onResponse(data) { - return __awaiter(this, void 0, void 0, function* () { - const cancelledKeyVerificationTxns = []; - let events = data["events"] || []; - if (events.length > 0 && this.cryptoCallbacks) { - events = yield this.cryptoCallbacks.preprocessToDeviceMessages(events); - } - events - .map(this.client.getEventMapper()) - .map((toDeviceEvent) => { - // map is a cheap inline forEach - // We want to flag m.key.verification.start events as cancelled - // if there's an accompanying m.key.verification.cancel event, so - // we pull out the transaction IDs from the cancellation events - // so we can flag the verification events as cancelled in the loop - // below. - if (toDeviceEvent.getType() === "m.key.verification.cancel") { - const txnId = toDeviceEvent.getContent()["transaction_id"]; - if (txnId) { - cancelledKeyVerificationTxns.push(txnId); - } - } - // as mentioned above, .map is a cheap inline forEach, so return - // the unmodified event. - return toDeviceEvent; - }) - .forEach((toDeviceEvent) => { - const content = toDeviceEvent.getContent(); - if (toDeviceEvent.getType() == "m.room.message" && content.msgtype == "m.bad.encrypted") { - // the mapper already logged a warning. - logger_1.logger.log("Ignoring undecryptable to-device event from " + toDeviceEvent.getSender()); - return; - } - if (toDeviceEvent.getType() === "m.key.verification.start" || - toDeviceEvent.getType() === "m.key.verification.request") { - const txnId = content["transaction_id"]; - if (cancelledKeyVerificationTxns.includes(txnId)) { - toDeviceEvent.flagCancelled(); - } - } - this.client.emit(client_1.ClientEvent.ToDeviceEvent, toDeviceEvent); - }); - this.nextBatch = data.next_batch; - }); - } -} -class ExtensionAccountData { - constructor(client) { - this.client = client; - } - name() { - return "account_data"; - } - when() { - return sliding_sync_1.ExtensionState.PostProcess; - } - onRequest(isInitial) { - if (!isInitial) { - return undefined; - } - return { - enabled: true, - }; - } - onResponse(data) { - if (data.global && data.global.length > 0) { - this.processGlobalAccountData(data.global); - } - for (const roomId in data.rooms) { - const accountDataEvents = mapEvents(this.client, roomId, data.rooms[roomId]); - const room = this.client.getRoom(roomId); - if (!room) { - logger_1.logger.warn("got account data for room but room doesn't exist on client:", roomId); - continue; - } - room.addAccountData(accountDataEvents); - accountDataEvents.forEach((e) => { - this.client.emit(client_1.ClientEvent.Event, e); - }); - } - } - processGlobalAccountData(globalAccountData) { - const events = mapEvents(this.client, undefined, globalAccountData); - const prevEventsMap = events.reduce((m, c) => { - m[c.getType()] = this.client.store.getAccountData(c.getType()); - return m; - }, {}); - this.client.store.storeAccountDataEvents(events); - events.forEach((accountDataEvent) => { - // Honour push rules that come down the sync stream but also - // honour push rules that were previously cached. Base rules - // will be updated when we receive push rules via getPushRules - // (see sync) before syncing over the network. - if (accountDataEvent.getType() === event_1.EventType.PushRules) { - const rules = accountDataEvent.getContent(); - this.client.setPushRules(rules); - } - const prevEvent = prevEventsMap[accountDataEvent.getType()]; - this.client.emit(client_1.ClientEvent.AccountData, accountDataEvent, prevEvent); - return accountDataEvent; - }); - } -} -class ExtensionTyping { - constructor(client) { - this.client = client; - } - name() { - return "typing"; - } - when() { - return sliding_sync_1.ExtensionState.PostProcess; - } - onRequest(isInitial) { - if (!isInitial) { - return undefined; // don't send a JSON object for subsequent requests, we don't need to. - } - return { - enabled: true, - }; - } - onResponse(data) { - if (!(data === null || data === void 0 ? void 0 : data.rooms)) { - return; - } - for (const roomId in data.rooms) { - processEphemeralEvents(this.client, roomId, [data.rooms[roomId]]); - } - } -} -class ExtensionReceipts { - constructor(client) { - this.client = client; - } - name() { - return "receipts"; - } - when() { - return sliding_sync_1.ExtensionState.PostProcess; - } - onRequest(isInitial) { - if (isInitial) { - return { - enabled: true, - }; - } - return undefined; // don't send a JSON object for subsequent requests, we don't need to. - } - onResponse(data) { - if (!(data === null || data === void 0 ? void 0 : data.rooms)) { - return; - } - for (const roomId in data.rooms) { - processEphemeralEvents(this.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. - */ -class SlidingSyncSdk { - constructor(slidingSync, client, opts, syncOpts) { - this.slidingSync = slidingSync; - this.client = client; - this.syncState = null; - this.lastPos = null; - this.failCount = 0; - this.notifEvents = []; // accumulator of sync events in the current sync response - this.opts = (0, sync_1.defaultClientOpts)(opts); - this.syncOpts = (0, sync_1.defaultSyncApiOpts)(syncOpts); - if (client.getNotifTimelineSet()) { - client.reEmitter.reEmit(client.getNotifTimelineSet(), [room_1.RoomEvent.Timeline, room_1.RoomEvent.TimelineReset]); - } - this.slidingSync.on(sliding_sync_1.SlidingSyncEvent.Lifecycle, this.onLifecycle.bind(this)); - this.slidingSync.on(sliding_sync_1.SlidingSyncEvent.RoomData, this.onRoomData.bind(this)); - const extensions = [ - new ExtensionToDevice(this.client, this.syncOpts.cryptoCallbacks), - new ExtensionAccountData(this.client), - new ExtensionTyping(this.client), - new ExtensionReceipts(this.client), - ]; - if (this.syncOpts.crypto) { - extensions.push(new ExtensionE2EE(this.syncOpts.crypto)); - } - extensions.forEach((ext) => { - this.slidingSync.registerExtension(ext); - }); - } - onRoomData(roomId, roomData) { - let room = this.client.store.getRoom(roomId); - if (!room) { - if (!roomData.initial) { - logger_1.logger.debug("initial flag not set but no stored room exists for room ", roomId, roomData); - return; - } - room = (0, sync_1._createAndReEmitRoom)(this.client, roomId, this.opts); - } - this.processRoomData(this.client, room, roomData); - } - onLifecycle(state, resp, err) { - if (err) { - logger_1.logger.debug("onLifecycle", state, err); - } - switch (state) { - case sliding_sync_1.SlidingSyncState.Complete: - this.purgeNotifications(); - if (!resp) { - break; - } - // Element won't stop showing the initial loading spinner unless we fire SyncState.Prepared - if (!this.lastPos) { - this.updateSyncState(sync_1.SyncState.Prepared, { - oldSyncToken: undefined, - nextSyncToken: resp.pos, - catchingUp: false, - fromCache: false, - }); - } - // Conversely, Element won't show the room list unless there is at least 1x SyncState.Syncing - // so hence for the very first sync we will fire prepared then immediately syncing. - this.updateSyncState(sync_1.SyncState.Syncing, { - oldSyncToken: this.lastPos, - nextSyncToken: resp.pos, - catchingUp: false, - fromCache: false, - }); - this.lastPos = resp.pos; - break; - case sliding_sync_1.SlidingSyncState.RequestFinished: - if (err) { - this.failCount += 1; - this.updateSyncState(this.failCount > FAILED_SYNC_ERROR_THRESHOLD ? sync_1.SyncState.Error : sync_1.SyncState.Reconnecting, { - error: new http_api_1.MatrixError(err), - }); - if (this.shouldAbortSync(new http_api_1.MatrixError(err))) { - return; // shouldAbortSync actually stops syncing too so we don't need to do anything. - } - } - else { - this.failCount = 0; - } - break; - } - } - /** - * Sync rooms the user has left. - * @returns Resolved when they've been added to the store. - */ - syncLeftRooms() { - return __awaiter(this, void 0, void 0, function* () { - return []; // TODO - }); - } - /** - * 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 __awaiter(this, void 0, void 0, function* () { - return null; // TODO - }); - } - /** - * Stop polling for updates in the peeked room. NOPs if there is no room being - * peeked. - */ - stopPeeking() { - // TODO - } - /** - * 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 _a; - return (_a = this.syncStateData) !== null && _a !== void 0 ? _a : null; - } - // Helper functions which set up JS SDK structs are below and are identical to the sync v2 counterparts - createRoom(roomId) { - // XXX cargoculted from sync.ts - const { timelineSupport } = this.client; - const room = new room_1.Room(roomId, this.client, this.client.getUserId(), { - lazyLoadMembers: this.opts.lazyLoadMembers, - pendingEventOrdering: this.opts.pendingEventOrdering, - timelineSupport, - }); - this.client.reEmitter.reEmit(room, [ - room_1.RoomEvent.Name, - room_1.RoomEvent.Redaction, - room_1.RoomEvent.RedactionCancelled, - room_1.RoomEvent.Receipt, - room_1.RoomEvent.Tags, - room_1.RoomEvent.LocalEchoUpdated, - room_1.RoomEvent.AccountData, - room_1.RoomEvent.MyMembership, - room_1.RoomEvent.Timeline, - room_1.RoomEvent.TimelineReset, - ]); - this.registerStateListeners(room); - return room; - } - registerStateListeners(room) { - // XXX cargoculted from sync.ts - // we need to also re-emit room state and room member events, so hook it up - // to the client now. We need to add a listener for RoomState.members in - // order to hook them correctly. - this.client.reEmitter.reEmit(room.currentState, [ - room_state_1.RoomStateEvent.Events, - room_state_1.RoomStateEvent.Members, - room_state_1.RoomStateEvent.NewMember, - room_state_1.RoomStateEvent.Update, - ]); - room.currentState.on(room_state_1.RoomStateEvent.NewMember, (event, state, member) => { - var _a; - member.user = (_a = this.client.getUser(member.userId)) !== null && _a !== void 0 ? _a : undefined; - this.client.reEmitter.reEmit(member, [ - room_member_1.RoomMemberEvent.Name, - room_member_1.RoomMemberEvent.Typing, - room_member_1.RoomMemberEvent.PowerLevel, - room_member_1.RoomMemberEvent.Membership, - ]); - }); - } - /* - private deregisterStateListeners(room: Room): void { // XXX cargoculted from sync.ts - // could do with a better way of achieving this. - room.currentState.removeAllListeners(RoomStateEvent.Events); - room.currentState.removeAllListeners(RoomStateEvent.Members); - room.currentState.removeAllListeners(RoomStateEvent.NewMember); - } */ - shouldAbortSync(error) { - if (error.errcode === "M_UNKNOWN_TOKEN") { - // The logout already happened, we just need to stop. - logger_1.logger.warn("Token no longer valid - assuming logout"); - this.stop(); - this.updateSyncState(sync_1.SyncState.Error, { error }); - return true; - } - return false; - } - processRoomData(client, room, roomData) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - roomData = ensureNameEvent(client, room.roomId, roomData); - const stateEvents = mapEvents(this.client, room.roomId, roomData.required_state); - // Prevent events from being decrypted ahead of time - // this helps large account to speed up faster - // room::decryptCriticalEvent is in charge of decrypting all the events - // required for a client to function properly - let timelineEvents = mapEvents(this.client, room.roomId, roomData.timeline, false); - const ephemeralEvents = []; // TODO this.mapSyncEventsFormat(joinObj.ephemeral); - // TODO: handle threaded / beacon events - if (roomData.initial) { - // we should not know about any of these timeline entries if this is a genuinely new room. - // If we do, then we've effectively done scrollback (e.g requesting timeline_limit: 1 for - // this room, then timeline_limit: 50). - const knownEvents = new Set(); - room.getLiveTimeline() - .getEvents() - .forEach((e) => { - knownEvents.add(e.getId()); - }); - // all unknown events BEFORE a known event must be scrollback e.g: - // D E <-- what we know - // A B C D E F <-- what we just received - // means: - // A B C <-- scrollback - // D E <-- dupes - // F <-- new event - // We bucket events based on if we have seen a known event yet. - const oldEvents = []; - const newEvents = []; - let seenKnownEvent = false; - for (let i = timelineEvents.length - 1; i >= 0; i--) { - const recvEvent = timelineEvents[i]; - if (knownEvents.has(recvEvent.getId())) { - seenKnownEvent = true; - continue; // don't include this event, it's a dupe - } - if (seenKnownEvent) { - // old -> new - oldEvents.push(recvEvent); - } - else { - // old -> new - newEvents.unshift(recvEvent); - } - } - timelineEvents = newEvents; - if (oldEvents.length > 0) { - // old events are scrollback, insert them now - room.addEventsToTimeline(oldEvents, true, room.getLiveTimeline(), roomData.prev_batch); - } - } - const encrypted = this.client.isRoomEncrypted(room.roomId); - // we do this first so it's correct when any of the events fire - if (roomData.notification_count != null) { - room.setUnreadNotificationCount(room_1.NotificationCountType.Total, roomData.notification_count); - } - if (roomData.highlight_count != null) { - // 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. - if (!encrypted || (encrypted && room.getUnreadNotificationCount(room_1.NotificationCountType.Highlight) <= 0)) { - room.setUnreadNotificationCount(room_1.NotificationCountType.Highlight, roomData.highlight_count); - } - } - 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) { - const inviteStateEvents = mapEvents(this.client, room.roomId, roomData.invite_state); - this.injectRoomEvents(room, inviteStateEvents); - if (roomData.initial) { - room.recalculate(); - this.client.store.storeRoom(room); - this.client.emit(client_1.ClientEvent.Room, room); - } - inviteStateEvents.forEach((e) => { - this.client.emit(client_1.ClientEvent.Event, e); - }); - room.updateMyMembership("invite"); - return; - } - if (roomData.initial) { - // set the back-pagination token. Do this *before* adding any - // events so that clients can start back-paginating. - room.getLiveTimeline().setPaginationToken((_a = roomData.prev_batch) !== null && _a !== void 0 ? _a : null, event_timeline_1.EventTimeline.BACKWARDS); - } - /* TODO - else if (roomData.limited) { - - let limited = true; - - // we've got a limited sync, so we *probably* have a gap in the - // timeline, so should reset. But we might have been peeking or - // paginating and already have some of the events, in which - // case we just want to append any subsequent events to the end - // of the existing timeline. - // - // This is particularly important in the case that we already have - // *all* of the events in the timeline - in that case, if we reset - // the timeline, we'll end up with an entirely empty timeline, - // which we'll try to paginate but not get any new events (which - // will stop us linking the empty timeline into the chain). - // - for (let i = timelineEvents.length - 1; i >= 0; i--) { - const eventId = timelineEvents[i].getId(); - if (room.getTimelineForEvent(eventId)) { - logger.debug("Already have event " + eventId + " in limited " + - "sync - not resetting"); - limited = false; - - // we might still be missing some of the events before i; - // we don't want to be adding them to the end of the - // timeline because that would put them out of order. - timelineEvents.splice(0, i); - - // XXX: there's a problem here if the skipped part of the - // timeline modifies the state set in stateEvents, because - // we'll end up using the state from stateEvents rather - // than the later state from timelineEvents. We probably - // need to wind stateEvents forward over the events we're - // skipping. - break; - } - } - - if (limited) { - room.resetLiveTimeline( - roomData.prev_batch, - null, // TODO this.syncOpts.canResetEntireTimeline(room.roomId) ? null : syncEventData.oldSyncToken, - ); - - // We have to assume any gap in any timeline is - // reason to stop incrementally tracking notifications and - // reset the timeline. - this.client.resetNotifTimelineSet(); - this.registerStateListeners(room); - } - } */ - this.injectRoomEvents(room, stateEvents, timelineEvents, roomData.num_live); - // we deliberately don't add ephemeral events to the timeline - room.addEphemeralEvents(ephemeralEvents); - // local fields must be set before any async calls because call site assumes - // synchronous execution prior to emitting SlidingSyncState.Complete - room.updateMyMembership("join"); - room.recalculate(); - if (roomData.initial) { - client.store.storeRoom(room); - client.emit(client_1.ClientEvent.Room, room); - } - // check if any timeline events should bing and add them to the notifEvents array: - // we'll purge this once we've fully processed the sync response - this.addNotifications(timelineEvents); - const processRoomEvent = (e) => __awaiter(this, void 0, void 0, function* () { - client.emit(client_1.ClientEvent.Event, e); - if (e.isState() && e.getType() == event_1.EventType.RoomEncryption && this.syncOpts.cryptoCallbacks) { - yield this.syncOpts.cryptoCallbacks.onCryptoEvent(room, e); - } - }); - yield utils.promiseMapSeries(stateEvents, processRoomEvent); - yield utils.promiseMapSeries(timelineEvents, processRoomEvent); - ephemeralEvents.forEach(function (e) { - client.emit(client_1.ClientEvent.Event, e); - }); - // Decrypt only the last message in all rooms to make sure we can generate a preview - // And decrypt all events after the recorded read receipt to ensure an accurate - // notification count - room.decryptCriticalEvents(); - }); - } - /** - * 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 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, timelineEventList, numLive) { - timelineEventList = timelineEventList || []; - stateEventList = stateEventList || []; - numLive = numLive || 0; - // If there are no events in the timeline yet, initialise it with - // the given state events - const liveTimeline = room.getLiveTimeline(); - const timelineWasEmpty = liveTimeline.getEvents().length == 0; - if (timelineWasEmpty) { - // Passing these events into initialiseState will freeze them, so we need - // to compute and cache the push actions for them now, otherwise sync dies - // with an attempt to assign to read only property. - // XXX: This is pretty horrible and is assuming all sorts of behaviour from - // these functions that it shouldn't be. We should probably either store the - // push actions cache elsewhere so we can freeze MatrixEvents, or otherwise - // find some solution where MatrixEvents are immutable but allow for a cache - // field. - for (const ev of stateEventList) { - this.client.getPushActionsForEvent(ev); - } - liveTimeline.initialiseState(stateEventList); - } - // If the timeline wasn't empty, we process the state events here: they're - // defined as updates to the state before the start of the timeline, so this - // starts to roll the state forward. - // XXX: That's what we *should* do, but this can happen if we were previously - // peeking in a room, in which case we obviously do *not* want to add the - // state events here onto the end of the timeline. Historically, the js-sdk - // has just set these new state events on the old and new state. This seems - // very wrong because there could be events in the timeline that diverge the - // state, in which case this is going to leave things out of sync. However, - // for now I think it;s best to behave the same as the code has done previously. - if (!timelineWasEmpty) { - // XXX: As above, don't do this... - //room.addLiveEvents(stateEventList || []); - // Do this instead... - room.oldState.setStateEvents(stateEventList); - room.currentState.setStateEvents(stateEventList); - } - // the timeline is broken into 'live' events which just happened and normal timeline events - // which are still to be appended to the end of the live timeline but happened a while ago. - // The live events are marked as fromCache=false to ensure that downstream components know - // this is a live event, not historical (from a remote server cache). - let liveTimelineEvents = []; - if (numLive > 0) { - // last numLive events are live - liveTimelineEvents = timelineEventList.slice(-1 * numLive); - // everything else is not live - timelineEventList = timelineEventList.slice(0, -1 * liveTimelineEvents.length); - } - // execute the timeline events. This will continue to diverge the current state - // if the timeline has any state events in it. - // This also needs to be done before running push rules on the events as they need - // to be decorated with sender etc. - room.addLiveEvents(timelineEventList, { - fromCache: true, - }); - if (liveTimelineEvents.length > 0) { - room.addLiveEvents(liveTimelineEvents, { - fromCache: false, - }); - } - room.recalculate(); - // resolve invites now we have set the latest state - this.resolveInvites(room); - } - resolveInvites(room) { - if (!room || !this.opts.resolveInvitesToProfiles) { - return; - } - const client = this.client; - // For each invited room member we want to give them a displayname/avatar url - // if they have one (the m.room.member invites don't contain this). - room.getMembersWithMembership("invite").forEach(function (member) { - if (member.requestedProfileInfo) - return; - member.requestedProfileInfo = true; - // try to get a cached copy first. - const user = client.getUser(member.userId); - let promise; - if (user) { - promise = Promise.resolve({ - avatar_url: user.avatarUrl, - displayname: user.displayName, - }); - } - else { - promise = client.getProfileInfo(member.userId); - } - promise.then(function (info) { - // slightly naughty by doctoring the invite event but this means all - // the code paths remain the same between invite/join display name stuff - // which is a worthy trade-off for some minor pollution. - const inviteEvent = member.events.member; - if (inviteEvent.getContent().membership !== "invite") { - // between resolving and now they have since joined, so don't clobber - return; - } - inviteEvent.getContent().avatar_url = info.avatar_url; - inviteEvent.getContent().displayname = info.displayname; - // fire listeners - member.setMembershipEvent(inviteEvent, room.currentState); - }, function (_err) { - // OH WELL. - }); - }); - } - retryImmediately() { - return true; - } - /** - * Main entry point. Blocks until stop() is called. - */ - sync() { - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.debug("Sliding sync init loop"); - // 1) We need to get push rules so we can check if events should bing as we get - // them from /sync. - while (!this.client.isGuest()) { - try { - logger_1.logger.debug("Getting push rules..."); - const result = yield this.client.getPushRules(); - logger_1.logger.debug("Got push rules"); - this.client.pushRules = result; - break; - } - catch (err) { - logger_1.logger.error("Getting push rules failed", err); - if (this.shouldAbortSync(err)) { - return; - } - } - } - // start syncing - yield this.slidingSync.start(); - }); - } - /** - * Stops the sync object from syncing. - */ - stop() { - logger_1.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) { - const old = this.syncState; - this.syncState = newState; - this.syncStateData = data; - this.client.emit(client_1.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) { - // gather our notifications into this.notifEvents - if (!this.client.getNotifTimelineSet()) { - return; - } - for (const timelineEvent of timelineEventList) { - const 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 _a; - (_a = this.client.getNotifTimelineSet()) === null || _a === void 0 ? void 0 : _a.addLiveEvent(event); - }); - this.notifEvents = []; - } -} -exports.SlidingSyncSdk = SlidingSyncSdk; -function ensureNameEvent(client, roomId, roomData) { - // make sure m.room.name is in required_state if there is a name, replacing anything previously - // there if need be. This ensures clients transparently 'calculate' the right room name. Native - // sliding sync clients should just read the "name" field. - if (!roomData.name) { - return roomData; - } - for (const stateEvent of roomData.required_state) { - if (stateEvent.type === event_1.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: event_1.EventType.RoomName, - content: { - name: roomData.name, - }, - sender: client.getUserId(), - origin_server_ts: new Date().getTime(), - }); - return roomData; -} -// Helper functions which set up JS SDK structs are below and are identical to the sync v2 counterparts, -// just outside the class. -function mapEvents(client, roomId, events, decrypt = true) { - const mapper = client.getEventMapper({ decrypt }); - return events.map(function (e) { - e.room_id = roomId; - return mapper(e); - }); -} -function processEphemeralEvents(client, roomId, ephEvents) { - const ephemeralEvents = mapEvents(client, roomId, ephEvents); - const room = client.getRoom(roomId); - if (!room) { - logger_1.logger.warn("got ephemeral events for room but room doesn't exist on client:", roomId); - return; - } - room.addEphemeralEvents(ephemeralEvents); - ephemeralEvents.forEach((e) => { - client.emit(client_1.ClientEvent.Event, e); - }); -} - -},{"./@types/event":306,"./client":321,"./http-api":367,"./logger":374,"./models/event-timeline":382,"./models/room":392,"./models/room-member":389,"./models/room-state":390,"./sliding-sync":407,"./sync":414,"./utils":416}],407:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SlidingSync = exports.SlidingSyncEvent = exports.ExtensionState = exports.SlidingSyncState = exports.MSC3575_STATE_KEY_LAZY = exports.MSC3575_STATE_KEY_ME = exports.MSC3575_WILDCARD = void 0; -const logger_1 = require("./logger"); -const typed_event_emitter_1 = require("./models/typed-event-emitter"); -const utils_1 = require("./utils"); -// /sync requests allow you to set a timeout= but the request may continue -// beyond that and wedge forever, so we need to track how long we are willing -// to keep open the connection. This constant is *ADDED* to the timeout= value -// to determine the max time we're willing to wait. -const BUFFER_PERIOD_MS = 10 * 1000; -exports.MSC3575_WILDCARD = "*"; -exports.MSC3575_STATE_KEY_ME = "$ME"; -exports.MSC3575_STATE_KEY_LAZY = "$LAZY"; -var SlidingSyncState; -(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"; -})(SlidingSyncState = exports.SlidingSyncState || (exports.SlidingSyncState = {})); -/** - * Internal Class. SlidingList represents a single list in sliding sync. The list can have filters, - * multiple sliding windows, and maintains the index-\>room_id mapping. - */ -class SlidingList { - /** - * Construct a new sliding list. - * @param list - The range, sort and filter values to use for this list. - */ - constructor(list) { - // returned data - this.roomIndexToRoomId = {}; - this.joinedCount = 0; - this.replaceList(list); - } - /** - * Mark this list as modified or not. Modified lists will return sticky params with calls to getList. - * This is useful for the first time the list is sent, or if the list has changed in some way. - * @param modified - True to mark this list as modified so all sticky parameters will be re-sent. - */ - setModified(modified) { - this.isModified = modified; - } - /** - * Update the list range for this list. Does not affect modified status as list ranges are non-sticky. - * @param newRanges - The new ranges for the list - */ - updateListRange(newRanges) { - this.list.ranges = JSON.parse(JSON.stringify(newRanges)); - } - /** - * Replace list parameters. All fields will be replaced with the new list parameters. - * @param list - The new list parameters - */ - replaceList(list) { - list.filters = list.filters || {}; - list.ranges = list.ranges || []; - this.list = JSON.parse(JSON.stringify(list)); - this.isModified = true; - // reset values as the join count may be very different (if filters changed) including the rooms - // (e.g. sort orders or sliding window ranges changed) - // the constantly changing sliding window ranges. Not an array for performance reasons - // E.g. tracking ranges 0-99, 500-599, we don't want to have a 600 element array - this.roomIndexToRoomId = {}; - // the total number of joined rooms according to the server, always >= len(roomIndexToRoomId) - this.joinedCount = 0; - } - /** - * Return a copy of the list suitable for a request body. - * @param forceIncludeAllParams - True to forcibly include all params even if the list - * hasn't been modified. Callers may want to do this if they are modifying the list prior to calling - * updateList. - */ - getList(forceIncludeAllParams) { - let list = { - ranges: JSON.parse(JSON.stringify(this.list.ranges)), - }; - if (this.isModified || forceIncludeAllParams) { - list = JSON.parse(JSON.stringify(this.list)); - } - return list; - } - /** - * Check if a given index is within the list range. This is required even though the /sync API - * provides explicit updates with index positions because of the following situation: - * 0 1 2 3 4 5 6 7 8 indexes - * a b c d e f COMMANDS: SYNC 0 2 a b c; SYNC 6 8 d e f; - * a b c d _ f COMMAND: DELETE 7; - * e a b c d f COMMAND: INSERT 0 e; - * c=3 is wrong as we are not tracking it, ergo we need to see if `i` is in range else drop it - * @param i - The index to check - * @returns True if the index is within a sliding window - */ - isIndexInRange(i) { - for (const r of this.list.ranges) { - if (r[0] <= i && i <= r[1]) { - return true; - } - } - return false; - } -} -/** - * When onResponse extensions should be invoked: before or after processing the main response. - */ -var ExtensionState; -(function (ExtensionState) { - // Call onResponse before processing the response body. This is useful when your extension is - // preparing the ground for the response body e.g. processing to-device messages before the - // encrypted event arrives. - ExtensionState["PreProcess"] = "ExtState.PreProcess"; - // Call onResponse after processing the response body. This is useful when your extension is - // decorating data from the client, and you rely on MatrixClient.getRoom returning the Room object - // e.g. room account data. - ExtensionState["PostProcess"] = "ExtState.PostProcess"; -})(ExtensionState = exports.ExtensionState || (exports.ExtensionState = {})); -/** - * 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. - * - List: concerns lists, useful for UI layers to re-render room lists. - * Specifically, the order of event invocation is: - * - Lifecycle (state=RequestFinished) - * - RoomData (N times) - * - Lifecycle (state=Complete) - * - List (at most once per list) - */ -var SlidingSyncEvent; -(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 all SlidingSyncEvent.RoomData have been fired but before - * SlidingSyncEvent.List. - */ - SlidingSyncEvent["Lifecycle"] = "SlidingSync.Lifecycle"; - /** - * This event fires whenever there has been a change to this list index. It fires exactly once - * per list, even if there were multiple operations for the list. - * It fires AFTER Lifecycle and RoomData events. - */ - SlidingSyncEvent["List"] = "SlidingSync.List"; -})(SlidingSyncEvent = exports.SlidingSyncEvent || (exports.SlidingSyncEvent = {})); -/** - * SlidingSync is a high-level data structure which controls the majority of sliding sync. - * It has no hooks into JS SDK except for needing a MatrixClient to perform the HTTP request. - * This means this class (and everything it uses) can be used in isolation from JS SDK if needed. - * To hook this up with the JS SDK, you need to use SlidingSyncSdk. - */ -class SlidingSync extends typed_event_emitter_1.TypedEventEmitter { - /** - * Create a new sliding sync instance - * @param proxyBaseUrl - The base URL of the sliding sync proxy - * @param lists - The lists to use for sliding sync. - * @param roomSubscriptionInfo - The params to use for room subscriptions. - * @param client - The client to use for /sync calls. - * @param timeoutMS - The number of milliseconds to wait for a response. - */ - constructor(proxyBaseUrl, lists, roomSubscriptionInfo, client, timeoutMS) { - super(); - this.proxyBaseUrl = proxyBaseUrl; - this.roomSubscriptionInfo = roomSubscriptionInfo; - this.client = client; - this.timeoutMS = timeoutMS; - this.listModifiedCount = 0; - this.terminated = false; - // flag set when resend() is called because we cannot rely on detecting AbortError in JS SDK :( - this.needsResend = false; - // the txn_id to send with the next request. - this.txnId = null; - // a list (in chronological order of when they were sent) of objects containing the txn ID and - // a defer to resolve/reject depending on whether they were successfully sent or not. - this.txnIdDefers = []; - // map of extension name to req/resp handler - this.extensions = {}; - this.desiredRoomSubscriptions = new Set(); // the *desired* room subscriptions - this.confirmedRoomSubscriptions = new Set(); - // map of custom subscription name to the subscription - this.customSubscriptions = new Map(); - // map of room ID to custom subscription name - this.roomIdToCustomSubscription = new Map(); - this.lists = new Map(); - lists.forEach((list, key) => { - this.lists.set(key, new SlidingList(list)); - }); - } - /** - * Add a custom room subscription, referred to by an arbitrary name. If a subscription with this - * name already exists, it is replaced. No requests are sent by calling this method. - * @param name - The name of the subscription. Only used to reference this subscription in - * useCustomSubscription. - * @param sub - The subscription information. - */ - addCustomSubscription(name, sub) { - if (this.customSubscriptions.has(name)) { - logger_1.logger.warn(`addCustomSubscription: ${name} already exists as a custom subscription, ignoring.`); - return; - } - this.customSubscriptions.set(name, sub); - } - /** - * Use a custom subscription previously added via addCustomSubscription. No requests are sent - * by calling this method. Use modifyRoomSubscriptions to resend subscription information. - * @param roomId - The room to use the subscription in. - * @param name - The name of the subscription. If this name is unknown, the default subscription - * will be used. - */ - useCustomSubscription(roomId, name) { - // We already know about this custom subscription, as it is immutable, - // we don't need to unconfirm the subscription. - if (this.roomIdToCustomSubscription.get(roomId) === name) { - return; - } - this.roomIdToCustomSubscription.set(roomId, name); - // unconfirm this subscription so a resend() will send it up afresh. - this.confirmedRoomSubscriptions.delete(roomId); - } - /** - * Get the room index data for a list. - * @param key - The list key - * @returns The list data which contains the rooms in this list - */ - getListData(key) { - const data = this.lists.get(key); - if (!data) { - return null; - } - return { - joinedCount: data.joinedCount, - roomIndexToRoomId: Object.assign({}, data.roomIndexToRoomId), - }; - } - /** - * Get the full request list parameters for a list index. This function is provided for callers to use - * in conjunction with setList to update fields on an existing list. - * @param key - The list key to get the params for. - * @returns A copy of the list params or undefined. - */ - getListParams(key) { - const params = this.lists.get(key); - if (!params) { - return null; - } - return params.getList(true); - } - /** - * Set new ranges for an existing list. Calling this function when _only_ the ranges have changed - * is more efficient than calling setList(index,list) as this function won't resend sticky params, - * whereas setList always will. - * @param key - The list key to modify - * @param ranges - The new ranges to apply. - * @returns A promise which resolves to the transaction ID when it has been received down sync - * (or rejects with the transaction ID if the action was not applied e.g the request was cancelled - * immediately after sending, in which case the action will be applied in the subsequent request) - */ - setListRanges(key, ranges) { - const list = this.lists.get(key); - if (!list) { - return Promise.reject(new Error("no list with key " + key)); - } - list.updateListRange(ranges); - return this.resend(); - } - /** - * Add or replace a list. Calling this function will interrupt the /sync request to resend new - * lists. - * @param key - The key to modify - * @param list - The new list parameters. - * @returns A promise which resolves to the transaction ID when it has been received down sync - * (or rejects with the transaction ID if the action was not applied e.g the request was cancelled - * immediately after sending, in which case the action will be applied in the subsequent request) - */ - setList(key, list) { - const existingList = this.lists.get(key); - if (existingList) { - existingList.replaceList(list); - this.lists.set(key, existingList); - } - else { - this.lists.set(key, new SlidingList(list)); - } - this.listModifiedCount += 1; - return this.resend(); - } - /** - * Get the room subscriptions for the sync API. - * @returns A copy of the desired room subscriptions. - */ - getRoomSubscriptions() { - return new Set(Array.from(this.desiredRoomSubscriptions)); - } - /** - * Modify the room subscriptions for the sync API. Calling this function will interrupt the - * /sync request to resend new subscriptions. If the /sync stream has not started, this will - * prepare the room subscriptions for when start() is called. - * @param s - The new desired room subscriptions. - * @returns A promise which resolves to the transaction ID when it has been received down sync - * (or rejects with the transaction ID if the action was not applied e.g the request was cancelled - * immediately after sending, in which case the action will be applied in the subsequent request) - */ - modifyRoomSubscriptions(s) { - this.desiredRoomSubscriptions = s; - return this.resend(); - } - /** - * Modify which events to retrieve for room subscriptions. Invalidates all room subscriptions - * such that they will be sent up afresh. - * @param rs - The new room subscription fields to fetch. - * @returns A promise which resolves to the transaction ID when it has been received down sync - * (or rejects with the transaction ID if the action was not applied e.g the request was cancelled - * immediately after sending, in which case the action will be applied in the subsequent request) - */ - modifyRoomSubscriptionInfo(rs) { - this.roomSubscriptionInfo = rs; - this.confirmedRoomSubscriptions = new Set(); - return this.resend(); - } - /** - * Register an extension to send with the /sync request. - * @param ext - The extension to register. - */ - registerExtension(ext) { - if (this.extensions[ext.name()]) { - throw new Error(`registerExtension: ${ext.name()} already exists as an extension`); - } - this.extensions[ext.name()] = ext; - } - getExtensionRequest(isInitial) { - const ext = {}; - Object.keys(this.extensions).forEach((extName) => { - ext[extName] = this.extensions[extName].onRequest(isInitial); - }); - return ext; - } - onPreExtensionsResponse(ext) { - Object.keys(ext).forEach((extName) => { - if (this.extensions[extName].when() == ExtensionState.PreProcess) { - this.extensions[extName].onResponse(ext[extName]); - } - }); - } - onPostExtensionsResponse(ext) { - Object.keys(ext).forEach((extName) => { - if (this.extensions[extName].when() == ExtensionState.PostProcess) { - this.extensions[extName].onResponse(ext[extName]); - } - }); - } - /** - * Invoke all attached room data listeners. - * @param roomId - The room which received some data. - * @param roomData - The raw sliding sync response JSON. - */ - invokeRoomDataListeners(roomId, roomData) { - if (!roomData.required_state) { - roomData.required_state = []; - } - if (!roomData.timeline) { - roomData.timeline = []; - } - this.emit(SlidingSyncEvent.RoomData, roomId, roomData); - } - /** - * Invoke all attached lifecycle listeners. - * @param state - The Lifecycle state - * @param resp - The raw sync response JSON - * @param err - Any error that occurred when making the request e.g. network errors. - */ - invokeLifecycleListeners(state, resp, err) { - this.emit(SlidingSyncEvent.Lifecycle, state, resp, err); - } - shiftRight(listKey, hi, low) { - const list = this.lists.get(listKey); - if (!list) { - return; - } - // l h - // 0,1,2,3,4 <- before - // 0,1,2,2,3 <- after, hi is deleted and low is duplicated - for (let i = hi; i > low; i--) { - if (list.isIndexInRange(i)) { - list.roomIndexToRoomId[i] = list.roomIndexToRoomId[i - 1]; - } - } - } - shiftLeft(listKey, hi, low) { - const list = this.lists.get(listKey); - if (!list) { - return; - } - // l h - // 0,1,2,3,4 <- before - // 0,1,3,4,4 <- after, low is deleted and hi is duplicated - for (let i = low; i < hi; i++) { - if (list.isIndexInRange(i)) { - list.roomIndexToRoomId[i] = list.roomIndexToRoomId[i + 1]; - } - } - } - removeEntry(listKey, index) { - const list = this.lists.get(listKey); - if (!list) { - return; - } - // work out the max index - let max = -1; - for (const n in list.roomIndexToRoomId) { - if (Number(n) > max) { - max = Number(n); - } - } - if (max < 0 || index > max) { - return; - } - // Everything higher than the gap needs to be shifted left. - this.shiftLeft(listKey, max, index); - delete list.roomIndexToRoomId[max]; - } - addEntry(listKey, index) { - const list = this.lists.get(listKey); - if (!list) { - return; - } - // work out the max index - let max = -1; - for (const n in list.roomIndexToRoomId) { - if (Number(n) > max) { - max = Number(n); - } - } - if (max < 0 || index > max) { - return; - } - // Everything higher than the gap needs to be shifted right, +1 so we don't delete the highest element - this.shiftRight(listKey, max + 1, index); - } - processListOps(list, listKey) { - let gapIndex = -1; - const listData = this.lists.get(listKey); - if (!listData) { - return; - } - list.ops.forEach((op) => { - if (!listData) { - return; - } - switch (op.op) { - case "DELETE": { - logger_1.logger.debug("DELETE", listKey, op.index, ";"); - delete listData.roomIndexToRoomId[op.index]; - if (gapIndex !== -1) { - // we already have a DELETE operation to process, so process it. - this.removeEntry(listKey, gapIndex); - } - gapIndex = op.index; - break; - } - case "INSERT": { - logger_1.logger.debug("INSERT", listKey, op.index, op.room_id, ";"); - if (listData.roomIndexToRoomId[op.index]) { - // something is in this space, shift items out of the way - if (gapIndex < 0) { - // we haven't been told where to shift from, so make way for a new room entry. - this.addEntry(listKey, op.index); - } - else if (gapIndex > op.index) { - // the gap is further down the list, shift every element to the right - // starting at the gap so we can just shift each element in turn: - // [A,B,C,_] gapIndex=3, op.index=0 - // [A,B,C,C] i=3 - // [A,B,B,C] i=2 - // [A,A,B,C] i=1 - // Terminate. We'll assign into op.index next. - this.shiftRight(listKey, gapIndex, op.index); - } - else if (gapIndex < op.index) { - // the gap is further up the list, shift every element to the left - // starting at the gap so we can just shift each element in turn - this.shiftLeft(listKey, op.index, gapIndex); - } - } - // forget the gap, we don't need it anymore. This is outside the check for - // a room being present in this index position because INSERTs always universally - // forget the gap, not conditionally based on the presence of a room in the INSERT - // position. Without this, DELETE 0; INSERT 0; would do the wrong thing. - gapIndex = -1; - listData.roomIndexToRoomId[op.index] = op.room_id; - break; - } - case "INVALIDATE": { - const startIndex = op.range[0]; - for (let i = startIndex; i <= op.range[1]; i++) { - delete listData.roomIndexToRoomId[i]; - } - logger_1.logger.debug("INVALIDATE", listKey, op.range[0], op.range[1], ";"); - break; - } - case "SYNC": { - const startIndex = op.range[0]; - for (let i = startIndex; i <= op.range[1]; i++) { - const roomId = op.room_ids[i - startIndex]; - if (!roomId) { - break; // we are at the end of list - } - listData.roomIndexToRoomId[i] = roomId; - } - logger_1.logger.debug("SYNC", listKey, op.range[0], op.range[1], (op.room_ids || []).join(" "), ";"); - break; - } - } - }); - if (gapIndex !== -1) { - // we already have a DELETE operation to process, so process it - // Everything higher than the gap needs to be shifted left. - this.removeEntry(listKey, gapIndex); - } - } - /** - * Resend a Sliding Sync request. Used when something has changed in the request. Resolves with - * the transaction ID of this request on success. Rejects with the transaction ID of this request - * on failure. - */ - resend() { - var _a; - if (this.needsResend && this.txnIdDefers.length > 0) { - // we already have a resend queued, so just return the same promise - return this.txnIdDefers[this.txnIdDefers.length - 1].promise; - } - this.needsResend = true; - this.txnId = this.client.makeTxnId(); - const d = (0, utils_1.defer)(); - this.txnIdDefers.push(Object.assign(Object.assign({}, d), { txnId: this.txnId })); - (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.abort(); - this.abortController = new AbortController(); - return d.promise; - } - resolveTransactionDefers(txnId) { - if (!txnId) { - return; - } - // find the matching index - let txnIndex = -1; - for (let i = 0; i < this.txnIdDefers.length; i++) { - if (this.txnIdDefers[i].txnId === txnId) { - txnIndex = i; - break; - } - } - if (txnIndex === -1) { - // this shouldn't happen; we shouldn't be seeing txn_ids for things we don't know about, - // whine about it. - logger_1.logger.warn(`resolveTransactionDefers: seen ${txnId} but it isn't a pending txn, ignoring.`); - return; - } - // This list is sorted in time, so if the input txnId ACKs in the middle of this array, - // then everything before it that hasn't been ACKed yet never will and we should reject them. - for (let i = 0; i < txnIndex; i++) { - this.txnIdDefers[i].reject(this.txnIdDefers[i].txnId); - } - this.txnIdDefers[txnIndex].resolve(txnId); - // clear out settled promises, including the one we resolved. - this.txnIdDefers = this.txnIdDefers.slice(txnIndex + 1); - } - /** - * Stop syncing with the server. - */ - stop() { - var _a; - this.terminated = true; - (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.abort(); - // remove all listeners so things can be GC'd - this.removeAllListeners(SlidingSyncEvent.Lifecycle); - this.removeAllListeners(SlidingSyncEvent.List); - this.removeAllListeners(SlidingSyncEvent.RoomData); - } - /** - * Re-setup this connection e.g in the event of an expired session. - */ - resetup() { - var _a; - logger_1.logger.warn("SlidingSync: resetting connection info"); - // any pending txn ID defers will be forgotten already by the server, so clear them out - this.txnIdDefers.forEach((d) => { - d.reject(d.txnId); - }); - this.txnIdDefers = []; - // resend sticky params and de-confirm all subscriptions - this.lists.forEach((l) => { - l.setModified(true); - }); - this.confirmedRoomSubscriptions = new Set(); // leave desired ones alone though! - // reset the connection as we might be wedged - this.needsResend = true; - (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.abort(); - this.abortController = new AbortController(); - } - /** - * Start syncing with the server. Blocks until stopped. - */ - start() { - return __awaiter(this, void 0, void 0, function* () { - this.abortController = new AbortController(); - let currentPos; - while (!this.terminated) { - this.needsResend = false; - let doNotUpdateList = false; - let resp; - try { - const listModifiedCount = this.listModifiedCount; - const reqLists = {}; - this.lists.forEach((l, key) => { - reqLists[key] = l.getList(false); - }); - const reqBody = { - lists: reqLists, - pos: currentPos, - timeout: this.timeoutMS, - clientTimeout: this.timeoutMS + BUFFER_PERIOD_MS, - extensions: this.getExtensionRequest(currentPos === undefined), - }; - // check if we are (un)subscribing to a room and modify request this one time for it - const newSubscriptions = difference(this.desiredRoomSubscriptions, this.confirmedRoomSubscriptions); - const unsubscriptions = difference(this.confirmedRoomSubscriptions, this.desiredRoomSubscriptions); - if (unsubscriptions.size > 0) { - reqBody.unsubscribe_rooms = Array.from(unsubscriptions); - } - if (newSubscriptions.size > 0) { - reqBody.room_subscriptions = {}; - for (const roomId of newSubscriptions) { - const customSubName = this.roomIdToCustomSubscription.get(roomId); - let sub = this.roomSubscriptionInfo; - if (customSubName && this.customSubscriptions.has(customSubName)) { - sub = this.customSubscriptions.get(customSubName); - } - reqBody.room_subscriptions[roomId] = sub; - } - } - if (this.txnId) { - reqBody.txn_id = this.txnId; - this.txnId = null; - } - this.pendingReq = this.client.slidingSync(reqBody, this.proxyBaseUrl, this.abortController.signal); - resp = yield this.pendingReq; - currentPos = resp.pos; - // update what we think we're subscribed to. - for (const roomId of newSubscriptions) { - this.confirmedRoomSubscriptions.add(roomId); - } - for (const roomId of unsubscriptions) { - this.confirmedRoomSubscriptions.delete(roomId); - } - if (listModifiedCount !== this.listModifiedCount) { - // the lists have been modified whilst we were waiting for 'await' to return, but the abort() - // call did nothing. It is NOT SAFE to modify the list array now. We'll process the response but - // not update list pointers. - logger_1.logger.debug("list modified during await call, not updating list"); - doNotUpdateList = true; - } - // mark all these lists as having been sent as sticky so we don't keep sending sticky params - this.lists.forEach((l) => { - l.setModified(false); - }); - // set default empty values so we don't need to null check - resp.lists = resp.lists || {}; - resp.rooms = resp.rooms || {}; - resp.extensions = resp.extensions || {}; - Object.keys(resp.lists).forEach((key) => { - const list = this.lists.get(key); - if (!list || !resp) { - return; - } - list.joinedCount = resp.lists[key].count; - }); - this.invokeLifecycleListeners(SlidingSyncState.RequestFinished, resp); - } - catch (err) { - if (err.httpStatus) { - this.invokeLifecycleListeners(SlidingSyncState.RequestFinished, null, err); - if (err.httpStatus === 400) { - // session probably expired TODO: assign an errcode - // so drop state and re-request - this.resetup(); - currentPos = undefined; - yield (0, utils_1.sleep)(50); // in case the 400 was for something else; don't tightloop - continue; - } // else fallthrough to generic error handling - } - else if (this.needsResend || err.name === "AbortError") { - continue; // don't sleep as we caused this error by abort()ing the request. - } - logger_1.logger.error(err); - yield (0, utils_1.sleep)(5000); - } - if (!resp) { - continue; - } - this.onPreExtensionsResponse(resp.extensions); - Object.keys(resp.rooms).forEach((roomId) => { - this.invokeRoomDataListeners(roomId, resp.rooms[roomId]); - }); - const listKeysWithUpdates = new Set(); - if (!doNotUpdateList) { - for (const [key, list] of Object.entries(resp.lists)) { - list.ops = list.ops || []; - if (list.ops.length > 0) { - listKeysWithUpdates.add(key); - } - this.processListOps(list, key); - } - } - this.invokeLifecycleListeners(SlidingSyncState.Complete, resp); - this.onPostExtensionsResponse(resp.extensions); - listKeysWithUpdates.forEach((listKey) => { - const list = this.lists.get(listKey); - if (!list) { - return; - } - this.emit(SlidingSyncEvent.List, listKey, list.joinedCount, Object.assign({}, list.roomIndexToRoomId)); - }); - this.resolveTransactionDefers(resp.txn_id); - } - }); - } -} -exports.SlidingSync = SlidingSync; -const difference = (setA, setB) => { - const diff = new Set(setA); - for (const elem of setB) { - diff.delete(elem); - } - return diff; -}; - -},{"./logger":374,"./models/typed-event-emitter":395,"./utils":416}],408:[function(require,module,exports){ -"use strict"; -/* -Copyright 2017 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.LocalIndexedDBStoreBackend = void 0; -const sync_accumulator_1 = require("../sync-accumulator"); -const utils = __importStar(require("../utils")); -const IndexedDBHelpers = __importStar(require("../indexeddb-helpers")); -const logger_1 = require("../logger"); -const DB_MIGRATIONS = [ - (db) => { - // Make user store, clobber based on user ID. (userId property of User objects) - db.createObjectStore("users", { keyPath: ["userId"] }); - // Make account data store, clobber based on event type. - // (event.type property of MatrixEvent objects) - db.createObjectStore("accountData", { keyPath: ["type"] }); - // Make /sync store (sync tokens, room data, etc), always clobber (const key). - db.createObjectStore("sync", { keyPath: ["clobber"] }); - }, - (db) => { - const oobMembersStore = db.createObjectStore("oob_membership_events", { - keyPath: ["room_id", "state_key"], - }); - oobMembersStore.createIndex("room", "room_id"); - }, - (db) => { - db.createObjectStore("client_options", { keyPath: ["clobber"] }); - }, - (db) => { - db.createObjectStore("to_device_queue", { autoIncrement: true }); - }, - // Expand as needed. -]; -const VERSION = DB_MIGRATIONS.length; -/** - * Helper method to collect results from a Cursor and promiseify it. - * @param store - The store to perform openCursor on. - * @param keyRange - Optional key range to apply on the cursor. - * @param resultMapper - A function which is repeatedly called with a - * Cursor. - * Return the data you want to keep. - * @returns Promise which resolves to an array of whatever you returned from - * resultMapper. - */ -function selectQuery(store, keyRange, resultMapper) { - const query = store.openCursor(keyRange); - return new Promise((resolve, reject) => { - const results = []; - query.onerror = () => { - reject(new Error("Query failed: " + query.error)); - }; - // collect results - query.onsuccess = () => { - const cursor = query.result; - if (!cursor) { - resolve(results); - return; // end of results - } - results.push(resultMapper(cursor)); - cursor.continue(); - }; - }); -} -function txnAsPromise(txn) { - return new Promise((resolve, reject) => { - txn.oncomplete = function (event) { - resolve(event); - }; - txn.onerror = function () { - reject(txn.error); - }; - }); -} -function reqAsEventPromise(req) { - return new Promise((resolve, reject) => { - req.onsuccess = function (event) { - resolve(event); - }; - req.onerror = function () { - reject(req.error); - }; - }); -} -function reqAsPromise(req) { - return new Promise((resolve, reject) => { - req.onsuccess = () => resolve(req); - req.onerror = (err) => reject(err); - }); -} -function reqAsCursorPromise(req) { - return reqAsEventPromise(req).then((event) => req.result); -} -class LocalIndexedDBStoreBackend { - static exists(indexedDB, dbName) { - dbName = "matrix-js-sdk:" + (dbName || "default"); - return IndexedDBHelpers.exists(indexedDB, dbName); - } - /** - * Does the actual reading from and writing to the indexeddb - * - * Construct a new Indexed Database store backend. This requires a call to - * `connect()` before this store can be used. - * @param indexedDB - The Indexed DB interface e.g - * `window.indexedDB` - * @param dbName - Optional database name. The same name must be used - * to open the same database. - */ - constructor(indexedDB, dbName = "default") { - this.indexedDB = indexedDB; - this.disconnected = true; - this._isNewlyCreated = false; - this.pendingUserPresenceData = []; - this.dbName = "matrix-js-sdk:" + dbName; - this.syncAccumulator = new sync_accumulator_1.SyncAccumulator(); - } - /** - * Attempt to connect to the database. This can fail if the user does not - * grant permission. - * @returns Promise which resolves if successfully connected. - */ - connect(onClose) { - if (!this.disconnected) { - logger_1.logger.log(`LocalIndexedDBStoreBackend.connect: already connected or connecting`); - return Promise.resolve(); - } - this.disconnected = false; - logger_1.logger.log(`LocalIndexedDBStoreBackend.connect: connecting...`); - const req = this.indexedDB.open(this.dbName, VERSION); - req.onupgradeneeded = (ev) => { - const db = req.result; - const oldVersion = ev.oldVersion; - logger_1.logger.log(`LocalIndexedDBStoreBackend.connect: upgrading from ${oldVersion}`); - if (oldVersion < 1) { - // The database did not previously exist - this._isNewlyCreated = true; - } - DB_MIGRATIONS.forEach((migration, index) => { - if (oldVersion <= index) - migration(db); - }); - }; - req.onblocked = () => { - logger_1.logger.log(`can't yet open LocalIndexedDBStoreBackend because it is open elsewhere`); - }; - logger_1.logger.log(`LocalIndexedDBStoreBackend.connect: awaiting connection...`); - return reqAsEventPromise(req).then(() => __awaiter(this, void 0, void 0, function* () { - logger_1.logger.log(`LocalIndexedDBStoreBackend.connect: connected`); - this.db = req.result; - // add a poorly-named listener for when deleteDatabase is called - // so we can close our db connections. - this.db.onversionchange = () => { - var _a; - (_a = this.db) === null || _a === void 0 ? void 0 : _a.close(); // this does not call onclose - this.disconnected = true; - this.db = undefined; - onClose === null || onClose === void 0 ? void 0 : onClose(); - }; - this.db.onclose = () => { - this.disconnected = true; - this.db = undefined; - onClose === null || onClose === void 0 ? void 0 : onClose(); - }; - yield this.init(); - })); - } - /** @returns whether or not the database was newly created in this session. */ - isNewlyCreated() { - return Promise.resolve(this._isNewlyCreated); - } - /** - * Having connected, load initial data from the database and prepare for use - * @returns Promise which resolves on success - */ - init() { - return Promise.all([this.loadAccountData(), this.loadSyncData()]).then(([accountData, syncData]) => { - logger_1.logger.log(`LocalIndexedDBStoreBackend: loaded initial data`); - this.syncAccumulator.accumulate({ - next_batch: syncData.nextBatch, - rooms: syncData.roomsData, - account_data: { - events: accountData, - }, - }, true); - }); - } - /** - * Returns the out-of-band membership events for this room that - * were previously loaded. - * @returns the events, potentially an empty array if OOB loading didn't yield any new members - * @returns in case the members for this room haven't been stored yet - */ - getOutOfBandMembers(roomId) { - return new Promise((resolve, reject) => { - const tx = this.db.transaction(["oob_membership_events"], "readonly"); - const store = tx.objectStore("oob_membership_events"); - const roomIndex = store.index("room"); - const range = IDBKeyRange.only(roomId); - const request = roomIndex.openCursor(range); - const membershipEvents = []; - // did we encounter the oob_written marker object - // amongst the results? That means OOB member - // loading already happened for this room - // but there were no members to persist as they - // were all known already - let oobWritten = false; - request.onsuccess = () => { - const cursor = request.result; - if (!cursor) { - // Unknown room - if (!membershipEvents.length && !oobWritten) { - return resolve(null); - } - return resolve(membershipEvents); - } - const record = cursor.value; - if (record.oob_written) { - oobWritten = true; - } - else { - membershipEvents.push(record); - } - cursor.continue(); - }; - request.onerror = (err) => { - reject(err); - }; - }).then((events) => { - logger_1.logger.log(`LL: got ${events === null || events === void 0 ? void 0 : events.length} membershipEvents from storage for room ${roomId} ...`); - return events; - }); - } - /** - * Stores the out-of-band membership events for this room. Note that - * it still makes sense to store an empty array as the OOB status for the room is - * marked as fetched, and getOutOfBandMembers will return an empty array instead of null - * @param membershipEvents - the membership events to store - */ - setOutOfBandMembers(roomId, membershipEvents) { - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.log(`LL: backend about to store ${membershipEvents.length}` + ` members for ${roomId}`); - const tx = this.db.transaction(["oob_membership_events"], "readwrite"); - const store = tx.objectStore("oob_membership_events"); - membershipEvents.forEach((e) => { - store.put(e); - }); - // aside from all the events, we also write a marker object to the store - // to mark the fact that OOB members have been written for this room. - // It's possible that 0 members need to be written as all where previously know - // but we still need to know whether to return null or [] from getOutOfBandMembers - // where null means out of band members haven't been stored yet for this room - const markerObject = { - room_id: roomId, - oob_written: true, - state_key: 0, - }; - store.put(markerObject); - yield txnAsPromise(tx); - logger_1.logger.log(`LL: backend done storing for ${roomId}!`); - }); - } - clearOutOfBandMembers(roomId) { - return __awaiter(this, void 0, void 0, function* () { - // the approach to delete all members for a room - // is to get the min and max state key from the index - // for that room, and then delete between those - // keys in the store. - // this should be way faster than deleting every member - // individually for a large room. - const readTx = this.db.transaction(["oob_membership_events"], "readonly"); - const store = readTx.objectStore("oob_membership_events"); - const roomIndex = store.index("room"); - const roomRange = IDBKeyRange.only(roomId); - const minStateKeyProm = reqAsCursorPromise(roomIndex.openKeyCursor(roomRange, "next")).then((cursor) => (cursor === null || cursor === void 0 ? void 0 : cursor.primaryKey)[1]); - const maxStateKeyProm = reqAsCursorPromise(roomIndex.openKeyCursor(roomRange, "prev")).then((cursor) => (cursor === null || cursor === void 0 ? void 0 : cursor.primaryKey)[1]); - const [minStateKey, maxStateKey] = yield Promise.all([minStateKeyProm, maxStateKeyProm]); - const writeTx = this.db.transaction(["oob_membership_events"], "readwrite"); - const writeStore = writeTx.objectStore("oob_membership_events"); - const membersKeyRange = IDBKeyRange.bound([roomId, minStateKey], [roomId, maxStateKey]); - logger_1.logger.log(`LL: Deleting all users + marker in storage for room ${roomId}, with key range:`, [roomId, minStateKey], [roomId, maxStateKey]); - yield reqAsPromise(writeStore.delete(membersKeyRange)); - }); - } - /** - * Clear the entire database. This should be used when logging out of a client - * to prevent mixing data between accounts. - * @returns Resolved when the database is cleared. - */ - clearDatabase() { - return new Promise((resolve) => { - logger_1.logger.log(`Removing indexeddb instance: ${this.dbName}`); - const req = this.indexedDB.deleteDatabase(this.dbName); - req.onblocked = () => { - logger_1.logger.log(`can't yet delete indexeddb ${this.dbName} because it is open elsewhere`); - }; - req.onerror = () => { - // in firefox, with indexedDB disabled, this fails with a - // DOMError. We treat this as non-fatal, so that we can still - // use the app. - logger_1.logger.warn(`unable to delete js-sdk store indexeddb: ${req.error}`); - resolve(); - }; - req.onsuccess = () => { - logger_1.logger.log(`Removed indexeddb instance: ${this.dbName}`); - resolve(); - }; - }); - } - /** - * @param copy - If false, the data returned is from internal - * buffers and must not be mutated. Otherwise, a copy is made before - * returning such that the data can be safely mutated. Default: true. - * - * @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(copy = true) { - const data = this.syncAccumulator.getJSON(); - if (!data.nextBatch) - return Promise.resolve(null); - if (copy) { - // We must deep copy the stored data so that the /sync processing code doesn't - // corrupt the internal state of the sync accumulator (it adds non-clonable keys) - return Promise.resolve(utils.deepCopy(data)); - } - else { - return Promise.resolve(data); - } - } - getNextBatchToken() { - return Promise.resolve(this.syncAccumulator.getNextBatchToken()); - } - setSyncData(syncData) { - return Promise.resolve().then(() => { - this.syncAccumulator.accumulate(syncData); - }); - } - /** - * Sync users and all accumulated sync data to the database. - * If a previous sync is in flight, the new data will be added to the - * next sync and the current sync's promise will be returned. - * @param userTuples - The user tuples - * @returns Promise which resolves if the data was persisted. - */ - syncToDatabase(userTuples) { - return __awaiter(this, void 0, void 0, function* () { - if (this.syncToDatabasePromise) { - logger_1.logger.warn("Skipping syncToDatabase() as persist already in flight"); - this.pendingUserPresenceData.push(...userTuples); - return this.syncToDatabasePromise; - } - userTuples.unshift(...this.pendingUserPresenceData); - this.syncToDatabasePromise = this.doSyncToDatabase(userTuples); - return this.syncToDatabasePromise; - }); - } - doSyncToDatabase(userTuples) { - return __awaiter(this, void 0, void 0, function* () { - try { - const syncData = this.syncAccumulator.getJSON(true); - yield Promise.all([ - this.persistUserPresenceEvents(userTuples), - this.persistAccountData(syncData.accountData), - this.persistSyncData(syncData.nextBatch, syncData.roomsData), - ]); - } - finally { - this.syncToDatabasePromise = undefined; - } - }); - } - /** - * Persist rooms /sync data along with the next batch token. - * @param nextBatch - The next_batch /sync value. - * @param roomsData - The 'rooms' /sync data from a SyncAccumulator - * @returns Promise which resolves if the data was persisted. - */ - persistSyncData(nextBatch, roomsData) { - logger_1.logger.log("Persisting sync data up to", nextBatch); - return utils.promiseTry(() => { - const txn = this.db.transaction(["sync"], "readwrite"); - const store = txn.objectStore("sync"); - store.put({ - clobber: "-", - nextBatch, - roomsData, - }); // put == UPSERT - return txnAsPromise(txn).then(() => { - logger_1.logger.log("Persisted sync data up to", nextBatch); - }); - }); - } - /** - * Persist a list of account data events. Events with the same 'type' will - * be replaced. - * @param accountData - An array of raw user-scoped account data events - * @returns Promise which resolves if the events were persisted. - */ - persistAccountData(accountData) { - return utils.promiseTry(() => { - const txn = this.db.transaction(["accountData"], "readwrite"); - const store = txn.objectStore("accountData"); - for (const event of accountData) { - store.put(event); // put == UPSERT - } - return txnAsPromise(txn).then(); - }); - } - /** - * Persist a list of [user id, presence event] they are for. - * Users with the same 'userId' will be replaced. - * Presence events should be the event in its raw form (not the Event - * object) - * @param tuples - An array of [userid, event] tuples - * @returns Promise which resolves if the users were persisted. - */ - persistUserPresenceEvents(tuples) { - return utils.promiseTry(() => { - const txn = this.db.transaction(["users"], "readwrite"); - const store = txn.objectStore("users"); - for (const tuple of tuples) { - store.put({ - userId: tuple[0], - event: tuple[1], - }); // put == UPSERT - } - return txnAsPromise(txn).then(); - }); - } - /** - * Load all user presence events from the database. This is not cached. - * FIXME: It would probably be more sensible to store the events in the - * sync. - * @returns A list of presence events in their raw form. - */ - getUserPresenceEvents() { - return utils.promiseTry(() => { - const txn = this.db.transaction(["users"], "readonly"); - const store = txn.objectStore("users"); - return selectQuery(store, undefined, (cursor) => { - return [cursor.value.userId, cursor.value.event]; - }); - }); - } - /** - * Load all the account data events from the database. This is not cached. - * @returns A list of raw global account events. - */ - loadAccountData() { - logger_1.logger.log(`LocalIndexedDBStoreBackend: loading account data...`); - return utils.promiseTry(() => { - const txn = this.db.transaction(["accountData"], "readonly"); - const store = txn.objectStore("accountData"); - return selectQuery(store, undefined, (cursor) => { - return cursor.value; - }).then((result) => { - logger_1.logger.log(`LocalIndexedDBStoreBackend: loaded account data`); - return result; - }); - }); - } - /** - * Load the sync data from the database. - * @returns An object with "roomsData" and "nextBatch" keys. - */ - loadSyncData() { - logger_1.logger.log(`LocalIndexedDBStoreBackend: loading sync data...`); - return utils.promiseTry(() => { - const txn = this.db.transaction(["sync"], "readonly"); - const store = txn.objectStore("sync"); - return selectQuery(store, undefined, (cursor) => { - return cursor.value; - }).then((results) => { - logger_1.logger.log(`LocalIndexedDBStoreBackend: loaded sync data`); - if (results.length > 1) { - logger_1.logger.warn("loadSyncData: More than 1 sync row found."); - } - return results.length > 0 ? results[0] : {}; - }); - }); - } - getClientOptions() { - return Promise.resolve().then(() => { - const txn = this.db.transaction(["client_options"], "readonly"); - const store = txn.objectStore("client_options"); - return selectQuery(store, undefined, (cursor) => { - var _a; - return (_a = cursor.value) === null || _a === void 0 ? void 0 : _a.options; - }).then((results) => results[0]); - }); - } - storeClientOptions(options) { - return __awaiter(this, void 0, void 0, function* () { - const txn = this.db.transaction(["client_options"], "readwrite"); - const store = txn.objectStore("client_options"); - store.put({ - clobber: "-", - options: options, - }); // put == UPSERT - yield txnAsPromise(txn); - }); - } - saveToDeviceBatches(batches) { - return __awaiter(this, void 0, void 0, function* () { - const txn = this.db.transaction(["to_device_queue"], "readwrite"); - const store = txn.objectStore("to_device_queue"); - for (const batch of batches) { - store.add(batch); - } - yield txnAsPromise(txn); - }); - } - getOldestToDeviceBatch() { - return __awaiter(this, void 0, void 0, function* () { - const txn = this.db.transaction(["to_device_queue"], "readonly"); - const store = txn.objectStore("to_device_queue"); - const cursor = yield reqAsCursorPromise(store.openCursor()); - if (!cursor) - return null; - const resultBatch = cursor.value; - return { - id: cursor.key, - txnId: resultBatch.txnId, - eventType: resultBatch.eventType, - batch: resultBatch.batch, - }; - }); - } - removeToDeviceBatch(id) { - return __awaiter(this, void 0, void 0, function* () { - const txn = this.db.transaction(["to_device_queue"], "readwrite"); - const store = txn.objectStore("to_device_queue"); - store.delete(id); - yield txnAsPromise(txn); - }); - } -} -exports.LocalIndexedDBStoreBackend = LocalIndexedDBStoreBackend; - -},{"../indexeddb-helpers":372,"../logger":374,"../sync-accumulator":413,"../utils":416}],409:[function(require,module,exports){ -"use strict"; -/* -Copyright 2017 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RemoteIndexedDBStoreBackend = void 0; -const logger_1 = require("../logger"); -const utils_1 = require("../utils"); -class RemoteIndexedDBStoreBackend { - /** - * An IndexedDB store backend where the actual backend sits in a web - * worker. - * - * Construct a new Indexed Database store backend. This requires a call to - * `connect()` before this store can be used. - * @param workerFactory - Factory which produces a Worker - * @param dbName - Optional database name. The same name must be used - * to open the same database. - */ - constructor(workerFactory, dbName) { - this.workerFactory = workerFactory; - this.dbName = dbName; - this.nextSeq = 0; - // The currently in-flight requests to the actual backend - this.inFlight = {}; // seq: promise - this.onWorkerMessage = (ev) => { - var _a; - const msg = ev.data; - if (msg.command == "closed") { - (_a = this.onClose) === null || _a === void 0 ? void 0 : _a.call(this); - } - else if (msg.command == "cmd_success" || msg.command == "cmd_fail") { - if (msg.seq === undefined) { - logger_1.logger.error("Got reply from worker with no seq"); - return; - } - const def = this.inFlight[msg.seq]; - if (def === undefined) { - logger_1.logger.error("Got reply for unknown seq " + msg.seq); - return; - } - delete this.inFlight[msg.seq]; - if (msg.command == "cmd_success") { - def.resolve(msg.result); - } - else { - const error = new Error(msg.error.message); - error.name = msg.error.name; - def.reject(error); - } - } - else { - logger_1.logger.warn("Unrecognised message from worker: ", msg); - } - }; - } - /** - * Attempt to connect to the database. This can fail if the user does not - * grant permission. - * @returns Promise which resolves if successfully connected. - */ - connect(onClose) { - this.onClose = onClose; - return this.ensureStarted().then(() => this.doCmd("connect")); - } - /** - * Clear the entire database. This should be used when logging out of a client - * to prevent mixing data between accounts. - * @returns Resolved when the database is cleared. - */ - clearDatabase() { - return this.ensureStarted().then(() => this.doCmd("clearDatabase")); - } - /** @returns whether or not the database was newly created in this session. */ - isNewlyCreated() { - return this.doCmd("isNewlyCreated"); - } - /** - * @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 this.doCmd("getSavedSync"); - } - getNextBatchToken() { - return this.doCmd("getNextBatchToken"); - } - setSyncData(syncData) { - return this.doCmd("setSyncData", [syncData]); - } - syncToDatabase(userTuples) { - return this.doCmd("syncToDatabase", [userTuples]); - } - /** - * Returns the out-of-band membership events for this room that - * were previously loaded. - * @returns the events, potentially an empty array if OOB loading didn't yield any new members - * @returns in case the members for this room haven't been stored yet - */ - getOutOfBandMembers(roomId) { - return this.doCmd("getOutOfBandMembers", [roomId]); - } - /** - * Stores the out-of-band membership events for this room. Note that - * it still makes sense to store an empty array as the OOB status for the room is - * marked as fetched, and getOutOfBandMembers will return an empty array instead of null - * @param membershipEvents - the membership events to store - * @returns when all members have been stored - */ - setOutOfBandMembers(roomId, membershipEvents) { - return this.doCmd("setOutOfBandMembers", [roomId, membershipEvents]); - } - clearOutOfBandMembers(roomId) { - return this.doCmd("clearOutOfBandMembers", [roomId]); - } - getClientOptions() { - return this.doCmd("getClientOptions"); - } - storeClientOptions(options) { - return this.doCmd("storeClientOptions", [options]); - } - /** - * Load all user presence events from the database. This is not cached. - * @returns A list of presence events in their raw form. - */ - getUserPresenceEvents() { - return this.doCmd("getUserPresenceEvents"); - } - saveToDeviceBatches(batches) { - return __awaiter(this, void 0, void 0, function* () { - return this.doCmd("saveToDeviceBatches", [batches]); - }); - } - getOldestToDeviceBatch() { - return __awaiter(this, void 0, void 0, function* () { - return this.doCmd("getOldestToDeviceBatch"); - }); - } - removeToDeviceBatch(id) { - return __awaiter(this, void 0, void 0, function* () { - return this.doCmd("removeToDeviceBatch", [id]); - }); - } - ensureStarted() { - if (!this.startPromise) { - this.worker = this.workerFactory(); - this.worker.onmessage = this.onWorkerMessage; - // tell the worker the db name. - this.startPromise = this.doCmd("setupWorker", [this.dbName]).then(() => { - logger_1.logger.log("IndexedDB worker is ready"); - }); - } - return this.startPromise; - } - doCmd(command, args) { - // wrap in a q so if the postMessage throws, - // the promise automatically gets rejected - return Promise.resolve().then(() => { - var _a; - const seq = this.nextSeq++; - const def = (0, utils_1.defer)(); - this.inFlight[seq] = def; - (_a = this.worker) === null || _a === void 0 ? void 0 : _a.postMessage({ command, seq, args }); - return def.promise; - }); - } -} -exports.RemoteIndexedDBStoreBackend = RemoteIndexedDBStoreBackend; - -},{"../logger":374,"../utils":416}],410:[function(require,module,exports){ -"use strict"; -/* -Copyright 2017 - 2021 Vector Creations Ltd - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.IndexedDBStore = void 0; -/* eslint-disable @babel/no-invalid-this */ -const memory_1 = require("./memory"); -const indexeddb_local_backend_1 = require("./indexeddb-local-backend"); -const indexeddb_remote_backend_1 = require("./indexeddb-remote-backend"); -const user_1 = require("../models/user"); -const event_1 = require("../models/event"); -const logger_1 = require("../logger"); -const typed_event_emitter_1 = require("../models/typed-event-emitter"); -/** - * This is an internal module. See {@link IndexedDBStore} for the public class. - */ -// If this value is too small we'll be writing very often which will cause -// noticeable stop-the-world pauses. If this value is too big we'll be writing -// so infrequently that the /sync size gets bigger on reload. Writing more -// often does not affect the length of the pause since the entire /sync -// response is persisted each time. -const WRITE_DELAY_MS = 1000 * 60 * 5; // once every 5 minutes -class IndexedDBStore extends memory_1.MemoryStore { - static exists(indexedDB, dbName) { - return indexeddb_local_backend_1.LocalIndexedDBStoreBackend.exists(indexedDB, dbName); - } - /** - * Construct a new Indexed Database store, which extends MemoryStore. - * - * This store functions like a MemoryStore except it periodically persists - * the contents of the store to an IndexedDB backend. - * - * All data is still kept in-memory but can be loaded from disk by calling - * `startup()`. This can make startup times quicker as a complete - * sync from the server is not required. This does not reduce memory usage as all - * the data is eagerly fetched when `startup()` is called. - * ``` - * let opts = { indexedDB: window.indexedDB, localStorage: window.localStorage }; - * let store = new IndexedDBStore(opts); - * await store.startup(); // load from indexed db - * let client = sdk.createClient({ - * store: store, - * }); - * client.startClient(); - * client.on("sync", function(state, prevState, data) { - * if (state === "PREPARED") { - * console.log("Started up, now with go faster stripes!"); - * } - * }); - * ``` - * - * @param opts - Options object. - */ - constructor(opts) { - super(opts); - this.startedUp = false; - this.syncTs = 0; - // Records the last-modified-time of each user at the last point we saved - // the database, such that we can derive the set if users that have been - // modified since we last saved. - this.userModifiedMap = {}; // user_id : timestamp - this.emitter = new typed_event_emitter_1.TypedEventEmitter(); - this.on = this.emitter.on.bind(this.emitter); - this.onClose = () => { - this.emitter.emit("closed"); - }; - /** - * @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. - */ - this.getSavedSync = this.degradable(() => { - return this.backend.getSavedSync(); - }, "getSavedSync"); - /** @returns whether or not the database was newly created in this session. */ - this.isNewlyCreated = this.degradable(() => { - return this.backend.isNewlyCreated(); - }, "isNewlyCreated"); - /** - * @returns If there is a saved sync, the nextBatch token - * for this sync, otherwise null. - */ - this.getSavedSyncToken = this.degradable(() => { - return this.backend.getNextBatchToken(); - }, "getSavedSyncToken"); - /** - * Delete all data from this store. - * @returns Promise which resolves if the data was deleted from the database. - */ - this.deleteAllData = this.degradable(() => { - super.deleteAllData(); - return this.backend.clearDatabase().then(() => { - logger_1.logger.log("Deleted indexeddb data."); - }, (err) => { - logger_1.logger.error(`Failed to delete indexeddb data: ${err}`); - throw err; - }); - }); - this.reallySave = this.degradable(() => { - this.syncTs = Date.now(); // set now to guard against multi-writes - // work out changed users (this doesn't handle deletions but you - // can't 'delete' users as they are just presence events). - const userTuples = []; - for (const u of this.getUsers()) { - if (this.userModifiedMap[u.userId] === u.getLastModifiedTime()) - continue; - if (!u.events.presence) - continue; - userTuples.push([u.userId, u.events.presence.event]); - // note that we've saved this version of the user - this.userModifiedMap[u.userId] = u.getLastModifiedTime(); - } - return this.backend.syncToDatabase(userTuples); - }); - this.setSyncData = this.degradable((syncData) => { - return this.backend.setSyncData(syncData); - }, "setSyncData"); - /** - * Returns the out-of-band membership events for this room that - * were previously loaded. - * @returns the events, potentially an empty array if OOB loading didn't yield any new members - * @returns in case the members for this room haven't been stored yet - */ - this.getOutOfBandMembers = this.degradable((roomId) => { - return this.backend.getOutOfBandMembers(roomId); - }, "getOutOfBandMembers"); - /** - * Stores the out-of-band membership events for this room. Note that - * it still makes sense to store an empty array as the OOB status for the room is - * marked as fetched, and getOutOfBandMembers will return an empty array instead of null - * @param membershipEvents - the membership events to store - * @returns when all members have been stored - */ - this.setOutOfBandMembers = this.degradable((roomId, membershipEvents) => { - super.setOutOfBandMembers(roomId, membershipEvents); - return this.backend.setOutOfBandMembers(roomId, membershipEvents); - }, "setOutOfBandMembers"); - this.clearOutOfBandMembers = this.degradable((roomId) => { - super.clearOutOfBandMembers(roomId); - return this.backend.clearOutOfBandMembers(roomId); - }, "clearOutOfBandMembers"); - this.getClientOptions = this.degradable(() => { - return this.backend.getClientOptions(); - }, "getClientOptions"); - this.storeClientOptions = this.degradable((options) => { - super.storeClientOptions(options); - return this.backend.storeClientOptions(options); - }, "storeClientOptions"); - if (!opts.indexedDB) { - throw new Error("Missing required option: indexedDB"); - } - if (opts.workerFactory) { - this.backend = new indexeddb_remote_backend_1.RemoteIndexedDBStoreBackend(opts.workerFactory, opts.dbName); - } - else { - this.backend = new indexeddb_local_backend_1.LocalIndexedDBStoreBackend(opts.indexedDB, opts.dbName); - } - } - /** - * @returns Resolved when loaded from indexed db. - */ - startup() { - if (this.startedUp) { - logger_1.logger.log(`IndexedDBStore.startup: already started`); - return Promise.resolve(); - } - logger_1.logger.log(`IndexedDBStore.startup: connecting to backend`); - return this.backend - .connect(this.onClose) - .then(() => { - logger_1.logger.log(`IndexedDBStore.startup: loading presence events`); - return this.backend.getUserPresenceEvents(); - }) - .then((userPresenceEvents) => { - logger_1.logger.log(`IndexedDBStore.startup: processing presence events`); - userPresenceEvents.forEach(([userId, rawEvent]) => { - const u = new user_1.User(userId); - if (rawEvent) { - u.setPresenceEvent(new event_1.MatrixEvent(rawEvent)); - } - this.userModifiedMap[u.userId] = u.getLastModifiedTime(); - this.storeUser(u); - }); - this.startedUp = true; - }); - } - /** - * Whether this store would like to save its data - * Note that obviously whether the store wants to save or - * not could change between calling this function and calling - * save(). - * - * @returns True if calling save() will actually save - * (at the time this function is called). - */ - wantsSave() { - const now = Date.now(); - return now - this.syncTs > WRITE_DELAY_MS; - } - /** - * Possibly write data to the database. - * - * @param force - True to force a save to happen - * @returns Promise resolves after the write completes - * (or immediately if no write is performed) - */ - save(force = false) { - if (force || this.wantsSave()) { - return this.reallySave(); - } - return Promise.resolve(); - } - /** - * All member functions of `IndexedDBStore` that access the backend use this wrapper to - * watch for failures after initial store startup, including `QuotaExceededError` as - * free disk space changes, etc. - * - * When IndexedDB fails via any of these paths, we degrade this back to a `MemoryStore` - * in place so that the current operation and all future ones are in-memory only. - * - * @param func - The degradable work to do. - * @param fallback - The method name for fallback. - * @returns A wrapped member function. - */ - degradable(func, fallback) { - const fallbackFn = fallback ? super[fallback] : null; - return (...args) => __awaiter(this, void 0, void 0, function* () { - try { - return yield func.call(this, ...args); - } - catch (e) { - logger_1.logger.error("IndexedDBStore failure, degrading to MemoryStore", e); - this.emitter.emit("degraded", e); - try { - // We try to delete IndexedDB after degrading since this store is only a - // cache (the app will still function correctly without the data). - // It's possible that deleting repair IndexedDB for the next app load, - // potentially by making a little more space available. - logger_1.logger.log("IndexedDBStore trying to delete degraded data"); - yield this.backend.clearDatabase(); - logger_1.logger.log("IndexedDBStore delete after degrading succeeded"); - } - catch (e) { - logger_1.logger.warn("IndexedDBStore delete after degrading failed", e); - } - // Degrade the store from being an instance of `IndexedDBStore` to instead be - // an instance of `MemoryStore` so that future API calls use the memory path - // directly and skip IndexedDB entirely. This should be safe as - // `IndexedDBStore` already extends from `MemoryStore`, so we are making the - // store become its parent type in a way. The mutator methods of - // `IndexedDBStore` also maintain the state that `MemoryStore` uses (many are - // not overridden at all). - if (fallbackFn) { - return fallbackFn.call(this, ...args); - } - } - }); - } - // XXX: ideally these would be stored in indexeddb as part of the room but, - // we don't store rooms as such and instead accumulate entire sync responses atm. - getPendingEvents(roomId) { - const _super = Object.create(null, { - getPendingEvents: { get: () => super.getPendingEvents } - }); - return __awaiter(this, void 0, void 0, function* () { - if (!this.localStorage) - return _super.getPendingEvents.call(this, roomId); - const serialized = this.localStorage.getItem(pendingEventsKey(roomId)); - if (serialized) { - try { - return JSON.parse(serialized); - } - catch (e) { - logger_1.logger.error("Could not parse persisted pending events", e); - } - } - return []; - }); - } - setPendingEvents(roomId, events) { - const _super = Object.create(null, { - setPendingEvents: { get: () => super.setPendingEvents } - }); - return __awaiter(this, void 0, void 0, function* () { - if (!this.localStorage) - return _super.setPendingEvents.call(this, roomId, events); - if (events.length > 0) { - this.localStorage.setItem(pendingEventsKey(roomId), JSON.stringify(events)); - } - else { - this.localStorage.removeItem(pendingEventsKey(roomId)); - } - }); - } - saveToDeviceBatches(batches) { - return this.backend.saveToDeviceBatches(batches); - } - getOldestToDeviceBatch() { - return this.backend.getOldestToDeviceBatch(); - } - removeToDeviceBatch(id) { - return this.backend.removeToDeviceBatch(id); - } -} -exports.IndexedDBStore = IndexedDBStore; -/** - * @param roomId - ID of the current room - * @returns Storage key to retrieve pending events - */ -function pendingEventsKey(roomId) { - return `mx_pending_events_${roomId}`; -} - -},{"../logger":374,"../models/event":383,"../models/typed-event-emitter":395,"../models/user":396,"./indexeddb-local-backend":408,"./indexeddb-remote-backend":409,"./memory":411}],411:[function(require,module,exports){ -"use strict"; -/* -Copyright 2015 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MemoryStore = void 0; -const user_1 = require("../models/user"); -const room_state_1 = require("../models/room-state"); -const utils_1 = require("../utils"); -function isValidFilterId(filterId) { - const isValidStr = typeof filterId === "string" && - !!filterId && - filterId !== "undefined" && // exclude these as we've serialized undefined in localStorage before - filterId !== "null"; - return isValidStr || typeof filterId === "number"; -} -class MemoryStore { - /** - * Construct a new in-memory data store for the Matrix Client. - * @param opts - Config options - */ - constructor(opts = {}) { - this.rooms = {}; // roomId: Room - this.users = {}; // userId: User - this.syncToken = null; - // userId: { - // filterId: Filter - // } - this.filters = new utils_1.MapWithDefault(() => new Map()); - this.accountData = new Map(); // type: content - this.oobMembers = new Map(); // roomId: [member events] - this.pendingEvents = {}; - this.pendingToDeviceBatches = []; - this.nextToDeviceBatchId = 0; - /** - * Called when a room member in a room being tracked by this store has been - * updated. - */ - this.onRoomMember = (event, state, member) => { - if (member.membership === "invite") { - // We do NOT add invited members because people love to typo user IDs - // which would then show up in these lists (!) - return; - } - const user = this.users[member.userId] || new user_1.User(member.userId); - if (member.name) { - user.setDisplayName(member.name); - if (member.events.member) { - user.setRawDisplayName(member.events.member.getDirectionalContent().displayname); - } - } - if (member.events.member && member.events.member.getContent().avatar_url) { - user.setAvatarUrl(member.events.member.getContent().avatar_url); - } - this.users[user.userId] = user; - }; - this.localStorage = opts.localStorage; - } - /** - * Retrieve the token to stream from. - * @returns The token or null. - */ - getSyncToken() { - return this.syncToken; - } - /** @returns whether or not the database was newly created in this session. */ - isNewlyCreated() { - return Promise.resolve(true); - } - /** - * Set the token to stream from. - * @param token - The token to stream from. - */ - setSyncToken(token) { - this.syncToken = token; - } - /** - * Store the given room. - * @param room - The room to be stored. All properties must be stored. - */ - storeRoom(room) { - this.rooms[room.roomId] = room; - // add listeners for room member changes so we can keep the room member - // map up-to-date. - room.currentState.on(room_state_1.RoomStateEvent.Members, this.onRoomMember); - // add existing members - room.currentState.getMembers().forEach((m) => { - this.onRoomMember(null, room.currentState, m); - }); - } - /** - * Retrieve a room by its' room ID. - * @param roomId - The room ID. - * @returns The room or null. - */ - getRoom(roomId) { - return this.rooms[roomId] || null; - } - /** - * Retrieve all known rooms. - * @returns A list of rooms, which may be empty. - */ - getRooms() { - return Object.values(this.rooms); - } - /** - * Permanently delete a room. - */ - removeRoom(roomId) { - if (this.rooms[roomId]) { - this.rooms[roomId].currentState.removeListener(room_state_1.RoomStateEvent.Members, this.onRoomMember); - } - delete this.rooms[roomId]; - } - /** - * Retrieve a summary of all the rooms. - * @returns A summary of each room. - */ - getRoomSummaries() { - return Object.values(this.rooms).map(function (room) { - return room.summary; - }); - } - /** - * Store a User. - * @param user - The user to store. - */ - storeUser(user) { - this.users[user.userId] = user; - } - /** - * Retrieve a User by its' user ID. - * @param userId - The user ID. - * @returns The user or null. - */ - getUser(userId) { - return this.users[userId] || null; - } - /** - * Retrieve all known users. - * @returns A list of users, which may be empty. - */ - getUsers() { - return Object.values(this.users); - } - /** - * Retrieve scrollback for this room. - * @param room - The matrix room - * @param limit - The max number of old events to retrieve. - * @returns An array of objects which will be at most 'limit' - * length and at least 0. The objects are the raw event JSON. - */ - scrollback(room, limit) { - return []; - } - /** - * Store events for a room. The events have already been added to the timeline - * @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) { - // no-op because they've already been added to the room instance. - } - /** - * Store a filter. - */ - storeFilter(filter) { - if (!(filter === null || filter === void 0 ? void 0 : filter.userId) || !(filter === null || filter === void 0 ? void 0 : filter.filterId)) - return; - this.filters.getOrCreate(filter.userId).set(filter.filterId, filter); - } - /** - * Retrieve a filter. - * @returns A filter or null. - */ - getFilter(userId, filterId) { - var _a; - return ((_a = this.filters.get(userId)) === null || _a === void 0 ? void 0 : _a.get(filterId)) || null; - } - /** - * Retrieve a filter ID with the given name. - * @param filterName - The filter name. - * @returns The filter ID or null. - */ - getFilterIdByName(filterName) { - if (!this.localStorage) { - return null; - } - const key = "mxjssdk_memory_filter_" + filterName; - // XXX Storage.getItem doesn't throw ... - // or are we using something different - // than window.localStorage in some cases - // that does throw? - // that would be very naughty - try { - const value = this.localStorage.getItem(key); - if (isValidFilterId(value)) { - return value; - } - } - catch (e) { } - return null; - } - /** - * Set a filter name to ID mapping. - */ - setFilterIdByName(filterName, filterId) { - if (!this.localStorage) { - return; - } - const key = "mxjssdk_memory_filter_" + filterName; - try { - if (isValidFilterId(filterId)) { - this.localStorage.setItem(key, filterId); - } - else { - this.localStorage.removeItem(key); - } - } - catch (e) { } - } - /** - * Store user-scoped account data events. - * N.B. that account data only allows a single event per type, so multiple - * events with the same type will replace each other. - * @param events - The events to store. - */ - storeAccountDataEvents(events) { - events.forEach((event) => { - // MSC3391: an event with content of {} should be interpreted as deleted - const isDeleted = !Object.keys(event.getContent()).length; - if (isDeleted) { - this.accountData.delete(event.getType()); - } - else { - this.accountData.set(event.getType(), event); - } - }); - } - /** - * Get account data event by event type - * @param eventType - The event type being queried - * @returns the user account_data event of given type, if any - */ - getAccountData(eventType) { - return this.accountData.get(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 becase 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. - * @param force - True to force a save (but the memory - * store still can't save anything) - */ - save(force) { } - /** - * Startup does nothing as this store doesn't require starting up. - * @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. - * @returns An immediately resolved promise. - */ - deleteAllData() { - this.rooms = { - // roomId: Room - }; - this.users = { - // userId: User - }; - this.syncToken = null; - this.filters = new utils_1.MapWithDefault(() => new Map()); - this.accountData = new Map(); // type : content - return Promise.resolve(); - } - /** - * Returns the out-of-band membership events for this room that - * were previously loaded. - * @returns the events, potentially an empty array if OOB loading didn't yield any new members - * @returns in case the members for this room haven't been stored yet - */ - getOutOfBandMembers(roomId) { - return Promise.resolve(this.oobMembers.get(roomId) || null); - } - /** - * Stores the out-of-band membership events for this room. Note that - * it still makes sense to store an empty array as the OOB status for the room is - * marked as fetched, and getOutOfBandMembers will return an empty array instead of null - * @param membershipEvents - the membership events to store - * @returns when all members have been stored - */ - setOutOfBandMembers(roomId, membershipEvents) { - this.oobMembers.set(roomId, membershipEvents); - return Promise.resolve(); - } - clearOutOfBandMembers(roomId) { - this.oobMembers.delete(roomId); - return Promise.resolve(); - } - getClientOptions() { - return Promise.resolve(this.clientOptions); - } - storeClientOptions(options) { - this.clientOptions = Object.assign({}, options); - return Promise.resolve(); - } - getPendingEvents(roomId) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - return (_a = this.pendingEvents[roomId]) !== null && _a !== void 0 ? _a : []; - }); - } - setPendingEvents(roomId, events) { - return __awaiter(this, void 0, void 0, function* () { - this.pendingEvents[roomId] = events; - }); - } - saveToDeviceBatches(batches) { - for (const batch of batches) { - this.pendingToDeviceBatches.push({ - id: this.nextToDeviceBatchId++, - eventType: batch.eventType, - txnId: batch.txnId, - batch: batch.batch, - }); - } - return Promise.resolve(); - } - getOldestToDeviceBatch() { - return __awaiter(this, void 0, void 0, function* () { - if (this.pendingToDeviceBatches.length === 0) - return null; - return this.pendingToDeviceBatches[0]; - }); - } - removeToDeviceBatch(id) { - this.pendingToDeviceBatches = this.pendingToDeviceBatches.filter((batch) => batch.id !== id); - return Promise.resolve(); - } -} -exports.MemoryStore = MemoryStore; - -},{"../models/room-state":390,"../models/user":396,"../utils":416}],412:[function(require,module,exports){ -"use strict"; -/* -Copyright 2015 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.StubStore = void 0; -/** - * Construct a stub store. This does no-ops on most store methods. - */ -class StubStore { - constructor() { - this.accountData = new Map(); // stub - 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) { - return; - } - /** - * 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 []; - } - /** - * 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) { - return undefined; - } - /** - * 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() { } - /** - * 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(undefined); - } - storeClientOptions(options) { - return Promise.resolve(); - } - getPendingEvents(roomId) { - return __awaiter(this, void 0, void 0, function* () { - return []; - }); - } - setPendingEvents(roomId, events) { - return Promise.resolve(); - } - saveToDeviceBatches(batch) { - return __awaiter(this, void 0, void 0, function* () { - return Promise.resolve(); - }); - } - getOldestToDeviceBatch() { - return Promise.resolve(null); - } - removeToDeviceBatch(id) { - return __awaiter(this, void 0, void 0, function* () { - return Promise.resolve(); - }); - } -} -exports.StubStore = StubStore; - -},{}],413:[function(require,module,exports){ -"use strict"; -/* -Copyright 2017 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SyncAccumulator = exports.Category = void 0; -/** - * This is an internal module. See {@link SyncAccumulator} for the public class. - */ -const logger_1 = require("./logger"); -const utils_1 = require("./utils"); -const event_1 = require("./@types/event"); -const read_receipts_1 = require("./@types/read_receipts"); -const sync_1 = require("./@types/sync"); -/* eslint-enable camelcase */ -var Category; -(function (Category) { - Category["Invite"] = "invite"; - Category["Leave"] = "leave"; - Category["Join"] = "join"; -})(Category = exports.Category || (exports.Category = {})); -function isTaggedEvent(event) { - return "_localTs" in event && event["_localTs"] !== undefined; -} -/** - * The purpose of this class is to accumulate /sync responses such that a - * complete "initial" JSON response can be returned which accurately represents - * the sum total of the /sync responses accumulated to date. It only handles - * room data: that is, everything under the "rooms" top-level key. - * - * This class is used when persisting room data so a complete /sync response can - * be loaded from disk and incremental syncs can be performed on the server, - * rather than asking the server to do an initial sync on startup. - */ -class SyncAccumulator { - constructor(opts = {}) { - this.opts = opts; - this.accountData = {}; // $event_type: Object - this.inviteRooms = {}; // $roomId: { ... sync 'invite' json data ... } - this.joinRooms = {}; - // the /sync token which corresponds to the last time rooms were - // accumulated. We remember this so that any caller can obtain a - // coherent /sync response and know at what point they should be - // streaming from without losing events. - this.nextBatch = null; - this.opts.maxTimelineEntries = this.opts.maxTimelineEntries || 50; - } - accumulate(syncResponse, fromDatabase = false) { - this.accumulateRooms(syncResponse, fromDatabase); - this.accumulateAccountData(syncResponse); - this.nextBatch = syncResponse.next_batch; - } - accumulateAccountData(syncResponse) { - if (!syncResponse.account_data || !syncResponse.account_data.events) { - return; - } - // Clobbers based on event type. - syncResponse.account_data.events.forEach((e) => { - this.accountData[e.type] = e; - }); - } - /** - * Accumulate incremental /sync room data. - * @param syncResponse - the complete /sync JSON - * @param fromDatabase - True if the sync response is one saved to the database - */ - accumulateRooms(syncResponse, fromDatabase = false) { - if (!syncResponse.rooms) { - return; - } - if (syncResponse.rooms.invite) { - Object.keys(syncResponse.rooms.invite).forEach((roomId) => { - this.accumulateRoom(roomId, Category.Invite, syncResponse.rooms.invite[roomId], fromDatabase); - }); - } - if (syncResponse.rooms.join) { - Object.keys(syncResponse.rooms.join).forEach((roomId) => { - this.accumulateRoom(roomId, Category.Join, syncResponse.rooms.join[roomId], fromDatabase); - }); - } - if (syncResponse.rooms.leave) { - Object.keys(syncResponse.rooms.leave).forEach((roomId) => { - this.accumulateRoom(roomId, Category.Leave, syncResponse.rooms.leave[roomId], fromDatabase); - }); - } - } - accumulateRoom(roomId, category, data, fromDatabase = false) { - // Valid /sync state transitions - // +--------+ <======+ 1: Accept an invite - // +== | INVITE | | (5) 2: Leave a room - // | +--------+ =====+ | 3: Join a public room previously - // |(1) (4) | | left (handle as if new room) - // V (2) V | 4: Reject an invite - // +------+ ========> +--------+ 5: Invite to a room previously - // | JOIN | (3) | LEAVE* | left (handle as if new room) - // +------+ <======== +--------+ - // - // * equivalent to "no state" - switch (category) { - case Category.Invite: // (5) - this.accumulateInviteState(roomId, data); - break; - case Category.Join: - if (this.inviteRooms[roomId]) { - // (1) - // was previously invite, now join. We expect /sync to give - // the entire state and timeline on 'join', so delete previous - // invite state - delete this.inviteRooms[roomId]; - } - // (3) - this.accumulateJoinState(roomId, data, fromDatabase); - break; - case Category.Leave: - if (this.inviteRooms[roomId]) { - // (4) - delete this.inviteRooms[roomId]; - } - else { - // (2) - delete this.joinRooms[roomId]; - } - break; - default: - logger_1.logger.error("Unknown cateogory: ", category); - } - } - accumulateInviteState(roomId, data) { - if (!data.invite_state || !data.invite_state.events) { - // no new data - return; - } - if (!this.inviteRooms[roomId]) { - this.inviteRooms[roomId] = { - invite_state: data.invite_state, - }; - return; - } - // accumulate extra keys for invite->invite transitions - // clobber based on event type / state key - // We expect invite_state to be small, so just loop over the events - const currentData = this.inviteRooms[roomId]; - data.invite_state.events.forEach((e) => { - let hasAdded = false; - for (let i = 0; i < currentData.invite_state.events.length; i++) { - const current = currentData.invite_state.events[i]; - if (current.type === e.type && current.state_key == e.state_key) { - currentData.invite_state.events[i] = e; // update - hasAdded = true; - } - } - if (!hasAdded) { - currentData.invite_state.events.push(e); - } - }); - } - // Accumulate timeline and state events in a room. - accumulateJoinState(roomId, data, fromDatabase = false) { - // We expect this function to be called a lot (every /sync) so we want - // this to be fast. /sync stores events in an array but we often want - // to clobber based on type/state_key. Rather than convert arrays to - // maps all the time, just keep private maps which contain - // the actual current accumulated sync state, and array-ify it when - // getJSON() is called. - var _a, _b, _c, _d, _e, _f, _g, _h; - // State resolution: - // The 'state' key is the delta from the previous sync (or start of time - // if no token was supplied), to the START of the timeline. To obtain - // the current state, we need to "roll forward" state by reading the - // timeline. We want to store the current state so we can drop events - // out the end of the timeline based on opts.maxTimelineEntries. - // - // 'state' 'timeline' current state - // |-------x<======================>x - // T I M E - // - // When getJSON() is called, we 'roll back' the current state by the - // number of entries in the timeline to work out what 'state' should be. - // Back-pagination: - // On an initial /sync, the server provides a back-pagination token for - // the start of the timeline. When /sync deltas come down, they also - // include back-pagination tokens for the start of the timeline. This - // means not all events in the timeline have back-pagination tokens, as - // it is only the ones at the START of the timeline which have them. - // In order for us to have a valid timeline (and back-pagination token - // to match), we need to make sure that when we remove old timeline - // events, that we roll forward to an event which has a back-pagination - // token. This means we can't keep a strict sliding-window based on - // opts.maxTimelineEntries, and we may have a few less. We should never - // have more though, provided that the /sync limit is less than or equal - // to opts.maxTimelineEntries. - if (!this.joinRooms[roomId]) { - // Create truly empty objects so event types of 'hasOwnProperty' and co - // don't cause this code to break. - this.joinRooms[roomId] = { - _currentState: Object.create(null), - _timeline: [], - _accountData: Object.create(null), - _unreadNotifications: {}, - _unreadThreadNotifications: {}, - _summary: {}, - _readReceipts: {}, - _threadReadReceipts: {}, - }; - } - const currentData = this.joinRooms[roomId]; - if (data.account_data && data.account_data.events) { - // clobber based on type - data.account_data.events.forEach((e) => { - currentData._accountData[e.type] = e; - }); - } - // these probably clobber, spec is unclear. - if (data.unread_notifications) { - currentData._unreadNotifications = data.unread_notifications; - } - currentData._unreadThreadNotifications = - (_b = (_a = data[sync_1.UNREAD_THREAD_NOTIFICATIONS.stable]) !== null && _a !== void 0 ? _a : data[sync_1.UNREAD_THREAD_NOTIFICATIONS.unstable]) !== null && _b !== void 0 ? _b : undefined; - if (data.summary) { - const HEROES_KEY = "m.heroes"; - const INVITED_COUNT_KEY = "m.invited_member_count"; - const JOINED_COUNT_KEY = "m.joined_member_count"; - const acc = currentData._summary; - const sum = data.summary; - acc[HEROES_KEY] = sum[HEROES_KEY] || acc[HEROES_KEY]; - acc[JOINED_COUNT_KEY] = sum[JOINED_COUNT_KEY] || acc[JOINED_COUNT_KEY]; - acc[INVITED_COUNT_KEY] = sum[INVITED_COUNT_KEY] || acc[INVITED_COUNT_KEY]; - } - (_d = (_c = data.ephemeral) === null || _c === void 0 ? void 0 : _c.events) === null || _d === void 0 ? void 0 : _d.forEach((e) => { - // We purposefully do not persist m.typing events. - // Technically you could refresh a browser before the timer on a - // typing event is up, so it'll look like you aren't typing when - // you really still are. However, the alternative is worse. If - // we do persist typing events, it will look like people are - // typing forever until someone really does start typing (which - // will prompt Synapse to send down an actual m.typing event to - // clobber the one we persisted). - if (e.type !== event_1.EventType.Receipt || !e.content) { - // This means we'll drop unknown ephemeral events but that - // seems okay. - return; - } - // Handle m.receipt events. They clobber based on: - // (user_id, receipt_type) - // but they are keyed in the event as: - // content:{ $event_id: { $receipt_type: { $user_id: {json} }}} - // so store them in the former so we can accumulate receipt deltas - // quickly and efficiently (we expect a lot of them). Fold the - // receipt type into the key name since we only have 1 at the - // moment (m.read) and nested JSON objects are slower and more - // of a hassle to work with. We'll inflate this back out when - // getJSON() is called. - Object.keys(e.content).forEach((eventId) => { - Object.entries(e.content[eventId]).forEach(([key, value]) => { - var _a; - if (!(0, utils_1.isSupportedReceiptType)(key)) - return; - for (const userId of Object.keys(value)) { - const data = e.content[eventId][key][userId]; - const receipt = { - data: e.content[eventId][key][userId], - type: key, - eventId: eventId, - }; - if (!data.thread_id || data.thread_id === read_receipts_1.MAIN_ROOM_TIMELINE) { - currentData._readReceipts[userId] = receipt; - } - else { - currentData._threadReadReceipts = Object.assign(Object.assign({}, currentData._threadReadReceipts), { [data.thread_id]: Object.assign(Object.assign({}, ((_a = currentData._threadReadReceipts[data.thread_id]) !== null && _a !== void 0 ? _a : {})), { [userId]: receipt }) }); - } - } - }); - }); - }); - // if we got a limited sync, we need to remove all timeline entries or else - // we will have gaps in the timeline. - if (data.timeline && data.timeline.limited) { - currentData._timeline = []; - } - // Work out the current state. The deltas need to be applied in the order: - // - existing state which didn't come down /sync. - // - State events under the 'state' key. - // - State events in the 'timeline'. - (_f = (_e = data.state) === null || _e === void 0 ? void 0 : _e.events) === null || _f === void 0 ? void 0 : _f.forEach((e) => { - setState(currentData._currentState, e); - }); - (_h = (_g = data.timeline) === null || _g === void 0 ? void 0 : _g.events) === null || _h === void 0 ? void 0 : _h.forEach((e, index) => { - var _a; - // this nops if 'e' isn't a state event - setState(currentData._currentState, e); - // append the event to the timeline. The back-pagination token - // corresponds to the first event in the timeline - let transformedEvent; - if (!fromDatabase) { - transformedEvent = Object.assign({}, e); - if (transformedEvent.unsigned !== undefined) { - transformedEvent.unsigned = Object.assign({}, transformedEvent.unsigned); - } - const age = e.unsigned ? e.unsigned.age : e.age; - if (age !== undefined) - transformedEvent._localTs = Date.now() - age; - } - else { - transformedEvent = e; - } - currentData._timeline.push({ - event: transformedEvent, - token: index === 0 ? (_a = data.timeline.prev_batch) !== null && _a !== void 0 ? _a : null : null, - }); - }); - // attempt to prune the timeline by jumping between events which have - // pagination tokens. - if (currentData._timeline.length > this.opts.maxTimelineEntries) { - const startIndex = currentData._timeline.length - this.opts.maxTimelineEntries; - for (let i = startIndex; i < currentData._timeline.length; i++) { - if (currentData._timeline[i].token) { - // keep all events after this, including this one - currentData._timeline = currentData._timeline.slice(i, currentData._timeline.length); - break; - } - } - } - } - /** - * Return everything under the 'rooms' key from a /sync response which - * represents all room data that should be stored. This should be paired - * with the sync token which represents the most recent /sync response - * provided to accumulate(). - * @param forDatabase - True to generate a sync to be saved to storage - * @returns An object with a "nextBatch", "roomsData" and "accountData" - * keys. - * The "nextBatch" key is a string which represents at what point in the - * /sync stream the accumulator reached. This token should be used when - * restarting a /sync stream at startup. Failure to do so can lead to missing - * events. The "roomsData" key is an Object which represents the entire - * /sync response from the 'rooms' key onwards. The "accountData" key is - * a list of raw events which represent global account data. - */ - getJSON(forDatabase = false) { - const data = { - join: {}, - invite: {}, - // always empty. This is set by /sync when a room was previously - // in 'invite' or 'join'. On fresh startup, the client won't know - // about any previous room being in 'invite' or 'join' so we can - // just omit mentioning it at all, even if it has previously come - // down /sync. - // The notable exception is when a client is kicked or banned: - // we may want to hold onto that room so the client can clearly see - // why their room has disappeared. We don't persist it though because - // it is unclear *when* we can safely remove the room from the DB. - // Instead, we assume that if you're loading from the DB, you've - // refreshed the page, which means you've seen the kick/ban already. - leave: {}, - }; - Object.keys(this.inviteRooms).forEach((roomId) => { - data.invite[roomId] = this.inviteRooms[roomId]; - }); - Object.keys(this.joinRooms).forEach((roomId) => { - const roomData = this.joinRooms[roomId]; - const roomJson = { - ephemeral: { events: [] }, - account_data: { events: [] }, - state: { events: [] }, - timeline: { - events: [], - prev_batch: null, - }, - unread_notifications: roomData._unreadNotifications, - unread_thread_notifications: roomData._unreadThreadNotifications, - summary: roomData._summary, - }; - // Add account data - Object.keys(roomData._accountData).forEach((evType) => { - roomJson.account_data.events.push(roomData._accountData[evType]); - }); - // Add receipt data - const receiptEvent = { - type: event_1.EventType.Receipt, - room_id: roomId, - content: { - // $event_id: { "m.read": { $user_id: $json } } - }, - }; - const receiptEventContent = new utils_1.MapWithDefault(() => new utils_1.MapWithDefault(() => new Map())); - for (const [userId, receiptData] of Object.entries(roomData._readReceipts)) { - receiptEventContent - .getOrCreate(receiptData.eventId) - .getOrCreate(receiptData.type) - .set(userId, receiptData.data); - } - for (const threadReceipts of Object.values(roomData._threadReadReceipts)) { - for (const [userId, receiptData] of Object.entries(threadReceipts)) { - receiptEventContent - .getOrCreate(receiptData.eventId) - .getOrCreate(receiptData.type) - .set(userId, receiptData.data); - } - } - receiptEvent.content = (0, utils_1.recursiveMapToObject)(receiptEventContent); - // add only if we have some receipt data - if (receiptEventContent.size > 0) { - roomJson.ephemeral.events.push(receiptEvent); - } - // Add timeline data - roomData._timeline.forEach((msgData) => { - if (!roomJson.timeline.prev_batch) { - // the first event we add to the timeline MUST match up to - // the prev_batch token. - if (!msgData.token) { - return; // this shouldn't happen as we prune constantly. - } - roomJson.timeline.prev_batch = msgData.token; - } - let transformedEvent; - if (!forDatabase && isTaggedEvent(msgData.event)) { - // This means we have to copy each event, so we can fix it up to - // set a correct 'age' parameter whilst keeping the local timestamp - // on our stored event. If this turns out to be a bottleneck, it could - // be optimised either by doing this in the main process after the data - // has been structured-cloned to go between the worker & main process, - // or special-casing data from saved syncs to read the local timestamp - // directly rather than turning it into age to then immediately be - // transformed back again into a local timestamp. - transformedEvent = Object.assign({}, msgData.event); - if (transformedEvent.unsigned !== undefined) { - transformedEvent.unsigned = Object.assign({}, transformedEvent.unsigned); - } - delete transformedEvent._localTs; - transformedEvent.unsigned = transformedEvent.unsigned || {}; - transformedEvent.unsigned.age = Date.now() - msgData.event._localTs; - } - else { - transformedEvent = msgData.event; - } - roomJson.timeline.events.push(transformedEvent); - }); - // Add state data: roll back current state to the start of timeline, - // by "reverse clobbering" from the end of the timeline to the start. - // Convert maps back into arrays. - const rollBackState = Object.create(null); - for (let i = roomJson.timeline.events.length - 1; i >= 0; i--) { - const timelineEvent = roomJson.timeline.events[i]; - if (timelineEvent.state_key === null || - timelineEvent.state_key === undefined) { - continue; // not a state event - } - // since we're going back in time, we need to use the previous - // state value else we'll break causality. We don't have the - // complete previous state event, so we need to create one. - const prevStateEvent = (0, utils_1.deepCopy)(timelineEvent); - if (prevStateEvent.unsigned) { - if (prevStateEvent.unsigned.prev_content) { - prevStateEvent.content = prevStateEvent.unsigned.prev_content; - } - if (prevStateEvent.unsigned.prev_sender) { - prevStateEvent.sender = prevStateEvent.unsigned.prev_sender; - } - } - setState(rollBackState, prevStateEvent); - } - Object.keys(roomData._currentState).forEach((evType) => { - Object.keys(roomData._currentState[evType]).forEach((stateKey) => { - let ev = roomData._currentState[evType][stateKey]; - if (rollBackState[evType] && rollBackState[evType][stateKey]) { - // use the reverse clobbered event instead. - ev = rollBackState[evType][stateKey]; - } - roomJson.state.events.push(ev); - }); - }); - data.join[roomId] = roomJson; - }); - // Add account data - const accData = []; - Object.keys(this.accountData).forEach((evType) => { - accData.push(this.accountData[evType]); - }); - return { - nextBatch: this.nextBatch, - roomsData: data, - accountData: accData, - }; - } - getNextBatchToken() { - return this.nextBatch; - } -} -exports.SyncAccumulator = SyncAccumulator; -function setState(eventMap, event) { - if (event.state_key === null || event.state_key === undefined || !event.type) { - return; - } - if (!eventMap[event.type]) { - eventMap[event.type] = Object.create(null); - } - eventMap[event.type][event.state_key] = event; -} - -},{"./@types/event":306,"./@types/read_receipts":311,"./@types/sync":314,"./logger":374,"./utils":416}],414:[function(require,module,exports){ -(function (global){(function (){ -"use strict"; -/* -Copyright 2015 - 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports._createAndReEmitRoom = exports.SyncApi = exports.defaultSyncApiOpts = exports.defaultClientOpts = exports.SyncState = void 0; -const user_1 = require("./models/user"); -const room_1 = require("./models/room"); -const utils = __importStar(require("./utils")); -const utils_1 = require("./utils"); -const filter_1 = require("./filter"); -const event_timeline_1 = require("./models/event-timeline"); -const logger_1 = require("./logger"); -const errors_1 = require("./errors"); -const client_1 = require("./client"); -const http_api_1 = require("./http-api"); -const event_1 = require("./@types/event"); -const room_state_1 = require("./models/room-state"); -const room_member_1 = require("./models/room-member"); -const beacon_1 = require("./models/beacon"); -const sync_1 = require("./@types/sync"); -const feature_1 = require("./feature"); -const DEBUG = true; -// /sync requests allow you to set a timeout= but the request may continue -// beyond that and wedge forever, so we need to track how long we are willing -// to keep open the connection. This constant is *ADDED* to the timeout= value -// to determine the max time we're willing to wait. -const BUFFER_PERIOD_MS = 80 * 1000; -// Number of consecutive failed syncs that will lead to a syncState of ERROR as opposed -// to RECONNECTING. This is needed to inform the client of server issues when the -// keepAlive is successful but the server /sync fails. -const FAILED_SYNC_ERROR_THRESHOLD = 3; -var SyncState; -(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"; -})(SyncState = exports.SyncState || (exports.SyncState = {})); -// Room versions where "insertion", "batch", and "marker" events are controlled -// by power-levels. MSC2716 is supported in existing room versions but they -// should only have special meaning when the room creator sends them. -const MSC2716_ROOM_VERSIONS = ["org.matrix.msc2716v3"]; -function getFilterName(userId, suffix) { - // scope this on the user ID because people may login on many accounts - // and they all need to be stored! - return `FILTER_SYNC_${userId}` + (suffix ? "_" + suffix : ""); -} -/* istanbul ignore next */ -function debuglog(...params) { - if (!DEBUG) - return; - logger_1.logger.log(...params); -} -var SetPresence; -(function (SetPresence) { - SetPresence["Offline"] = "offline"; - SetPresence["Online"] = "online"; - SetPresence["Unavailable"] = "unavailable"; -})(SetPresence || (SetPresence = {})); -/** add default settings to an IStoredClientOpts */ -function defaultClientOpts(opts) { - return Object.assign({ initialSyncLimit: 8, resolveInvitesToProfiles: false, pollTimeout: 30 * 1000, pendingEventOrdering: client_1.PendingEventOrdering.Chronological, threadSupport: false }, opts); -} -exports.defaultClientOpts = defaultClientOpts; -function defaultSyncApiOpts(syncOpts) { - return Object.assign({ canResetEntireTimeline: (_roomId) => false }, syncOpts); -} -exports.defaultSyncApiOpts = defaultSyncApiOpts; -class SyncApi { - /** - * 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) { - this.client = client; - this._peekRoom = null; - this.syncState = null; - this.catchingUp = false; - this.running = false; - this.notifEvents = []; // accumulator of sync events in the current sync response - this.failedSyncCount = 0; // Number of consecutive failed /sync requests - this.storeIsInvalid = false; // flag set if the store needs to be cleared before we can start - this.getPushRules = () => __awaiter(this, void 0, void 0, function* () { - try { - debuglog("Getting push rules..."); - const result = yield this.client.getPushRules(); - debuglog("Got push rules"); - this.client.pushRules = result; - } - catch (err) { - logger_1.logger.error("Getting push rules failed", err); - if (this.shouldAbortSync(err)) - return; - // wait for saved sync to complete before doing anything else, - // otherwise the sync state will end up being incorrect - debuglog("Waiting for saved sync before retrying push rules..."); - yield this.recoverFromSyncStartupError(this.savedSyncPromise, err); - return this.getPushRules(); // try again - } - }); - this.buildDefaultFilter = () => { - const filter = new filter_1.Filter(this.client.credentials.userId); - if (this.client.canSupport.get(feature_1.Feature.ThreadUnreadNotifications) !== feature_1.ServerSupport.Unsupported) { - filter.setUnreadThreadNotifications(true); - } - return filter; - }; - this.checkLazyLoadStatus = () => __awaiter(this, void 0, void 0, function* () { - var _a; - debuglog("Checking lazy load status..."); - if (this.opts.lazyLoadMembers && this.client.isGuest()) { - this.opts.lazyLoadMembers = false; - } - if (this.opts.lazyLoadMembers) { - debuglog("Checking server lazy load support..."); - const supported = yield this.client.doesServerSupportLazyLoading(); - if (supported) { - debuglog("Enabling lazy load on sync filter..."); - if (!this.opts.filter) { - this.opts.filter = this.buildDefaultFilter(); - } - this.opts.filter.setLazyLoadMembers(true); - } - else { - debuglog("LL: lazy loading requested but not supported " + "by server, so disabling"); - this.opts.lazyLoadMembers = false; - } - } - // need to vape the store when enabling LL and wasn't enabled before - debuglog("Checking whether lazy loading has changed in store..."); - const shouldClear = yield this.wasLazyLoadingToggled(this.opts.lazyLoadMembers); - if (shouldClear) { - this.storeIsInvalid = true; - const error = new errors_1.InvalidStoreError(errors_1.InvalidStoreState.ToggledLazyLoading, !!this.opts.lazyLoadMembers); - this.updateSyncState(SyncState.Error, { error }); - // bail out of the sync loop now: the app needs to respond to this error. - // we leave the state as 'ERROR' which isn't great since this normally means - // we're retrying. The client must be stopped before clearing the stores anyway - // so the app should stop the client, clear the store and start it again. - logger_1.logger.warn("InvalidStoreError: store is not usable: stopping sync."); - return; - } - if (this.opts.lazyLoadMembers) { - (_a = this.syncOpts.crypto) === null || _a === void 0 ? void 0 : _a.enableLazyLoading(); - } - try { - debuglog("Storing client options..."); - yield this.client.storeClientOptions(); - debuglog("Stored client options"); - } - catch (err) { - logger_1.logger.error("Storing client options failed", err); - throw err; - } - }); - this.getFilter = () => __awaiter(this, void 0, void 0, function* () { - debuglog("Getting filter..."); - let filter; - if (this.opts.filter) { - filter = this.opts.filter; - } - else { - filter = this.buildDefaultFilter(); - } - let filterId; - try { - filterId = yield this.client.getOrCreateFilter(getFilterName(this.client.credentials.userId), filter); - } - catch (err) { - logger_1.logger.error("Getting filter failed", err); - if (this.shouldAbortSync(err)) - return {}; - // wait for saved sync to complete before doing anything else, - // otherwise the sync state will end up being incorrect - debuglog("Waiting for saved sync before retrying filter..."); - yield this.recoverFromSyncStartupError(this.savedSyncPromise, err); - return this.getFilter(); // try again - } - return { filter, filterId }; - }); - /** - * 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. - */ - this.onOnline = () => { - debuglog("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(), [room_1.RoomEvent.Timeline, room_1.RoomEvent.TimelineReset]); - } - } - createRoom(roomId) { - const room = _createAndReEmitRoom(this.client, roomId, this.opts); - room.on(room_state_1.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, { timelineWasEmpty } = {}) { - // We don't need to refresh the timeline if it was empty before the - // marker arrived. This could be happen in a variety of cases: - // 1. From the initial sync - // 2. If it's from the first state we're seeing after joining the room - // 3. Or whether it's coming from `syncFromCache` - if (timelineWasEmpty) { - logger_1.logger.debug(`MarkerState: Ignoring markerEventId=${markerEvent.getId()} in roomId=${room.roomId} ` + - `because the timeline was empty before the marker arrived which means there is nothing to refresh.`); - return; - } - const isValidMsc2716Event = - // Check whether the room version directly supports MSC2716, in - // which case, "marker" events are already auth'ed by - // power_levels - MSC2716_ROOM_VERSIONS.includes(room.getVersion()) || - // MSC2716 is also supported in all existing room versions but - // special meaning should only be given to "insertion", "batch", - // and "marker" events when they come from the room creator - markerEvent.getSender() === room.getCreator(); - // It would be nice if we could also specifically tell whether the - // historical messages actually affected the locally cached client - // timeline or not. The problem is we can't see the prev_events of - // the base insertion event that the marker was pointing to because - // prev_events aren't available in the client API's. In most cases, - // the history won't be in people's locally cached timelines in the - // client, so we don't need to bother everyone about refreshing - // their timeline. This works for a v1 though and there are use - // cases like initially bootstrapping your bridged room where people - // are likely to encounter the historical messages affecting their - // current timeline (think someone signing up for Beeper and - // importing their Whatsapp history). - if (isValidMsc2716Event) { - // Saw new marker event, let's let the clients know they should - // refresh the timeline. - logger_1.logger.debug(`MarkerState: Timeline needs to be refreshed because ` + - `a new markerEventId=${markerEvent.getId()} was sent in roomId=${room.roomId}`); - room.setTimelineNeedsRefresh(true); - room.emit(room_1.RoomEvent.HistoryImportedWithinTimeline, markerEvent, room); - } - else { - logger_1.logger.debug(`MarkerState: Ignoring markerEventId=${markerEvent.getId()} in roomId=${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 _a; - return __awaiter(this, void 0, void 0, function* () { - const client = this.client; - // grab a filter with limit=1 and include_leave=true - const filter = new filter_1.Filter(this.client.credentials.userId); - filter.setTimelineLimit(1); - filter.setIncludeLeaveRooms(true); - const localTimeoutMs = this.opts.pollTimeout + BUFFER_PERIOD_MS; - const filterId = yield client.getOrCreateFilter(getFilterName(client.credentials.userId, "LEFT_ROOMS"), filter); - const qps = { - timeout: 0, - filter: filterId, - }; - const data = yield client.http.authedRequest(http_api_1.Method.Get, "/sync", qps, undefined, { - localTimeoutMs, - }); - let leaveRooms = []; - if ((_a = data.rooms) === null || _a === void 0 ? void 0 : _a.leave) { - leaveRooms = this.mapSyncResponseToRoomArray(data.rooms.leave); - } - const rooms = yield Promise.all(leaveRooms.map((leaveObj) => __awaiter(this, void 0, void 0, function* () { - const room = leaveObj.room; - if (!leaveObj.isBrandNewRoom) { - // the intention behind syncLeftRooms is to add in rooms which were - // *omitted* from the initial /sync. Rooms the user were joined to - // but then left whilst the app is running will appear in this list - // and we do not want to bother with them since they will have the - // current state already (and may get dupe messages if we add - // yet more timeline events!), so skip them. - // NB: When we persist rooms to localStorage this will be more - // complicated... - return; - } - leaveObj.timeline = leaveObj.timeline || { - prev_batch: null, - events: [], - }; - const events = this.mapSyncEventsFormat(leaveObj.timeline, room); - const stateEvents = this.mapSyncEventsFormat(leaveObj.state, room); - // set the back-pagination token. Do this *before* adding any - // events so that clients can start back-paginating. - room.getLiveTimeline().setPaginationToken(leaveObj.timeline.prev_batch, event_timeline_1.EventTimeline.BACKWARDS); - yield this.injectRoomEvents(room, stateEvents, events); - room.recalculate(); - client.store.storeRoom(room); - client.emit(client_1.ClientEvent.Room, room); - this.processEventsForNotifs(room, events); - return room; - }))); - return rooms.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. - * @returns A promise which resolves once the room has been added to the - * store. - */ - peek(roomId) { - var _a; - if (((_a = this._peekRoom) === null || _a === void 0 ? void 0 : _a.roomId) === roomId) { - return Promise.resolve(this._peekRoom); - } - const client = this.client; - this._peekRoom = this.createRoom(roomId); - return this.client.roomInitialSync(roomId, 20).then((response) => { - // make sure things are init'd - response.messages = response.messages || { chunk: [] }; - response.messages.chunk = response.messages.chunk || []; - response.state = response.state || []; - // FIXME: Mostly duplicated from injectRoomEvents but not entirely - // because "state" in this API is at the BEGINNING of the chunk - const oldStateEvents = utils.deepCopy(response.state).map(client.getEventMapper()); - const stateEvents = response.state.map(client.getEventMapper()); - const messages = response.messages.chunk.map(client.getEventMapper()); - // XXX: copypasted from /sync until we kill off this minging v1 API stuff) - // handle presence events (User objects) - if (Array.isArray(response.presence)) { - response.presence.map(client.getEventMapper()).forEach(function (presenceEvent) { - let user = client.store.getUser(presenceEvent.getContent().user_id); - if (user) { - user.setPresenceEvent(presenceEvent); - } - else { - user = createNewUser(client, presenceEvent.getContent().user_id); - user.setPresenceEvent(presenceEvent); - client.store.storeUser(user); - } - client.emit(client_1.ClientEvent.Event, presenceEvent); - }); - } - // set the pagination token before adding the events in case people - // fire off pagination requests in response to the Room.timeline - // events. - if (response.messages.start) { - this._peekRoom.oldState.paginationToken = response.messages.start; - } - // set the state of the room to as it was after the timeline executes - this._peekRoom.oldState.setStateEvents(oldStateEvents); - this._peekRoom.currentState.setStateEvents(stateEvents); - this.resolveInvites(this._peekRoom); - this._peekRoom.recalculate(); - // roll backwards to diverge old state. addEventsToTimeline - // will overwrite the pagination token, so make sure it overwrites - // it with the right thing. - this._peekRoom.addEventsToTimeline(messages.reverse(), true, this._peekRoom.getLiveTimeline(), response.messages.start); - client.store.storeRoom(this._peekRoom); - client.emit(client_1.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 _a; - if (this._peekRoom !== peekRoom) { - debuglog("Stopped peeking in room %s", peekRoom.roomId); - return; - } - // FIXME: gut wrenching; hard-coded timeout values - this.client.http - .authedRequest(http_api_1.Method.Get, "/events", { - room_id: peekRoom.roomId, - timeout: String(30 * 1000), - from: token, - }, undefined, { - localTimeoutMs: 50 * 1000, - abortSignal: (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.signal, - }) - .then((res) => { - if (this._peekRoom !== peekRoom) { - debuglog("Stopped peeking in room %s", peekRoom.roomId); - return; - } - // We have a problem that we get presence both from /events and /sync - // however, /sync only returns presence for users in rooms - // you're actually joined to. - // in order to be sure to get presence for all of the users in the - // peeked room, we handle presence explicitly here. This may result - // in duplicate presence events firing for some users, which is a - // performance drain, but such is life. - // XXX: copypasted from /sync until we can kill this minging v1 stuff. - res.chunk - .filter(function (e) { - return e.type === "m.presence"; - }) - .map(this.client.getEventMapper()) - .forEach((presenceEvent) => { - let user = this.client.store.getUser(presenceEvent.getContent().user_id); - if (user) { - user.setPresenceEvent(presenceEvent); - } - else { - user = createNewUser(this.client, presenceEvent.getContent().user_id); - user.setPresenceEvent(presenceEvent); - this.client.store.storeUser(user); - } - this.client.emit(client_1.ClientEvent.Event, presenceEvent); - }); - // strip out events which aren't for the given room_id (e.g presence) - // and also ephemeral events (which we're assuming is anything without - // and event ID because the /events API doesn't separate them). - const events = res.chunk - .filter(function (e) { - return e.room_id === peekRoom.roomId && e.event_id; - }) - .map(this.client.getEventMapper()); - peekRoom.addLiveEvents(events); - this.peekPoll(peekRoom, res.end); - }, (err) => { - logger_1.logger.error("[%s] Peek poll failed: %s", peekRoom.roomId, err); - setTimeout(() => { - this.peekPoll(peekRoom, token); - }, 30 * 1000); - }); - } - /** - * 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 _a; - return (_a = this.syncStateData) !== null && _a !== void 0 ? _a : null; - } - recoverFromSyncStartupError(savedSyncPromise, error) { - return __awaiter(this, void 0, void 0, function* () { - // Wait for the saved sync to complete - we send the pushrules and filter requests - // before the saved sync has finished so they can run in parallel, but only process - // the results after the saved sync is done. Equivalently, we wait for it to finish - // before reporting failures from these functions. - yield savedSyncPromise; - const keepaliveProm = this.startKeepAlives(); - this.updateSyncState(SyncState.Error, { error }); - yield keepaliveProm; - }); - } - /** - * Is the lazy loading option different than in previous session? - * @param lazyLoadMembers - current options for lazy loading - * @returns whether or not the option has changed compared to the previous session */ - wasLazyLoadingToggled(lazyLoadMembers = false) { - return __awaiter(this, void 0, void 0, function* () { - // assume it was turned off before - // if we don't know any better - let lazyLoadMembersBefore = false; - const isStoreNewlyCreated = yield this.client.store.isNewlyCreated(); - if (!isStoreNewlyCreated) { - const prevClientOptions = yield this.client.store.getClientOptions(); - if (prevClientOptions) { - lazyLoadMembersBefore = !!prevClientOptions.lazyLoadMembers; - } - return lazyLoadMembersBefore !== lazyLoadMembers; - } - return false; - }); - } - shouldAbortSync(error) { - if (error.errcode === "M_UNKNOWN_TOKEN") { - // The logout already happened, we just need to stop. - logger_1.logger.warn("Token no longer valid - assuming logout"); - this.stop(); - this.updateSyncState(SyncState.Error, { error }); - return true; - } - return false; - } - /** - * Main entry point - */ - sync() { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - this.running = true; - this.abortController = new AbortController(); - (_b = (_a = global.window) === null || _a === void 0 ? void 0 : _a.addEventListener) === null || _b === void 0 ? void 0 : _b.call(_a, "online", this.onOnline, false); - if (this.client.isGuest()) { - // no push rules for guests, no access to POST filter for guests. - return this.doSync({}); - } - // Pull the saved sync token out first, before the worker starts sending - // all the sync data which could take a while. This will let us send our - // first incremental sync request before we've processed our saved data. - debuglog("Getting saved sync token..."); - const savedSyncTokenPromise = this.client.store.getSavedSyncToken().then((tok) => { - debuglog("Got saved sync token"); - return tok; - }); - this.savedSyncPromise = this.client.store - .getSavedSync() - .then((savedSync) => { - debuglog(`Got reply from saved sync, exists? ${!!savedSync}`); - if (savedSync) { - return this.syncFromCache(savedSync); - } - }) - .catch((err) => { - logger_1.logger.error("Getting saved sync failed", err); - }); - // We need to do one-off checks before we can begin the /sync loop. - // These are: - // 1) We need to get push rules so we can check if events should bing as we get - // them from /sync. - // 2) We need to get/create a filter which we can use for /sync. - // 3) We need to check the lazy loading option matches what was used in the - // stored sync. If it doesn't, we can't use the stored sync. - // Now start the first incremental sync request: this can also - // take a while so if we set it going now, we can wait for it - // to finish while we process our saved sync data. - yield this.getPushRules(); - yield this.checkLazyLoadStatus(); - const { filterId, filter } = yield this.getFilter(); - if (!filter) - return; // bail, getFilter failed - // reset the notifications timeline to prepare it to paginate from - // the current point in time. - // The right solution would be to tie /sync pagination tokens into - // /notifications API somehow. - this.client.resetNotifTimelineSet(); - if (!this.currentSyncRequest) { - let firstSyncFilter = filterId; - const savedSyncToken = yield savedSyncTokenPromise; - if (savedSyncToken) { - debuglog("Sending first sync request..."); - } - else { - debuglog("Sending initial sync request..."); - const initialFilter = this.buildDefaultFilter(); - initialFilter.setDefinition(filter.getDefinition()); - initialFilter.setTimelineLimit(this.opts.initialSyncLimit); - // Use an inline filter, no point uploading it for a single usage - firstSyncFilter = JSON.stringify(initialFilter.getDefinition()); - } - // Send this first sync request here so we can then wait for the saved - // sync data to finish processing before we process the results of this one. - this.currentSyncRequest = this.doSyncRequest({ filter: firstSyncFilter }, savedSyncToken); - } - // Now wait for the saved sync to finish... - debuglog("Waiting for saved sync before starting sync processing..."); - yield this.savedSyncPromise; - // process the first sync request and continue syncing with the normal filterId - return this.doSync({ filter: filterId }); - }); - } - /** - * Stops the sync object from syncing. - */ - stop() { - var _a, _b, _c; - debuglog("SyncApi.stop"); - // It is necessary to check for the existance of - // global.window AND global.window.removeEventListener. - // Some platforms (e.g. React Native) register global.window, - // but do not have global.window.removeEventListener. - (_b = (_a = global.window) === null || _a === void 0 ? void 0 : _a.removeEventListener) === null || _b === void 0 ? void 0 : _b.call(_a, "online", this.onOnline, false); - this.running = false; - (_c = this.abortController) === null || _c === void 0 ? void 0 : _c.abort(); - if (this.keepAliveTimer) { - clearTimeout(this.keepAliveTimer); - this.keepAliveTimer = undefined; - } - } - /** - * Retry a backed off syncing request immediately. This should only be used when - * the user explicitly attempts to retry their lost connection. - * @returns True if this resulted in a request being retried. - */ - retryImmediately() { - if (!this.connectionReturnedDefer) { - 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) { - return __awaiter(this, void 0, void 0, function* () { - debuglog("sync(): not doing HTTP hit, instead returning stored /sync data"); - const nextSyncToken = savedSync.nextBatch; - // Set sync token for future incremental syncing - this.client.store.setSyncToken(nextSyncToken); - // No previous sync, set old token to null - const syncEventData = { - nextSyncToken, - catchingUp: false, - fromCache: true, - }; - const data = { - next_batch: nextSyncToken, - rooms: savedSync.roomsData, - account_data: { - events: savedSync.accountData, - }, - }; - try { - yield this.processSyncResponse(syncEventData, data); - } - catch (e) { - logger_1.logger.error("Error processing cached sync", e); - } - // Don't emit a prepared if we've bailed because the store is invalid: - // in this case the client will not be usable until stopped & restarted - // so this would be useless and misleading. - if (!this.storeIsInvalid) { - this.updateSyncState(SyncState.Prepared, syncEventData); - } - }); - } - /** - * Invoke me to do /sync calls - */ - doSync(syncOptions) { - return __awaiter(this, void 0, void 0, function* () { - while (this.running) { - const syncToken = this.client.store.getSyncToken(); - let data; - try { - if (!this.currentSyncRequest) { - this.currentSyncRequest = this.doSyncRequest(syncOptions, syncToken); - } - data = yield this.currentSyncRequest; - } - catch (e) { - const abort = yield this.onSyncError(e); - if (abort) - return; - continue; - } - finally { - this.currentSyncRequest = undefined; - } - // set the sync token NOW *before* processing the events. We do this so - // if something barfs on an event we can skip it rather than constantly - // polling with the same token. - this.client.store.setSyncToken(data.next_batch); - // Reset after a successful sync - this.failedSyncCount = 0; - yield this.client.store.setSyncData(data); - const syncEventData = { - oldSyncToken: syncToken !== null && syncToken !== void 0 ? syncToken : undefined, - nextSyncToken: data.next_batch, - catchingUp: this.catchingUp, - }; - if (this.syncOpts.crypto) { - // tell the crypto module we're about to process a sync - // response - yield this.syncOpts.crypto.onSyncWillProcess(syncEventData); - } - try { - yield this.processSyncResponse(syncEventData, data); - } - catch (e) { - // log the exception with stack if we have it, else fall back - // to the plain description - logger_1.logger.error("Caught /sync error", e); - // Emit the exception for client handling - this.client.emit(client_1.ClientEvent.SyncUnexpectedError, e); - } - // update this as it may have changed - syncEventData.catchingUp = this.catchingUp; - // emit synced events - if (!syncOptions.hasSyncedBefore) { - this.updateSyncState(SyncState.Prepared, syncEventData); - syncOptions.hasSyncedBefore = true; - } - // tell the crypto module to do its processing. It may block (to do a - // /keys/changes request). - if (this.syncOpts.cryptoCallbacks) { - yield this.syncOpts.cryptoCallbacks.onSyncCompleted(syncEventData); - } - // keep emitting SYNCING -> SYNCING for clients who want to do bulk updates - this.updateSyncState(SyncState.Syncing, syncEventData); - if (this.client.store.wantsSave()) { - // We always save the device list (if it's dirty) before saving the sync data: - // this means we know the saved device list data is at least as fresh as the - // stored sync data which means we don't have to worry that we may have missed - // device changes. We can also skip the delay since we're not calling this very - // frequently (and we don't really want to delay the sync for it). - if (this.syncOpts.crypto) { - yield this.syncOpts.crypto.saveDeviceList(0); - } - // tell databases that everything is now in a consistent state and can be saved. - this.client.store.save(); - } - } - if (!this.running) { - debuglog("Sync no longer running: exiting."); - if (this.connectionReturnedDefer) { - this.connectionReturnedDefer.reject(); - this.connectionReturnedDefer = undefined; - } - this.updateSyncState(SyncState.Stopped); - } - }); - } - doSyncRequest(syncOptions, syncToken) { - var _a; - const qps = this.getSyncParams(syncOptions, syncToken); - return this.client.http.authedRequest(http_api_1.Method.Get, "/sync", qps, undefined, { - localTimeoutMs: qps.timeout + BUFFER_PERIOD_MS, - abortSignal: (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.signal, - }); - } - getSyncParams(syncOptions, syncToken) { - let timeout = this.opts.pollTimeout; - if (this.getSyncState() !== SyncState.Syncing || this.catchingUp) { - // unless we are happily syncing already, we want the server to return - // as quickly as possible, even if there are no events queued. This - // serves two purposes: - // - // * When the connection dies, we want to know asap when it comes back, - // so that we can hide the error from the user. (We don't want to - // have to wait for an event or a timeout). - // - // * We want to know if the server has any to_device messages queued up - // for us. We do that by calling it with a zero timeout until it - // doesn't give us any more to_device messages. - this.catchingUp = true; - timeout = 0; - } - let filter = syncOptions.filter; - if (this.client.isGuest() && !filter) { - filter = this.getGuestFilter(); - } - const qps = { filter, timeout }; - if (this.opts.disablePresence) { - qps.set_presence = SetPresence.Offline; - } - if (syncToken) { - qps.since = syncToken; - } - else { - // use a cachebuster for initialsyncs, to make sure that - // we don't get a stale sync - // (https://github.com/vector-im/vector-web/issues/1354) - qps._cacheBuster = Date.now(); - } - if ([SyncState.Reconnecting, SyncState.Error].includes(this.getSyncState())) { - // we think the connection is dead. If it comes back up, we won't know - // about it till /sync returns. If the timeout= is high, this could - // be a long time. Set it to 0 when doing retries so we don't have to wait - // for an event or a timeout before emiting the SYNCING event. - qps.timeout = 0; - } - return qps; - } - onSyncError(err) { - return __awaiter(this, void 0, void 0, function* () { - if (!this.running) { - debuglog("Sync no longer running: exiting"); - if (this.connectionReturnedDefer) { - this.connectionReturnedDefer.reject(); - this.connectionReturnedDefer = undefined; - } - this.updateSyncState(SyncState.Stopped); - return true; // abort - } - logger_1.logger.error("/sync error %s", err); - if (this.shouldAbortSync(err)) { - return true; // abort - } - this.failedSyncCount++; - logger_1.logger.log("Number of consecutive failed sync requests:", this.failedSyncCount); - debuglog("Starting keep-alive"); - // Note that we do *not* mark the sync connection as - // lost yet: we only do this if a keepalive poke - // fails, since long lived HTTP connections will - // go away sometimes and we shouldn't treat this as - // erroneous. We set the state to 'reconnecting' - // instead, so that clients can observe this state - // if they wish. - const keepAlivePromise = this.startKeepAlives(); - this.currentSyncRequest = undefined; - // Transition from RECONNECTING to ERROR after a given number of failed syncs - this.updateSyncState(this.failedSyncCount >= FAILED_SYNC_ERROR_THRESHOLD ? SyncState.Error : SyncState.Reconnecting, { error: err }); - const connDidFail = yield keepAlivePromise; - // Only emit CATCHUP if we detected a connectivity error: if we didn't, - // it's quite likely the sync will fail again for the same reason and we - // want to stay in ERROR rather than keep flip-flopping between ERROR - // and CATCHUP. - if (connDidFail && this.getSyncState() === SyncState.Error) { - this.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 _a, _b, _c, _d; - return __awaiter(this, void 0, void 0, function* () { - const client = this.client; - // data looks like: - // { - // next_batch: $token, - // presence: { events: [] }, - // account_data: { events: [] }, - // device_lists: { changed: ["@user:server", ... ]}, - // to_device: { events: [] }, - // device_one_time_keys_count: { signed_curve25519: 42 }, - // rooms: { - // invite: { - // $roomid: { - // invite_state: { events: [] } - // } - // }, - // join: { - // $roomid: { - // state: { events: [] }, - // timeline: { events: [], prev_batch: $token, limited: true }, - // ephemeral: { events: [] }, - // summary: { - // m.heroes: [ $user_id ], - // m.joined_member_count: $count, - // m.invited_member_count: $count - // }, - // account_data: { events: [] }, - // unread_notifications: { - // highlight_count: 0, - // notification_count: 0, - // } - // } - // }, - // leave: { - // $roomid: { - // state: { events: [] }, - // timeline: { events: [], prev_batch: $token } - // } - // } - // } - // } - // TODO-arch: - // - Each event we pass through needs to be emitted via 'event', can we - // do this in one place? - // - The isBrandNewRoom boilerplate is boilerplatey. - // handle presence events (User objects) - if (Array.isArray((_a = data.presence) === null || _a === void 0 ? void 0 : _a.events)) { - data.presence.events.filter(utils_1.noUnsafeEventProps) - .map(client.getEventMapper()) - .forEach(function (presenceEvent) { - let user = client.store.getUser(presenceEvent.getSender()); - if (user) { - user.setPresenceEvent(presenceEvent); - } - else { - user = createNewUser(client, presenceEvent.getSender()); - user.setPresenceEvent(presenceEvent); - client.store.storeUser(user); - } - client.emit(client_1.ClientEvent.Event, presenceEvent); - }); - } - // handle non-room account_data - if (Array.isArray((_b = data.account_data) === null || _b === void 0 ? void 0 : _b.events)) { - const events = data.account_data.events.filter(utils_1.noUnsafeEventProps).map(client.getEventMapper()); - const prevEventsMap = events.reduce((m, c) => { - m[c.getType()] = client.store.getAccountData(c.getType()); - return m; - }, {}); - client.store.storeAccountDataEvents(events); - events.forEach(function (accountDataEvent) { - // Honour push rules that come down the sync stream but also - // honour push rules that were previously cached. Base rules - // will be updated when we receive push rules via getPushRules - // (see sync) before syncing over the network. - if (accountDataEvent.getType() === event_1.EventType.PushRules) { - const rules = accountDataEvent.getContent(); - client.setPushRules(rules); - } - const prevEvent = prevEventsMap[accountDataEvent.getType()]; - client.emit(client_1.ClientEvent.AccountData, accountDataEvent, prevEvent); - return accountDataEvent; - }); - } - // handle to-device events - if (data.to_device && Array.isArray(data.to_device.events) && data.to_device.events.length > 0) { - let toDeviceMessages = data.to_device.events.filter(utils_1.noUnsafeEventProps); - if (this.syncOpts.cryptoCallbacks) { - toDeviceMessages = yield this.syncOpts.cryptoCallbacks.preprocessToDeviceMessages(toDeviceMessages); - } - const cancelledKeyVerificationTxns = []; - toDeviceMessages - .map(client.getEventMapper({ toDevice: true })) - .map((toDeviceEvent) => { - // map is a cheap inline forEach - // We want to flag m.key.verification.start events as cancelled - // if there's an accompanying m.key.verification.cancel event, so - // we pull out the transaction IDs from the cancellation events - // so we can flag the verification events as cancelled in the loop - // below. - if (toDeviceEvent.getType() === "m.key.verification.cancel") { - const txnId = toDeviceEvent.getContent()["transaction_id"]; - if (txnId) { - cancelledKeyVerificationTxns.push(txnId); - } - } - // as mentioned above, .map is a cheap inline forEach, so return - // the unmodified event. - return toDeviceEvent; - }) - .forEach(function (toDeviceEvent) { - const content = toDeviceEvent.getContent(); - if (toDeviceEvent.getType() == "m.room.message" && content.msgtype == "m.bad.encrypted") { - // the mapper already logged a warning. - logger_1.logger.log("Ignoring undecryptable to-device event from " + toDeviceEvent.getSender()); - return; - } - if (toDeviceEvent.getType() === "m.key.verification.start" || - toDeviceEvent.getType() === "m.key.verification.request") { - const txnId = content["transaction_id"]; - if (cancelledKeyVerificationTxns.includes(txnId)) { - toDeviceEvent.flagCancelled(); - } - } - client.emit(client_1.ClientEvent.ToDeviceEvent, toDeviceEvent); - }); - } - else { - // no more to-device events: we can stop polling with a short timeout. - this.catchingUp = false; - } - // the returned json structure is a bit crap, so make it into a - // nicer form (array) after applying sanity to make sure we don't fail - // on missing keys (on the off chance) - let inviteRooms = []; - let joinRooms = []; - let leaveRooms = []; - if (data.rooms) { - if (data.rooms.invite) { - inviteRooms = this.mapSyncResponseToRoomArray(data.rooms.invite); - } - if (data.rooms.join) { - joinRooms = this.mapSyncResponseToRoomArray(data.rooms.join); - } - if (data.rooms.leave) { - leaveRooms = this.mapSyncResponseToRoomArray(data.rooms.leave); - } - } - this.notifEvents = []; - // Handle invites - yield utils.promiseMapSeries(inviteRooms, (inviteObj) => __awaiter(this, void 0, void 0, function* () { - var _e; - const room = inviteObj.room; - const stateEvents = this.mapSyncEventsFormat(inviteObj.invite_state, room); - yield this.injectRoomEvents(room, stateEvents); - const inviter = (_e = room.currentState.getStateEvents(event_1.EventType.RoomMember, client.getUserId())) === null || _e === void 0 ? void 0 : _e.getSender(); - const crypto = client.crypto; - if (crypto) { - const parkedHistory = yield crypto.cryptoStore.takeParkedSharedHistory(room.roomId); - for (const parked of parkedHistory) { - if (parked.senderId === inviter) { - yield crypto.olmDevice.addInboundGroupSession(room.roomId, parked.senderKey, parked.forwardingCurve25519KeyChain, parked.sessionId, parked.sessionKey, parked.keysClaimed, true, { sharedHistory: true, untrusted: true }); - } - } - } - if (inviteObj.isBrandNewRoom) { - room.recalculate(); - client.store.storeRoom(room); - client.emit(client_1.ClientEvent.Room, room); - } - else { - // Update room state for invite->reject->invite cycles - room.recalculate(); - } - stateEvents.forEach(function (e) { - client.emit(client_1.ClientEvent.Event, e); - }); - })); - // Handle joins - yield utils.promiseMapSeries(joinRooms, (joinObj) => __awaiter(this, void 0, void 0, function* () { - var _f, _g, _h, _j, _k, _l; - const room = joinObj.room; - const stateEvents = this.mapSyncEventsFormat(joinObj.state, room); - // Prevent events from being decrypted ahead of time - // this helps large account to speed up faster - // room::decryptCriticalEvent is in charge of decrypting all the events - // required for a client to function properly - const events = this.mapSyncEventsFormat(joinObj.timeline, room, false); - const ephemeralEvents = this.mapSyncEventsFormat(joinObj.ephemeral); - const accountDataEvents = this.mapSyncEventsFormat(joinObj.account_data); - const encrypted = client.isRoomEncrypted(room.roomId); - // We store the server-provided value first so it's correct when any of the events fire. - 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. - * - * @see import("./client").fixNotificationCountOnDecryption - */ - if (!encrypted || joinObj.unread_notifications.notification_count === 0) { - // In an encrypted room, if the room has notifications enabled then it's typical for - // the server to flag all new messages as notifying. However, some push rules calculate - // events as ignored based on their event contents (e.g. ignoring msgtype=m.notice messages) - // so we want to calculate this figure on the client in all cases. - room.setUnreadNotificationCount(room_1.NotificationCountType.Total, (_f = joinObj.unread_notifications.notification_count) !== null && _f !== void 0 ? _f : 0); - } - if (!encrypted || room.getUnreadNotificationCount(room_1.NotificationCountType.Highlight) <= 0) { - // If the locally stored highlight count is zero, use the server provided value. - room.setUnreadNotificationCount(room_1.NotificationCountType.Highlight, (_g = joinObj.unread_notifications.highlight_count) !== null && _g !== void 0 ? _g : 0); - } - } - const unreadThreadNotifications = (_h = joinObj[sync_1.UNREAD_THREAD_NOTIFICATIONS.name]) !== null && _h !== void 0 ? _h : joinObj[sync_1.UNREAD_THREAD_NOTIFICATIONS.altName]; - if (unreadThreadNotifications) { - // Only partially reset unread notification - // We want to keep the client-generated count. Particularly important - // for encrypted room that refresh their notification count on event - // decryption - room.resetThreadUnreadNotificationCount(Object.keys(unreadThreadNotifications)); - for (const [threadId, unreadNotification] of Object.entries(unreadThreadNotifications)) { - if (!encrypted || unreadNotification.notification_count === 0) { - room.setThreadUnreadNotificationCount(threadId, room_1.NotificationCountType.Total, (_j = unreadNotification.notification_count) !== null && _j !== void 0 ? _j : 0); - } - const hasNoNotifications = room.getThreadUnreadNotificationCount(threadId, room_1.NotificationCountType.Highlight) <= 0; - if (!encrypted || (encrypted && hasNoNotifications)) { - room.setThreadUnreadNotificationCount(threadId, room_1.NotificationCountType.Highlight, (_k = unreadNotification.highlight_count) !== null && _k !== void 0 ? _k : 0); - } - } - } - else { - room.resetThreadUnreadNotificationCount(); - } - joinObj.timeline = joinObj.timeline || {}; - if (joinObj.isBrandNewRoom) { - // set the back-pagination token. Do this *before* adding any - // events so that clients can start back-paginating. - if (joinObj.timeline.prev_batch !== null) { - room.getLiveTimeline().setPaginationToken(joinObj.timeline.prev_batch, event_timeline_1.EventTimeline.BACKWARDS); - } - } - else if (joinObj.timeline.limited) { - let limited = true; - // we've got a limited sync, so we *probably* have a gap in the - // timeline, so should reset. But we might have been peeking or - // paginating and already have some of the events, in which - // case we just want to append any subsequent events to the end - // of the existing timeline. - // - // This is particularly important in the case that we already have - // *all* of the events in the timeline - in that case, if we reset - // the timeline, we'll end up with an entirely empty timeline, - // which we'll try to paginate but not get any new events (which - // will stop us linking the empty timeline into the chain). - // - for (let i = events.length - 1; i >= 0; i--) { - const eventId = events[i].getId(); - if (room.getTimelineForEvent(eventId)) { - debuglog(`Already have event ${eventId} in limited sync - not resetting`); - limited = false; - // we might still be missing some of the events before i; - // we don't want to be adding them to the end of the - // timeline because that would put them out of order. - events.splice(0, i); - // XXX: there's a problem here if the skipped part of the - // timeline modifies the state set in stateEvents, because - // we'll end up using the state from stateEvents rather - // than the later state from timelineEvents. We probably - // need to wind stateEvents forward over the events we're - // skipping. - break; - } - } - if (limited) { - room.resetLiveTimeline(joinObj.timeline.prev_batch, this.syncOpts.canResetEntireTimeline(room.roomId) ? null : (_l = syncEventData.oldSyncToken) !== null && _l !== void 0 ? _l : null); - // We have to assume any gap in any timeline is - // reason to stop incrementally tracking notifications and - // reset the timeline. - client.resetNotifTimelineSet(); - } - } - // process any crypto events *before* emitting the RoomStateEvent events. This - // avoids a race condition if the application tries to send a message after the - // state event is processed, but before crypto is enabled, which then causes the - // crypto layer to complain. - if (this.syncOpts.cryptoCallbacks) { - for (const e of stateEvents.concat(events)) { - if (e.isState() && e.getType() === event_1.EventType.RoomEncryption && e.getStateKey() === "") { - yield this.syncOpts.cryptoCallbacks.onCryptoEvent(room, e); - } - } - } - try { - yield this.injectRoomEvents(room, stateEvents, events, syncEventData.fromCache); - } - catch (e) { - logger_1.logger.error(`Failed to process events on room ${room.roomId}:`, e); - } - // set summary after processing events, - // because it will trigger a name calculation - // which needs the room state to be up to date - if (joinObj.summary) { - room.setSummary(joinObj.summary); - } - // we deliberately don't add ephemeral events to the timeline - room.addEphemeralEvents(ephemeralEvents); - // we deliberately don't add accountData to the timeline - room.addAccountData(accountDataEvents); - room.recalculate(); - if (joinObj.isBrandNewRoom) { - client.store.storeRoom(room); - client.emit(client_1.ClientEvent.Room, room); - } - this.processEventsForNotifs(room, events); - const emitEvent = (e) => client.emit(client_1.ClientEvent.Event, e); - stateEvents.forEach(emitEvent); - events.forEach(emitEvent); - ephemeralEvents.forEach(emitEvent); - accountDataEvents.forEach(emitEvent); - // Decrypt only the last message in all rooms to make sure we can generate a preview - // And decrypt all events after the recorded read receipt to ensure an accurate - // notification count - room.decryptCriticalEvents(); - })); - // Handle leaves (e.g. kicked rooms) - yield utils.promiseMapSeries(leaveRooms, (leaveObj) => __awaiter(this, void 0, void 0, function* () { - const room = leaveObj.room; - const stateEvents = this.mapSyncEventsFormat(leaveObj.state, room); - const events = this.mapSyncEventsFormat(leaveObj.timeline, room); - const accountDataEvents = this.mapSyncEventsFormat(leaveObj.account_data); - yield this.injectRoomEvents(room, stateEvents, events); - room.addAccountData(accountDataEvents); - room.recalculate(); - if (leaveObj.isBrandNewRoom) { - client.store.storeRoom(room); - client.emit(client_1.ClientEvent.Room, room); - } - this.processEventsForNotifs(room, events); - stateEvents.forEach(function (e) { - client.emit(client_1.ClientEvent.Event, e); - }); - events.forEach(function (e) { - client.emit(client_1.ClientEvent.Event, e); - }); - accountDataEvents.forEach(function (e) { - client.emit(client_1.ClientEvent.Event, e); - }); - })); - // update the notification timeline, if appropriate. - // we only do this for live events, as otherwise we can't order them sanely - // in the timeline relative to ones paginated in by /notifications. - // XXX: we could fix this by making EventTimeline support chronological - // ordering... but it doesn't, right now. - if (syncEventData.oldSyncToken && this.notifEvents.length) { - this.notifEvents.sort(function (a, b) { - return a.getTs() - b.getTs(); - }); - this.notifEvents.forEach(function (event) { - var _a; - (_a = client.getNotifTimelineSet()) === null || _a === void 0 ? void 0 : _a.addLiveEvent(event); - }); - } - // Handle device list updates - if (data.device_lists) { - if (this.syncOpts.crypto) { - yield this.syncOpts.crypto.handleDeviceListChanges(syncEventData, data.device_lists); - } - else { - // FIXME if we *don't* have a crypto module, we still need to - // invalidate the device lists. But that would require a - // substantial bit of rework :/. - } - } - // Handle one_time_keys_count - if (data.device_one_time_keys_count) { - const map = new Map(Object.entries(data.device_one_time_keys_count)); - (_c = this.syncOpts.cryptoCallbacks) === null || _c === void 0 ? void 0 : _c.preprocessOneTimeKeyCounts(map); - } - if (data.device_unused_fallback_key_types || data["org.matrix.msc2732.device_unused_fallback_key_types"]) { - // The presence of device_unused_fallback_key_types indicates that the - // server supports fallback keys. If there's no unused - // signed_curve25519 fallback key we need a new one. - const unusedFallbackKeys = data.device_unused_fallback_key_types || data["org.matrix.msc2732.device_unused_fallback_key_types"]; - (_d = this.syncOpts.cryptoCallbacks) === null || _d === void 0 ? void 0 : _d.preprocessUnusedFallbackKeys(new Set(unusedFallbackKeys || null)); - } - }); - } - /** - * 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 === undefined) { - delay = 2000 + Math.floor(Math.random() * 5000); - } - if (this.keepAliveTimer !== null) { - clearTimeout(this.keepAliveTimer); - } - if (delay > 0) { - this.keepAliveTimer = setTimeout(this.pokeKeepAlive.bind(this), delay); - } - else { - this.pokeKeepAlive(); - } - if (!this.connectionReturnedDefer) { - this.connectionReturnedDefer = utils.defer(); - } - return this.connectionReturnedDefer.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.connectionReturnedDefer. - * - * @param connDidFail - True if a connectivity failure has been detected. Optional. - */ - pokeKeepAlive(connDidFail = false) { - var _a; - const success = () => { - clearTimeout(this.keepAliveTimer); - if (this.connectionReturnedDefer) { - this.connectionReturnedDefer.resolve(connDidFail); - this.connectionReturnedDefer = undefined; - } - }; - this.client.http - .request(http_api_1.Method.Get, "/_matrix/client/versions", undefined, // queryParams - undefined, // data - { - prefix: "", - localTimeoutMs: 15 * 1000, - abortSignal: (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.signal, - }) - .then(() => { - success(); - }, (err) => { - if (err.httpStatus == 400 || err.httpStatus == 404) { - // treat this as a success because the server probably just doesn't - // support /versions: point is, we're getting a response. - // We wait a short time though, just in case somehow the server - // is in a mode where it 400s /versions responses and sync etc. - // responses fail, this will mean we don't hammer in a loop. - this.keepAliveTimer = setTimeout(success, 2000); - } - else { - connDidFail = true; - this.keepAliveTimer = setTimeout(this.pokeKeepAlive.bind(this, connDidFail), 5000 + Math.floor(Math.random() * 5000)); - // A keepalive has failed, so we emit the - // error state (whether or not this is the - // first failure). - // Note we do this after setting the timer: - // this lets the unit tests advance the mock - // clock when they get the error. - this.updateSyncState(SyncState.Error, { error: err }); - } - }); - } - mapSyncResponseToRoomArray(obj) { - // Maps { roomid: {stuff}, roomid: {stuff} } - // to - // [{stuff+Room+isBrandNewRoom}, {stuff+Room+isBrandNewRoom}] - const client = this.client; - return Object.keys(obj) - .filter((k) => !(0, utils_1.unsafeProp)(k)) - .map((roomId) => { - const arrObj = obj[roomId]; - let room = client.store.getRoom(roomId); - let isBrandNewRoom = false; - if (!room) { - room = this.createRoom(roomId); - isBrandNewRoom = true; - } - arrObj.room = room; - arrObj.isBrandNewRoom = isBrandNewRoom; - return arrObj; - }); - } - mapSyncEventsFormat(obj, room, decrypt = true) { - if (!obj || !Array.isArray(obj.events)) { - return []; - } - const mapper = this.client.getEventMapper({ decrypt }); - return obj.events.filter(utils_1.noUnsafeEventProps).map(function (e) { - if (room) { - e.room_id = room.roomId; - } - return mapper(e); - }); - } - /** - */ - resolveInvites(room) { - if (!room || !this.opts.resolveInvitesToProfiles) { - return; - } - const client = this.client; - // For each invited room member we want to give them a displayname/avatar url - // if they have one (the m.room.member invites don't contain this). - room.getMembersWithMembership("invite").forEach(function (member) { - if (member.requestedProfileInfo) - return; - member.requestedProfileInfo = true; - // try to get a cached copy first. - const user = client.getUser(member.userId); - let promise; - if (user) { - promise = Promise.resolve({ - avatar_url: user.avatarUrl, - displayname: user.displayName, - }); - } - else { - promise = client.getProfileInfo(member.userId); - } - promise.then(function (info) { - // slightly naughty by doctoring the invite event but this means all - // the code paths remain the same between invite/join display name stuff - // which is a worthy trade-off for some minor pollution. - const inviteEvent = member.events.member; - if ((inviteEvent === null || inviteEvent === void 0 ? void 0 : inviteEvent.getContent().membership) !== "invite") { - // between resolving and now they have since joined, so don't clobber - return; - } - inviteEvent.getContent().avatar_url = info.avatar_url; - inviteEvent.getContent().displayname = info.displayname; - // fire listeners - member.setMembershipEvent(inviteEvent, room.currentState); - }, function (err) { - // OH WELL. - }); - }); - } - /** - * 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 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 - */ - injectRoomEvents(room, stateEventList, timelineEventList, fromCache = false) { - return __awaiter(this, void 0, void 0, function* () { - // If there are no events in the timeline yet, initialise it with - // the given state events - const liveTimeline = room.getLiveTimeline(); - const timelineWasEmpty = liveTimeline.getEvents().length == 0; - if (timelineWasEmpty) { - // Passing these events into initialiseState will freeze them, so we need - // to compute and cache the push actions for them now, otherwise sync dies - // with an attempt to assign to read only property. - // XXX: This is pretty horrible and is assuming all sorts of behaviour from - // these functions that it shouldn't be. We should probably either store the - // push actions cache elsewhere so we can freeze MatrixEvents, or otherwise - // find some solution where MatrixEvents are immutable but allow for a cache - // field. - for (const ev of stateEventList) { - this.client.getPushActionsForEvent(ev); - } - liveTimeline.initialiseState(stateEventList, { - timelineWasEmpty, - }); - } - this.resolveInvites(room); - // recalculate the room name at this point as adding events to the timeline - // may make notifications appear which should have the right name. - // XXX: This looks suspect: we'll end up recalculating the room once here - // and then again after adding events (processSyncResponse calls it after - // calling us) even if no state events were added. It also means that if - // one of the room events in timelineEventList is something that needs - // a recalculation (like m.room.name) we won't recalculate until we've - // finished adding all the events, which will cause the notification to have - // the old room name rather than the new one. - room.recalculate(); - // If the timeline wasn't empty, we process the state events here: they're - // defined as updates to the state before the start of the timeline, so this - // starts to roll the state forward. - // XXX: That's what we *should* do, but this can happen if we were previously - // peeking in a room, in which case we obviously do *not* want to add the - // state events here onto the end of the timeline. Historically, the js-sdk - // has just set these new state events on the old and new state. This seems - // very wrong because there could be events in the timeline that diverge the - // state, in which case this is going to leave things out of sync. However, - // for now I think it;s best to behave the same as the code has done previously. - if (!timelineWasEmpty) { - // XXX: As above, don't do this... - //room.addLiveEvents(stateEventList || []); - // Do this instead... - room.oldState.setStateEvents(stateEventList || []); - room.currentState.setStateEvents(stateEventList || []); - } - // Execute the timeline events. This will continue to diverge the current state - // if the timeline has any state events in it. - // This also needs to be done before running push rules on the events as they need - // to be decorated with sender etc. - room.addLiveEvents(timelineEventList || [], { - fromCache, - timelineWasEmpty, - }); - this.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) { - var _a; - // gather our notifications into this.notifEvents - if (this.client.getNotifTimelineSet()) { - for (const event of timelineEventList) { - const pushActions = this.client.getPushActionsForEvent(event); - if ((pushActions === null || pushActions === void 0 ? void 0 : pushActions.notify) && ((_a = pushActions.tweaks) === null || _a === void 0 ? void 0 : _a.highlight)) { - this.notifEvents.push(event); - } - } - } - } - getGuestFilter() { - // Dev note: This used to be conditional to return a filter of 20 events maximum, but - // the condition never went to the other branch. This is now hardcoded. - 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) { - const old = this.syncState; - this.syncState = newState; - this.syncStateData = data; - this.client.emit(client_1.ClientEvent.Sync, this.syncState, old, data); - } -} -exports.SyncApi = SyncApi; -function createNewUser(client, userId) { - const user = new user_1.User(userId); - client.reEmitter.reEmit(user, [ - user_1.UserEvent.AvatarUrl, - user_1.UserEvent.DisplayName, - user_1.UserEvent.Presence, - user_1.UserEvent.CurrentlyActive, - user_1.UserEvent.LastPresenceTs, - ]); - return user; -} -// /!\ This function is not intended for public use! It's only exported from -// here in order to share some common logic with sliding-sync-sdk.ts. -function _createAndReEmitRoom(client, roomId, opts) { - const { timelineSupport } = client; - const room = new room_1.Room(roomId, client, client.getUserId(), { - lazyLoadMembers: opts.lazyLoadMembers, - pendingEventOrdering: opts.pendingEventOrdering, - timelineSupport, - }); - client.reEmitter.reEmit(room, [ - room_1.RoomEvent.Name, - room_1.RoomEvent.Redaction, - room_1.RoomEvent.RedactionCancelled, - room_1.RoomEvent.Receipt, - room_1.RoomEvent.Tags, - room_1.RoomEvent.LocalEchoUpdated, - room_1.RoomEvent.AccountData, - room_1.RoomEvent.MyMembership, - room_1.RoomEvent.Timeline, - room_1.RoomEvent.TimelineReset, - room_state_1.RoomStateEvent.Events, - room_state_1.RoomStateEvent.Members, - room_state_1.RoomStateEvent.NewMember, - room_state_1.RoomStateEvent.Update, - beacon_1.BeaconEvent.New, - beacon_1.BeaconEvent.Update, - beacon_1.BeaconEvent.Destroy, - beacon_1.BeaconEvent.LivenessChange, - ]); - // We need to add a listener for RoomState.members in order to hook them - // correctly. - room.on(room_state_1.RoomStateEvent.NewMember, (event, state, member) => { - var _a; - member.user = (_a = client.getUser(member.userId)) !== null && _a !== void 0 ? _a : undefined; - client.reEmitter.reEmit(member, [ - room_member_1.RoomMemberEvent.Name, - room_member_1.RoomMemberEvent.Typing, - room_member_1.RoomMemberEvent.PowerLevel, - room_member_1.RoomMemberEvent.Membership, - ]); - }); - return room; -} -exports._createAndReEmitRoom = _createAndReEmitRoom; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) - -},{"./@types/event":306,"./@types/sync":314,"./client":321,"./errors":359,"./feature":362,"./filter":364,"./http-api":367,"./logger":374,"./models/beacon":378,"./models/event-timeline":382,"./models/room":392,"./models/room-member":389,"./models/room-state":390,"./models/user":396,"./utils":416}],415:[function(require,module,exports){ -"use strict"; -/* -Copyright 2016 - 2021 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TimelineIndex = exports.TimelineWindow = void 0; -const event_timeline_1 = require("./models/event-timeline"); -const logger_1 = require("./logger"); -/** - * @internal - */ -const DEBUG = false; -/** - * @internal - */ -/* istanbul ignore next */ -const debuglog = DEBUG ? logger_1.logger.log.bind(logger_1.logger) : function () { }; -/** - * the number of times we ask the server for more events before giving up - * - * @internal - */ -const DEFAULT_PAGINATE_LOOP_LIMIT = 5; -class TimelineWindow { - /** - * Construct a TimelineWindow. - * - *

This abstracts the separate timelines in a Matrix {@link Room} into a single iterable thing. - * It keeps track of the start and endpoints of the window, which can be advanced with the help - * of pagination requests. - * - *

Before the window is useful, it must be initialised by calling {@link TimelineWindow#load}. - * - *

Note that the window will not automatically extend itself when new events - * are received from /sync; you should arrange to call {@link TimelineWindow#paginate} - * on {@link RoomEvent.Timeline} events. - * - * @param client - MatrixClient to be used for context/pagination - * requests. - * - * @param timelineSet - The timelineSet to track - * - * @param opts - Configuration options for this window - */ - constructor(client, timelineSet, opts = {}) { - this.client = client; - this.timelineSet = timelineSet; - this.eventCount = 0; - this.windowLimit = opts.windowLimit || 1000; - } - /** - * Initialise the window to point at a given event, or the live timeline - * - * @param initialEventId - If given, the window will contain the - * given event - * @param initialWindowSize - Size of the initial window - */ - load(initialEventId, initialWindowSize = 20) { - // given an EventTimeline, find the event we were looking for, and initialise our - // fields so that the event in question is in the middle of the window. - const initFields = (timeline) => { - if (!timeline) { - throw new Error("No timeline given to initFields"); - } - let eventIndex; - const events = timeline.getEvents(); - if (!initialEventId) { - // we were looking for the live timeline: initialise to the end - eventIndex = events.length; - } - else { - eventIndex = events.findIndex((e) => e.getId() === initialEventId); - if (eventIndex < 0) { - throw new Error("getEventTimeline result didn't include requested event"); - } - } - const endIndex = Math.min(events.length, eventIndex + Math.ceil(initialWindowSize / 2)); - const startIndex = Math.max(0, endIndex - initialWindowSize); - this.start = new TimelineIndex(timeline, startIndex - timeline.getBaseIndex()); - this.end = new TimelineIndex(timeline, endIndex - timeline.getBaseIndex()); - this.eventCount = endIndex - startIndex; - }; - // We avoid delaying the resolution of the promise by a reactor tick if we already have the data we need, - // which is important to keep room-switching feeling snappy. - if (this.timelineSet.getTimelineForEvent(initialEventId)) { - initFields(this.timelineSet.getTimelineForEvent(initialEventId)); - return Promise.resolve(); - } - else if (initialEventId) { - return this.client.getEventTimeline(this.timelineSet, initialEventId).then(initFields); - } - else { - initFields(this.timelineSet.getLiveTimeline()); - return Promise.resolve(); - } - } - /** - * Get the TimelineIndex of the window in the given direction. - * - * @param direction - EventTimeline.BACKWARDS to get the TimelineIndex - * at the start of the window; EventTimeline.FORWARDS to get the TimelineIndex at - * the end. - * - * @returns The requested timeline index if one exists, null - * otherwise. - */ - getTimelineIndex(direction) { - var _a, _b; - if (direction == event_timeline_1.EventTimeline.BACKWARDS) { - return (_a = this.start) !== null && _a !== void 0 ? _a : null; - } - else if (direction == event_timeline_1.EventTimeline.FORWARDS) { - return (_b = this.end) !== null && _b !== void 0 ? _b : null; - } - else { - throw new Error("Invalid direction '" + direction + "'"); - } - } - /** - * Try to extend the window using events that are already in the underlying - * TimelineIndex. - * - * @param direction - EventTimeline.BACKWARDS to try extending it - * backwards; EventTimeline.FORWARDS to try extending it forwards. - * @param size - number of events to try to extend by. - * - * @returns true if the window was extended, false otherwise. - */ - extend(direction, size) { - const tl = this.getTimelineIndex(direction); - if (!tl) { - debuglog("TimelineWindow: no timeline yet"); - return false; - } - const count = direction == event_timeline_1.EventTimeline.BACKWARDS ? tl.retreat(size) : tl.advance(size); - if (count) { - this.eventCount += count; - debuglog("TimelineWindow: increased cap by " + count + " (now " + this.eventCount + ")"); - // remove some events from the other end, if necessary - const excess = this.eventCount - this.windowLimit; - if (excess > 0) { - this.unpaginate(excess, direction != event_timeline_1.EventTimeline.BACKWARDS); - } - return true; - } - return false; - } - /** - * Check if this window can be extended - * - *

This returns true if we either have more events, or if we have a - * pagination token which means we can paginate in that direction. It does not - * necessarily mean that there are more events available in that direction at - * this time. - * - * @param direction - EventTimeline.BACKWARDS to check if we can - * paginate backwards; EventTimeline.FORWARDS to check if we can go forwards - * - * @returns true if we can paginate in the given direction - */ - canPaginate(direction) { - const tl = this.getTimelineIndex(direction); - if (!tl) { - debuglog("TimelineWindow: no timeline yet"); - return false; - } - if (direction == event_timeline_1.EventTimeline.BACKWARDS) { - if (tl.index > tl.minIndex()) { - return true; - } - } - else { - if (tl.index < tl.maxIndex()) { - return true; - } - } - const hasNeighbouringTimeline = tl.timeline.getNeighbouringTimeline(direction); - const paginationToken = tl.timeline.getPaginationToken(direction); - return Boolean(hasNeighbouringTimeline) || Boolean(paginationToken); - } - /** - * Attempt to extend the window - * - * @param direction - EventTimeline.BACKWARDS to extend the window - * backwards (towards older events); EventTimeline.FORWARDS to go forwards. - * - * @param size - number of events to try to extend by. If fewer than this - * number are immediately available, then we return immediately rather than - * making an API call. - * - * @param makeRequest - whether we should make API calls to - * fetch further events if we don't have any at all. (This has no effect if - * the room already knows about additional events in the relevant direction, - * even if there are fewer than 'size' of them, as we will just return those - * we already know about.) - * - * @param requestLimit - limit for the number of API requests we - * should make. - * - * @returns Promise which resolves to a boolean which is true if more events - * were successfully retrieved. - */ - paginate(direction, size, makeRequest = true, requestLimit = DEFAULT_PAGINATE_LOOP_LIMIT) { - return __awaiter(this, void 0, void 0, function* () { - // Either wind back the message cap (if there are enough events in the - // timeline to do so), or fire off a pagination request. - const tl = this.getTimelineIndex(direction); - if (!tl) { - debuglog("TimelineWindow: no timeline yet"); - return false; - } - if (tl.pendingPaginate) { - return tl.pendingPaginate; - } - // try moving the cap - if (this.extend(direction, size)) { - return true; - } - if (!makeRequest || requestLimit === 0) { - // todo: should we return something different to indicate that there - // might be more events out there, but we haven't found them yet? - return false; - } - // try making a pagination request - const token = tl.timeline.getPaginationToken(direction); - if (!token) { - debuglog("TimelineWindow: no token"); - return false; - } - debuglog("TimelineWindow: starting request"); - const prom = this.client - .paginateEventTimeline(tl.timeline, { - backwards: direction == event_timeline_1.EventTimeline.BACKWARDS, - limit: size, - }) - .finally(function () { - tl.pendingPaginate = undefined; - }) - .then((r) => { - debuglog("TimelineWindow: request completed with result " + r); - if (!r) { - return this.paginate(direction, size, false, 0); - } - // recurse to advance the index into the results. - // - // If we don't get any new events, we want to make sure we keep asking - // the server for events for as long as we have a valid pagination - // token. In particular, we want to know if we've actually hit the - // start of the timeline, or if we just happened to know about all of - // the events thanks to https://matrix.org/jira/browse/SYN-645. - // - // On the other hand, we necessarily want to wait forever for the - // server to make its mind up about whether there are other events, - // because it gives a bad user experience - // (https://github.com/vector-im/vector-web/issues/1204). - return this.paginate(direction, size, true, requestLimit - 1); - }); - tl.pendingPaginate = prom; - return prom; - }); - } - /** - * Remove `delta` events from the start or end of the timeline. - * - * @param delta - number of events to remove from the timeline - * @param startOfTimeline - if events should be removed from the start - * of the timeline. - */ - unpaginate(delta, startOfTimeline) { - const tl = startOfTimeline ? this.start : this.end; - if (!tl) { - throw new Error(`Attempting to unpaginate startOfTimeline=${startOfTimeline} but don't have this direction`); - } - // sanity-check the delta - if (delta > this.eventCount || delta < 0) { - throw new Error(`Attemting to unpaginate ${delta} events, but only have ${this.eventCount} in the timeline`); - } - while (delta > 0) { - const count = startOfTimeline ? tl.advance(delta) : tl.retreat(delta); - if (count <= 0) { - // sadness. This shouldn't be possible. - throw new Error("Unable to unpaginate any further, but still have " + this.eventCount + " events"); - } - delta -= count; - this.eventCount -= count; - debuglog("TimelineWindow.unpaginate: dropped " + count + " (now " + this.eventCount + ")"); - } - } - /** - * Get a list of the events currently in the window - * - * @returns the events in the window - */ - getEvents() { - var _a, _b; - if (!this.start) { - // not yet loaded - return []; - } - const result = []; - // iterate through each timeline between this.start and this.end - // (inclusive). - let timeline = this.start.timeline; - // eslint-disable-next-line no-constant-condition - while (true) { - const events = timeline.getEvents(); - // For the first timeline in the chain, we want to start at - // this.start.index. For the last timeline in the chain, we want to - // stop before this.end.index. Otherwise, we want to copy all of the - // events in the timeline. - // - // (Note that both this.start.index and this.end.index are relative - // to their respective timelines' BaseIndex). - // - let startIndex = 0; - let endIndex = events.length; - if (timeline === this.start.timeline) { - startIndex = this.start.index + timeline.getBaseIndex(); - } - if (timeline === ((_a = this.end) === null || _a === void 0 ? void 0 : _a.timeline)) { - endIndex = this.end.index + timeline.getBaseIndex(); - } - for (let i = startIndex; i < endIndex; i++) { - result.push(events[i]); - } - // if we're not done, iterate to the next timeline. - if (timeline === ((_b = this.end) === null || _b === void 0 ? void 0 : _b.timeline)) { - break; - } - else { - timeline = timeline.getNeighbouringTimeline(event_timeline_1.EventTimeline.FORWARDS); - } - } - return result; - } -} -exports.TimelineWindow = TimelineWindow; -/** - * A thing which contains a timeline reference, and an index into it. - * @internal - */ -class TimelineIndex { - // index: the indexes are relative to BaseIndex, so could well be negative. - constructor(timeline, index) { - this.timeline = timeline; - this.index = index; - } - /** - * @returns the minimum possible value for the index in the current - * timeline - */ - minIndex() { - return this.timeline.getBaseIndex() * -1; - } - /** - * @returns the maximum possible value for the index in the current - * timeline (exclusive - ie, it actually returns one more than the index - * of the last element). - */ - maxIndex() { - return this.timeline.getEvents().length - this.timeline.getBaseIndex(); - } - /** - * Try move the index forward, or into the neighbouring timeline - * - * @param delta - number of events to advance by - * @returns number of events successfully advanced by - */ - advance(delta) { - if (!delta) { - return 0; - } - // first try moving the index in the current timeline. See if there is room - // to do so. - let cappedDelta; - if (delta < 0) { - // we want to wind the index backwards. - // - // (this.minIndex() - this.index) is a negative number whose magnitude - // is the amount of room we have to wind back the index in the current - // timeline. We cap delta to this quantity. - cappedDelta = Math.max(delta, this.minIndex() - this.index); - if (cappedDelta < 0) { - this.index += cappedDelta; - return cappedDelta; - } - } - else { - // we want to wind the index forwards. - // - // (this.maxIndex() - this.index) is a (positive) number whose magnitude - // is the amount of room we have to wind forward the index in the current - // timeline. We cap delta to this quantity. - cappedDelta = Math.min(delta, this.maxIndex() - this.index); - if (cappedDelta > 0) { - this.index += cappedDelta; - return cappedDelta; - } - } - // the index is already at the start/end of the current timeline. - // - // next see if there is a neighbouring timeline to switch to. - const neighbour = this.timeline.getNeighbouringTimeline(delta < 0 ? event_timeline_1.EventTimeline.BACKWARDS : event_timeline_1.EventTimeline.FORWARDS); - if (neighbour) { - this.timeline = neighbour; - if (delta < 0) { - this.index = this.maxIndex(); - } - else { - this.index = this.minIndex(); - } - debuglog("paginate: switched to new neighbour"); - // recurse, using the next timeline - return this.advance(delta); - } - return 0; - } - /** - * Try move the index backwards, or into the neighbouring timeline - * - * @param delta - number of events to retreat by - * @returns number of events successfully retreated by - */ - retreat(delta) { - return this.advance(delta * -1) * -1; - } -} -exports.TimelineIndex = TimelineIndex; - -},{"./logger":374,"./models/event-timeline":382}],416:[function(require,module,exports){ -(function (setImmediate){(function (){ -"use strict"; -/* -Copyright 2015, 2016, 2019, 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MapWithDefault = exports.noUnsafeEventProps = exports.safeSet = exports.unsafeProp = exports.recursiveMapToObject = exports.mapsEqual = exports.isSupportedReceiptType = exports.sortEventsByLatestContentTimestamp = exports.recursivelyAssign = exports.compare = exports.lexicographicCompare = exports.prevString = exports.nextString = exports.averageBetweenStrings = exports.stringToBase = exports.baseToString = exports.alphabetPad = exports.DEFAULT_ALPHABET = exports.simpleRetryOperation = exports.chunkPromises = exports.promiseTry = exports.promiseMapSeries = exports.defer = exports.isNullOrUndefined = exports.immediate = exports.sleep = exports.ensureNoTrailingSlash = exports.globToRegexp = exports.escapeRegExp = exports.normalize = exports.removeDirectionOverrideChars = exports.removeHiddenChars = exports.isNumber = exports.deepSortedObjectEntries = exports.deepCompare = exports.deepCopy = exports.checkObjectHasKeys = exports.isFunction = exports.removeElement = exports.encodeUri = exports.decodeParams = exports.replaceParam = exports.encodeParams = exports.internaliseString = void 0; -/** - * This is an internal module. - */ -const unhomoglyph_1 = __importDefault(require("unhomoglyph")); -const p_retry_1 = __importDefault(require("p-retry")); -const location_1 = require("./@types/location"); -const read_receipts_1 = require("./@types/read_receipts"); -const interns = 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) { - // Unwrap strings before entering the map, if we somehow got a wrapped - // string as our input. This should only happen from tests. - if (str instanceof String) { - str = str.toString(); - } - // Check the map to see if we can store the value - if (!interns.has(str)) { - interns.set(str, str); - } - // Return any cached string reference - return interns.get(str); -} -exports.internaliseString = internaliseString; -/** - * 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) { - const searchParams = urlSearchParams !== null && urlSearchParams !== void 0 ? urlSearchParams : new URLSearchParams(); - for (const [key, val] of Object.entries(params)) { - if (val !== undefined && val !== null) { - if (Array.isArray(val)) { - val.forEach((v) => { - searchParams.append(key, String(v)); - }); - } - else { - searchParams.append(key, String(val)); - } - } - } - return searchParams; -} -exports.encodeParams = encodeParams; -/** - * Replace a stable parameter with the unstable naming for params - */ -function replaceParam(stable, unstable, dict) { - const result = Object.assign(Object.assign({}, dict), { [unstable]: dict[stable] }); - delete result[stable]; - return result; -} -exports.replaceParam = replaceParam; -/** - * Decode a query string in `application/x-www-form-urlencoded` format. - * @param query - A query string to decode e.g. - * foo=bar&via=server1&server2 - * @returns The decoded object, if any keys occurred multiple times - * then the value will be an array of strings, else it will be an array. - * This behaviour matches Node's qs.parse but is built on URLSearchParams - * for native web compatibility - */ -function decodeParams(query) { - const o = {}; - const params = new URLSearchParams(query); - for (const key of params.keys()) { - const val = params.getAll(key); - o[key] = val.length === 1 ? val[0] : val; - } - return o; -} -exports.decodeParams = decodeParams; -/** - * 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 (const key in variables) { - if (!variables.hasOwnProperty(key)) { - continue; - } - const value = variables[key]; - if (value === undefined || value === null) { - continue; - } - pathTemplate = pathTemplate.replace(key, encodeURIComponent(value)); - } - return pathTemplate; -} -exports.encodeUri = encodeUri; -/** - * 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) { - let 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; -} -exports.removeElement = removeElement; -/** - * Checks if the given thing is a function. - * @param value - The thing to check. - * @returns True if it is a function. - */ -function isFunction(value) { - return Object.prototype.toString.call(value) === "[object Function]"; -} -exports.isFunction = isFunction; -/** - * 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. - */ -// note using 'keys' here would shadow the 'keys' function defined above -function checkObjectHasKeys(obj, keys) { - for (const key of keys) { - if (!obj.hasOwnProperty(key)) { - throw new Error("Missing required key: " + key); - } - } -} -exports.checkObjectHasKeys = checkObjectHasKeys; -/** - * 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)); -} -exports.deepCopy = deepCopy; -/** - * 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) { - // Inspired by - // http://stackoverflow.com/questions/1068834/object-comparison-in-javascript#1144249 - // Compare primitives and functions. - // Also check if both arguments link to the same object. - if (x === y) { - return true; - } - if (typeof x !== typeof y) { - return false; - } - // special-case NaN (since NaN !== NaN) - if (typeof x === "number" && isNaN(x) && isNaN(y)) { - return true; - } - // special-case null (since typeof null == 'object', but null.constructor - // throws) - if (x === null || y === null) { - return x === y; - } - // everything else is either an unequal primitive, or an object - if (!(x instanceof Object)) { - return false; - } - // check they are the same type of object - if (x.constructor !== y.constructor || x.prototype !== y.prototype) { - return false; - } - // special-casing for some special types of object - if (x instanceof RegExp || x instanceof Date) { - return x.toString() === y.toString(); - } - // the object algorithm works for Array, but it's sub-optimal. - if (Array.isArray(x)) { - if (x.length !== y.length) { - return false; - } - for (let i = 0; i < x.length; i++) { - if (!deepCompare(x[i], y[i])) { - return false; - } - } - } - else { - // check that all of y's direct keys are in x - for (const p in y) { - if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) { - return false; - } - } - // finally, compare each of x's keys with y - for (const p in x) { - if (y.hasOwnProperty(p) !== x.hasOwnProperty(p) || !deepCompare(x[p], y[p])) { - return false; - } - } - } - return true; -} -exports.deepCompare = deepCompare; -// Dev note: This returns an array of tuples, but jsdoc doesn't like that. https://github.com/jsdoc/jsdoc/issues/1703 -/** - * 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; - // Apparently these are object types... - if (obj === null || obj === undefined || Array.isArray(obj)) - return obj; - const pairs = []; - for (const [k, v] of Object.entries(obj)) { - pairs.push([k, deepSortedObjectEntries(v)]); - } - // lexicographicCompare is faster than localeCompare, so let's use that. - pairs.sort((a, b) => lexicographicCompare(a[0], b[0])); - return pairs; -} -exports.deepSortedObjectEntries = deepSortedObjectEntries; -/** - * 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); -} -exports.isNumber = isNumber; -/** - * 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, unhomoglyph_1.default)(str.normalize("NFD").replace(removeHiddenCharsRegex, "")); - } - return ""; -} -exports.removeHiddenChars = removeHiddenChars; -/** - * 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 ""; -} -exports.removeDirectionOverrideChars = removeDirectionOverrideChars; -function normalize(str) { - // Note: we have to match the filter with the removeHiddenChars() because the - // function strips spaces and other characters (M becomes RN for example, in lowercase). - return (removeHiddenChars(str.toLowerCase()) - // Strip all punctuation - .replace(/[\\'!"#$%&()*+,\-./:;<=>?@[\]^_`{|}~\u2000-\u206f\u2e00-\u2e7f]/g, "") - // We also doubly convert to lowercase to work around oddities of the library. - .toLowerCase()); -} -exports.normalize = normalize; -// Regex matching bunch of unicode control characters and otherwise misleading/invisible characters. -// Includes: -// various width spaces U+2000 - U+200D -// LTR and RTL marks U+200E and U+200F -// LTR/RTL and other directional formatting marks U+202A - U+202F -// Arabic Letter RTL mark U+061C -// Combining characters U+0300 - U+036F -// Zero width no-break space (BOM) U+FEFF -// Blank/invisible characters (U2800, U2062-U2063) -// eslint-disable-next-line no-misleading-character-class -const removeHiddenCharsRegex = /[\u2000-\u200F\u202A-\u202F\u0300-\u036F\uFEFF\u061C\u2800\u2062-\u2063\s]/g; -function escapeRegExp(string) { - return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} -exports.escapeRegExp = escapeRegExp; -function globToRegexp(glob, extended = false) { - // From - // https://github.com/matrix-org/synapse/blob/abbee6b29be80a77e05730707602f3bbfc3f38cb/synapse/push/__init__.py#L132 - // Because micromatch is about 130KB with dependencies, - // and minimatch is not much better. - const replacements = [ - [/\\\*/g, ".*"], - [/\?/g, "."], - ]; - if (!extended) { - replacements.push([ - /\\\[(!|)(.*)\\]/g, - (_match, neg, pat) => ["[", neg ? "^" : "", pat.replace(/\\-/, "-"), "]"].join(""), - ]); - } - return replacements.reduce( - // https://github.com/microsoft/TypeScript/issues/30134 - (pat, args) => (args ? pat.replace(args[0], args[1]) : pat), escapeRegExp(glob)); -} -exports.globToRegexp = globToRegexp; -function ensureNoTrailingSlash(url) { - if (url === null || url === void 0 ? void 0 : url.endsWith("/")) { - return url.slice(0, -1); - } - else { - return url; - } -} -exports.ensureNoTrailingSlash = ensureNoTrailingSlash; -/** - * 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); - }); -} -exports.sleep = sleep; -/** - * Promise/async version of {@link setImmediate}. - */ -function immediate() { - return new Promise(setImmediate); -} -exports.immediate = immediate; -function isNullOrUndefined(val) { - return val === null || val === undefined; -} -exports.isNullOrUndefined = isNullOrUndefined; -// Returns a Deferred -function defer() { - let resolve; - let reject; - const promise = new Promise((_resolve, _reject) => { - resolve = _resolve; - reject = _reject; - }); - return { resolve, reject, promise }; -} -exports.defer = defer; -function promiseMapSeries(promises, fn) { - return __awaiter(this, void 0, void 0, function* () { - for (const o of promises) { - yield fn(yield o); - } - }); -} -exports.promiseMapSeries = promiseMapSeries; -function promiseTry(fn) { - return Promise.resolve(fn()); -} -exports.promiseTry = promiseTry; -// Creates and awaits all promises, running no more than `chunkSize` at the same time -function chunkPromises(fns, chunkSize) { - return __awaiter(this, void 0, void 0, function* () { - const results = []; - for (let i = 0; i < fns.length; i += chunkSize) { - results.push(...(yield Promise.all(fns.slice(i, i + chunkSize).map((fn) => fn())))); - } - return results; - }); -} -exports.chunkPromises = chunkPromises; -/** - * Retries the function until it succeeds or is interrupted. The given function must return - * a promise which throws/rejects on error, otherwise the retry will assume the request - * succeeded. The promise chain returned will contain the successful promise. The given function - * should always return a new promise. - * @param promiseFn - The function to call to get a fresh promise instance. Takes an - * attempt count as an argument, for logging/debugging purposes. - * @returns The promise for the retried operation. - */ -function simpleRetryOperation(promiseFn) { - return (0, p_retry_1.default)((attempt) => { - return promiseFn(attempt); - }, { - forever: true, - factor: 2, - minTimeout: 3000, - maxTimeout: 15000, // ms - }); -} -exports.simpleRetryOperation = simpleRetryOperation; -// String averaging inspired by https://stackoverflow.com/a/2510816 -// Dev note: We make the alphabet a string because it's easier to write syntactically -// than arrays. Thankfully, strings implement the useful parts of the Array interface -// anyhow. -/** - * The default alphabet used by string averaging in this SDK. This matches - * all usefully printable ASCII characters (0x20-0x7E, inclusive). - */ -exports.DEFAULT_ALPHABET = (() => { - let str = ""; - for (let c = 0x20; c <= 0x7e; 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, alphabet = exports.DEFAULT_ALPHABET) { - return s.padEnd(n, alphabet[0]); -} -exports.alphabetPad = alphabetPad; -/** - * 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, alphabet = exports.DEFAULT_ALPHABET) { - // Developer note: the stringToBase() function offsets the character set by 1 so that repeated - // characters (ie: "aaaaaa" in a..z) don't come out as zero. We have to reverse this here as - // otherwise we'll be wrong in our conversion. Undoing a +1 before an exponent isn't very fun - // though, so we rely on a lengthy amount of `x - 1` and integer division rules to reach a - // sane state. This also means we have to do rollover detection: see below. - var _a; - const len = BigInt(alphabet.length); - if (n <= len) { - return (_a = alphabet[Number(n) - 1]) !== null && _a !== void 0 ? _a : ""; - } - let d = n / len; - let r = Number(n % len) - 1; - // Rollover detection: if the remainder is negative, it means that the string needs - // to roll over by 1 character downwards (ie: in a..z, the previous to "aaa" would be - // "zz"). - if (r < 0) { - d -= BigInt(Math.abs(r)); // abs() is just to be clear what we're doing. Could also `+= r`. - r = Number(len) - 1; - } - return baseToString(d, alphabet) + alphabet[r]; -} -exports.baseToString = baseToString; -/** - * 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, alphabet = exports.DEFAULT_ALPHABET) { - const len = BigInt(alphabet.length); - // In our conversion to baseN we do a couple performance optimizations to avoid using - // excess CPU and such. To create baseN numbers, the input string needs to be reversed - // so the exponents stack up appropriately, as the last character in the unreversed - // string has less impact than the first character (in "abc" the A is a lot more important - // for lexicographic sorts). We also do a trick with the character codes to optimize the - // alphabet lookup, avoiding an index scan of `alphabet.indexOf(reversedStr[i])` - we know - // that the alphabet and (theoretically) the input string are constrained on character sets - // and thus can do simple subtraction to end up with the same result. - // Developer caution: we carefully cast to BigInt here to avoid losing precision. We cannot - // rely on Math.pow() (for example) to be capable of handling our insane numbers. - let result = BigInt(0); - for (let i = s.length - 1, j = BigInt(0); i >= 0; i--, j++) { - const charIndex = s.charCodeAt(i) - alphabet.charCodeAt(0); - // We add 1 to the char index to offset the whole numbering scheme. We unpack this in - // the baseToString() function. - result += BigInt(1 + charIndex) * len ** j; - } - return result; -} -exports.stringToBase = stringToBase; -/** - * 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, alphabet = exports.DEFAULT_ALPHABET) { - const padN = Math.max(a.length, b.length); - const baseA = stringToBase(alphabetPad(a, padN, alphabet), alphabet); - const baseB = stringToBase(alphabetPad(b, padN, alphabet), alphabet); - const avg = (baseA + baseB) / BigInt(2); - // Detect integer division conflicts. This happens when two numbers are divided too close so - // we lose a .5 precision. We need to add a padding character in these cases. - if (avg === baseA || avg == baseB) { - return baseToString(avg, alphabet) + alphabet[0]; - } - return baseToString(avg, alphabet); -} -exports.averageBetweenStrings = averageBetweenStrings; -/** - * 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, alphabet = exports.DEFAULT_ALPHABET) { - return baseToString(stringToBase(s, alphabet) + BigInt(1), alphabet); -} -exports.nextString = nextString; -/** - * 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, alphabet = exports.DEFAULT_ALPHABET) { - return baseToString(stringToBase(s, alphabet) - BigInt(1), alphabet); -} -exports.prevString = prevString; -/** - * 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) { - // Dev note: this exists because I'm sad that you can use math operators on strings, so I've - // hidden the operation in this function. - if (a < b) { - return -1; - } - else if (a > b) { - return 1; - } - else { - return 0; - } -} -exports.lexicographicCompare = lexicographicCompare; -const collator = new Intl.Collator(); -/** - * Performant language-sensitive string comparison - * @param a - the first string to compare - * @param b - the second string to compare - */ -function compare(a, b) { - return collator.compare(a, b); -} -exports.compare = compare; -/** - * 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, ignoreNullish = false) { - for (const [sourceKey, sourceValue] of Object.entries(source)) { - if (target[sourceKey] instanceof Object && sourceValue) { - recursivelyAssign(target[sourceKey], sourceValue); - continue; - } - if ((sourceValue !== null && sourceValue !== undefined) || !ignoreNullish) { - target[sourceKey] = sourceValue; - continue; - } - } - return target; -} -exports.recursivelyAssign = recursivelyAssign; -function getContentTimestampWithFallback(event) { - var _a; - return (_a = location_1.M_TIMESTAMP.findIn(event.getContent())) !== null && _a !== void 0 ? _a : -1; -} -/** - * Sort events by their content m.ts property - * Latest timestamp first - */ -function sortEventsByLatestContentTimestamp(left, right) { - return getContentTimestampWithFallback(right) - getContentTimestampWithFallback(left); -} -exports.sortEventsByLatestContentTimestamp = sortEventsByLatestContentTimestamp; -function isSupportedReceiptType(receiptType) { - return [read_receipts_1.ReceiptType.Read, read_receipts_1.ReceiptType.ReadPrivate].includes(receiptType); -} -exports.isSupportedReceiptType = isSupportedReceiptType; -/** - * Determines whether two maps are equal. - * @param eq - The equivalence relation to compare values by. Defaults to strict equality. - */ -function mapsEqual(x, y, eq = (v1, v2) => v1 === v2) { - if (x.size !== y.size) - return false; - for (const [k, v1] of x) { - const v2 = y.get(k); - if (v2 === undefined || !eq(v1, v2)) - return false; - } - return true; -} -exports.mapsEqual = mapsEqual; -function processMapToObjectValue(value) { - if (value instanceof Map) { - // Value is a Map. Recursively map it to an object. - return recursiveMapToObject(value); - } - else if (Array.isArray(value)) { - // Value is an Array. Recursively map the value (e.g. to cover Array of Arrays). - return value.map((v) => processMapToObjectValue(v)); - } - else { - return value; - } -} -/** - * Recursively converts Maps to plain objects. - * Also supports sub-lists of Maps. - */ -function recursiveMapToObject(map) { - const targetMap = new Map(); - for (const [key, value] of map) { - targetMap.set(key, processMapToObjectValue(value)); - } - return Object.fromEntries(targetMap.entries()); -} -exports.recursiveMapToObject = recursiveMapToObject; -function unsafeProp(prop) { - return prop === "__proto__" || prop === "prototype" || prop === "constructor"; -} -exports.unsafeProp = unsafeProp; -function safeSet(obj, prop, value) { - if (unsafeProp(prop)) { - throw new Error("Trying to modify prototype or constructor"); - } - obj[prop] = value; -} -exports.safeSet = safeSet; -function noUnsafeEventProps(event) { - return !(unsafeProp(event.room_id) || - unsafeProp(event.sender) || - unsafeProp(event.user_id) || - unsafeProp(event.event_id)); -} -exports.noUnsafeEventProps = noUnsafeEventProps; -class MapWithDefault 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); - } -} -exports.MapWithDefault = MapWithDefault; - -}).call(this)}).call(this,require("timers").setImmediate) - -},{"./@types/location":308,"./@types/read_receipts":311,"p-retry":225,"timers":280,"unhomoglyph":282}],417:[function(require,module,exports){ -"use strict"; -/* -Copyright 2022 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.releaseContext = exports.acquireContext = void 0; -let audioContext = null; -let 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 - */ -const acquireContext = () => { - if (audioContext === null) - audioContext = new AudioContext(); - refCount++; - return audioContext; -}; -exports.acquireContext = acquireContext; -/** - * 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. - */ -const releaseContext = () => { - refCount--; - if (refCount === 0) { - audioContext === null || audioContext === void 0 ? void 0 : audioContext.close(); - audioContext = null; - } -}; -exports.releaseContext = releaseContext; - -},{}],418:[function(require,module,exports){ -(function (process){(function (){ -"use strict"; -/* -Copyright 2015, 2016 OpenMarket Ltd -Copyright 2017 New Vector Ltd -Copyright 2019, 2020 The Matrix.org Foundation C.I.C. -Copyright 2021 - 2022 Šimon Brandner - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createNewMatrixCall = exports.supportsMatrixCall = exports.setTracksEnabled = exports.MatrixCall = exports.genCallID = exports.CallError = exports.CallErrorCode = exports.CallEvent = exports.CallParty = exports.CallDirection = exports.CallType = exports.CallState = void 0; -/** - * This is an internal module. See {@link createNewMatrixCall} for the public API. - */ -const uuid_1 = require("uuid"); -const sdp_transform_1 = require("sdp-transform"); -const logger_1 = require("../logger"); -const utils = __importStar(require("../utils")); -const event_1 = require("../@types/event"); -const randomstring_1 = require("../randomstring"); -const callEventTypes_1 = require("./callEventTypes"); -const callFeed_1 = require("./callFeed"); -const typed_event_emitter_1 = require("../models/typed-event-emitter"); -const deviceinfo_1 = require("../crypto/deviceinfo"); -const groupCall_1 = require("./groupCall"); -const http_api_1 = require("../http-api"); -var MediaType; -(function (MediaType) { - MediaType["AUDIO"] = "audio"; - MediaType["VIDEO"] = "video"; -})(MediaType || (MediaType = {})); -var CodecName; -(function (CodecName) { - CodecName["OPUS"] = "opus"; - // add more as needed -})(CodecName || (CodecName = {})); -var CallState; -(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"; -})(CallState = exports.CallState || (exports.CallState = {})); -var CallType; -(function (CallType) { - CallType["Voice"] = "voice"; - CallType["Video"] = "video"; -})(CallType = exports.CallType || (exports.CallType = {})); -var CallDirection; -(function (CallDirection) { - CallDirection["Inbound"] = "inbound"; - CallDirection["Outbound"] = "outbound"; -})(CallDirection = exports.CallDirection || (exports.CallDirection = {})); -var CallParty; -(function (CallParty) { - CallParty["Local"] = "local"; - CallParty["Remote"] = "remote"; -})(CallParty = exports.CallParty || (exports.CallParty = {})); -var CallEvent; -(function (CallEvent) { - CallEvent["Hangup"] = "hangup"; - CallEvent["State"] = "state"; - CallEvent["Error"] = "error"; - CallEvent["Replaced"] = "replaced"; - // The value of isLocalOnHold() has changed - CallEvent["LocalHoldUnhold"] = "local_hold_unhold"; - // The value of isRemoteOnHold() has changed - CallEvent["RemoteHoldUnhold"] = "remote_hold_unhold"; - // backwards compat alias for LocalHoldUnhold: remove in a major version bump - CallEvent["HoldUnhold"] = "hold_unhold"; - // Feeds have changed - CallEvent["FeedsChanged"] = "feeds_changed"; - CallEvent["AssertedIdentityChanged"] = "asserted_identity_changed"; - CallEvent["LengthChanged"] = "length_changed"; - CallEvent["DataChannel"] = "datachannel"; - CallEvent["SendVoipEvent"] = "send_voip_event"; -})(CallEvent = exports.CallEvent || (exports.CallEvent = {})); -var CallErrorCode; -(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"; -})(CallErrorCode = exports.CallErrorCode || (exports.CallErrorCode = {})); -/** - * The version field that we set in m.call.* events - */ -const VOIP_PROTO_VERSION = "1"; -/** The fallback ICE server to use for STUN or TURN protocols. */ -const FALLBACK_ICE_SERVER = "stun:turn.matrix.org"; -/** The length of time a call can be ringing for. */ -const CALL_TIMEOUT_MS = 60 * 1000; // ms -/** The time after which we increment callLength */ -const CALL_LENGTH_INTERVAL = 1000; // ms -/** The time after which we end the call, if ICE got disconnected */ -const ICE_DISCONNECTED_TIMEOUT = 30 * 1000; // ms -class CallError extends Error { - constructor(code, msg, err) { - // Still don't think there's any way to have proper nested errors - super(msg + ": " + err); - this.code = code; - } -} -exports.CallError = CallError; -function genCallID() { - return Date.now().toString() + (0, randomstring_1.randomString)(16); -} -exports.genCallID = genCallID; -function getCodecParamMods(isPtt) { - const mods = [ - { - mediaType: "audio", - codec: "opus", - enableDtx: true, - maxAverageBitrate: isPtt ? 12000 : undefined, - }, - ]; - return mods; -} -// generates keys for the map of transceivers -// kind is unfortunately a string rather than MediaType as this is the type of -// track.kind -function getTransceiverKey(purpose, kind) { - return purpose + ":" + kind; -} -class MatrixCall extends typed_event_emitter_1.TypedEventEmitter { - /** - * Construct a new Matrix Call. - * @param opts - Config options. - */ - constructor(opts) { - var _a; - super(); - this.toDeviceSeq = 0; - // whether this call should have push-to-talk semantics - // This should be set by the consumer on incoming & outgoing calls. - this.isPtt = false; - this._state = CallState.Fledgling; - // A queue for candidates waiting to go out. - // We try to amalgamate candidates into a single candidate message where - // possible - this.candidateSendQueue = []; - this.candidateSendTries = 0; - this.candidatesEnded = false; - this.feeds = []; - // our transceivers for each purpose and type of media - this.transceivers = new Map(); - this.inviteOrAnswerSent = false; - this.waitForLocalAVStream = false; - this.removeTrackListeners = new Map(); - // The logic of when & if a call is on hold is nontrivial and explained in is*OnHold - // This flag represents whether we want the other party to be on hold - this.remoteOnHold = false; - // Perfect negotiation state: https://www.w3.org/TR/webrtc/#perfect-negotiation-example - this.makingOffer = false; - this.ignoreOffer = false; - // If candidates arrive before we've picked an opponent (which, in particular, - // will happen if the opponent sends candidates eagerly before the user answers - // the call) we buffer them up here so we can then add the ones from the party we pick - this.remoteCandidateBuffer = new Map(); - /** - * Internal - */ - this.gotLocalIceCandidate = (event) => { - if (event.candidate) { - if (this.candidatesEnded) { - logger_1.logger.warn(`Call ${this.callId} gotLocalIceCandidate() got candidate after candidates have ended - ignoring!`); - return; - } - logger_1.logger.debug(`Call ${this.callId} got local ICE ${event.candidate.sdpMid} ${event.candidate.candidate}`); - if (this.callHasEnded()) - return; - // As with the offer, note we need to make a copy of this object, not - // pass the original: that broke in Chrome ~m43. - if (event.candidate.candidate === "") { - this.queueCandidate(null); - } - else { - this.queueCandidate(event.candidate); - } - } - }; - this.onIceGatheringStateChange = (event) => { - var _a; - logger_1.logger.debug(`Call ${this.callId} onIceGatheringStateChange() ice gathering state changed to ${this.peerConn.iceGatheringState}`); - if (((_a = this.peerConn) === null || _a === void 0 ? void 0 : _a.iceGatheringState) === "complete") { - this.queueCandidate(null); - } - }; - this.getLocalOfferFailed = (err) => { - logger_1.logger.error(`Call ${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); - }; - this.getUserMediaFailed = (err) => { - if (this.successor) { - this.successor.getUserMediaFailed(err); - return; - } - logger_1.logger.warn(`Call ${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); - }; - this.onIceConnectionStateChanged = () => { - var _a, _b, _c, _d, _e, _f; - if (this.callHasEnded()) { - return; // because ICE can still complete as we're ending the call - } - logger_1.logger.debug(`Call ${this.callId} onIceConnectionStateChanged() running (state=${(_a = this.peerConn) === null || _a === void 0 ? void 0 : _a.iceConnectionState})`); - // ideally we'd consider the call to be connected when we get media but - // chrome doesn't implement any of the 'onstarted' events yet - if (["connected", "completed"].includes((_c = (_b = this.peerConn) === null || _b === void 0 ? void 0 : _b.iceConnectionState) !== null && _c !== void 0 ? _c : "")) { - clearTimeout(this.iceDisconnectedTimeout); - this.iceDisconnectedTimeout = undefined; - 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) / 1000), this); - }, CALL_LENGTH_INTERVAL); - } - } - else if (((_d = this.peerConn) === null || _d === void 0 ? void 0 : _d.iceConnectionState) == "failed") { - // Firefox for Android does not yet have support for restartIce() - // (the types say it's always defined though, so we have to cast - // to prevent typescript from warning). - if ((_e = this.peerConn) === null || _e === void 0 ? void 0 : _e.restartIce) { - this.candidatesEnded = false; - this.peerConn.restartIce(); - } - else { - logger_1.logger.info(`Call ${this.callId} onIceConnectionStateChanged() hanging up call (ICE failed and no ICE restart method)`); - this.hangup(CallErrorCode.IceFailed, false); - } - } - else if (((_f = this.peerConn) === null || _f === void 0 ? void 0 : _f.iceConnectionState) == "disconnected") { - this.iceDisconnectedTimeout = setTimeout(() => { - logger_1.logger.info(`Call ${this.callId} onIceConnectionStateChanged() hanging up call (ICE disconnected for too long)`); - this.hangup(CallErrorCode.IceFailed, false); - }, ICE_DISCONNECTED_TIMEOUT); - this.state = CallState.Connecting; - } - // In PTT mode, override feed status to muted when we lose connection to - // the peer, since we don't want to block the line if they're not saying anything. - // Experimenting in Chrome, this happens after 5 or 6 seconds, which is probably - // fast enough. - if (this.isPtt && ["failed", "disconnected"].includes(this.peerConn.iceConnectionState)) { - for (const feed of this.getRemoteFeeds()) { - feed.setAudioVideoMuted(true, true); - } - } - }; - this.onSignallingStateChanged = () => { - var _a; - logger_1.logger.debug(`Call ${this.callId} onSignallingStateChanged() running (state=${(_a = this.peerConn) === null || _a === void 0 ? void 0 : _a.signalingState})`); - }; - this.onTrack = (ev) => { - if (ev.streams.length === 0) { - logger_1.logger.warn(`Call ${this.callId} onTrack() called with streamless track streamless (kind=${ev.track.kind})`); - return; - } - const stream = ev.streams[0]; - this.pushRemoteFeed(stream); - if (!this.removeTrackListeners.has(stream)) { - const onRemoveTrack = () => { - if (stream.getTracks().length === 0) { - logger_1.logger.info(`Call ${this.callId} onTrack() removing track (streamId=${stream.id})`); - this.deleteFeedByStream(stream); - stream.removeEventListener("removetrack", onRemoveTrack); - this.removeTrackListeners.delete(stream); - } - }; - stream.addEventListener("removetrack", onRemoveTrack); - this.removeTrackListeners.set(stream, onRemoveTrack); - } - }; - this.onDataChannel = (ev) => { - this.emit(CallEvent.DataChannel, ev.channel, this); - }; - this.onNegotiationNeeded = () => __awaiter(this, void 0, void 0, function* () { - logger_1.logger.info(`Call ${this.callId} onNegotiationNeeded() negotiation is needed!`); - if (this.state !== CallState.CreateOffer && this.opponentVersion === 0) { - logger_1.logger.info(`Call ${this.callId} onNegotiationNeeded() opponent does not support renegotiation: ignoring negotiationneeded event`); - return; - } - this.queueGotLocalOffer(); - }); - this.onHangupReceived = (msg) => { - logger_1.logger.debug(`Call ${this.callId} onHangupReceived() running`); - // party ID must match (our chosen partner hanging up the call) or be undefined (we haven't chosen - // a partner yet but we're treating the hangup as a reject as per VoIP v0) - if (this.partyIdMatches(msg) || this.state === CallState.Ringing) { - // default reason is user_hangup - this.terminate(CallParty.Remote, msg.reason || CallErrorCode.UserHangup, true); - } - else { - logger_1.logger.info(`Call ${this.callId} onHangupReceived() ignoring message from party ID ${msg.party_id}: our partner is ${this.opponentPartyId}`); - } - }; - this.onRejectReceived = (msg) => { - logger_1.logger.debug(`Call ${this.callId} onRejectReceived() running`); - // No need to check party_id for reject because if we'd received either - // an answer or reject, we wouldn't be in state InviteSent - const shouldTerminate = - // reject events also end the call if it's ringing: it's another of - // our devices rejecting the call. - [CallState.InviteSent, CallState.Ringing].includes(this.state) || - // also if we're in the init state and it's an inbound call, since - // this means we just haven't entered the ringing state yet - (this.state === CallState.Fledgling && this.direction === CallDirection.Inbound); - if (shouldTerminate) { - this.terminate(CallParty.Remote, msg.reason || CallErrorCode.UserHangup, true); - } - else { - logger_1.logger.debug(`Call ${this.callId} onRejectReceived() called in wrong state (state=${this.state})`); - } - }; - this.onAnsweredElsewhere = (msg) => { - logger_1.logger.debug(`Call ${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 = (_a = opts.forceTURN) !== null && _a !== void 0 ? _a : false; - this.ourPartyId = this.client.deviceId; - this.opponentDeviceId = opts.opponentDeviceId; - this.opponentSessionId = opts.opponentSessionId; - this.groupCallId = opts.groupCallId; - // Array of Objects with urls, username, credential keys - this.turnServers = opts.turnServers || []; - if (this.turnServers.length === 0 && this.client.isFallbackICEServerAllowed()) { - this.turnServers.push({ - urls: [FALLBACK_ICE_SERVER], - }); - } - for (const server of this.turnServers) { - utils.checkObjectHasKeys(server, ["urls"]); - } - this.callId = genCallID(); - // If the Client provides calls without audio and video we need a datachannel for a webrtc connection - this.isOnlyDataChannelAllowed = this.client.isVoipWithNoMediaAllowed; - } - /** - * Place a voice call to this room. - * @throws If you have not specified a listener for 'error' events. - */ - placeVoiceCall() { - return __awaiter(this, void 0, void 0, function* () { - yield this.placeCall(true, false); - }); - } - /** - * Place a video call to this room. - * @throws If you have not specified a listener for 'error' events. - */ - placeVideoCall() { - return __awaiter(this, void 0, void 0, function* () { - yield this.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) { - const 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) { - const oldState = this._state; - this._state = state; - this.emit(CallEvent.State, state, oldState, this); - } - get type() { - // we may want to look for a video receiver here rather than a track to match the - // sender behaviour, although in practice they should be the same thing - return this.hasUserMediaVideoSender || this.hasRemoteUserMediaVideoTrack ? CallType.Video : CallType.Voice; - } - get hasLocalUserMediaVideoTrack() { - var _a; - return !!((_a = this.localUsermediaStream) === null || _a === void 0 ? void 0 : _a.getVideoTracks().length); - } - get hasRemoteUserMediaVideoTrack() { - return this.getRemoteFeeds().some((feed) => { - var _a; - return feed.purpose === callEventTypes_1.SDPStreamMetadataPurpose.Usermedia && ((_a = feed.stream) === null || _a === void 0 ? void 0 : _a.getVideoTracks().length); - }); - } - get hasLocalUserMediaAudioTrack() { - var _a; - return !!((_a = this.localUsermediaStream) === null || _a === void 0 ? void 0 : _a.getAudioTracks().length); - } - get hasRemoteUserMediaAudioTrack() { - return this.getRemoteFeeds().some((feed) => { - var _a; - return feed.purpose === callEventTypes_1.SDPStreamMetadataPurpose.Usermedia && !!((_a = feed.stream) === null || _a === void 0 ? void 0 : _a.getAudioTracks().length); - }); - } - get hasUserMediaAudioSender() { - var _a; - return Boolean((_a = this.transceivers.get(getTransceiverKey(callEventTypes_1.SDPStreamMetadataPurpose.Usermedia, "audio"))) === null || _a === void 0 ? void 0 : _a.sender); - } - get hasUserMediaVideoSender() { - var _a; - return Boolean((_a = this.transceivers.get(getTransceiverKey(callEventTypes_1.SDPStreamMetadataPurpose.Usermedia, "video"))) === null || _a === void 0 ? void 0 : _a.sender); - } - get localUsermediaFeed() { - return this.getLocalFeeds().find((feed) => feed.purpose === callEventTypes_1.SDPStreamMetadataPurpose.Usermedia); - } - get localScreensharingFeed() { - return this.getLocalFeeds().find((feed) => feed.purpose === callEventTypes_1.SDPStreamMetadataPurpose.Screenshare); - } - get localUsermediaStream() { - var _a; - return (_a = this.localUsermediaFeed) === null || _a === void 0 ? void 0 : _a.stream; - } - get localScreensharingStream() { - var _a; - return (_a = this.localScreensharingFeed) === null || _a === void 0 ? void 0 : _a.stream; - } - get remoteUsermediaFeed() { - return this.getRemoteFeeds().find((feed) => feed.purpose === callEventTypes_1.SDPStreamMetadataPurpose.Usermedia); - } - get remoteScreensharingFeed() { - return this.getRemoteFeeds().find((feed) => feed.purpose === callEventTypes_1.SDPStreamMetadataPurpose.Screenshare); - } - get remoteUsermediaStream() { - var _a; - return (_a = this.remoteUsermediaFeed) === null || _a === void 0 ? void 0 : _a.stream; - } - get remoteScreensharingStream() { - var _a; - return (_a = this.remoteScreensharingFeed) === null || _a === void 0 ? void 0 : _a.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 _a, _b; - return __awaiter(this, void 0, void 0, function* () { - if (!this.opponentDeviceId) - return; - if (!this.client.getUseE2eForGroupCall()) - return; - // It's possible to want E2EE and yet not have the means to manage E2EE - // ourselves (for example if the client is a RoomWidgetClient) - if (!this.client.isCryptoEnabled()) { - // All we know is the device ID - this.opponentDeviceInfo = new deviceinfo_1.DeviceInfo(this.opponentDeviceId); - return; - } - // if we've got to this point, we do want to init crypto, so throw if we can't - if (!this.client.crypto) - throw new Error("Crypto is not initialised."); - const userId = this.invitee || ((_a = this.getOpponentMember()) === null || _a === void 0 ? void 0 : _a.userId); - if (!userId) - throw new Error("Couldn't find opponent user ID to init crypto"); - const deviceInfoMap = yield this.client.crypto.deviceList.downloadKeys([userId], false); - this.opponentDeviceInfo = (_b = deviceInfoMap.get(userId)) === null || _b === void 0 ? void 0 : _b.get(this.opponentDeviceId); - if (this.opponentDeviceInfo === undefined) { - throw new groupCall_1.GroupCallUnknownDeviceError(userId); - } - }); - } - /** - * Generates and returns localSDPStreamMetadata - * @returns localSDPStreamMetadata - */ - getLocalSDPStreamMetadata(updateStreamIds = false) { - const metadata = {}; - for (const 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) { - // Fallback to old behavior if the other side doesn't support SDPStreamMetadata - if (!this.opponentSupportsSDPStreamMetadata()) { - this.pushRemoteFeedWithoutMetadata(stream); - return; - } - const userId = this.getOpponentMember().userId; - const purpose = this.remoteSDPStreamMetadata[stream.id].purpose; - const audioMuted = this.remoteSDPStreamMetadata[stream.id].audio_muted; - const videoMuted = this.remoteSDPStreamMetadata[stream.id].video_muted; - if (!purpose) { - logger_1.logger.warn(`Call ${this.callId} pushRemoteFeed() ignoring stream because we didn't get any metadata about it (streamId=${stream.id})`); - return; - } - if (this.getFeedByStreamId(stream.id)) { - logger_1.logger.warn(`Call ${this.callId} pushRemoteFeed() ignoring stream because we already have a feed for it (streamId=${stream.id})`); - return; - } - this.feeds.push(new callFeed_1.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_1.logger.info(`Call ${this.callId} pushRemoteFeed() pushed stream (streamId=${stream.id}, active=${stream.active}, purpose=${purpose})`); - } - /** - * This method is used ONLY if the other client doesn't support sending SDPStreamMetadata - */ - pushRemoteFeedWithoutMetadata(stream) { - var _a; - const userId = this.getOpponentMember().userId; - // We can guess the purpose here since the other client can only send one stream - const purpose = callEventTypes_1.SDPStreamMetadataPurpose.Usermedia; - const oldRemoteStream = (_a = this.feeds.find((feed) => !feed.isLocal())) === null || _a === void 0 ? void 0 : _a.stream; - // Note that we check by ID and always set the remote stream: Chrome appears - // to make new stream objects when transceiver directionality is changed and the 'active' - // status of streams change - Dave - // If we already have a stream, check this stream has the same id - if (oldRemoteStream && stream.id !== oldRemoteStream.id) { - logger_1.logger.warn(`Call ${this.callId} pushRemoteFeedWithoutMetadata() ignoring new stream because we already have stream (streamId=${stream.id})`); - return; - } - if (this.getFeedByStreamId(stream.id)) { - logger_1.logger.warn(`Call ${this.callId} pushRemoteFeedWithoutMetadata() ignoring stream because we already have a feed for it (streamId=${stream.id})`); - return; - } - this.feeds.push(new callFeed_1.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_1.logger.info(`Call ${this.callId} pushRemoteFeedWithoutMetadata() pushed stream (streamId=${stream.id}, active=${stream.active})`); - } - pushNewLocalFeed(stream, purpose, addToPeerConnection = true) { - const userId = this.client.getUserId(); - // Tracks don't always start off enabled, eg. chrome will give a disabled - // audio track if you ask for user media audio and already had one that - // you'd set to disabled (presumably because it clones them internally). - setTracksEnabled(stream.getAudioTracks(), true); - setTracksEnabled(stream.getVideoTracks(), true); - if (this.getFeedByStreamId(stream.id)) { - logger_1.logger.warn(`Call ${this.callId} pushNewLocalFeed() ignoring stream because we already have a feed for it (streamId=${stream.id})`); - return; - } - this.pushLocalFeed(new callFeed_1.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, addToPeerConnection = true) { - if (this.feeds.some((feed) => callFeed.stream.id === feed.stream.id)) { - logger_1.logger.info(`Call ${this.callId} pushLocalFeed() ignoring duplicate local stream (streamId=${callFeed.stream.id})`); - return; - } - this.feeds.push(callFeed); - if (addToPeerConnection) { - for (const track of callFeed.stream.getTracks()) { - logger_1.logger.info(`Call ${this.callId} pushLocalFeed() adding track to peer connection (id=${track.id}, kind=${track.kind}, streamId=${callFeed.stream.id}, streamPurpose=${callFeed.purpose}, enabled=${track.enabled})`); - const tKey = getTransceiverKey(callFeed.purpose, track.kind); - if (this.transceivers.has(tKey)) { - // we already have a sender, so we re-use it. We try to re-use transceivers as much - // as possible because they can't be removed once added, so otherwise they just - // accumulate which makes the SDP very large very quickly: in fact it only takes - // about 6 video tracks to exceed the maximum size of an Olm-encrypted - // Matrix event. - const transceiver = this.transceivers.get(tKey); - transceiver.sender.replaceTrack(track); - // set the direction to indicate we're going to start sending again - // (this will trigger the re-negotiation) - transceiver.direction = transceiver.direction === "inactive" ? "sendonly" : "sendrecv"; - } - else { - // create a new one. We need to use addTrack rather addTransceiver for this because firefox - // doesn't yet implement RTCRTPSender.setStreams() - // (https://bugzilla.mozilla.org/show_bug.cgi?id=1510802) so we'd have no way to group the - // two tracks together into a stream. - const newSender = this.peerConn.addTrack(track, callFeed.stream); - // now go & fish for the new transceiver - const newTransceiver = this.peerConn.getTransceivers().find((t) => t.sender === newSender); - if (newTransceiver) { - this.transceivers.set(tKey, newTransceiver); - } - else { - logger_1.logger.warn(`Call ${this.callId} pushLocalFeed() didn't find a matching transceiver after adding track!`); - } - } - } - } - logger_1.logger.info(`Call ${this.callId} pushLocalFeed() pushed stream (id=${callFeed.stream.id}, active=${callFeed.stream.active}, purpose=${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) { - const audioTransceiverKey = getTransceiverKey(callFeed.purpose, "audio"); - const videoTransceiverKey = getTransceiverKey(callFeed.purpose, "video"); - for (const transceiverKey of [audioTransceiverKey, videoTransceiverKey]) { - // this is slightly mixing the track and transceiver API but is basically just shorthand. - // There is no way to actually remove a transceiver, so this just sets it to inactive - // (or recvonly) and replaces the source with nothing. - if (this.transceivers.has(transceiverKey)) { - const transceiver = this.transceivers.get(transceiverKey); - if (transceiver.sender) - this.peerConn.removeTrack(transceiver.sender); - } - } - if (callFeed.purpose === callEventTypes_1.SDPStreamMetadataPurpose.Screenshare) { - this.client.getMediaHandler().stopScreensharingStream(callFeed.stream); - } - this.deleteFeed(callFeed); - } - deleteAllFeeds() { - for (const feed of this.feeds) { - if (!feed.isLocal() || !this.groupCallId) { - feed.dispose(); - } - } - this.feeds = []; - this.emit(CallEvent.FeedsChanged, this.feeds, this); - } - deleteFeedByStream(stream) { - const feed = this.getFeedByStreamId(stream.id); - if (!feed) { - logger_1.logger.warn(`Call ${this.callId} deleteFeedByStream() didn't find the feed to delete (streamId=${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); - } - // The typescript definitions have this type as 'any' :( - getCurrentCallStats() { - return __awaiter(this, void 0, void 0, function* () { - if (this.callHasEnded()) { - return this.callStatsAtEnd; - } - return this.collectCallStats(); - }); - } - collectCallStats() { - return __awaiter(this, void 0, void 0, function* () { - // This happens when the call fails before it starts. - // For example when we fail to get capture sources - if (!this.peerConn) - return; - const statsReport = yield this.peerConn.getStats(); - const 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 _a; - return __awaiter(this, void 0, void 0, function* () { - const invite = event.getContent(); - this.direction = CallDirection.Inbound; - // make sure we have valid turn creds. Unless something's gone wrong, it should - // poll and keep the credentials valid so this should be instant. - const haveTurnCreds = yield this.client.checkTurnServers(); - if (!haveTurnCreds) { - logger_1.logger.warn(`Call ${this.callId} initWithInvite() failed to get TURN credentials! Proceeding with call anyway...`); - } - const sdpStreamMetadata = invite[callEventTypes_1.SDPStreamMetadataKey]; - if (sdpStreamMetadata) { - this.updateRemoteSDPStreamMetadata(sdpStreamMetadata); - } - else { - logger_1.logger.debug(`Call ${this.callId} initWithInvite() did not get any SDPStreamMetadata! Can not send/receive multiple streams`); - } - this.peerConn = this.createPeerConnection(); - // we must set the party ID before await-ing on anything: the call event - // handler will start giving us more call events (eg. candidates) so if - // we haven't set the party ID, we'll ignore them. - this.chooseOpponent(event); - yield this.initOpponentCrypto(); - try { - yield this.peerConn.setRemoteDescription(invite.offer); - yield this.addBufferedIceCandidates(); - } - catch (e) { - logger_1.logger.debug(`Call ${this.callId} initWithInvite() failed to set remote description`, e); - this.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false); - return; - } - const remoteStream = (_a = this.feeds.find((feed) => !feed.isLocal())) === null || _a === void 0 ? void 0 : _a.stream; - // According to previous comments in this file, firefox at some point did not - // add streams until media started arriving on them. Testing latest firefox - // (81 at time of writing), this is no longer a problem, so let's do it the correct way. - // - // For example in case of no media webrtc connections like screen share only call we have to allow webrtc - // connections without remote media. In this case we always use a data channel. At the moment we allow as well - // only data channel as media in the WebRTC connection with this setup here. - if (!this.isOnlyDataChannelAllowed && (!remoteStream || remoteStream.getTracks().length === 0)) { - logger_1.logger.error(`Call ${this.callId} initWithInvite() no remote stream or no tracks after setting remote description!`); - this.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false); - return; - } - this.state = CallState.Ringing; - if (event.getLocalAge()) { - // Time out the call if it's ringing for too long - const ringingTimer = setTimeout(() => { - var _a; - if (this.state == CallState.Ringing) { - logger_1.logger.debug(`Call ${this.callId} initWithInvite() invite has expired. Hanging up.`); - this.hangupParty = CallParty.Remote; // effectively - this.state = CallState.Ended; - this.stopAllMedia(); - if (this.peerConn.signalingState != "closed") { - this.peerConn.close(); - } - (_a = this.stats) === null || _a === void 0 ? void 0 : _a.removeStatsReportGatherer(this.callId); - this.emit(CallEvent.Hangup, this); - } - }, invite.lifetime - event.getLocalAge()); - const onState = (state) => { - if (state !== CallState.Ringing) { - clearTimeout(ringingTimer); - this.off(CallEvent.State, onState); - } - }; - this.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) { - // perverse as it may seem, sometimes we want to instantiate a call with a - // hangup message (because when getting the state of the room on load, events - // come in reverse order and we want to remember that a call has been hung up) - this.state = CallState.Ended; - } - shouldAnswerWithMediaType(wantedValue, valueOfTheOtherSide, type) { - if (wantedValue && !valueOfTheOtherSide) { - // TODO: Figure out how to do this - logger_1.logger.warn(`Call ${this.callId} shouldAnswerWithMediaType() unable to answer with ${type} because the other side isn't sending it either.`); - return false; - } - else if (!utils.isNullOrUndefined(wantedValue) && - wantedValue !== valueOfTheOtherSide && - !this.opponentSupportsSDPStreamMetadata()) { - logger_1.logger.warn(`Call ${this.callId} shouldAnswerWithMediaType() unable to answer with ${type}=${wantedValue} because the other side doesn't support it. Answering with ${type}=${valueOfTheOtherSide}.`); - return valueOfTheOtherSide; - } - return wantedValue !== null && wantedValue !== void 0 ? wantedValue : valueOfTheOtherSide; - } - /** - * Answer a call. - */ - answer(audio, video) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - if (this.inviteOrAnswerSent) - return; - // TODO: Figure out how to do this - if (audio === false && video === false) - throw new Error("You CANNOT answer a call without media"); - if (!this.localUsermediaStream && !this.waitForLocalAVStream) { - const prevState = this.state; - const answerWithAudio = this.shouldAnswerWithMediaType(audio, this.hasRemoteUserMediaAudioTrack, "audio"); - const answerWithVideo = this.shouldAnswerWithMediaType(video, this.hasRemoteUserMediaVideoTrack, "video"); - this.state = CallState.WaitLocalMedia; - this.waitForLocalAVStream = true; - try { - const stream = yield this.client.getMediaHandler().getUserMediaStream(answerWithAudio, answerWithVideo); - this.waitForLocalAVStream = false; - const usermediaFeed = new callFeed_1.CallFeed({ - client: this.client, - roomId: this.roomId, - userId: this.client.getUserId(), - deviceId: (_a = this.client.getDeviceId()) !== null && _a !== void 0 ? _a : undefined, - stream, - purpose: callEventTypes_1.SDPStreamMetadataPurpose.Usermedia, - audioMuted: false, - videoMuted: false, - }); - const feeds = [usermediaFeed]; - if (this.localScreensharingFeed) { - feeds.push(this.localScreensharingFeed); - } - this.answerWithCallFeeds(feeds); - } - catch (e) { - if (answerWithVideo) { - // Try to answer without video - logger_1.logger.warn(`Call ${this.callId} answer() failed to getUserMedia(), trying to getUserMedia() without video`); - this.state = prevState; - this.waitForLocalAVStream = false; - yield this.answer(answerWithAudio, false); - } - else { - this.getUserMediaFailed(e); - return; - } - } - } - else if (this.waitForLocalAVStream) { - this.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_1.logger.debug(`Call ${this.callId} replacedBy() running (newCallId=${newCall.callId})`); - if (this.state === CallState.WaitLocalMedia) { - logger_1.logger.debug(`Call ${this.callId} replacedBy() telling new call to wait for local media (newCallId=${newCall.callId})`); - newCall.waitForLocalAVStream = true; - } - else if ([CallState.CreateOffer, CallState.InviteSent].includes(this.state)) { - if (newCall.direction === CallDirection.Outbound) { - newCall.queueGotCallFeedsForAnswer([]); - } - else { - logger_1.logger.debug(`Call ${this.callId} replacedBy() handing local stream to new call(newCallId=${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_1.logger.debug(`Call ${this.callId} hangup() ending call (reason=${reason})`); - this.terminate(CallParty.Local, reason, !suppressEvent); - // We don't want to send hangup here if we didn't even get to sending an invite - if ([CallState.Fledgling, CallState.WaitLocalMedia].includes(this.state)) - return; - const content = {}; - // Don't send UserHangup reason to older clients - if ((this.opponentVersion && this.opponentVersion !== 0) || reason !== CallErrorCode.UserHangup) { - content["reason"] = reason; - } - this.sendVoipEvent(event_1.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_1.logger.info(`Call ${this.callId} reject() opponent version is less than 1: sending hangup instead of reject (opponentVersion=${this.opponentVersion})`); - this.hangup(CallErrorCode.UserHangup, true); - return; - } - logger_1.logger.debug("Rejecting call: " + this.callId); - this.terminate(CallParty.Local, CallErrorCode.UserHangup, true); - this.sendVoipEvent(event_1.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) { - return __awaiter(this, void 0, void 0, function* () { - // We don't do call downgrades - if (!audio && !video) - return; - if (!this.opponentSupportsSDPStreamMetadata()) - return; - try { - logger_1.logger.debug(`Call ${this.callId} upgradeCall() upgrading call (audio=${audio}, video=${video})`); - const getAudio = audio || this.hasLocalUserMediaAudioTrack; - const getVideo = video || this.hasLocalUserMediaVideoTrack; - // updateLocalUsermediaStream() will take the tracks, use them as - // replacement and throw the stream away, so it isn't reusable - const stream = yield this.client.getMediaHandler().getUserMediaStream(getAudio, getVideo, false); - yield this.updateLocalUsermediaStream(stream, audio, video); - } - catch (error) { - logger_1.logger.error(`Call ${this.callId} upgradeCall() failed to upgrade the call`, error); - this.emit(CallEvent.Error, new CallError(CallErrorCode.NoUserMedia, "Failed to get camera access: ", error), this); - } - }); - } - /** - * 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 desktopCapturerSourceId - optional id of the desktop capturer source to use - * @returns new screensharing state - */ - setScreensharingEnabled(enabled, opts) { - return __awaiter(this, void 0, void 0, function* () { - // Skip if there is nothing to do - if (enabled && this.isScreensharing()) { - logger_1.logger.warn(`Call ${this.callId} setScreensharingEnabled() there is already a screensharing stream - there is nothing to do!`); - return true; - } - else if (!enabled && !this.isScreensharing()) { - logger_1.logger.warn(`Call ${this.callId} setScreensharingEnabled() there already isn't a screensharing stream - there is nothing to do!`); - return false; - } - // Fallback to replaceTrack() - if (!this.opponentSupportsSDPStreamMetadata()) { - return this.setScreensharingEnabledWithoutMetadataSupport(enabled, opts); - } - logger_1.logger.debug(`Call ${this.callId} setScreensharingEnabled() running (enabled=${enabled})`); - if (enabled) { - try { - const stream = yield this.client.getMediaHandler().getScreensharingStream(opts); - if (!stream) - return false; - this.pushNewLocalFeed(stream, callEventTypes_1.SDPStreamMetadataPurpose.Screenshare); - return true; - } - catch (err) { - logger_1.logger.error(`Call ${this.callId} setScreensharingEnabled() failed to get screen-sharing stream:`, err); - return false; - } - } - else { - const audioTransceiver = this.transceivers.get(getTransceiverKey(callEventTypes_1.SDPStreamMetadataPurpose.Screenshare, "audio")); - const videoTransceiver = this.transceivers.get(getTransceiverKey(callEventTypes_1.SDPStreamMetadataPurpose.Screenshare, "video")); - for (const transceiver of [audioTransceiver, videoTransceiver]) { - // this is slightly mixing the track and transceiver API but is basically just shorthand - // for removing the sender. - if (transceiver && transceiver.sender) - this.peerConn.removeTrack(transceiver.sender); - } - this.client.getMediaHandler().stopScreensharingStream(this.localScreensharingStream); - this.deleteFeedByStream(this.localScreensharingStream); - return false; - } - }); - } - /** - * Starts/stops screensharing - * Should be used ONLY if the opponent doesn't support SDPStreamMetadata - * @param enabled - the desired screensharing state - * @param desktopCapturerSourceId - optional id of the desktop capturer source to use - * @returns new screensharing state - */ - setScreensharingEnabledWithoutMetadataSupport(enabled, opts) { - var _a, _b, _c; - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.debug(`Call ${this.callId} setScreensharingEnabledWithoutMetadataSupport() running (enabled=${enabled})`); - if (enabled) { - try { - const stream = yield this.client.getMediaHandler().getScreensharingStream(opts); - if (!stream) - return false; - const track = stream.getTracks().find((track) => track.kind === "video"); - const sender = (_a = this.transceivers.get(getTransceiverKey(callEventTypes_1.SDPStreamMetadataPurpose.Usermedia, "video"))) === null || _a === void 0 ? void 0 : _a.sender; - sender === null || sender === void 0 ? void 0 : sender.replaceTrack(track !== null && track !== void 0 ? track : null); - this.pushNewLocalFeed(stream, callEventTypes_1.SDPStreamMetadataPurpose.Screenshare, false); - return true; - } - catch (err) { - logger_1.logger.error(`Call ${this.callId} setScreensharingEnabledWithoutMetadataSupport() failed to get screen-sharing stream:`, err); - return false; - } - } - else { - const track = (_b = this.localUsermediaStream) === null || _b === void 0 ? void 0 : _b.getTracks().find((track) => track.kind === "video"); - const sender = (_c = this.transceivers.get(getTransceiverKey(callEventTypes_1.SDPStreamMetadataPurpose.Usermedia, "video"))) === null || _c === void 0 ? void 0 : _c.sender; - sender === null || sender === void 0 ? void 0 : sender.replaceTrack(track !== null && track !== void 0 ? track : null); - this.client.getMediaHandler().stopScreensharingStream(this.localScreensharingStream); - this.deleteFeedByStream(this.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, forceAudio = false, forceVideo = false) { - return __awaiter(this, void 0, void 0, function* () { - const callFeed = this.localUsermediaFeed; - const audioEnabled = forceAudio || (!callFeed.isAudioMuted() && !this.remoteOnHold); - const videoEnabled = forceVideo || (!callFeed.isVideoMuted() && !this.remoteOnHold); - logger_1.logger.log(`Call ${this.callId} updateLocalUsermediaStream() running (streamId=${stream.id}, audio=${audioEnabled}, video=${videoEnabled})`); - setTracksEnabled(stream.getAudioTracks(), audioEnabled); - setTracksEnabled(stream.getVideoTracks(), videoEnabled); - // We want to keep the same stream id, so we replace the tracks rather - // than the whole stream. - // Firstly, we replace the tracks in our localUsermediaStream. - for (const track of this.localUsermediaStream.getTracks()) { - this.localUsermediaStream.removeTrack(track); - track.stop(); - } - for (const track of stream.getTracks()) { - this.localUsermediaStream.addTrack(track); - } - // Then replace the old tracks, if possible. - for (const track of stream.getTracks()) { - const tKey = getTransceiverKey(callEventTypes_1.SDPStreamMetadataPurpose.Usermedia, track.kind); - const transceiver = this.transceivers.get(tKey); - const oldSender = transceiver === null || transceiver === void 0 ? void 0 : transceiver.sender; - let added = false; - if (oldSender) { - try { - logger_1.logger.info(`Call ${this.callId} updateLocalUsermediaStream() replacing track (id=${track.id}, kind=${track.kind}, streamId=${stream.id}, streamPurpose=${callFeed.purpose})`); - yield oldSender.replaceTrack(track); - // Set the direction to indicate we're going to be sending. - // This is only necessary in the cases where we're upgrading - // the call to video after downgrading it. - transceiver.direction = transceiver.direction === "inactive" ? "sendonly" : "sendrecv"; - added = true; - } - catch (error) { - logger_1.logger.warn(`Call ${this.callId} updateLocalUsermediaStream() replaceTrack failed: adding new transceiver instead`, error); - } - } - if (!added) { - logger_1.logger.info(`Call ${this.callId} updateLocalUsermediaStream() adding track to peer connection (id=${track.id}, kind=${track.kind}, streamId=${stream.id}, streamPurpose=${callFeed.purpose})`); - const newSender = this.peerConn.addTrack(track, this.localUsermediaStream); - const newTransceiver = this.peerConn.getTransceivers().find((t) => t.sender === newSender); - if (newTransceiver) { - this.transceivers.set(tKey, newTransceiver); - } - else { - logger_1.logger.warn(`Call ${this.callId} updateLocalUsermediaStream() couldn't find matching transceiver for newly added track!`); - } - } - } - }); - } - /** - * 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 _a, _b; - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.log(`Call ${this.callId} setLocalVideoMuted() running ${muted}`); - // if we were still thinking about stopping and removing the video - // track: don't, because we want it back. - if (!muted && this.stopVideoTrackTimer !== undefined) { - clearTimeout(this.stopVideoTrackTimer); - this.stopVideoTrackTimer = undefined; - } - if (!(yield this.client.getMediaHandler().hasVideoDevice())) { - return this.isLocalVideoMuted(); - } - if (!this.hasUserMediaVideoSender && !muted) { - (_a = this.localUsermediaFeed) === null || _a === void 0 ? void 0 : _a.setAudioVideoMuted(null, muted); - yield this.upgradeCall(false, true); - return this.isLocalVideoMuted(); - } - // we may not have a video track - if not, re-request usermedia - if (!muted && this.localUsermediaStream.getVideoTracks().length === 0) { - const stream = yield this.client.getMediaHandler().getUserMediaStream(true, true); - yield this.updateLocalUsermediaStream(stream); - } - (_b = this.localUsermediaFeed) === null || _b === void 0 ? void 0 : _b.setAudioVideoMuted(null, muted); - this.updateMuteStatus(); - yield this.sendMetadataUpdate(); - // if we're muting video, set a timeout to stop & remove the video track so we release - // the camera. We wait a short time to do this because when we disable a track, WebRTC - // will send black video for it. If we just stop and remove it straight away, the video - // will just freeze which means that when we unmute video, the other side will briefly - // get a static frame of us from before we muted. This way, the still frame is just black. - // A very small delay is not always enough so the theory here is that it needs to be long - // enough for WebRTC to encode a frame: 120ms should be long enough even if we're only - // doing 10fps. - if (muted) { - this.stopVideoTrackTimer = setTimeout(() => { - for (const t of this.localUsermediaStream.getVideoTracks()) { - t.stop(); - this.localUsermediaStream.removeTrack(t); - } - }, 120); - } - return this.isLocalVideoMuted(); - }); - } - /** - * Check if local video is muted. - * - * If there are multiple video tracks, all 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 _a, _b; - return (_b = (_a = this.localUsermediaFeed) === null || _a === void 0 ? void 0 : _a.isVideoMuted()) !== null && _b !== void 0 ? _b : 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 _a; - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.log(`Call ${this.callId} setMicrophoneMuted() running ${muted}`); - if (!(yield this.client.getMediaHandler().hasAudioDevice())) { - return this.isMicrophoneMuted(); - } - if (!muted && (!this.hasUserMediaAudioSender || !this.hasLocalUserMediaAudioTrack)) { - yield this.upgradeCall(true, false); - return this.isMicrophoneMuted(); - } - (_a = this.localUsermediaFeed) === null || _a === void 0 ? void 0 : _a.setAudioVideoMuted(muted, null); - this.updateMuteStatus(); - yield this.sendMetadataUpdate(); - return this.isMicrophoneMuted(); - }); - } - /** - * Check if the microphone is muted. - * - * If there are multiple audio tracks, all 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 _a, _b; - return (_b = (_a = this.localUsermediaFeed) === null || _a === void 0 ? void 0 : _a.isAudioMuted()) !== null && _b !== void 0 ? _b : 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 (const transceiver of this.peerConn.getTransceivers()) { - // We don't send hold music or anything so we're not actually - // sending anything, but sendrecv is fairly standard for hold and - // it makes it a lot easier to figure out who's put who on hold. - 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; - let callOnHold = true; - // We consider a call to be on hold only if *all* the tracks are on hold - // (is this the right thing to do?) - for (const transceiver of this.peerConn.getTransceivers()) { - const trackOnHold = ["inactive", "recvonly"].includes(transceiver.currentDirection); - if (!trackOnHold) - callOnHold = false; - } - return callOnHold; - } - /** - * Sends a DTMF digit to the other party - * @param digit - The digit (nb. string - '#' and '*' are dtmf too) - */ - sendDtmfDigit(digit) { - var _a; - for (const sender of this.peerConn.getSenders()) { - if (((_a = sender.track) === null || _a === void 0 ? void 0 : _a.kind) === "audio" && sender.dtmf) { - sender.dtmf.insertDTMF(digit); - return; - } - } - throw new Error("Unable to find a track to send DTMF on"); - } - updateMuteStatus() { - const micShouldBeMuted = this.isMicrophoneMuted() || this.remoteOnHold; - const vidShouldBeMuted = this.isLocalVideoMuted() || this.remoteOnHold; - logger_1.logger.log(`Call ${this.callId} updateMuteStatus stream ${this.localUsermediaStream.id} micShouldBeMuted ${micShouldBeMuted} vidShouldBeMuted ${vidShouldBeMuted}`); - setTracksEnabled(this.localUsermediaStream.getAudioTracks(), !micShouldBeMuted); - setTracksEnabled(this.localUsermediaStream.getVideoTracks(), !vidShouldBeMuted); - } - sendMetadataUpdate() { - return __awaiter(this, void 0, void 0, function* () { - yield this.sendVoipEvent(event_1.EventType.CallSDPStreamMetadataChangedPrefix, { - [callEventTypes_1.SDPStreamMetadataKey]: this.getLocalSDPStreamMetadata(), - }); - }); - } - gotCallFeedsForInvite(callFeeds, requestScreenshareFeed = false) { - if (this.successor) { - this.successor.queueGotCallFeedsForAnswer(callFeeds); - return; - } - if (this.callHasEnded()) { - this.stopAllMedia(); - return; - } - for (const feed of callFeeds) { - this.pushLocalFeed(feed); - } - if (requestScreenshareFeed) { - this.peerConn.addTransceiver("video", { - direction: "recvonly", - }); - } - this.state = CallState.CreateOffer; - logger_1.logger.debug(`Call ${this.callId} gotUserMediaForInvite() run`); - // Now we wait for the negotiationneeded event - } - sendAnswer() { - return __awaiter(this, void 0, void 0, function* () { - const answerContent = { - answer: { - sdp: this.peerConn.localDescription.sdp, - // type is now deprecated as of Matrix VoIP v1, but - // required to still be sent for backwards compat - type: this.peerConn.localDescription.type, - }, - [callEventTypes_1.SDPStreamMetadataKey]: this.getLocalSDPStreamMetadata(true), - }; - answerContent.capabilities = { - "m.call.transferee": this.client.supportsCallTransfer, - "m.call.dtmf": false, - }; - // We have just taken the local description from the peerConn which will - // contain all the local candidates added so far, so we can discard any candidates - // we had queued up because they'll be in the answer. - const discardCount = this.discardDuplicateCandidates(); - logger_1.logger.info(`Call ${this.callId} sendAnswer() discarding ${discardCount} candidates that will be sent in answer`); - try { - yield this.sendVoipEvent(event_1.EventType.CallAnswer, answerContent); - // If this isn't the first time we've tried to send the answer, - // we may have candidates queued up, so send them now. - this.inviteOrAnswerSent = true; - } - catch (error) { - // We've failed to answer: back to the ringing state - this.state = CallState.Ringing; - if (error instanceof http_api_1.MatrixError && error.event) - this.client.cancelPendingEvent(error.event); - let code = CallErrorCode.SendAnswer; - let message = "Failed to send answer"; - if (error.name == "UnknownDeviceError") { - code = CallErrorCode.UnknownDevices; - message = "Unknown devices present in the room"; - } - this.emit(CallEvent.Error, new CallError(code, message, error), this); - throw error; - } - // error handler re-throws so this won't happen on error, but - // we don't want the same error handling on the candidate queue - this.sendCandidateQueue(); - }); - } - queueGotCallFeedsForAnswer(callFeeds) { - // Ensure only one negotiate/answer event is being processed at a time. - if (this.responsePromiseChain) { - this.responsePromiseChain = this.responsePromiseChain.then(() => this.gotCallFeedsForAnswer(callFeeds)); - } - else { - this.responsePromiseChain = this.gotCallFeedsForAnswer(callFeeds); - } - } - // Enables DTX (discontinuous transmission) on the given session to reduce - // bandwidth when transmitting silence - mungeSdp(description, mods) { - // The only way to enable DTX at this time is through SDP munging - const sdp = (0, sdp_transform_1.parse)(description.sdp); - sdp.media.forEach((media) => { - const payloadTypeToCodecMap = new Map(); - const codecToPayloadTypeMap = new Map(); - for (const rtp of media.rtp) { - payloadTypeToCodecMap.set(rtp.payload, rtp.codec); - codecToPayloadTypeMap.set(rtp.codec, rtp.payload); - } - for (const mod of mods) { - if (mod.mediaType !== media.type) - continue; - if (!codecToPayloadTypeMap.has(mod.codec)) { - logger_1.logger.info(`Call ${this.callId} mungeSdp() ignoring SDP modifications for ${mod.codec} as it's not present.`); - continue; - } - const extraConfig = []; - if (mod.enableDtx !== undefined) { - extraConfig.push(`usedtx=${mod.enableDtx ? "1" : "0"}`); - } - if (mod.maxAverageBitrate !== undefined) { - extraConfig.push(`maxaveragebitrate=${mod.maxAverageBitrate}`); - } - let found = false; - for (const 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, sdp_transform_1.write)(sdp); - } - createOffer() { - return __awaiter(this, void 0, void 0, function* () { - const offer = yield this.peerConn.createOffer(); - this.mungeSdp(offer, getCodecParamMods(this.isPtt)); - return offer; - }); - } - createAnswer() { - return __awaiter(this, void 0, void 0, function* () { - const answer = yield this.peerConn.createAnswer(); - this.mungeSdp(answer, getCodecParamMods(this.isPtt)); - return answer; - }); - } - gotCallFeedsForAnswer(callFeeds) { - return __awaiter(this, void 0, void 0, function* () { - if (this.callHasEnded()) - return; - this.waitForLocalAVStream = false; - for (const feed of callFeeds) { - this.pushLocalFeed(feed); - } - this.state = CallState.CreateAnswer; - let answer; - try { - this.getRidOfRTXCodecs(); - answer = yield this.createAnswer(); - } - catch (err) { - logger_1.logger.debug(`Call ${this.callId} gotCallFeedsForAnswer() failed to create answer: `, err); - this.terminate(CallParty.Local, CallErrorCode.CreateAnswer, true); - return; - } - try { - yield this.peerConn.setLocalDescription(answer); - // make sure we're still going - if (this.callHasEnded()) - return; - this.state = CallState.Connecting; - // Allow a short time for initial candidates to be gathered - yield new Promise((resolve) => { - setTimeout(resolve, 200); - }); - // make sure the call hasn't ended before we continue - if (this.callHasEnded()) - return; - this.sendAnswer(); - } - catch (err) { - logger_1.logger.debug(`Call ${this.callId} gotCallFeedsForAnswer() error setting local description!`, err); - this.terminate(CallParty.Local, CallErrorCode.SetLocalDescription, true); - return; - } - }); - } - onRemoteIceCandidatesReceived(ev) { - return __awaiter(this, void 0, void 0, function* () { - if (this.callHasEnded()) { - //debuglog("Ignoring remote ICE candidate because call has ended"); - return; - } - const content = ev.getContent(); - const candidates = content.candidates; - if (!candidates) { - logger_1.logger.info(`Call ${this.callId} onRemoteIceCandidatesReceived() ignoring candidates event with no candidates!`); - return; - } - const fromPartyId = content.version === 0 ? null : content.party_id || null; - if (this.opponentPartyId === undefined) { - // we haven't picked an opponent yet so save the candidates - if (fromPartyId) { - logger_1.logger.info(`Call ${this.callId} onRemoteIceCandidatesReceived() buffering ${candidates.length} candidates until we pick an opponent`); - const bufferedCandidates = this.remoteCandidateBuffer.get(fromPartyId) || []; - bufferedCandidates.push(...candidates); - this.remoteCandidateBuffer.set(fromPartyId, bufferedCandidates); - } - return; - } - if (!this.partyIdMatches(content)) { - logger_1.logger.info(`Call ${this.callId} onRemoteIceCandidatesReceived() ignoring candidates from party ID ${content.party_id}: we have chosen party ID ${this.opponentPartyId}`); - return; - } - yield this.addIceCandidates(candidates); - }); - } - /** - * Used by MatrixClient. - */ - onAnswerReceived(event) { - return __awaiter(this, void 0, void 0, function* () { - const content = event.getContent(); - logger_1.logger.debug(`Call ${this.callId} onAnswerReceived() running (hangupParty=${content.party_id})`); - if (this.callHasEnded()) { - logger_1.logger.debug(`Call ${this.callId} onAnswerReceived() ignoring answer because call has ended`); - return; - } - if (this.opponentPartyId !== undefined) { - logger_1.logger.info(`Call ${this.callId} onAnswerReceived() ignoring answer from party ID ${content.party_id}: we already have an answer/reject from ${this.opponentPartyId}`); - return; - } - this.chooseOpponent(event); - yield this.addBufferedIceCandidates(); - this.state = CallState.Connecting; - const sdpStreamMetadata = content[callEventTypes_1.SDPStreamMetadataKey]; - if (sdpStreamMetadata) { - this.updateRemoteSDPStreamMetadata(sdpStreamMetadata); - } - else { - logger_1.logger.warn(`Call ${this.callId} onAnswerReceived() did not get any SDPStreamMetadata! Can not send/receive multiple streams`); - } - try { - yield this.peerConn.setRemoteDescription(content.answer); - } - catch (e) { - logger_1.logger.debug(`Call ${this.callId} onAnswerReceived() failed to set remote description`, e); - this.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false); - return; - } - // If the answer we selected has a party_id, send a select_answer event - // We do this after setting the remote description since otherwise we'd block - // call setup on it - if (this.opponentPartyId !== null) { - try { - yield this.sendVoipEvent(event_1.EventType.CallSelectAnswer, { - selected_party_id: this.opponentPartyId, - }); - } - catch (err) { - // This isn't fatal, and will just mean that if another party has raced to answer - // the call, they won't know they got rejected, so we carry on & don't retry. - logger_1.logger.warn(`Call ${this.callId} onAnswerReceived() failed to send select_answer event`, err); - } - } - }); - } - onSelectAnswerReceived(event) { - return __awaiter(this, void 0, void 0, function* () { - if (this.direction !== CallDirection.Inbound) { - logger_1.logger.warn(`Call ${this.callId} onSelectAnswerReceived() got select_answer for an outbound call: ignoring`); - return; - } - const selectedPartyId = event.getContent().selected_party_id; - if (selectedPartyId === undefined || selectedPartyId === null) { - logger_1.logger.warn(`Call ${this.callId} onSelectAnswerReceived() got nonsensical select_answer with null/undefined selected_party_id: ignoring`); - return; - } - if (selectedPartyId !== this.ourPartyId) { - logger_1.logger.info(`Call ${this.callId} onSelectAnswerReceived() got select_answer for party ID ${selectedPartyId}: we are party ID ${this.ourPartyId}.`); - // The other party has picked somebody else's answer - yield this.terminate(CallParty.Remote, CallErrorCode.AnsweredElsewhere, true); - } - }); - } - onNegotiateReceived(event) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const content = event.getContent(); - const description = content.description; - if (!description || !description.sdp || !description.type) { - logger_1.logger.info(`Call ${this.callId} onNegotiateReceived() ignoring invalid m.call.negotiate event`); - return; - } - // Politeness always follows the direction of the call: in a glare situation, - // we pick either the inbound or outbound call, so one side will always be - // inbound and one outbound - const polite = this.direction === CallDirection.Inbound; - // Here we follow the perfect negotiation logic from - // https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Perfect_negotiation - const offerCollision = description.type === "offer" && (this.makingOffer || this.peerConn.signalingState !== "stable"); - this.ignoreOffer = !polite && offerCollision; - if (this.ignoreOffer) { - logger_1.logger.info(`Call ${this.callId} onNegotiateReceived() ignoring colliding negotiate event because we're impolite`); - return; - } - const prevLocalOnHold = this.isLocalOnHold(); - const sdpStreamMetadata = content[callEventTypes_1.SDPStreamMetadataKey]; - if (sdpStreamMetadata) { - this.updateRemoteSDPStreamMetadata(sdpStreamMetadata); - } - else { - logger_1.logger.warn(`Call ${this.callId} onNegotiateReceived() received negotiation event without SDPStreamMetadata!`); - } - try { - yield this.peerConn.setRemoteDescription(description); - if (description.type === "offer") { - let answer; - try { - this.getRidOfRTXCodecs(); - answer = yield this.createAnswer(); - } - catch (err) { - logger_1.logger.debug(`Call ${this.callId} onNegotiateReceived() failed to create answer: `, err); - this.terminate(CallParty.Local, CallErrorCode.CreateAnswer, true); - return; - } - yield this.peerConn.setLocalDescription(answer); - this.sendVoipEvent(event_1.EventType.CallNegotiate, { - description: (_a = this.peerConn.localDescription) === null || _a === void 0 ? void 0 : _a.toJSON(), - [callEventTypes_1.SDPStreamMetadataKey]: this.getLocalSDPStreamMetadata(true), - }); - } - } - catch (err) { - logger_1.logger.warn(`Call ${this.callId} onNegotiateReceived() failed to complete negotiation`, err); - } - const newLocalOnHold = this.isLocalOnHold(); - if (prevLocalOnHold !== newLocalOnHold) { - this.emit(CallEvent.LocalHoldUnhold, newLocalOnHold, this); - // also this one for backwards compat - this.emit(CallEvent.HoldUnhold, newLocalOnHold); - } - }); - } - updateRemoteSDPStreamMetadata(metadata) { - var _a; - this.remoteSDPStreamMetadata = utils.recursivelyAssign(this.remoteSDPStreamMetadata || {}, metadata, true); - for (const feed of this.getRemoteFeeds()) { - const streamId = feed.stream.id; - const 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 = (_a = this.remoteSDPStreamMetadata[streamId]) === null || _a === void 0 ? void 0 : _a.purpose; - } - } - onSDPStreamMetadataChangedReceived(event) { - const content = event.getContent(); - const metadata = content[callEventTypes_1.SDPStreamMetadataKey]; - this.updateRemoteSDPStreamMetadata(metadata); - } - onAssertedIdentityReceived(event) { - return __awaiter(this, void 0, void 0, function* () { - const content = event.getContent(); - if (!content.asserted_identity) - return; - this.remoteAssertedIdentity = { - id: content.asserted_identity.id, - displayName: content.asserted_identity.display_name, - }; - this.emit(CallEvent.AssertedIdentityChanged, this); - }); - } - callHasEnded() { - // This exists as workaround to typescript trying to be clever and erroring - // when putting if (this.state === CallState.Ended) return; twice in the same - // function, even though that function is async. - return this.state === CallState.Ended; - } - queueGotLocalOffer() { - // Ensure only one negotiate/answer event is being processed at a time. - if (this.responsePromiseChain) { - this.responsePromiseChain = this.responsePromiseChain.then(() => this.wrappedGotLocalOffer()); - } - else { - this.responsePromiseChain = this.wrappedGotLocalOffer(); - } - } - wrappedGotLocalOffer() { - return __awaiter(this, void 0, void 0, function* () { - this.makingOffer = true; - try { - // XXX: in what situations do we believe gotLocalOffer actually throws? It appears - // to handle most of its exceptions itself and terminate the call. I'm not entirely - // sure it would ever throw, so I can't add a test for these lines. - // Also the tense is different between "gotLocalOffer" and "getLocalOfferFailed" so - // it's not entirely clear whether getLocalOfferFailed is just misnamed or whether - // they've been cross-polinated somehow at some point. - yield this.gotLocalOffer(); - } - catch (e) { - this.getLocalOfferFailed(e); - return; - } - finally { - this.makingOffer = false; - } - }); - } - gotLocalOffer() { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.debug(`Call ${this.callId} gotLocalOffer() running`); - if (this.callHasEnded()) { - logger_1.logger.debug(`Call ${this.callId} gotLocalOffer() ignoring newly created offer because the call has ended"`); - return; - } - let offer; - try { - this.getRidOfRTXCodecs(); - offer = yield this.createOffer(); - } - catch (err) { - logger_1.logger.debug(`Call ${this.callId} gotLocalOffer() failed to create offer: `, err); - this.terminate(CallParty.Local, CallErrorCode.CreateOffer, true); - return; - } - try { - yield this.peerConn.setLocalDescription(offer); - } - catch (err) { - logger_1.logger.debug(`Call ${this.callId} gotLocalOffer() error setting local description!`, err); - this.terminate(CallParty.Local, CallErrorCode.SetLocalDescription, true); - return; - } - if (this.peerConn.iceGatheringState === "gathering") { - // Allow a short time for initial candidates to be gathered - yield new Promise((resolve) => { - setTimeout(resolve, 200); - }); - } - if (this.callHasEnded()) - return; - const eventType = this.state === CallState.CreateOffer ? event_1.EventType.CallInvite : event_1.EventType.CallNegotiate; - const content = { - lifetime: CALL_TIMEOUT_MS, - }; - if (eventType === event_1.EventType.CallInvite && this.invitee) { - content.invitee = this.invitee; - } - // clunky because TypeScript can't follow the types through if we use an expression as the key - if (this.state === CallState.CreateOffer) { - content.offer = (_a = this.peerConn.localDescription) === null || _a === void 0 ? void 0 : _a.toJSON(); - } - else { - content.description = (_b = this.peerConn.localDescription) === null || _b === void 0 ? void 0 : _b.toJSON(); - } - content.capabilities = { - "m.call.transferee": this.client.supportsCallTransfer, - "m.call.dtmf": false, - }; - content[callEventTypes_1.SDPStreamMetadataKey] = this.getLocalSDPStreamMetadata(true); - // Get rid of any candidates waiting to be sent: they'll be included in the local - // description we just got and will send in the offer. - const discardCount = this.discardDuplicateCandidates(); - logger_1.logger.info(`Call ${this.callId} gotLocalOffer() discarding ${discardCount} candidates that will be sent in offer`); - try { - yield this.sendVoipEvent(eventType, content); - } - catch (error) { - logger_1.logger.error(`Call ${this.callId} gotLocalOffer() failed to send invite`, error); - if (error instanceof http_api_1.MatrixError && error.event) - this.client.cancelPendingEvent(error.event); - let code = CallErrorCode.SignallingFailed; - let message = "Signalling failed"; - if (this.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"; - } - this.emit(CallEvent.Error, new CallError(code, message, error), this); - this.terminate(CallParty.Local, code, false); - // no need to carry on & send the candidate queue, but we also - // don't want to rethrow the error - return; - } - this.sendCandidateQueue(); - if (this.state === CallState.CreateOffer) { - this.inviteOrAnswerSent = true; - this.state = CallState.InviteSent; - this.inviteTimeout = setTimeout(() => { - this.inviteTimeout = undefined; - if (this.state === CallState.InviteSent) { - this.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() { - // RTCRtpReceiver.getCapabilities and RTCRtpSender.getCapabilities don't seem to be supported on FF - if (!RTCRtpReceiver.getCapabilities || !RTCRtpSender.getCapabilities) - return; - const recvCodecs = RTCRtpReceiver.getCapabilities("video").codecs; - const sendCodecs = RTCRtpSender.getCapabilities("video").codecs; - const codecs = [...sendCodecs, ...recvCodecs]; - for (const codec of codecs) { - if (codec.mimeType === "video/rtx") { - const rtxCodecIndex = codecs.indexOf(codec); - codecs.splice(rtxCodecIndex, 1); - } - } - const screenshareVideoTransceiver = this.transceivers.get(getTransceiverKey(callEventTypes_1.SDPStreamMetadataPurpose.Screenshare, "video")); - if (screenshareVideoTransceiver) - screenshareVideoTransceiver.setCodecPreferences(codecs); - } - /** - * @internal - */ - sendVoipEvent(eventType, content) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - const realContent = Object.assign({}, content, { - version: VOIP_PROTO_VERSION, - call_id: this.callId, - party_id: this.ourPartyId, - conf_id: this.groupCallId, - }); - if (this.opponentDeviceId) { - const toDeviceSeq = this.toDeviceSeq++; - const content = Object.assign(Object.assign({}, realContent), { device_id: this.client.deviceId, sender_session_id: this.client.getSessionId(), dest_session_id: this.opponentSessionId, seq: toDeviceSeq, [event_1.ToDeviceMessageId]: (0, uuid_1.v4)() }); - this.emit(CallEvent.SendVoipEvent, { - type: "toDevice", - eventType, - userId: this.invitee || ((_a = this.getOpponentMember()) === null || _a === void 0 ? void 0 : _a.userId), - opponentDeviceId: this.opponentDeviceId, - content, - }, this); - const userId = this.invitee || this.getOpponentMember().userId; - if (this.client.getUseE2eForGroupCall()) { - if (!this.opponentDeviceInfo) { - logger_1.logger.warn(`Call ${this.callId} sendVoipEvent() failed: we do not have opponentDeviceInfo`); - return; - } - yield this.client.encryptAndSendToDevices([ - { - userId, - deviceInfo: this.opponentDeviceInfo, - }, - ], { - type: eventType, - content, - }); - } - else { - yield this.client.sendToDevice(eventType, new Map([[userId, new Map([[this.opponentDeviceId, content]])]])); - } - } - else { - this.emit(CallEvent.SendVoipEvent, { - type: "sendEvent", - eventType, - roomId: this.roomId, - content: realContent, - userId: this.invitee || ((_b = this.getOpponentMember()) === null || _b === void 0 ? void 0 : _b.userId), - }, this); - yield this.client.sendEvent(this.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) { - // We partially de-trickle candidates by waiting for `delay` before sending them - // amalgamated, in order to avoid sending too many m.call.candidates events and hitting - // rate limits in Matrix. - // In practice, it'd be better to remove rate limits for m.call.* - // N.B. this deliberately lets you queue and send blank candidates, which MSC2746 - // currently proposes as the way to indicate that candidate gathering is complete. - // This will hopefully be changed to an explicit rather than implicit notification - // shortly. - if (content) { - this.candidateSendQueue.push(content); - } - else { - this.candidatesEnded = true; - } - // Don't send the ICE candidates yet if the call is in the ringing state: this - // means we tried to pick (ie. started generating candidates) and then failed to - // send the answer and went back to the ringing state. Queue up the candidates - // to send if we successfully send the answer. - // Equally don't send if we haven't yet sent the answer because we can send the - // first batch of candidates along with the answer - if (this.state === CallState.Ringing || !this.inviteOrAnswerSent) - return; - // MSC2746 recommends these values (can be quite long when calling because the - // callee will need a while to answer the call) - const delay = this.direction === CallDirection.Inbound ? 500 : 2000; - if (this.candidateSendTries === 0) { - setTimeout(() => { - this.sendCandidateQueue(); - }, delay); - } - } - // Discard all non-end-of-candidates messages - // Return the number of candidate messages that were discarded. - // Call this method before sending an invite or answer message - discardDuplicateCandidates() { - let discardCount = 0; - const newQueue = []; - for (let i = 0; i < this.candidateSendQueue.length; i++) { - const candidate = this.candidateSendQueue[i]; - if (candidate.candidate === "") { - newQueue.push(candidate); - } - else { - discardCount++; - } - } - this.candidateSendQueue = newQueue; - return discardCount; - } - /* - * Transfers this call to another user - */ - transfer(targetUserId) { - return __awaiter(this, void 0, void 0, function* () { - // Fetch the target user's global profile info: their room avatar / displayname - // could be different in whatever room we share with them. - const profileInfo = yield this.client.getProfileInfo(targetUserId); - const replacementId = genCallID(); - const body = { - replacement_id: genCallID(), - target_user: { - id: targetUserId, - display_name: profileInfo.displayname, - avatar_url: profileInfo.avatar_url, - }, - create_call: replacementId, - }; - yield this.sendVoipEvent(event_1.EventType.CallReplaces, body); - yield this.terminate(CallParty.Local, CallErrorCode.Transferred, true); - }); - } - /* - * Transfers this call to the target call, effectively 'joining' the - * two calls (so the remote parties on each call are connected together). - */ - transferToCall(transferTargetCall) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - const targetUserId = (_a = transferTargetCall.getOpponentMember()) === null || _a === void 0 ? void 0 : _a.userId; - const targetProfileInfo = targetUserId ? yield this.client.getProfileInfo(targetUserId) : undefined; - const opponentUserId = (_b = this.getOpponentMember()) === null || _b === void 0 ? void 0 : _b.userId; - const transfereeProfileInfo = opponentUserId ? yield this.client.getProfileInfo(opponentUserId) : undefined; - const newCallId = genCallID(); - const bodyToTransferTarget = { - // the replacements on each side have their own ID, and it's distinct from the - // ID of the new call (but we can use the same function to generate it) - 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(event_1.EventType.CallReplaces, bodyToTransferTarget); - const 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 this.sendVoipEvent(event_1.EventType.CallReplaces, bodyToTransferee); - yield this.terminate(CallParty.Local, CallErrorCode.Transferred, true); - yield transferTargetCall.terminate(CallParty.Local, CallErrorCode.Transferred, true); - }); - } - terminate(hangupParty, hangupReason, shouldEmit) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - if (this.callHasEnded()) - return; - this.hangupParty = hangupParty; - this.hangupReason = hangupReason; - this.state = CallState.Ended; - if (this.inviteTimeout) { - clearTimeout(this.inviteTimeout); - this.inviteTimeout = undefined; - } - if (this.iceDisconnectedTimeout !== undefined) { - clearTimeout(this.iceDisconnectedTimeout); - this.iceDisconnectedTimeout = undefined; - } - if (this.callLengthInterval) { - clearInterval(this.callLengthInterval); - this.callLengthInterval = undefined; - } - if (this.stopVideoTrackTimer !== undefined) { - clearTimeout(this.stopVideoTrackTimer); - this.stopVideoTrackTimer = undefined; - } - for (const [stream, listener] of this.removeTrackListeners) { - stream.removeEventListener("removetrack", listener); - } - this.removeTrackListeners.clear(); - this.callStatsAtEnd = yield this.collectCallStats(); - // Order is important here: first we stopAllMedia() and only then we can deleteAllFeeds() - this.stopAllMedia(); - this.deleteAllFeeds(); - if (this.peerConn && this.peerConn.signalingState !== "closed") { - this.peerConn.close(); - } - (_a = this.stats) === null || _a === void 0 ? void 0 : _a.removeStatsReportGatherer(this.callId); - if (shouldEmit) { - this.emit(CallEvent.Hangup, this); - } - this.client.callEventHandler.calls.delete(this.callId); - }); - } - stopAllMedia() { - logger_1.logger.debug(`Call ${this.callId} stopAllMedia() running`); - for (const feed of this.feeds) { - // Slightly awkward as local feed need to go via the correct method on - // the MediaHandler so they get removed from MediaHandler (remote tracks - // don't) - // NB. We clone local streams when passing them to individual calls in a group - // call, so we can (and should) stop the clones once we no longer need them: - // the other clones will continue fine. - if (feed.isLocal() && feed.purpose === callEventTypes_1.SDPStreamMetadataPurpose.Usermedia) { - this.client.getMediaHandler().stopUserMediaStream(feed.stream); - } - else if (feed.isLocal() && feed.purpose === callEventTypes_1.SDPStreamMetadataPurpose.Screenshare) { - this.client.getMediaHandler().stopScreensharingStream(feed.stream); - } - else if (!feed.isLocal()) { - logger_1.logger.debug(`Call ${this.callId} stopAllMedia() stopping stream (streamId=${feed.stream.id})`); - for (const track of feed.stream.getTracks()) { - track.stop(); - } - } - } - } - checkForErrorListener() { - if (this.listeners(typed_event_emitter_1.EventEmitterEvents.Error).length === 0) { - throw new Error("You MUST attach an error listener using call.on('error', function() {})"); - } - } - sendCandidateQueue() { - return __awaiter(this, void 0, void 0, function* () { - if (this.candidateSendQueue.length === 0 || this.callHasEnded()) { - return; - } - const candidates = this.candidateSendQueue; - this.candidateSendQueue = []; - ++this.candidateSendTries; - const content = { candidates: candidates.map((candidate) => candidate.toJSON()) }; - if (this.candidatesEnded) { - // If there are no more candidates, signal this by adding an empty string candidate - content.candidates.push({ - candidate: "", - }); - } - logger_1.logger.debug(`Call ${this.callId} sendCandidateQueue() attempting to send ${candidates.length} candidates`); - try { - yield this.sendVoipEvent(event_1.EventType.CallCandidates, content); - // reset our retry count if we have successfully sent our candidates - // otherwise queueCandidate() will refuse to try to flush the queue - this.candidateSendTries = 0; - // Try to send candidates again just in case we received more candidates while sending. - this.sendCandidateQueue(); - } - catch (error) { - // don't retry this event: we'll send another one later as we might - // have more candidates by then. - if (error instanceof http_api_1.MatrixError && error.event) - this.client.cancelPendingEvent(error.event); - // put all the candidates we failed to send back in the queue - this.candidateSendQueue.push(...candidates); - if (this.candidateSendTries > 5) { - logger_1.logger.debug(`Call ${this.callId} sendCandidateQueue() failed to send candidates on attempt ${this.candidateSendTries}. Giving up on this call.`, error); - const code = CallErrorCode.SignallingFailed; - const message = "Signalling failed"; - this.emit(CallEvent.Error, new CallError(code, message, error), this); - this.hangup(code, false); - return; - } - const delayMs = 500 * Math.pow(2, this.candidateSendTries); - ++this.candidateSendTries; - logger_1.logger.debug(`Call ${this.callId} sendCandidateQueue() failed to send candidates. Retrying in ${delayMs}ms`, error); - setTimeout(() => { - this.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 _a; - return __awaiter(this, void 0, void 0, function* () { - if (!audio) { - throw new Error("You CANNOT start a call without audio"); - } - this.state = CallState.WaitLocalMedia; - try { - const stream = yield this.client.getMediaHandler().getUserMediaStream(audio, video); - // make sure all the tracks are enabled (same as pushNewLocalFeed - - // we probably ought to just have one code path for adding streams) - setTracksEnabled(stream.getAudioTracks(), true); - setTracksEnabled(stream.getVideoTracks(), true); - const callFeed = new callFeed_1.CallFeed({ - client: this.client, - roomId: this.roomId, - userId: this.client.getUserId(), - deviceId: (_a = this.client.getDeviceId()) !== null && _a !== void 0 ? _a : undefined, - stream, - purpose: callEventTypes_1.SDPStreamMetadataPurpose.Usermedia, - audioMuted: false, - videoMuted: false, - }); - yield this.placeCallWithCallFeeds([callFeed]); - } - catch (e) { - this.getUserMediaFailed(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, requestScreenshareFeed = false) { - return __awaiter(this, void 0, void 0, function* () { - this.checkForErrorListener(); - this.direction = CallDirection.Outbound; - yield this.initOpponentCrypto(); - // XXX Find a better way to do this - this.client.callEventHandler.calls.set(this.callId, this); - // make sure we have valid turn creds. Unless something's gone wrong, it should - // poll and keep the credentials valid so this should be instant. - const haveTurnCreds = yield this.client.checkTurnServers(); - if (!haveTurnCreds) { - logger_1.logger.warn(`Call ${this.callId} placeCallWithCallFeeds() failed to get TURN credentials! Proceeding with call anyway...`); - } - // create the peer connection now so it can be gathering candidates while we get user - // media (assuming a candidate pool size is configured) - this.peerConn = this.createPeerConnection(); - this.gotCallFeedsForInvite(callFeeds, requestScreenshareFeed); - }); - } - createPeerConnection() { - var _a; - const pc = new window.RTCPeerConnection({ - iceTransportPolicy: this.forceTURN ? "relay" : undefined, - iceServers: this.turnServers, - iceCandidatePoolSize: this.client.iceCandidatePoolSize, - bundlePolicy: "max-bundle", - }); - // 'connectionstatechange' would be better, but firefox doesn't implement that. - 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); - (_a = this.stats) === null || _a === void 0 ? void 0 : _a.addStatsReportGatherer(this.callId, "unknown", pc); - return pc; - } - partyIdMatches(msg) { - // They must either match or both be absent (in which case opponentPartyId will be null) - // Also we ignore party IDs on the invite/offer if the version is 0, so we must do the same - // here and use null if the version is 0 (woe betide any opponent sending messages in the - // same call with different versions) - const msgPartyId = msg.version === 0 ? null : msg.party_id || null; - return msgPartyId === this.opponentPartyId; - } - // Commits to an opponent for the call - // ev: An invite or answer event - chooseOpponent(ev) { - var _a; - // I choo-choo-choose you - const msg = ev.getContent(); - logger_1.logger.debug(`Call ${this.callId} chooseOpponent() running (partyId=${msg.party_id})`); - this.opponentVersion = msg.version; - if (this.opponentVersion === 0) { - // set to null to indicate that we've chosen an opponent, but because - // they're v0 they have no party ID (even if they sent one, we're ignoring it) - this.opponentPartyId = null; - } - else { - // set to their party ID, or if they're naughty and didn't send one despite - // not being v0, set it to null to indicate we picked an opponent with no - // party ID - this.opponentPartyId = msg.party_id || null; - } - this.opponentCaps = msg.capabilities || {}; - this.opponentMember = (_a = this.client.getRoom(this.roomId).getMember(ev.getSender())) !== null && _a !== void 0 ? _a : undefined; - } - addBufferedIceCandidates() { - return __awaiter(this, void 0, void 0, function* () { - const bufferedCandidates = this.remoteCandidateBuffer.get(this.opponentPartyId); - if (bufferedCandidates) { - logger_1.logger.info(`Call ${this.callId} addBufferedIceCandidates() adding ${bufferedCandidates.length} buffered candidates for opponent ${this.opponentPartyId}`); - yield this.addIceCandidates(bufferedCandidates); - } - this.remoteCandidateBuffer.clear(); - }); - } - addIceCandidates(candidates) { - return __awaiter(this, void 0, void 0, function* () { - for (const candidate of candidates) { - if ((candidate.sdpMid === null || candidate.sdpMid === undefined) && - (candidate.sdpMLineIndex === null || candidate.sdpMLineIndex === undefined)) { - logger_1.logger.debug(`Call ${this.callId} addIceCandidates() got remote ICE end-of-candidates`); - } - else { - logger_1.logger.debug(`Call ${this.callId} addIceCandidates() got remote ICE candidate (sdpMid=${candidate.sdpMid}, candidate=${candidate.candidate})`); - } - try { - yield this.peerConn.addIceCandidate(candidate); - } - catch (err) { - if (!this.ignoreOffer) { - logger_1.logger.info(`Call ${this.callId} addIceCandidates() failed to add remote ICE candidate`, err); - } - } - } - }); - } - get hasPeerConnection() { - return Boolean(this.peerConn); - } - initStats(stats, peerId = "unknown") { - this.stats = stats; - this.stats.start(); - } -} -exports.MatrixCall = MatrixCall; -function setTracksEnabled(tracks, enabled) { - for (const track of tracks) { - track.enabled = enabled; - } -} -exports.setTracksEnabled = setTracksEnabled; -function supportsMatrixCall() { - // typeof prevents Node from erroring on an undefined reference - if (typeof window === "undefined" || typeof document === "undefined") { - // NB. We don't log here as apps try to create a call object as a test for - // whether calls are supported, so we shouldn't fill the logs up. - return false; - } - // Firefox throws on so little as accessing the RTCPeerConnection when operating in a secure mode. - // There's some information at https://bugzilla.mozilla.org/show_bug.cgi?id=1542616 though the concern - // is that the browser throwing a SecurityError will brick the client creation process. - try { - const supported = Boolean(window.RTCPeerConnection || - window.RTCSessionDescription || - window.RTCIceCandidate || - navigator.mediaDevices); - if (!supported) { - /* istanbul ignore if */ // Adds a lot of noise to test runs, so disable logging there. - if (process.env.NODE_ENV !== "test") { - logger_1.logger.error("WebRTC is not supported in this browser / environment"); - } - return false; - } - } - catch (e) { - logger_1.logger.error("Exception thrown when trying to access WebRTC", e); - return false; - } - return true; -} -exports.supportsMatrixCall = supportsMatrixCall; -/** - * 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; - const optionsForceTURN = options ? options.forceTURN : false; - const opts = { - client: client, - roomId: roomId, - invitee: options === null || options === void 0 ? void 0 : options.invitee, - turnServers: client.getTurnServers(), - // call level options - 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, - }; - const call = new MatrixCall(opts); - client.reEmitter.reEmit(call, Object.values(CallEvent)); - return call; -} -exports.createNewMatrixCall = createNewMatrixCall; - -}).call(this)}).call(this,require('_process')) - -},{"../@types/event":306,"../crypto/deviceinfo":340,"../http-api":367,"../logger":374,"../models/typed-event-emitter":395,"../randomstring":398,"../utils":416,"./callEventTypes":420,"./callFeed":421,"./groupCall":422,"_process":237,"sdp-transform":253,"uuid":287}],419:[function(require,module,exports){ -"use strict"; -/* -Copyright 2020 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CallEventHandler = exports.CallEventHandlerEvent = void 0; -const logger_1 = require("../logger"); -const call_1 = require("./call"); -const event_1 = require("../@types/event"); -const client_1 = require("../client"); -const groupCall_1 = require("./groupCall"); -const room_1 = require("../models/room"); -// Don't ring unless we'd be ringing for at least 3 seconds: the user needs some -// time to press the 'accept' button -const RING_GRACE_PERIOD = 3000; -var CallEventHandlerEvent; -(function (CallEventHandlerEvent) { - CallEventHandlerEvent["Incoming"] = "Call.incoming"; -})(CallEventHandlerEvent = exports.CallEventHandlerEvent || (exports.CallEventHandlerEvent = {})); -class CallEventHandler { - constructor(client) { - this.nextSeqByCall = new Map(); - this.toDeviceEventBuffers = new Map(); - this.onSync = () => { - // Process the current event buffer and start queuing into a new one. - const currentEventBuffer = this.callEventBuffer; - this.callEventBuffer = []; - // Ensure correct ordering by only processing this queue after the previous one has finished processing - if (this.eventBufferPromiseChain) { - this.eventBufferPromiseChain = this.eventBufferPromiseChain.then(() => this.evaluateEventBuffer(currentEventBuffer)); - } - else { - this.eventBufferPromiseChain = this.evaluateEventBuffer(currentEventBuffer); - } - }; - this.onRoomTimeline = (event) => { - this.callEventBuffer.push(event); - }; - this.onToDeviceEvent = (event) => { - const 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 === undefined) { - this.callEventBuffer.push(event); - return; - } - const 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, []); - } - const buffer = this.toDeviceEventBuffers.get(content.call_id); - const index = buffer.findIndex((e) => e.getContent().seq > content.seq); - if (index === -1) { - buffer.push(event); - } - else { - buffer.splice(index, 0, event); - } - } - else { - const callId = content.call_id; - this.callEventBuffer.push(event); - this.nextSeqByCall.set(callId, content.seq + 1); - const buffer = this.toDeviceEventBuffers.get(callId); - let 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 = new Map(); - // The sync code always emits one event at a time, so it will patiently - // wait for us to finish processing a call invite before delivering the - // next event, even if that next event is a hangup. We therefore accumulate - // all our call events and then process them on the 'sync' event, ie. - // each time a sync has completed. This way, we can avoid emitting incoming - // call events if we get both the invite and answer/hangup in the same sync. - // This happens quite often, eg. replaying sync from storage, catchup sync - // after loading and after we've been offline for a bit. - this.callEventBuffer = []; - this.candidateEventsByCall = new Map(); - } - start() { - this.client.on(client_1.ClientEvent.Sync, this.onSync); - this.client.on(room_1.RoomEvent.Timeline, this.onRoomTimeline); - this.client.on(client_1.ClientEvent.ToDeviceEvent, this.onToDeviceEvent); - } - stop() { - this.client.removeListener(client_1.ClientEvent.Sync, this.onSync); - this.client.removeListener(room_1.RoomEvent.Timeline, this.onRoomTimeline); - this.client.removeListener(client_1.ClientEvent.ToDeviceEvent, this.onToDeviceEvent); - } - evaluateEventBuffer(eventBuffer) { - return __awaiter(this, void 0, void 0, function* () { - yield Promise.all(eventBuffer.map((event) => this.client.decryptEventIfNeeded(event))); - const callEvents = eventBuffer.filter((event) => { - const eventType = event.getType(); - return eventType.startsWith("m.call.") || eventType.startsWith("org.matrix.call."); - }); - const ignoreCallIds = new Set(); - // inspect the buffer and mark all calls which have been answered - // or hung up before passing them to the call event handler. - for (const event of callEvents) { - const eventType = event.getType(); - if (eventType === event_1.EventType.CallAnswer || eventType === event_1.EventType.CallHangup) { - ignoreCallIds.add(event.getContent().call_id); - } - } - // Process call events in the order that they were received - for (const event of callEvents) { - const eventType = event.getType(); - const callId = event.getContent().call_id; - if (eventType === event_1.EventType.CallInvite && ignoreCallIds.has(callId)) { - // This call has previously been answered or hung up: ignore it - continue; - } - try { - yield this.handleCallEvent(event); - } - catch (e) { - logger_1.logger.error("CallEventHandler evaluateEventBuffer() caught exception handling call event", e); - } - } - }); - } - handleCallEvent(event) { - var _a, _b, _c, _d, _e, _f; - return __awaiter(this, void 0, void 0, function* () { - this.client.emit(client_1.ClientEvent.ReceivedVoipEvent, event); - const content = event.getContent(); - const callRoomId = event.getRoomId() || ((_b = (_a = this.client.groupCallEventHandler.getGroupCallById(content.conf_id)) === null || _a === void 0 ? void 0 : _a.room) === null || _b === void 0 ? void 0 : _b.roomId); - const groupCallId = content.conf_id; - const type = event.getType(); - const senderId = event.getSender(); - let call = content.call_id ? this.calls.get(content.call_id) : undefined; - let opponentDeviceId; - let groupCall; - if (groupCallId) { - groupCall = this.client.groupCallEventHandler.getGroupCallById(groupCallId); - if (!groupCall) { - logger_1.logger.warn(`CallEventHandler handleCallEvent() could not find a group call - ignoring event (groupCallId=${groupCallId}, type=${type})`); - return; - } - opponentDeviceId = content.device_id; - if (!opponentDeviceId) { - logger_1.logger.warn(`CallEventHandler handleCallEvent() could not find a device id - ignoring event (senderId=${senderId})`); - groupCall.emit(groupCall_1.GroupCallEvent.Error, new groupCall_1.GroupCallUnknownDeviceError(senderId)); - return; - } - if (content.dest_session_id !== this.client.getSessionId()) { - logger_1.logger.warn("CallEventHandler handleCallEvent() call event does not match current session id - ignoring"); - return; - } - } - const weSentTheEvent = senderId === this.client.credentials.userId && - (opponentDeviceId === undefined || opponentDeviceId === this.client.getDeviceId()); - if (!callRoomId) - return; - if (type === event_1.EventType.CallInvite) { - // ignore invites you send - if (weSentTheEvent) - return; - // expired call - if (event.getLocalAge() > content.lifetime - RING_GRACE_PERIOD) - return; - // stale/old invite event - if (call && call.state === call_1.CallState.Ended) - return; - if (call) { - logger_1.logger.warn(`CallEventHandler handleCallEvent() already has a call but got an invite - clobbering (callId=${content.call_id})`); - } - if (content.invitee && content.invitee !== this.client.getUserId()) { - return; // This invite was meant for another user in the room - } - const timeUntilTurnCresExpire = ((_c = this.client.getTurnServersExpiry()) !== null && _c !== void 0 ? _c : 0) - Date.now(); - logger_1.logger.info("CallEventHandler handleCallEvent() current turn creds expire in " + timeUntilTurnCresExpire + " ms"); - call = - (_d = (0, call_1.createNewMatrixCall)(this.client, callRoomId, { - forceTURN: this.client.forceTURN, - opponentDeviceId, - groupCallId, - opponentSessionId: content.sender_session_id, - })) !== null && _d !== void 0 ? _d : undefined; - if (!call) { - logger_1.logger.log(`CallEventHandler handleCallEvent() this client does not support WebRTC (callId=${content.call_id})`); - // don't hang up the call: there could be other clients - // connected that do support WebRTC and declining the - // the call on their behalf would be really annoying. - return; - } - call.callId = content.call_id; - const stats = groupCall === null || groupCall === void 0 ? void 0 : groupCall.getGroupCallStats(); - if (stats) { - call.initStats(stats); - } - try { - yield call.initWithInvite(event); - } - catch (e) { - if (e instanceof call_1.CallError) { - if (e.code === groupCall_1.GroupCallErrorCode.UnknownDevice) { - groupCall === null || groupCall === void 0 ? void 0 : groupCall.emit(groupCall_1.GroupCallEvent.Error, e); - } - else { - logger_1.logger.error(e); - } - } - } - this.calls.set(call.callId, call); - // if we stashed candidate events for that call ID, play them back now - if (this.candidateEventsByCall.get(call.callId)) { - for (const ev of this.candidateEventsByCall.get(call.callId)) { - call.onRemoteIceCandidatesReceived(ev); - } - } - // Were we trying to call that user (room)? - let existingCall; - for (const thisCall of this.calls.values()) { - const isCalling = [call_1.CallState.WaitLocalMedia, call_1.CallState.CreateOffer, call_1.CallState.InviteSent].includes(thisCall.state); - if (call.roomId === thisCall.roomId && - thisCall.direction === call_1.CallDirection.Outbound && - ((_e = call.getOpponentMember()) === null || _e === void 0 ? void 0 : _e.userId) === thisCall.invitee && - isCalling) { - existingCall = thisCall; - break; - } - } - if (existingCall) { - if (existingCall.callId > call.callId) { - logger_1.logger.log(`CallEventHandler handleCallEvent() detected glare - answering incoming call and canceling outgoing call (incomingId=${call.callId}, outgoingId=${existingCall.callId})`); - existingCall.replacedBy(call); - } - else { - logger_1.logger.log(`CallEventHandler handleCallEvent() detected glare - hanging up incoming call (incomingId=${call.callId}, outgoingId=${existingCall.callId})`); - call.hangup(call_1.CallErrorCode.Replaced, true); - } - } - else { - this.client.emit(CallEventHandlerEvent.Incoming, call); - } - return; - } - else if (type === event_1.EventType.CallCandidates) { - if (weSentTheEvent) - return; - if (!call) { - // store the candidates; we may get a call eventually. - if (!this.candidateEventsByCall.has(content.call_id)) { - this.candidateEventsByCall.set(content.call_id, []); - } - this.candidateEventsByCall.get(content.call_id).push(event); - } - else { - call.onRemoteIceCandidatesReceived(event); - } - return; - } - else if ([event_1.EventType.CallHangup, event_1.EventType.CallReject].includes(type)) { - // Note that we also observe our own hangups here so we can see - // if we've already rejected a call that would otherwise be valid - if (!call) { - // if not live, store the fact that the call has ended because - // we're probably getting events backwards so - // the hangup will come before the invite - call = - (_f = (0, call_1.createNewMatrixCall)(this.client, callRoomId, { - opponentDeviceId, - opponentSessionId: content.sender_session_id, - })) !== null && _f !== void 0 ? _f : undefined; - if (call) { - call.callId = content.call_id; - call.initWithHangup(event); - this.calls.set(content.call_id, call); - } - } - else { - if (call.state !== call_1.CallState.Ended) { - if (type === event_1.EventType.CallHangup) { - call.onHangupReceived(content); - } - else { - call.onRejectReceived(content); - } - // @ts-expect-error typescript thinks the state can't be 'ended' because we're - // inside the if block where it wasn't, but it could have changed because - // on[Hangup|Reject]Received are side-effecty. - if (call.state === call_1.CallState.Ended) - this.calls.delete(content.call_id); - } - } - return; - } - // The following events need a call and a peer connection - if (!call || !call.hasPeerConnection) { - logger_1.logger.info(`CallEventHandler handleCallEvent() discarding possible call event as we don't have a call (type=${type})`); - return; - } - // Ignore remote echo - if (event.getContent().party_id === call.ourPartyId) - return; - switch (type) { - case event_1.EventType.CallAnswer: - if (weSentTheEvent) { - if (call.state === call_1.CallState.Ringing) { - call.onAnsweredElsewhere(content); - } - } - else { - call.onAnswerReceived(event); - } - break; - case event_1.EventType.CallSelectAnswer: - call.onSelectAnswerReceived(event); - break; - case event_1.EventType.CallNegotiate: - call.onNegotiateReceived(event); - break; - case event_1.EventType.CallAssertedIdentity: - case event_1.EventType.CallAssertedIdentityPrefix: - call.onAssertedIdentityReceived(event); - break; - case event_1.EventType.CallSDPStreamMetadataChanged: - case event_1.EventType.CallSDPStreamMetadataChangedPrefix: - call.onSDPStreamMetadataChangedReceived(event); - break; - } - }); - } -} -exports.CallEventHandler = CallEventHandler; - -},{"../@types/event":306,"../client":321,"../logger":374,"../models/room":392,"./call":418,"./groupCall":422}],420:[function(require,module,exports){ -"use strict"; -// allow non-camelcase as these are events type that go onto the wire -/* eslint-disable camelcase */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SDPStreamMetadataPurpose = exports.SDPStreamMetadataKey = void 0; -// TODO: Change to "sdp_stream_metadata" when MSC3077 is merged -exports.SDPStreamMetadataKey = "org.matrix.msc3077.sdp_stream_metadata"; -var SDPStreamMetadataPurpose; -(function (SDPStreamMetadataPurpose) { - SDPStreamMetadataPurpose["Usermedia"] = "m.usermedia"; - SDPStreamMetadataPurpose["Screenshare"] = "m.screenshare"; -})(SDPStreamMetadataPurpose = exports.SDPStreamMetadataPurpose || (exports.SDPStreamMetadataPurpose = {})); -/* eslint-enable camelcase */ - -},{}],421:[function(require,module,exports){ -"use strict"; -/* -Copyright 2021 Šimon Brandner - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CallFeed = exports.CallFeedEvent = exports.SPEAKING_THRESHOLD = void 0; -const callEventTypes_1 = require("./callEventTypes"); -const audioContext_1 = require("./audioContext"); -const logger_1 = require("../logger"); -const typed_event_emitter_1 = require("../models/typed-event-emitter"); -const call_1 = require("./call"); -const POLLING_INTERVAL = 200; // ms -exports.SPEAKING_THRESHOLD = -60; // dB -const SPEAKING_SAMPLE_COUNT = 8; // samples -var CallFeedEvent; -(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"; -})(CallFeedEvent = exports.CallFeedEvent || (exports.CallFeedEvent = {})); -class CallFeed extends typed_event_emitter_1.TypedEventEmitter { - constructor(opts) { - super(); - this.localVolume = 1; - this.measuringVolumeActivity = false; - this.speakingThreshold = exports.SPEAKING_THRESHOLD; - this.speaking = false; - this._disposed = false; - this._connected = false; - this.onAddTrack = () => { - this.emit(CallFeedEvent.NewStream, this.stream); - }; - this.onCallState = (state) => { - if (state === call_1.CallState.Connected) { - this.connected = true; - } - else if (state === call_1.CallState.Connecting) { - this.connected = false; - } - }; - this.volumeLooper = () => { - if (!this.analyser) - return; - if (!this.measuringVolumeActivity) - return; - this.analyser.getFloatFrequencyData(this.frequencyBinCount); - let maxVolume = -Infinity; - for (const volume of this.frequencyBinCount) { - if (volume > maxVolume) { - maxVolume = volume; - } - } - this.speakingVolumeSamples.shift(); - this.speakingVolumeSamples.push(maxVolume); - this.emit(CallFeedEvent.VolumeChanged, maxVolume); - let newSpeaking = false; - for (const 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; // updateStream does this, but this makes TS happier - if (this.hasAudioTrack) { - this.initVolumeMeasuring(); - } - if (opts.call) { - opts.call.addListener(call_1.CallEvent.State, this.onCallState); - this.onCallState(opts.call.state); - } - } - get connected() { - // Local feeds are always considered 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; - if (oldStream) { - oldStream.removeEventListener("addtrack", this.onAddTrack); - this.measureVolumeActivity(false); - } - this.stream = newStream; - newStream.addEventListener("addtrack", this.onAddTrack); - if (this.hasAudioTrack) { - this.initVolumeMeasuring(); - } - else { - this.measureVolumeActivity(false); - } - this.emit(CallFeedEvent.NewStream, this.stream); - } - initVolumeMeasuring() { - if (!this.hasAudioTrack) - return; - if (!this.audioContext) - this.audioContext = (0, audioContext_1.acquireContext)(); - this.analyser = this.audioContext.createAnalyser(); - this.analyser.fftSize = 512; - this.analyser.smoothingTimeConstant = 0.1; - const mediaStreamAudioSourceNode = this.audioContext.createMediaStreamSource(this.stream); - mediaStreamAudioSourceNode.connect(this.analyser); - this.frequencyBinCount = new Float32Array(this.analyser.frequencyBinCount); - } - /** - * Returns callRoom member - * @returns member of the callRoom - */ - getMember() { - var _a; - const callRoom = this.client.getRoom(this.roomId); - return (_a = callRoom === null || callRoom === void 0 ? void 0 : callRoom.getMember(this.userId)) !== null && _a !== void 0 ? _a : null; - } - /** - * Returns true if CallFeed is local, otherwise returns false - * @returns is local? - */ - isLocal() { - return (this.userId === this.client.getUserId() && - (this.deviceId === undefined || 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() { - // We assume only one video track - 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() { - const mediaHandler = this.client.getMediaHandler(); - const stream = this.stream.clone(); - logger_1.logger.log(`CallFeed clone() cloning stream (originalStreamId=${this.stream.id}, newStreamId${stream.id})`); - if (this.purpose === callEventTypes_1.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 _a, _b; - clearTimeout(this.volumeLooperTimeout); - (_a = this.stream) === null || _a === void 0 ? void 0 : _a.removeEventListener("addtrack", this.onAddTrack); - (_b = this.call) === null || _b === void 0 ? void 0 : _b.removeListener(call_1.CallEvent.State, this.onCallState); - if (this.audioContext) { - this.audioContext = undefined; - this.analyser = undefined; - (0, audioContext_1.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); - } -} -exports.CallFeed = CallFeed; - -},{"../logger":374,"../models/typed-event-emitter":395,"./audioContext":417,"./call":418,"./callEventTypes":420}],422:[function(require,module,exports){ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.GroupCall = exports.GroupCallState = exports.OtherUserSpeakingError = exports.GroupCallUnknownDeviceError = exports.GroupCallError = exports.GroupCallErrorCode = exports.GroupCallStatsReportEvent = exports.GroupCallEvent = exports.GroupCallTerminationReason = exports.GroupCallType = exports.GroupCallIntent = void 0; -const typed_event_emitter_1 = require("../models/typed-event-emitter"); -const callFeed_1 = require("./callFeed"); -const call_1 = require("./call"); -const room_state_1 = require("../models/room-state"); -const logger_1 = require("../logger"); -const ReEmitter_1 = require("../ReEmitter"); -const callEventTypes_1 = require("./callEventTypes"); -const event_1 = require("../@types/event"); -const callEventHandler_1 = require("./callEventHandler"); -const groupCallEventHandler_1 = require("./groupCallEventHandler"); -const utils_1 = require("../utils"); -const groupCallStats_1 = require("./stats/groupCallStats"); -const statsReport_1 = require("./stats/statsReport"); -var GroupCallIntent; -(function (GroupCallIntent) { - GroupCallIntent["Ring"] = "m.ring"; - GroupCallIntent["Prompt"] = "m.prompt"; - GroupCallIntent["Room"] = "m.room"; -})(GroupCallIntent = exports.GroupCallIntent || (exports.GroupCallIntent = {})); -var GroupCallType; -(function (GroupCallType) { - GroupCallType["Video"] = "m.video"; - GroupCallType["Voice"] = "m.voice"; -})(GroupCallType = exports.GroupCallType || (exports.GroupCallType = {})); -var GroupCallTerminationReason; -(function (GroupCallTerminationReason) { - GroupCallTerminationReason["CallEnded"] = "call_ended"; -})(GroupCallTerminationReason = exports.GroupCallTerminationReason || (exports.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; -(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"; -})(GroupCallEvent = exports.GroupCallEvent || (exports.GroupCallEvent = {})); -var GroupCallStatsReportEvent; -(function (GroupCallStatsReportEvent) { - GroupCallStatsReportEvent["ConnectionStats"] = "GroupCall.connection_stats"; - GroupCallStatsReportEvent["ByteSentStats"] = "GroupCall.byte_sent_stats"; -})(GroupCallStatsReportEvent = exports.GroupCallStatsReportEvent || (exports.GroupCallStatsReportEvent = {})); -var GroupCallErrorCode; -(function (GroupCallErrorCode) { - GroupCallErrorCode["NoUserMedia"] = "no_user_media"; - GroupCallErrorCode["UnknownDevice"] = "unknown_device"; - GroupCallErrorCode["PlaceCallFailed"] = "place_call_failed"; -})(GroupCallErrorCode = exports.GroupCallErrorCode || (exports.GroupCallErrorCode = {})); -class GroupCallError extends Error { - constructor(code, msg, err) { - // Still don't think there's any way to have proper nested errors - if (err) { - super(msg + ": " + err); - } - else { - super(msg); - } - this.code = code; - } -} -exports.GroupCallError = GroupCallError; -class GroupCallUnknownDeviceError extends GroupCallError { - constructor(userId) { - super(GroupCallErrorCode.UnknownDevice, "No device found for " + userId); - this.userId = userId; - } -} -exports.GroupCallUnknownDeviceError = GroupCallUnknownDeviceError; -class OtherUserSpeakingError extends Error { - constructor() { - super("Cannot unmute: another user is speaking"); - } -} -exports.OtherUserSpeakingError = OtherUserSpeakingError; -var GroupCallState; -(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"; -})(GroupCallState = exports.GroupCallState || (exports.GroupCallState = {})); -const DEVICE_TIMEOUT = 1000 * 60 * 60; // 1 hour -function getCallUserId(call) { - var _a; - return ((_a = call.getOpponentMember()) === null || _a === void 0 ? void 0 : _a.userId) || call.invitee || null; -} -class GroupCall extends typed_event_emitter_1.TypedEventEmitter { - constructor(client, room, type, isPtt, intent, groupCallId, dataChannelsEnabled, dataChannelOptions, isCallWithoutVideoAndAudio) { - var _a, _b; - super(); - this.client = client; - this.room = room; - this.type = type; - this.isPtt = isPtt; - this.intent = intent; - this.dataChannelsEnabled = dataChannelsEnabled; - this.dataChannelOptions = dataChannelOptions; - // Config - this.activeSpeakerInterval = 1000; - this.retryCallInterval = 5000; - this.participantTimeout = 1000 * 15; - this.pttMaxTransmitTime = 1000 * 20; - this.userMediaFeeds = []; - this.screenshareFeeds = []; - this.calls = new Map(); // user_id -> device_id -> MatrixCall - this.callHandlers = new Map(); // user_id -> device_id -> ICallHandlers - this.retryCallCounts = new Map(); // user_id -> device_id -> count - this.transmitTimer = null; - this.participantsExpirationTimer = null; - this.resendMemberStateTimer = null; - this.initWithAudioMuted = false; - this.initWithVideoMuted = false; - this.onConnectionStats = (report) => { - // @TODO: Implement data argumentation - this.emit(GroupCallStatsReportEvent.ConnectionStats, { report }); - }; - this.onByteSentStats = (report) => { - // @TODO: Implement data argumentation - this.emit(GroupCallStatsReportEvent.ByteSentStats, { report }); - }; - this._state = GroupCallState.LocalCallFeedUninitialized; - this._participants = new Map(); - this._creationTs = null; - this._enteredViaAnotherSession = false; - /* - * Call Setup - * - * There are two different paths for calls to be created: - * 1. Incoming calls triggered by the Call.incoming event. - * 2. Outgoing calls to the initial members of a room or new members - * as they are observed by the RoomState.members event. - */ - this.onIncomingCall = (newCall) => { - var _a, _b; - // The incoming calls may be for another room, which we will ignore. - if (newCall.roomId !== this.room.roomId) { - return; - } - if (newCall.state !== call_1.CallState.Ringing) { - logger_1.logger.warn(`GroupCall ${this.groupCallId} onIncomingCall() incoming call no longer in ringing state - ignoring`); - return; - } - if (!newCall.groupCallId || newCall.groupCallId !== this.groupCallId) { - logger_1.logger.log(`GroupCall ${this.groupCallId} onIncomingCall() ignored because it doesn't match the current group call`); - newCall.reject(); - return; - } - const opponentUserId = (_a = newCall.getOpponentMember()) === null || _a === void 0 ? void 0 : _a.userId; - if (opponentUserId === undefined) { - logger_1.logger.warn(`GroupCall ${this.groupCallId} onIncomingCall() incoming call with no member - ignoring`); - return; - } - const deviceMap = (_b = this.calls.get(opponentUserId)) !== null && _b !== void 0 ? _b : new Map(); - const prevCall = deviceMap.get(newCall.getOpponentDeviceId()); - if ((prevCall === null || prevCall === void 0 ? void 0 : prevCall.callId) === newCall.callId) - return; - logger_1.logger.log(`GroupCall ${this.groupCallId} onIncomingCall() incoming call (userId=${opponentUserId}, callId=${newCall.callId})`); - if (prevCall) - prevCall.hangup(call_1.CallErrorCode.Replaced, false); - this.initCall(newCall); - const feeds = this.getLocalFeeds().map((feed) => feed.clone()); - if (!this.callExpected(newCall)) { - // Disable our tracks for users not explicitly participating in the - // call but trying to receive the feeds - for (const feed of feeds) { - (0, call_1.setTracksEnabled)(feed.stream.getAudioTracks(), false); - (0, call_1.setTracksEnabled)(feed.stream.getVideoTracks(), false); - } - } - newCall.answerWithCallFeeds(feeds); - deviceMap.set(newCall.getOpponentDeviceId(), newCall); - this.calls.set(opponentUserId, deviceMap); - this.emit(GroupCallEvent.CallsChanged, this.calls); - }; - this.onRetryCallLoop = () => { - var _a; - let needsRetry = false; - for (const [{ userId }, participantMap] of this.participants) { - const callMap = this.calls.get(userId); - let retriesMap = this.retryCallCounts.get(userId); - for (const [deviceId, participant] of participantMap) { - const call = callMap === null || callMap === void 0 ? void 0 : callMap.get(deviceId); - const retries = (_a = retriesMap === null || retriesMap === void 0 ? void 0 : retriesMap.get(deviceId)) !== null && _a !== void 0 ? _a : 0; - if ((call === null || call === void 0 ? void 0 : call.getOpponentSessionId()) !== participant.sessionId && - this.wantsOutgoingCall(userId, deviceId) && - retries < 3) { - if (retriesMap === undefined) { - retriesMap = new Map(); - this.retryCallCounts.set(userId, retriesMap); - } - retriesMap.set(deviceId, retries + 1); - needsRetry = true; - } - } - } - if (needsRetry) - this.placeOutgoingCalls(); - }; - this.onCallFeedsChanged = (call) => { - const opponentMemberId = getCallUserId(call); - const opponentDeviceId = call.getOpponentDeviceId(); - if (!opponentMemberId) { - throw new Error("Cannot change call feeds without user id"); - } - const currentUserMediaFeed = this.getUserMediaFeed(opponentMemberId, opponentDeviceId); - const remoteUsermediaFeed = call.remoteUsermediaFeed; - const remoteFeedChanged = remoteUsermediaFeed !== currentUserMediaFeed; - if (remoteFeedChanged) { - if (!currentUserMediaFeed && remoteUsermediaFeed) { - this.addUserMediaFeed(remoteUsermediaFeed); - } - else if (currentUserMediaFeed && remoteUsermediaFeed) { - this.replaceUserMediaFeed(currentUserMediaFeed, remoteUsermediaFeed); - } - else if (currentUserMediaFeed && !remoteUsermediaFeed) { - this.removeUserMediaFeed(currentUserMediaFeed); - } - } - const currentScreenshareFeed = this.getScreenshareFeed(opponentMemberId, opponentDeviceId); - const remoteScreensharingFeed = call.remoteScreensharingFeed; - const remoteScreenshareFeedChanged = remoteScreensharingFeed !== currentScreenshareFeed; - if (remoteScreenshareFeedChanged) { - if (!currentScreenshareFeed && remoteScreensharingFeed) { - this.addScreenshareFeed(remoteScreensharingFeed); - } - else if (currentScreenshareFeed && remoteScreensharingFeed) { - this.replaceScreenshareFeed(currentScreenshareFeed, remoteScreensharingFeed); - } - else if (currentScreenshareFeed && !remoteScreensharingFeed) { - this.removeScreenshareFeed(currentScreenshareFeed); - } - } - }; - this.onCallStateChanged = (call, state, _oldState) => { - var _a; - if (state === call_1.CallState.Ended) - return; - const audioMuted = this.localCallFeed.isAudioMuted(); - if (call.localUsermediaStream && call.isMicrophoneMuted() !== audioMuted) { - call.setMicrophoneMuted(audioMuted); - } - const videoMuted = this.localCallFeed.isVideoMuted(); - if (call.localUsermediaStream && call.isLocalVideoMuted() !== videoMuted) { - call.setLocalVideoMuted(videoMuted); - } - const opponentUserId = (_a = call.getOpponentMember()) === null || _a === void 0 ? void 0 : _a.userId; - if (state === call_1.CallState.Connected && opponentUserId) { - const retriesMap = this.retryCallCounts.get(opponentUserId); - retriesMap === null || retriesMap === void 0 ? void 0 : retriesMap.delete(call.getOpponentDeviceId()); - if ((retriesMap === null || retriesMap === void 0 ? void 0 : retriesMap.size) === 0) - this.retryCallCounts.delete(opponentUserId); - } - }; - this.onCallHangup = (call) => { - var _a, _b; - if (call.hangupReason === call_1.CallErrorCode.Replaced) - return; - const opponentUserId = (_b = (_a = call.getOpponentMember()) === null || _a === void 0 ? void 0 : _a.userId) !== null && _b !== void 0 ? _b : this.room.getMember(call.invitee).userId; - const deviceMap = this.calls.get(opponentUserId); - // Sanity check that this call is in fact in the map - 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); - } - }; - this.onCallReplaced = (prevCall, newCall) => { - const opponentUserId = prevCall.getOpponentMember().userId; - let deviceMap = this.calls.get(opponentUserId); - if (deviceMap === undefined) { - deviceMap = new Map(); - this.calls.set(opponentUserId, deviceMap); - } - prevCall.hangup(call_1.CallErrorCode.Replaced, false); - this.initCall(newCall); - deviceMap.set(prevCall.getOpponentDeviceId(), newCall); - this.emit(GroupCallEvent.CallsChanged, this.calls); - }; - this.onActiveSpeakerLoop = () => { - let topAvg = undefined; - let nextActiveSpeaker = undefined; - for (const callFeed of this.userMediaFeeds) { - if (callFeed.isLocal() && this.userMediaFeeds.length > 1) - continue; - const total = callFeed.speakingVolumeSamples.reduce((acc, volume) => acc + Math.max(volume, callFeed_1.SPEAKING_THRESHOLD)); - const avg = total / callFeed.speakingVolumeSamples.length; - if (!topAvg || avg > topAvg) { - topAvg = avg; - nextActiveSpeaker = callFeed; - } - } - if (nextActiveSpeaker && this.activeSpeaker !== nextActiveSpeaker && topAvg && topAvg > callFeed_1.SPEAKING_THRESHOLD) { - this.activeSpeaker = nextActiveSpeaker; - this.emit(GroupCallEvent.ActiveSpeakerChanged, this.activeSpeaker); - } - }; - this.onRoomState = () => this.updateParticipants(); - this.onParticipantsChanged = () => { - // Re-run setTracksEnabled on all calls, so that participants that just - // left get denied access to our media, and participants that just - // joined get granted access - this.forEachCall((call) => { - const expected = this.callExpected(call); - for (const feed of call.getLocalFeeds()) { - (0, call_1.setTracksEnabled)(feed.stream.getAudioTracks(), !feed.isAudioMuted() && expected); - (0, call_1.setTracksEnabled)(feed.stream.getVideoTracks(), !feed.isVideoMuted() && expected); - } - }); - if (this.state === GroupCallState.Entered) - this.placeOutgoingCalls(); - }; - this.onStateChanged = (newState, oldState) => { - if (newState === GroupCallState.Entered || - oldState === GroupCallState.Entered || - newState === GroupCallState.Ended) { - // We either entered, left, or ended the call - this.updateParticipants(); - this.updateMemberState().catch((e) => logger_1.logger.error(`GroupCall ${this.groupCallId} onStateChanged() failed to update member state devices"`, e)); - } - }; - this.onLocalFeedsChanged = () => { - if (this.state === GroupCallState.Entered) { - this.updateMemberState().catch((e) => logger_1.logger.error(`GroupCall ${this.groupCallId} onLocalFeedsChanged() failed to update member state feeds`, e)); - } - }; - this.reEmitter = new ReEmitter_1.ReEmitter(this); - this.groupCallId = groupCallId !== null && groupCallId !== void 0 ? groupCallId : (0, call_1.genCallID)(); - this.creationTs = - (_b = (_a = room.currentState.getStateEvents(event_1.EventType.GroupCallPrefix, this.groupCallId)) === null || _a === void 0 ? void 0 : _a.getTs()) !== null && _b !== void 0 ? _b : null; - this.updateParticipants(); - room.on(room_state_1.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; - const userID = this.client.getUserId() || "unknown"; - this.stats = new groupCallStats_1.GroupCallStats(this.groupCallId, userID); - this.stats.reports.on(statsReport_1.StatsReport.CONNECTION_STATS, this.onConnectionStats); - this.stats.reports.on(statsReport_1.StatsReport.BYTE_SENT_STATS, this.onByteSentStats); - } - create() { - return __awaiter(this, void 0, void 0, function* () { - this.creationTs = Date.now(); - this.client.groupCallEventHandler.groupCalls.set(this.room.roomId, this); - this.client.emit(groupCallEventHandler_1.GroupCallEventHandlerEvent.Outgoing, this); - const groupCallState = { - "m.intent": this.intent, - "m.type": this.type, - "io.element.ptt": this.isPtt, - // TODO: Specify data-channels better - "dataChannelsEnabled": this.dataChannelsEnabled, - "dataChannelOptions": this.dataChannelsEnabled ? this.dataChannelOptions : undefined, - }; - yield this.client.sendStateEvent(this.room.roomId, event_1.EventType.GroupCallPrefix, groupCallState, this.groupCallId); - return this; - }); - } - /** - * The group call's state. - */ - get state() { - return this._state; - } - set state(value) { - const 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) { - const prevValue = this._participants; - const participantStateEqual = (x, y) => x.sessionId === y.sessionId && x.screensharing === y.screensharing; - const deviceMapsEqual = (x, y) => (0, utils_1.mapsEqual)(x, y, participantStateEqual); - // Only update if the map actually changed - if (!(0, utils_1.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 (const deviceMap of this.calls.values()) { - for (const call of deviceMap.values()) - f(call); - } - } - getLocalFeeds() { - const feeds = []; - if (this.localCallFeed) - feeds.push(this.localCallFeed); - if (this.localScreenshareFeed) - feeds.push(this.localScreenshareFeed); - return feeds; - } - hasLocalParticipant() { - var _a, _b; - return ((_b = (_a = this.participants.get(this.room.getMember(this.client.getUserId()))) === null || _a === void 0 ? void 0 : _a.has(this.client.getDeviceId())) !== null && _b !== void 0 ? _b : 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 _a; - const userId = getCallUserId(call); - const member = userId === null ? null : this.room.getMember(userId); - const deviceId = call.getOpponentDeviceId(); - return member !== null && deviceId !== undefined && ((_a = this.participants.get(member)) === null || _a === void 0 ? void 0 : _a.get(deviceId)) !== undefined; - } - initLocalCallFeed() { - return __awaiter(this, void 0, void 0, function* () { - if (this.state !== GroupCallState.LocalCallFeedUninitialized) { - throw new Error(`Cannot initialize local call feed in the "${this.state}" state.`); - } - this.state = GroupCallState.InitializingLocalCallFeed; - // wraps the real method to serialise calls, because we don't want to try starting - // multiple call feeds at once - if (this.initCallFeedPromise) - return this.initCallFeedPromise; - try { - this.initCallFeedPromise = this.initLocalCallFeedInternal(); - yield this.initCallFeedPromise; - } - finally { - this.initCallFeedPromise = undefined; - } - }); - } - initLocalCallFeedInternal() { - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.log(`GroupCall ${this.groupCallId} initLocalCallFeedInternal() running`); - let stream; - try { - stream = yield this.client.getMediaHandler().getUserMediaStream(true, this.type === GroupCallType.Video); - } - catch (error) { - // If is allowed to join a call without a media stream, then we - // don't throw an error here. But we need an empty Local Feed to establish - // a connection later. - if (this.allowCallWithoutVideoAndAudio) { - stream = new MediaStream(); - } - else { - this.state = GroupCallState.LocalCallFeedUninitialized; - throw error; - } - } - // The call could've been disposed while we were waiting, and could - // also have been started back up again (hello, React 18) so if we're - // still in this 'initializing' state, carry on, otherwise bail. - if (this._state !== GroupCallState.InitializingLocalCallFeed) { - this.client.getMediaHandler().stopUserMediaStream(stream); - throw new Error("Group call disposed while gathering media stream"); - } - const callFeed = new callFeed_1.CallFeed({ - client: this.client, - roomId: this.room.roomId, - userId: this.client.getUserId(), - deviceId: this.client.getDeviceId(), - stream, - purpose: callEventTypes_1.SDPStreamMetadataPurpose.Usermedia, - audioMuted: this.initWithAudioMuted || stream.getAudioTracks().length === 0 || this.isPtt, - videoMuted: this.initWithVideoMuted || stream.getVideoTracks().length === 0, - }); - (0, call_1.setTracksEnabled)(stream.getAudioTracks(), !callFeed.isAudioMuted()); - (0, call_1.setTracksEnabled)(stream.getVideoTracks(), !callFeed.isVideoMuted()); - this.localCallFeed = callFeed; - this.addUserMediaFeed(callFeed); - this.state = GroupCallState.LocalCallFeedInitialized; - }); - } - updateLocalUsermediaStream(stream) { - return __awaiter(this, void 0, void 0, function* () { - if (this.localCallFeed) { - const oldStream = this.localCallFeed.stream; - this.localCallFeed.setNewStream(stream); - const micShouldBeMuted = this.localCallFeed.isAudioMuted(); - const vidShouldBeMuted = this.localCallFeed.isVideoMuted(); - logger_1.logger.log(`GroupCall ${this.groupCallId} updateLocalUsermediaStream() (oldStreamId=${oldStream.id}, newStreamId=${stream.id}, micShouldBeMuted=${micShouldBeMuted}, vidShouldBeMuted=${vidShouldBeMuted})`); - (0, call_1.setTracksEnabled)(stream.getAudioTracks(), !micShouldBeMuted); - (0, call_1.setTracksEnabled)(stream.getVideoTracks(), !vidShouldBeMuted); - this.client.getMediaHandler().stopUserMediaStream(oldStream); - } - }); - } - enter() { - return __awaiter(this, void 0, void 0, function* () { - if (this.state === GroupCallState.LocalCallFeedUninitialized) { - yield this.initLocalCallFeed(); - } - else if (this.state !== GroupCallState.LocalCallFeedInitialized) { - throw new Error(`Cannot enter call in the "${this.state}" state`); - } - logger_1.logger.log(`GroupCall ${this.groupCallId} enter() running`); - this.state = GroupCallState.Entered; - this.client.on(callEventHandler_1.CallEventHandlerEvent.Incoming, this.onIncomingCall); - for (const call of this.client.callEventHandler.calls.values()) { - this.onIncomingCall(call); - } - this.retryCallLoopInterval = setInterval(this.onRetryCallLoop, this.retryCallInterval); - this.activeSpeaker = undefined; - this.onActiveSpeakerLoop(); - this.activeSpeakerLoopInterval = setInterval(this.onActiveSpeakerLoop, this.activeSpeakerInterval); - }); - } - dispose() { - if (this.localCallFeed) { - this.removeUserMediaFeed(this.localCallFeed); - this.localCallFeed = undefined; - } - if (this.localScreenshareFeed) { - this.client.getMediaHandler().stopScreensharingStream(this.localScreenshareFeed.stream); - this.removeScreenshareFeed(this.localScreenshareFeed); - this.localScreenshareFeed = undefined; - this.localDesktopCapturerSourceId = undefined; - } - this.client.getMediaHandler().stopAllStreams(); - if (this.transmitTimer !== null) { - clearTimeout(this.transmitTimer); - this.transmitTimer = null; - } - if (this.retryCallLoopInterval !== undefined) { - clearInterval(this.retryCallLoopInterval); - this.retryCallLoopInterval = undefined; - } - if (this.participantsExpirationTimer !== null) { - clearTimeout(this.participantsExpirationTimer); - this.participantsExpirationTimer = null; - } - if (this.state !== GroupCallState.Entered) { - return; - } - this.forEachCall((call) => call.hangup(call_1.CallErrorCode.UserHangup, false)); - this.activeSpeaker = undefined; - clearInterval(this.activeSpeakerLoopInterval); - this.retryCallCounts.clear(); - clearInterval(this.retryCallLoopInterval); - this.client.removeListener(callEventHandler_1.CallEventHandlerEvent.Incoming, this.onIncomingCall); - this.stats.stop(); - } - leave() { - this.dispose(); - this.state = GroupCallState.LocalCallFeedUninitialized; - } - terminate(emitStateEvent = true) { - return __awaiter(this, void 0, void 0, function* () { - this.dispose(); - this.room.off(room_state_1.RoomStateEvent.Update, this.onRoomState); - this.client.groupCallEventHandler.groupCalls.delete(this.room.roomId); - this.client.emit(groupCallEventHandler_1.GroupCallEventHandlerEvent.Ended, this); - this.state = GroupCallState.Ended; - if (emitStateEvent) { - const existingStateEvent = this.room.currentState.getStateEvents(event_1.EventType.GroupCallPrefix, this.groupCallId); - yield this.client.sendStateEvent(this.room.roomId, event_1.EventType.GroupCallPrefix, Object.assign(Object.assign({}, existingStateEvent.getContent()), { "m.terminated": GroupCallTerminationReason.CallEnded }), this.groupCallId); - } - }); - } - /* - * Local Usermedia - */ - 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) { - return __awaiter(this, void 0, void 0, function* () { - // hasAudioDevice can block indefinitely if the window has lost focus, - // and it doesn't make much sense to keep a device from being muted, so - // we always allow muted = true changes to go through - if (!muted && !(yield this.client.getMediaHandler().hasAudioDevice())) { - return false; - } - const sendUpdatesBefore = !muted && this.isPtt; - // set a timer for the maximum transmit time on PTT calls - if (this.isPtt) { - // Set or clear the max transmit timer - if (!muted && this.isMicrophoneMuted()) { - this.transmitTimer = setTimeout(() => { - this.setMicrophoneMuted(true); - }, this.pttMaxTransmitTime); - } - else if (muted && !this.isMicrophoneMuted()) { - if (this.transmitTimer !== null) - clearTimeout(this.transmitTimer); - this.transmitTimer = null; - } - } - this.forEachCall((call) => { var _a; return (_a = call.localUsermediaFeed) === null || _a === void 0 ? void 0 : _a.setAudioVideoMuted(muted, null); }); - const sendUpdates = () => __awaiter(this, void 0, void 0, function* () { - const updates = []; - this.forEachCall((call) => updates.push(call.sendMetadataUpdate())); - yield Promise.all(updates).catch((e) => logger_1.logger.info(`GroupCall ${this.groupCallId} setMicrophoneMuted() failed to send some metadata updates`, e)); - }); - if (sendUpdatesBefore) - yield sendUpdates(); - if (this.localCallFeed) { - logger_1.logger.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() (streamId=${this.localCallFeed.stream.id}, muted=${muted})`); - // We needed this here to avoid an error in case user join a call without a device. - // I can not use .then .catch functions because linter :-( - try { - if (!muted) { - const stream = yield this.client - .getMediaHandler() - .getUserMediaStream(true, !this.localCallFeed.isVideoMuted()); - if (stream === null) { - // if case permission denied to get a stream stop this here - /* istanbul ignore next */ - logger_1.logger.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() no device to receive local stream, muted=${muted}`); - return false; - } - } - } - catch (e) { - /* istanbul ignore next */ - logger_1.logger.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() no device or permission to receive local stream, muted=${muted}`); - return false; - } - this.localCallFeed.setAudioVideoMuted(muted, null); - // I don't believe its actually necessary to enable these tracks: they - // are the one on the GroupCall's own CallFeed and are cloned before being - // given to any of the actual calls, so these tracks don't actually go - // anywhere. Let's do it anyway to avoid confusion. - (0, call_1.setTracksEnabled)(this.localCallFeed.stream.getAudioTracks(), !muted); - } - else { - logger_1.logger.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() no stream muted (muted=${muted})`); - this.initWithAudioMuted = muted; - } - this.forEachCall((call) => (0, call_1.setTracksEnabled)(call.localUsermediaFeed.stream.getAudioTracks(), !muted && this.callExpected(call))); - this.emit(GroupCallEvent.LocalMuteStateChanged, muted, this.isLocalVideoMuted()); - if (!sendUpdatesBefore) - yield sendUpdates(); - 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) { - return __awaiter(this, void 0, void 0, function* () { - // hasAudioDevice can block indefinitely if the window has lost focus, - // and it doesn't make much sense to keep a device from being muted, so - // we always allow muted = true changes to go through - if (!muted && !(yield this.client.getMediaHandler().hasVideoDevice())) { - return false; - } - if (this.localCallFeed) { - /* istanbul ignore next */ - logger_1.logger.log(`GroupCall ${this.groupCallId} setLocalVideoMuted() (stream=${this.localCallFeed.stream.id}, muted=${muted})`); - try { - const stream = yield this.client.getMediaHandler().getUserMediaStream(true, !muted); - yield this.updateLocalUsermediaStream(stream); - this.localCallFeed.setAudioVideoMuted(null, muted); - (0, call_1.setTracksEnabled)(this.localCallFeed.stream.getVideoTracks(), !muted); - } - catch (_) { - // No permission to video device - /* istanbul ignore next */ - logger_1.logger.log(`GroupCall ${this.groupCallId} setLocalVideoMuted() no device or permission to receive local stream, muted=${muted}`); - return false; - } - } - else { - logger_1.logger.log(`GroupCall ${this.groupCallId} setLocalVideoMuted() no stream muted (muted=${muted})`); - this.initWithVideoMuted = muted; - } - const updates = []; - this.forEachCall((call) => updates.push(call.setLocalVideoMuted(muted))); - yield Promise.all(updates); - // We setTracksEnabled again, independently from the call doing it - // internally, since we might not be expecting the call - this.forEachCall((call) => (0, call_1.setTracksEnabled)(call.localUsermediaFeed.stream.getVideoTracks(), !muted && this.callExpected(call))); - this.emit(GroupCallEvent.LocalMuteStateChanged, this.isMicrophoneMuted(), muted); - return true; - }); - } - setScreensharingEnabled(enabled, opts = {}) { - return __awaiter(this, void 0, void 0, function* () { - if (enabled === this.isScreensharing()) { - return enabled; - } - if (enabled) { - try { - logger_1.logger.log(`GroupCall ${this.groupCallId} setScreensharingEnabled() is asking for screensharing permissions`); - const stream = yield this.client.getMediaHandler().getScreensharingStream(opts); - for (const track of stream.getTracks()) { - const onTrackEnded = () => { - this.setScreensharingEnabled(false); - track.removeEventListener("ended", onTrackEnded); - }; - track.addEventListener("ended", onTrackEnded); - } - logger_1.logger.log(`GroupCall ${this.groupCallId} setScreensharingEnabled() granted screensharing permissions. Setting screensharing enabled on all calls`); - this.localDesktopCapturerSourceId = opts.desktopCapturerSourceId; - this.localScreenshareFeed = new callFeed_1.CallFeed({ - client: this.client, - roomId: this.room.roomId, - userId: this.client.getUserId(), - deviceId: this.client.getDeviceId(), - stream, - purpose: callEventTypes_1.SDPStreamMetadataPurpose.Screenshare, - audioMuted: false, - videoMuted: false, - }); - this.addScreenshareFeed(this.localScreenshareFeed); - this.emit(GroupCallEvent.LocalScreenshareStateChanged, true, this.localScreenshareFeed, this.localDesktopCapturerSourceId); - // TODO: handle errors - this.forEachCall((call) => call.pushLocalFeed(this.localScreenshareFeed.clone())); - return true; - } - catch (error) { - if (opts.throwOnFail) - throw error; - logger_1.logger.error(`GroupCall ${this.groupCallId} setScreensharingEnabled() enabling screensharing error`, error); - this.emit(GroupCallEvent.Error, new GroupCallError(GroupCallErrorCode.NoUserMedia, "Failed to get screen-sharing stream: ", error)); - return false; - } - } - else { - this.forEachCall((call) => { - if (call.localScreensharingFeed) - call.removeLocalFeed(call.localScreensharingFeed); - }); - this.client.getMediaHandler().stopScreensharingStream(this.localScreenshareFeed.stream); - this.removeScreenshareFeed(this.localScreenshareFeed); - this.localScreenshareFeed = undefined; - this.localDesktopCapturerSourceId = undefined; - this.emit(GroupCallEvent.LocalScreenshareStateChanged, false, undefined, undefined); - 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) { - const localUserId = this.client.getUserId(); - const localDeviceId = this.client.getDeviceId(); - return ( - // If a user's ID is less than our own, they'll call us - userId >= localUserId && - // If this is another one of our devices, compare device IDs to tell whether it'll call us - (userId !== localUserId || deviceId > localDeviceId)); - } - /** - * Places calls to all participants that we're responsible for calling. - */ - placeOutgoingCalls() { - var _a; - let callsChanged = false; - for (const [{ userId }, participantMap] of this.participants) { - const callMap = (_a = this.calls.get(userId)) !== null && _a !== void 0 ? _a : new Map(); - for (const [deviceId, participant] of participantMap) { - const prevCall = callMap.get(deviceId); - if ((prevCall === null || prevCall === void 0 ? void 0 : prevCall.getOpponentSessionId()) !== participant.sessionId && - this.wantsOutgoingCall(userId, deviceId)) { - callsChanged = true; - if (prevCall !== undefined) { - logger_1.logger.debug(`GroupCall ${this.groupCallId} placeOutgoingCalls() replacing call (userId=${userId}, deviceId=${deviceId}, callId=${prevCall.callId})`); - prevCall.hangup(call_1.CallErrorCode.NewSession, false); - } - const newCall = (0, call_1.createNewMatrixCall)(this.client, this.room.roomId, { - invitee: userId, - opponentDeviceId: deviceId, - opponentSessionId: participant.sessionId, - groupCallId: this.groupCallId, - }); - if (newCall === null) { - logger_1.logger.error(`GroupCall ${this.groupCallId} placeOutgoingCalls() failed to create call (userId=${userId}, device=${deviceId})`); - callMap.delete(deviceId); - } - else { - this.initCall(newCall); - callMap.set(deviceId, newCall); - logger_1.logger.debug(`GroupCall ${this.groupCallId} placeOutgoingCalls() placing call (userId=${userId}, deviceId=${deviceId}, sessionId=${participant.sessionId})`); - newCall - .placeCallWithCallFeeds(this.getLocalFeeds().map((feed) => feed.clone()), participant.screensharing) - .then(() => { - if (this.dataChannelsEnabled) { - newCall.createDataChannel("datachannel", this.dataChannelOptions); - } - }) - .catch((e) => { - logger_1.logger.warn(`GroupCall ${this.groupCallId} placeOutgoingCalls() failed to place call (userId=${userId})`, e); - if (e instanceof call_1.CallError && e.code === GroupCallErrorCode.UnknownDevice) { - this.emit(GroupCallEvent.Error, e); - } - else { - this.emit(GroupCallEvent.Error, new GroupCallError(GroupCallErrorCode.PlaceCallFailed, `Failed to place call to ${userId}`)); - } - newCall.hangup(call_1.CallErrorCode.SignallingFailed, false); - if (callMap.get(deviceId) === newCall) - callMap.delete(deviceId); - }); - } - } - } - if (callMap.size > 0) { - this.calls.set(userId, callMap); - } - else { - this.calls.delete(userId); - } - } - if (callsChanged) - this.emit(GroupCallEvent.CallsChanged, this.calls); - } - getMemberStateEvents(userId) { - return userId === undefined - ? this.room.currentState.getStateEvents(event_1.EventType.GroupCallMemberPrefix) - : this.room.currentState.getStateEvents(event_1.EventType.GroupCallMemberPrefix, userId); - } - initCall(call) { - const opponentMemberId = getCallUserId(call); - if (!opponentMemberId) { - throw new Error("Cannot init call without user id"); - } - const onCallFeedsChanged = () => this.onCallFeedsChanged(call); - const onCallStateChanged = (state, oldState) => this.onCallStateChanged(call, state, oldState); - const onCallHangup = this.onCallHangup; - const onCallReplaced = (newCall) => this.onCallReplaced(call, newCall); - let deviceMap = this.callHandlers.get(opponentMemberId); - if (deviceMap === undefined) { - deviceMap = new Map(); - this.callHandlers.set(opponentMemberId, deviceMap); - } - deviceMap.set(call.getOpponentDeviceId(), { - onCallFeedsChanged, - onCallStateChanged, - onCallHangup, - onCallReplaced, - }); - call.on(call_1.CallEvent.FeedsChanged, onCallFeedsChanged); - call.on(call_1.CallEvent.State, onCallStateChanged); - call.on(call_1.CallEvent.Hangup, onCallHangup); - call.on(call_1.CallEvent.Replaced, onCallReplaced); - call.isPtt = this.isPtt; - this.reEmitter.reEmit(call, Object.values(call_1.CallEvent)); - call.initStats(this.stats); - onCallFeedsChanged(); - } - disposeCall(call, hangupReason) { - const opponentMemberId = getCallUserId(call); - const opponentDeviceId = call.getOpponentDeviceId(); - if (!opponentMemberId) { - throw new Error("Cannot dispose call without user id"); - } - const deviceMap = this.callHandlers.get(opponentMemberId); - const { onCallFeedsChanged, onCallStateChanged, onCallHangup, onCallReplaced } = deviceMap.get(opponentDeviceId); - call.removeListener(call_1.CallEvent.FeedsChanged, onCallFeedsChanged); - call.removeListener(call_1.CallEvent.State, onCallStateChanged); - call.removeListener(call_1.CallEvent.Hangup, onCallHangup); - call.removeListener(call_1.CallEvent.Replaced, onCallReplaced); - deviceMap.delete(opponentMemberId); - if (deviceMap.size === 0) - this.callHandlers.delete(opponentMemberId); - if (call.hangupReason === call_1.CallErrorCode.Replaced) { - return; - } - const usermediaFeed = this.getUserMediaFeed(opponentMemberId, opponentDeviceId); - if (usermediaFeed) { - this.removeUserMediaFeed(usermediaFeed); - } - const screenshareFeed = this.getScreenshareFeed(opponentMemberId, opponentDeviceId); - if (screenshareFeed) { - this.removeScreenshareFeed(screenshareFeed); - } - } - /* - * UserMedia CallFeed Event Handlers - */ - 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) { - const 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) { - const 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); - } - } - /* - * Screenshare Call Feed Event Handlers - */ - 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) { - const 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) { - const 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() { - const localMember = this.room.getMember(this.client.getUserId()); - if (!localMember) { - // The client hasn't fetched enough of the room state to get our own member - // event. This probably shouldn't happen, but sanity check & exit for now. - logger_1.logger.warn(`GroupCall ${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 = new Map(); - return; - } - const participants = new Map(); - const now = Date.now(); - const entered = this.state === GroupCallState.Entered || this.enteredViaAnotherSession; - let nextExpiration = Infinity; - for (const e of this.getMemberStateEvents()) { - const member = this.room.getMember(e.getStateKey()); - const content = e.getContent(); - const calls = Array.isArray(content["m.calls"]) ? content["m.calls"] : []; - const call = calls.find((call) => call["m.call_id"] === this.groupCallId); - const devices = Array.isArray(call === null || call === void 0 ? void 0 : call["m.devices"]) ? call["m.devices"] : []; - // Filter out invalid and expired devices - let validDevices = 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)); - // Apply local echo for the unentered case - if (!entered && (member === null || member === void 0 ? void 0 : member.userId) === this.client.getUserId()) { - validDevices = validDevices.filter((d) => d.device_id !== this.client.getDeviceId()); - } - // Must have a connected device and be joined to the room - if (validDevices.length > 0 && (member === null || member === void 0 ? void 0 : member.membership) === "join") { - const deviceMap = new Map(); - participants.set(member, deviceMap); - for (const d of validDevices) { - deviceMap.set(d.device_id, { - sessionId: d.session_id, - screensharing: d.feeds.some((f) => f.purpose === callEventTypes_1.SDPStreamMetadataPurpose.Screenshare), - }); - if (d.expires_ts < nextExpiration) - nextExpiration = d.expires_ts; - } - } - } - // Apply local echo for the entered case - if (entered) { - let deviceMap = participants.get(localMember); - if (deviceMap === undefined) { - deviceMap = 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 === callEventTypes_1.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, keepAlive = false) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const now = Date.now(); - const localUserId = this.client.getUserId(); - const event = this.getMemberStateEvents(localUserId); - const content = (_a = event === null || event === void 0 ? void 0 : event.getContent()) !== null && _a !== void 0 ? _a : {}; - const calls = Array.isArray(content["m.calls"]) ? content["m.calls"] : []; - let call = null; - const otherCalls = []; - for (const c of calls) { - if (c["m.call_id"] === this.groupCallId) { - call = c; - } - else { - otherCalls.push(c); - } - } - if (call === null) - call = {}; - const devices = Array.isArray(call["m.devices"]) ? call["m.devices"] : []; - // Filter out invalid and expired devices - const validDevices = 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)); - const newDevices = fn(validDevices); - if (newDevices === null) - return; - const newCalls = [...otherCalls]; - if (newDevices.length > 0) { - newCalls.push(Object.assign(Object.assign({}, call), { "m.call_id": this.groupCallId, "m.devices": newDevices })); - } - const newContent = { "m.calls": newCalls }; - yield this.client.sendStateEvent(this.room.roomId, event_1.EventType.GroupCallMemberPrefix, newContent, localUserId, { - keepAlive, - }); - }); - } - addDeviceToMemberState() { - return __awaiter(this, void 0, void 0, function* () { - yield this.updateDevices((devices) => [ - ...devices.filter((d) => d.device_id !== this.client.getDeviceId()), - { - device_id: this.client.getDeviceId(), - session_id: this.client.getSessionId(), - expires_ts: Date.now() + DEVICE_TIMEOUT, - feeds: this.getLocalFeeds().map((feed) => ({ purpose: feed.purpose })), - // TODO: Add data channels - }, - ]); - }); - } - updateMemberState() { - return __awaiter(this, void 0, void 0, function* () { - // Clear the old update interval before proceeding - if (this.resendMemberStateTimer !== null) { - clearInterval(this.resendMemberStateTimer); - this.resendMemberStateTimer = null; - } - if (this.state === GroupCallState.Entered) { - // Add the local device - yield this.addDeviceToMemberState(); - // Resend the state event every so often so it doesn't become stale - this.resendMemberStateTimer = setInterval(() => __awaiter(this, void 0, void 0, function* () { - logger_1.logger.log(`GroupCall ${this.groupCallId} updateMemberState() resending call member state"`); - try { - yield this.addDeviceToMemberState(); - } - catch (e) { - logger_1.logger.error(`GroupCall ${this.groupCallId} updateMemberState() failed to resend call member state`, e); - } - }), (DEVICE_TIMEOUT * 3) / 4); - } - else { - // Remove the local device - yield this.updateDevices((devices) => devices.filter((d) => d.device_id !== this.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() { - return __awaiter(this, void 0, void 0, function* () { - const { devices: myDevices } = yield this.client.getDevices(); - const deviceMap = new Map(myDevices.map((d) => [d.device_id, d])); - // updateDevices takes care of filtering out inactive devices for us - yield this.updateDevices((devices) => { - const newDevices = devices.filter((d) => { - const device = deviceMap.get(d.device_id); - return ((device === null || device === void 0 ? void 0 : device.last_seen_ts) !== undefined && - !(d.device_id === this.client.getDeviceId() && - this.state !== GroupCallState.Entered && - !this.enteredViaAnotherSession)); - }); - // Skip the update if the devices are unchanged - return newDevices.length === devices.length ? null : newDevices; - }); - }); - } - getGroupCallStats() { - return this.stats; - } -} -exports.GroupCall = GroupCall; - -},{"../@types/event":306,"../ReEmitter":317,"../logger":374,"../models/room-state":390,"../models/typed-event-emitter":395,"../utils":416,"./call":418,"./callEventHandler":419,"./callEventTypes":420,"./callFeed":421,"./groupCallEventHandler":423,"./stats/groupCallStats":427,"./stats/statsReport":432}],423:[function(require,module,exports){ -"use strict"; -/* -Copyright 2021 Šimon Brandner - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.GroupCallEventHandler = exports.GroupCallEventHandlerEvent = void 0; -const client_1 = require("../client"); -const groupCall_1 = require("./groupCall"); -const room_state_1 = require("../models/room-state"); -const logger_1 = require("../logger"); -const event_1 = require("../@types/event"); -const sync_1 = require("../sync"); -var GroupCallEventHandlerEvent; -(function (GroupCallEventHandlerEvent) { - GroupCallEventHandlerEvent["Incoming"] = "GroupCall.incoming"; - GroupCallEventHandlerEvent["Outgoing"] = "GroupCall.outgoing"; - GroupCallEventHandlerEvent["Ended"] = "GroupCall.ended"; - GroupCallEventHandlerEvent["Participants"] = "GroupCall.participants"; -})(GroupCallEventHandlerEvent = exports.GroupCallEventHandlerEvent || (exports.GroupCallEventHandlerEvent = {})); -class GroupCallEventHandler { - constructor(client) { - this.client = client; - this.groupCalls = new Map(); // roomId -> GroupCall - // All rooms we know about and whether we've seen a 'Room' event - // for them. The promise will be fulfilled once we've processed that - // event which means we're "up to date" on what calls are in a room - // and get - this.roomDeferreds = new Map(); - this.onRoomsChanged = (room) => { - this.createGroupCallForRoom(room); - }; - this.onRoomStateChanged = (event, state) => { - const eventType = event.getType(); - if (eventType === event_1.EventType.GroupCallPrefix) { - const groupCallId = event.getStateKey(); - const content = event.getContent(); - const 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) { - // TODO: Handle the callType changing when the room state changes - logger_1.logger.warn(`GroupCallEventHandler onRoomStateChanged() currently does not support changing type (roomId=${state.roomId})`); - } - } - else if (currentGroupCall && currentGroupCall.groupCallId !== groupCallId) { - // TODO: Handle new group calls and multiple group calls - logger_1.logger.warn(`GroupCallEventHandler onRoomStateChanged() currently does not support multiple calls (roomId=${state.roomId})`); - } - } - }; - } - start() { - return __awaiter(this, void 0, void 0, function* () { - // We wait until the client has started syncing for real. - // This is because we only support one call at a time, and want - // the latest. We therefore want the latest state of the room before - // we create a group call for the room so we can be fairly sure that - // the group call we create is really the latest one. - if (this.client.getSyncState() !== sync_1.SyncState.Syncing) { - logger_1.logger.debug("GroupCallEventHandler start() waiting for client to start syncing"); - yield new Promise((resolve) => { - const onSync = () => { - if (this.client.getSyncState() === sync_1.SyncState.Syncing) { - this.client.off(client_1.ClientEvent.Sync, onSync); - return resolve(); - } - }; - this.client.on(client_1.ClientEvent.Sync, onSync); - }); - } - const rooms = this.client.getRooms(); - for (const room of rooms) { - this.createGroupCallForRoom(room); - } - this.client.on(client_1.ClientEvent.Room, this.onRoomsChanged); - this.client.on(room_state_1.RoomStateEvent.Events, this.onRoomStateChanged); - }); - } - stop() { - this.client.removeListener(room_state_1.RoomStateEvent.Events, this.onRoomStateChanged); - } - getRoomDeferred(roomId) { - let deferred = this.roomDeferreds.get(roomId); - if (deferred === undefined) { - let 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) { - const callEvents = room.currentState.getStateEvents(event_1.EventType.GroupCallPrefix); - const sortedCallEvents = callEvents.sort((a, b) => b.getTs() - a.getTs()); - for (const callEvent of sortedCallEvents) { - const content = callEvent.getContent(); - if (content["m.terminated"] || callEvent.isRedacted()) { - continue; - } - logger_1.logger.debug(`GroupCallEventHandler createGroupCallForRoom() choosing group call from possible calls (stateKey=${callEvent.getStateKey()}, ts=${callEvent.getTs()}, roomId=${room.roomId}, numOfPossibleCalls=${callEvents.length})`); - this.createGroupCallFromRoomStateEvent(callEvent); - break; - } - logger_1.logger.info(`GroupCallEventHandler createGroupCallForRoom() processed room (roomId=${room.roomId})`); - this.getRoomDeferred(room.roomId).resolve(); - } - createGroupCallFromRoomStateEvent(event) { - const roomId = event.getRoomId(); - const content = event.getContent(); - const room = this.client.getRoom(roomId); - if (!room) { - logger_1.logger.warn(`GroupCallEventHandler createGroupCallFromRoomStateEvent() couldn't find room for call (roomId=${roomId})`); - return; - } - const groupCallId = event.getStateKey(); - const callType = content["m.type"]; - if (!Object.values(groupCall_1.GroupCallType).includes(callType)) { - logger_1.logger.warn(`GroupCallEventHandler createGroupCallFromRoomStateEvent() received invalid call type (type=${callType}, roomId=${roomId})`); - return; - } - const callIntent = content["m.intent"]; - if (!Object.values(groupCall_1.GroupCallIntent).includes(callIntent)) { - logger_1.logger.warn(`Received invalid group call intent (type=${callType}, roomId=${roomId})`); - return; - } - const isPtt = Boolean(content["io.element.ptt"]); - let dataChannelOptions; - if ((content === null || content === void 0 ? void 0 : content.dataChannelsEnabled) && (content === null || content === void 0 ? void 0 : content.dataChannelOptions)) { - // Pull out just the dataChannelOptions we want to support. - const { ordered, maxPacketLifeTime, maxRetransmits, protocol } = content.dataChannelOptions; - dataChannelOptions = { ordered, maxPacketLifeTime, maxRetransmits, protocol }; - } - const groupCall = new groupCall_1.GroupCall(this.client, room, callType, isPtt, callIntent, groupCallId, - // Because without Media section a WebRTC connection is not possible, so need a RTCDataChannel to set up a - // no media WebRTC connection anyway. - (content === null || content === void 0 ? void 0 : content.dataChannelsEnabled) || this.client.isVoipWithNoMediaAllowed, dataChannelOptions, this.client.isVoipWithNoMediaAllowed); - this.groupCalls.set(room.roomId, groupCall); - this.client.emit(GroupCallEventHandlerEvent.Incoming, groupCall); - return groupCall; - } -} -exports.GroupCallEventHandler = GroupCallEventHandler; - -},{"../@types/event":306,"../client":321,"../logger":374,"../models/room-state":390,"../sync":414,"./groupCall":422}],424:[function(require,module,exports){ -"use strict"; -/* -Copyright 2015, 2016 OpenMarket Ltd -Copyright 2017 New Vector Ltd -Copyright 2019, 2020 The Matrix.org Foundation C.I.C. -Copyright 2021 - 2022 Šimon Brandner - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MediaHandler = exports.MediaHandlerEvent = void 0; -const typed_event_emitter_1 = require("../models/typed-event-emitter"); -const groupCall_1 = require("../webrtc/groupCall"); -const logger_1 = require("../logger"); -var MediaHandlerEvent; -(function (MediaHandlerEvent) { - MediaHandlerEvent["LocalStreamsChanged"] = "local_streams_changed"; -})(MediaHandlerEvent = exports.MediaHandlerEvent || (exports.MediaHandlerEvent = {})); -class MediaHandler extends typed_event_emitter_1.TypedEventEmitter { - constructor(client) { - super(); - this.client = client; - this.userMediaStreams = []; - this.screensharingStreams = []; - } - 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) { - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.info(`MediaHandler setAudioInput() running (deviceId=${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) { - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.info(`MediaHandler setAudioSettings() running (opts=${JSON.stringify(opts)})`); - this.audioSettings = Object.assign({}, opts); - yield this.updateLocalUsermediaStreams(); - }); - } - /** - * Set a video input device to use for MatrixCalls - * @param deviceId - the identifier for the device - * undefined treated as unset - */ - setVideoInput(deviceId) { - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.info(`MediaHandler setVideoInput() running (deviceId=${deviceId})`); - if (this.videoInput === deviceId) - return; - this.videoInput = deviceId; - yield this.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) { - return __awaiter(this, void 0, void 0, function* () { - logger_1.logger.log(`MediaHandler setMediaInputs() running (audioInput: ${audioInput} videoInput: ${videoInput})`); - this.audioInput = audioInput; - this.videoInput = videoInput; - yield this.updateLocalUsermediaStreams(); - }); - } - /* - * Requests new usermedia streams and replace the old ones - */ - updateLocalUsermediaStreams() { - return __awaiter(this, void 0, void 0, function* () { - if (this.userMediaStreams.length === 0) - return; - const callMediaStreamParams = new Map(); - for (const call of this.client.callEventHandler.calls.values()) { - callMediaStreamParams.set(call.callId, { - audio: call.hasLocalUserMediaAudioTrack, - video: call.hasLocalUserMediaVideoTrack, - }); - } - for (const stream of this.userMediaStreams) { - logger_1.logger.log(`MediaHandler updateLocalUsermediaStreams() stopping all tracks (streamId=${stream.id})`); - for (const track of stream.getTracks()) { - track.stop(); - } - } - this.userMediaStreams = []; - this.localUserMediaStream = undefined; - for (const call of this.client.callEventHandler.calls.values()) { - if (call.callHasEnded() || !callMediaStreamParams.has(call.callId)) { - continue; - } - const { audio, video } = callMediaStreamParams.get(call.callId); - logger_1.logger.log(`MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (callId=${call.callId})`); - const stream = yield this.getUserMediaStream(audio, video); - if (call.callHasEnded()) { - continue; - } - yield call.updateLocalUsermediaStream(stream); - } - for (const groupCall of this.client.groupCallEventHandler.groupCalls.values()) { - if (!groupCall.localCallFeed) { - continue; - } - logger_1.logger.log(`MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (groupCallId=${groupCall.groupCallId})`); - const stream = yield this.getUserMediaStream(true, groupCall.type === groupCall_1.GroupCallType.Video); - if (groupCall.state === groupCall_1.GroupCallState.Ended) { - continue; - } - yield groupCall.updateLocalUsermediaStream(stream); - } - this.emit(MediaHandlerEvent.LocalStreamsChanged); - }); - } - hasAudioDevice() { - return __awaiter(this, void 0, void 0, function* () { - try { - const devices = yield navigator.mediaDevices.enumerateDevices(); - return devices.filter((device) => device.kind === "audioinput").length > 0; - } - catch (err) { - logger_1.logger.log(`MediaHandler hasAudioDevice() calling navigator.mediaDevices.enumerateDevices with error`, err); - return false; - } - }); - } - hasVideoDevice() { - return __awaiter(this, void 0, void 0, function* () { - try { - const devices = yield navigator.mediaDevices.enumerateDevices(); - return devices.filter((device) => device.kind === "videoinput").length > 0; - } - catch (err) { - logger_1.logger.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, reusable = true) { - return __awaiter(this, void 0, void 0, function* () { - // Serialise calls, othertwise we can't sensibly re-use the stream - if (this.getMediaStreamPromise) { - this.getMediaStreamPromise = this.getMediaStreamPromise.then(() => { - return this.getUserMediaStreamInternal(audio, video, reusable); - }); - } - else { - this.getMediaStreamPromise = this.getUserMediaStreamInternal(audio, video, reusable); - } - return this.getMediaStreamPromise; - }); - } - getUserMediaStreamInternal(audio, video, reusable) { - var _a, _b, _c, _d, _e; - return __awaiter(this, void 0, void 0, function* () { - const shouldRequestAudio = audio && (yield this.hasAudioDevice()); - const shouldRequestVideo = video && (yield this.hasVideoDevice()); - let stream; - let canReuseStream = true; - if (this.localUserMediaStream) { - // This figures out if we can reuse the current localUsermediaStream - // based on whether or not the "mute state" (presence of tracks of a - // given kind) matches what is being requested - if (shouldRequestAudio !== this.localUserMediaStream.getAudioTracks().length > 0) { - canReuseStream = false; - } - if (shouldRequestVideo !== this.localUserMediaStream.getVideoTracks().length > 0) { - canReuseStream = false; - } - // This code checks that the device ID is the same as the localUserMediaStream stream, but we update - // the localUserMediaStream whenever the device ID changes (apart from when restoring) so it's not - // clear why this would ever be different, unless there's a race. - if (shouldRequestAudio && - ((_b = (_a = this.localUserMediaStream.getAudioTracks()[0]) === null || _a === void 0 ? void 0 : _a.getSettings()) === null || _b === void 0 ? void 0 : _b.deviceId) !== this.audioInput) { - canReuseStream = false; - } - if (shouldRequestVideo && - ((_d = (_c = this.localUserMediaStream.getVideoTracks()[0]) === null || _c === void 0 ? void 0 : _c.getSettings()) === null || _d === void 0 ? void 0 : _d.deviceId) !== this.videoInput) { - canReuseStream = false; - } - } - else { - canReuseStream = false; - } - if (!canReuseStream) { - const constraints = this.getUserMediaContraints(shouldRequestAudio, shouldRequestVideo); - stream = yield navigator.mediaDevices.getUserMedia(constraints); - logger_1.logger.log(`MediaHandler getUserMediaStreamInternal() calling getUserMediaStream (streamId=${stream.id}, shouldRequestAudio=${shouldRequestAudio}, shouldRequestVideo=${shouldRequestVideo}, constraints=${JSON.stringify(constraints)})`); - for (const track of stream.getTracks()) { - const settings = track.getSettings(); - if (track.kind === "audio") { - this.audioInput = settings.deviceId; - } - else if (track.kind === "video") { - this.videoInput = settings.deviceId; - } - } - if (reusable) { - this.localUserMediaStream = stream; - } - } - else { - stream = this.localUserMediaStream.clone(); - logger_1.logger.log(`MediaHandler getUserMediaStreamInternal() cloning (oldStreamId=${(_e = this.localUserMediaStream) === null || _e === void 0 ? void 0 : _e.id} newStreamId=${stream.id} shouldRequestAudio=${shouldRequestAudio} shouldRequestVideo=${shouldRequestVideo})`); - if (!shouldRequestAudio) { - for (const track of stream.getAudioTracks()) { - stream.removeTrack(track); - } - } - if (!shouldRequestVideo) { - for (const track of stream.getVideoTracks()) { - stream.removeTrack(track); - } - } - } - if (reusable) { - this.userMediaStreams.push(stream); - } - this.emit(MediaHandlerEvent.LocalStreamsChanged); - return stream; - }); - } - /** - * Stops all tracks on the provided usermedia stream - */ - stopUserMediaStream(mediaStream) { - logger_1.logger.log(`MediaHandler stopUserMediaStream() stopping (streamId=${mediaStream.id})`); - for (const track of mediaStream.getTracks()) { - track.stop(); - } - const index = this.userMediaStreams.indexOf(mediaStream); - if (index !== -1) { - logger_1.logger.debug(`MediaHandler stopUserMediaStream() splicing usermedia stream out stream array (streamId=${mediaStream.id})`, mediaStream.id); - this.userMediaStreams.splice(index, 1); - } - this.emit(MediaHandlerEvent.LocalStreamsChanged); - if (this.localUserMediaStream === mediaStream) { - this.localUserMediaStream = undefined; - } - } - /** - * @param desktopCapturerSourceId - sourceId for Electron DesktopCapturer - * @param reusable - is allowed to be reused by the MediaHandler - * @returns based on passed parameters - */ - getScreensharingStream(opts = {}, reusable = true) { - return __awaiter(this, void 0, void 0, function* () { - let stream; - if (this.screensharingStreams.length === 0) { - const screenshareConstraints = this.getScreenshareContraints(opts); - if (opts.desktopCapturerSourceId) { - // We are using Electron - logger_1.logger.debug(`MediaHandler getScreensharingStream() calling getUserMedia() (opts=${JSON.stringify(opts)})`); - stream = yield navigator.mediaDevices.getUserMedia(screenshareConstraints); - } - else { - // We are not using Electron - logger_1.logger.debug(`MediaHandler getScreensharingStream() calling getDisplayMedia() (opts=${JSON.stringify(opts)})`); - stream = yield navigator.mediaDevices.getDisplayMedia(screenshareConstraints); - } - } - else { - const matchingStream = this.screensharingStreams[this.screensharingStreams.length - 1]; - logger_1.logger.log(`MediaHandler getScreensharingStream() cloning (streamId=${matchingStream.id})`); - stream = matchingStream.clone(); - } - if (reusable) { - this.screensharingStreams.push(stream); - } - this.emit(MediaHandlerEvent.LocalStreamsChanged); - return stream; - }); - } - /** - * Stops all tracks on the provided screensharing stream - */ - stopScreensharingStream(mediaStream) { - logger_1.logger.debug(`MediaHandler stopScreensharingStream() stopping stream (streamId=${mediaStream.id})`); - for (const track of mediaStream.getTracks()) { - track.stop(); - } - const index = this.screensharingStreams.indexOf(mediaStream); - if (index !== -1) { - logger_1.logger.debug(`MediaHandler stopScreensharingStream() splicing stream out (streamId=${mediaStream.id})`); - this.screensharingStreams.splice(index, 1); - } - this.emit(MediaHandlerEvent.LocalStreamsChanged); - } - /** - * Stops all local media tracks - */ - stopAllStreams() { - for (const stream of this.userMediaStreams) { - logger_1.logger.log(`MediaHandler stopAllStreams() stopping (streamId=${stream.id})`); - for (const track of stream.getTracks()) { - track.stop(); - } - } - for (const stream of this.screensharingStreams) { - for (const track of stream.getTracks()) { - track.stop(); - } - } - this.userMediaStreams = []; - this.screensharingStreams = []; - this.localUserMediaStream = undefined; - this.emit(MediaHandlerEvent.LocalStreamsChanged); - } - getUserMediaContraints(audio, video) { - const isWebkit = !!navigator.webkitGetUserMedia; - return { - audio: audio - ? { - deviceId: this.audioInput ? { ideal: this.audioInput } : undefined, - autoGainControl: this.audioSettings ? { ideal: this.audioSettings.autoGainControl } : undefined, - echoCancellation: this.audioSettings ? { ideal: this.audioSettings.echoCancellation } : undefined, - noiseSuppression: this.audioSettings ? { ideal: this.audioSettings.noiseSuppression } : undefined, - } - : false, - video: video - ? { - deviceId: this.videoInput ? { ideal: this.videoInput } : undefined, - /* We want 640x360. Chrome will give it only if we ask exactly, - FF refuses entirely if we ask exactly, so have to ask for ideal - instead - XXX: Is this still true? - */ - width: isWebkit ? { exact: 640 } : { ideal: 640 }, - height: isWebkit ? { exact: 360 } : { ideal: 360 }, - } - : false, - }; - } - getScreenshareContraints(opts) { - const { 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, - }; - } - } -} -exports.MediaHandler = MediaHandler; - -},{"../logger":374,"../models/typed-event-emitter":395,"../webrtc/groupCall":422}],425:[function(require,module,exports){ -"use strict"; -/* -Copyright 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConnectionStats = void 0; -class ConnectionStats { - constructor() { - this.bandwidth = {}; - this.bitrate = {}; - this.packetLoss = {}; - this.transport = []; - } -} -exports.ConnectionStats = ConnectionStats; - -},{}],426:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConnectionStatsReporter = void 0; -class ConnectionStatsReporter { - static buildBandwidthReport(now) { - const availableIncomingBitrate = now.availableIncomingBitrate; - const availableOutgoingBitrate = now.availableOutgoingBitrate; - return { - download: availableIncomingBitrate ? Math.round(availableIncomingBitrate / 1000) : 0, - upload: availableOutgoingBitrate ? Math.round(availableOutgoingBitrate / 1000) : 0, - }; - } -} -exports.ConnectionStatsReporter = ConnectionStatsReporter; - -},{}],427:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.GroupCallStats = void 0; -/* -Copyright 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -const statsReportGatherer_1 = require("./statsReportGatherer"); -const statsReportEmitter_1 = require("./statsReportEmitter"); -class GroupCallStats { - constructor(groupCallId, userId, interval = 10000) { - this.groupCallId = groupCallId; - this.userId = userId; - this.interval = interval; - this.gatherers = new Map(); - this.reports = new statsReportEmitter_1.StatsReportEmitter(); - } - start() { - if (this.timer === undefined) { - this.timer = setInterval(() => { - this.processStats(); - }, this.interval); - } - } - stop() { - if (this.timer !== undefined) { - clearInterval(this.timer); - this.gatherers.forEach((c) => c.stopProcessingStats()); - } - } - hasStatsReportGatherer(callId) { - return this.gatherers.has(callId); - } - addStatsReportGatherer(callId, userId, peerConnection) { - if (this.hasStatsReportGatherer(callId)) { - return false; - } - this.gatherers.set(callId, new statsReportGatherer_1.StatsReportGatherer(callId, userId, peerConnection, this.reports)); - return true; - } - removeStatsReportGatherer(callId) { - return this.gatherers.delete(callId); - } - getStatsReportGatherer(callId) { - return this.hasStatsReportGatherer(callId) ? this.gatherers.get(callId) : undefined; - } - processStats() { - this.gatherers.forEach((c) => c.processStats(this.groupCallId, this.userId)); - } -} -exports.GroupCallStats = GroupCallStats; - -},{"./statsReportEmitter":434,"./statsReportGatherer":435}],428:[function(require,module,exports){ -"use strict"; -/* -Copyright 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MediaSsrcHandler = void 0; -const sdp_transform_1 = require("sdp-transform"); -class MediaSsrcHandler { - constructor() { - this.ssrcToMid = { local: new Map(), remote: new Map() }; - } - findMidBySsrc(ssrc, type) { - let mid; - this.ssrcToMid[type].forEach((ssrcs, m) => { - if (ssrcs.find((s) => s == ssrc)) { - mid = m; - return; - } - }); - return mid; - } - parse(description, type) { - const sdp = (0, sdp_transform_1.parse)(description); - const ssrcToMid = new Map(); - sdp.media.forEach((m) => { - var _a; - if ((!!m.mid && m.type === "video") || m.type === "audio") { - const ssrcs = []; - (_a = m.ssrcs) === null || _a === void 0 ? void 0 : _a.forEach((ssrc) => { - if (ssrc.attribute === "cname") { - ssrcs.push(`${ssrc.id}`); - } - }); - ssrcToMid.set(`${m.mid}`, ssrcs); - } - }); - this.ssrcToMid[type] = ssrcToMid; - } - getSsrcToMidMap(type) { - return this.ssrcToMid[type]; - } -} -exports.MediaSsrcHandler = MediaSsrcHandler; - -},{"sdp-transform":253}],429:[function(require,module,exports){ -"use strict"; -/* -Copyright 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MediaTrackHandler = void 0; -class MediaTrackHandler { - constructor(pc) { - this.pc = pc; - } - getLocalTracks(kind) { - const isNotNullAndKind = (track) => { - return track !== null && track.kind === kind; - }; - // @ts-ignore The linter don't get it - 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; - } - return undefined; - }) - .find((t) => t !== undefined); - } - getLocalTrackIdByMid(mid) { - const transceiver = this.pc.getTransceivers().find((t) => t.mid === mid); - if (transceiver !== undefined && !!transceiver.sender && !!transceiver.sender.track) { - return transceiver.sender.track.id; - } - return undefined; - } - getRemoteTrackIdByMid(mid) { - const transceiver = this.pc.getTransceivers().find((t) => t.mid === mid); - if (transceiver !== undefined && !!transceiver.receiver && !!transceiver.receiver.track) { - return transceiver.receiver.track.id; - } - return undefined; - } - getActiveSimulcastStreams() { - //@TODO implement this right.. Check how many layer configured - return 3; - } -} -exports.MediaTrackHandler = MediaTrackHandler; - -},{}],430:[function(require,module,exports){ -"use strict"; -/* -Copyright 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MediaTrackStats = void 0; -class MediaTrackStats { - constructor(trackId, type, kind) { - this.trackId = trackId; - this.type = type; - this.kind = kind; - this.loss = { packetsTotal: 0, packetsLost: 0, isDownloadStream: false }; - this.bitrate = { download: 0, upload: 0 }; - this.resolution = { width: -1, height: -1 }; - this.framerate = 0; - this.codec = ""; - } - getType() { - return this.type; - } - setLoss(loos) { - this.loss = loos; - } - 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 }; - } -} -exports.MediaTrackStats = MediaTrackStats; - -},{}],431:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MediaTrackStatsHandler = void 0; -const mediaTrackStats_1 = require("./mediaTrackStats"); -class MediaTrackStatsHandler { - constructor(mediaSsrcHandler, mediaTrackHandler) { - this.mediaSsrcHandler = mediaSsrcHandler; - this.mediaTrackHandler = mediaTrackHandler; - this.track2stats = 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) { - let 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) { - const mid = this.mediaSsrcHandler.findMidBySsrc(report.ssrc, type); - if (!mid) { - return undefined; - } - trackID = - type === "remote" - ? this.mediaTrackHandler.getRemoteTrackIdByMid(report.mid) - : this.mediaTrackHandler.getLocalTrackIdByMid(report.mid); - } - if (!trackID) { - return undefined; - } - let trackStats = this.track2stats.get(trackID); - if (!trackStats) { - const track = this.mediaTrackHandler.getTackById(trackID); - if (track !== undefined) { - const kind = track.kind === "audio" ? track.kind : "video"; - trackStats = new mediaTrackStats_1.MediaTrackStats(trackID, type, kind); - this.track2stats.set(trackID, trackStats); - } - else { - return undefined; - } - } - return trackStats; - } - findLocalVideoTrackStats(report) { - const localVideoTracks = this.mediaTrackHandler.getLocalTracks("video"); - if (localVideoTracks.length === 0) { - return undefined; - } - return this.findTrack2Stats(report, "local"); - } - getTrack2stats() { - return this.track2stats; - } -} -exports.MediaTrackStatsHandler = MediaTrackStatsHandler; - -},{"./mediaTrackStats":430}],432:[function(require,module,exports){ -"use strict"; -/* -Copyright 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.StatsReport = void 0; -var StatsReport; -(function (StatsReport) { - StatsReport["CONNECTION_STATS"] = "StatsReport.connection_stats"; - StatsReport["BYTE_SENT_STATS"] = "StatsReport.byte_sent_stats"; -})(StatsReport = exports.StatsReport || (exports.StatsReport = {})); - -},{}],433:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.StatsReportBuilder = void 0; -class StatsReportBuilder { - static build(stats) { - const report = {}; - // process stats - const totalPackets = { - download: 0, - upload: 0, - }; - const lostPackets = { - download: 0, - upload: 0, - }; - let bitrateDownload = 0; - let bitrateUpload = 0; - const resolutions = { - local: new Map(), - remote: new Map(), - }; - const framerates = { local: new Map(), remote: new Map() }; - const codecs = { local: new Map(), remote: new Map() }; - let audioBitrateDownload = 0; - let audioBitrateUpload = 0; - let videoBitrateDownload = 0; - let videoBitrateUpload = 0; - for (const [trackId, trackStats] of stats) { - // process packet loss stats - const loss = trackStats.getLoss(); - const type = loss.isDownloadStream ? "download" : "upload"; - totalPackets[type] += loss.packetsTotal; - lostPackets[type] += loss.packetsLost; - // process bitrate stats - bitrateDownload += trackStats.getBitrate().download; - bitrateUpload += trackStats.getBitrate().upload; - // collect resolutions and framerates - if (trackStats.kind === "audio") { - 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()); - 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: StatsReportBuilder.calculatePacketLoss(lostPackets.download + lostPackets.upload, totalPackets.download + totalPackets.upload), - download: StatsReportBuilder.calculatePacketLoss(lostPackets.download, totalPackets.download), - upload: StatsReportBuilder.calculatePacketLoss(lostPackets.upload, totalPackets.upload), - }; - report.framerate = framerates; - report.resolution = resolutions; - report.codec = codecs; - return report; - } - static calculatePacketLoss(lostPackets, totalPackets) { - if (!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0) { - return 0; - } - return Math.round((lostPackets / totalPackets) * 100); - } -} -exports.StatsReportBuilder = StatsReportBuilder; - -},{}],434:[function(require,module,exports){ -"use strict"; -/* -Copyright 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.StatsReportEmitter = void 0; -const typed_event_emitter_1 = require("../../models/typed-event-emitter"); -const statsReport_1 = require("./statsReport"); -class StatsReportEmitter extends typed_event_emitter_1.TypedEventEmitter { - emitByteSendReport(byteSentStats) { - this.emit(statsReport_1.StatsReport.BYTE_SENT_STATS, byteSentStats); - } - emitConnectionStatsReport(report) { - this.emit(statsReport_1.StatsReport.CONNECTION_STATS, report); - } -} -exports.StatsReportEmitter = StatsReportEmitter; - -},{"../../models/typed-event-emitter":395,"./statsReport":432}],435:[function(require,module,exports){ -"use strict"; -/* -Copyright 2023 The Matrix.org Foundation C.I.C. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.StatsReportGatherer = void 0; -const connectionStats_1 = require("./connectionStats"); -const connectionStatsReporter_1 = require("./connectionStatsReporter"); -const transportStatsReporter_1 = require("./transportStatsReporter"); -const mediaSsrcHandler_1 = require("./media/mediaSsrcHandler"); -const mediaTrackHandler_1 = require("./media/mediaTrackHandler"); -const mediaTrackStatsHandler_1 = require("./media/mediaTrackStatsHandler"); -const trackStatsReporter_1 = require("./trackStatsReporter"); -const statsReportBuilder_1 = require("./statsReportBuilder"); -const statsValueFormatter_1 = require("./statsValueFormatter"); -class StatsReportGatherer { - // private readonly ssrcToMid = { local: new Map(), remote: new Map() }; - constructor(callId, remoteUserId, pc, emitter, isFocus = true) { - this.callId = callId; - this.remoteUserId = remoteUserId; - this.pc = pc; - this.emitter = emitter; - this.isFocus = isFocus; - this.isActive = true; - this.connectionStats = new connectionStats_1.ConnectionStats(); - pc.addEventListener("signalingstatechange", this.onSignalStateChange.bind(this)); - this.trackStats = new mediaTrackStatsHandler_1.MediaTrackStatsHandler(new mediaSsrcHandler_1.MediaSsrcHandler(), new mediaTrackHandler_1.MediaTrackHandler(pc)); - } - processStats(groupCallId, localUserId) { - return __awaiter(this, void 0, void 0, function* () { - if (this.isActive) { - const statsPromise = this.pc.getStats(); - if (typeof (statsPromise === null || statsPromise === void 0 ? void 0 : statsPromise.then) === "function") { - return statsPromise - .then((report) => { - // @ts-ignore - this.currentStatsReport = typeof (report === null || report === void 0 ? void 0 : report.result) === "function" ? report.result() : report; - try { - this.processStatsReport(groupCallId, localUserId); - } - catch (error) { - this.isActive = false; - return false; - } - this.previousStatsReport = this.currentStatsReport; - return true; - }) - .catch((error) => { - this.handleError(error); - return false; - }); - } - this.isActive = false; - } - return Promise.resolve(false); - }); - } - processStatsReport(groupCallId, localUserId) { - var _a; - const byteSentStats = new Map(); - (_a = this.currentStatsReport) === null || _a === void 0 ? void 0 : _a.forEach((now) => { - const before = this.previousStatsReport ? this.previousStatsReport.get(now.id) : null; - // RTCIceCandidatePairStats - https://w3c.github.io/webrtc-stats/#candidatepair-dict* - if (now.type === "candidate-pair" && now.nominated && now.state === "succeeded") { - this.connectionStats.bandwidth = connectionStatsReporter_1.ConnectionStatsReporter.buildBandwidthReport(now); - this.connectionStats.transport = transportStatsReporter_1.TransportStatsReporter.buildReport(this.currentStatsReport, now, this.connectionStats.transport, this.isFocus); - // RTCReceivedRtpStreamStats - // https://w3c.github.io/webrtc-stats/#receivedrtpstats-dict* - // RTCSentRtpStreamStats - // https://w3c.github.io/webrtc-stats/#sentrtpstats-dict* - } - else if (now.type === "inbound-rtp" || now.type === "outbound-rtp") { - const trackStats = this.trackStats.findTrack2Stats(now, now.type === "inbound-rtp" ? "remote" : "local"); - if (!trackStats) { - return; - } - if (before) { - trackStatsReporter_1.TrackStatsReporter.buildPacketsLost(trackStats, now, before); - } - // Get the resolution and framerate for only remote video sources here. For the local video sources, - // 'track' stats will be used since they have the updated resolution based on the simulcast streams - // currently being sent. Promise based getStats reports three 'outbound-rtp' streams and there will be - // more calculations needed to determine what is the highest resolution stream sent by the client if the - // 'outbound-rtp' stats are used. - if (now.type === "inbound-rtp") { - trackStatsReporter_1.TrackStatsReporter.buildFramerateResolution(trackStats, now); - if (before) { - trackStatsReporter_1.TrackStatsReporter.buildBitrateReceived(trackStats, now, before); - } - } - else if (before) { - byteSentStats.set(trackStats.trackId, statsValueFormatter_1.StatsValueFormatter.getNonNegativeValue(now.bytesSent)); - trackStatsReporter_1.TrackStatsReporter.buildBitrateSend(trackStats, now, before); - } - trackStatsReporter_1.TrackStatsReporter.buildCodec(this.currentStatsReport, trackStats, now); - } - else if (now.type === "track" && now.kind === "video" && !now.remoteSource) { - const trackStats = this.trackStats.findLocalVideoTrackStats(now); - if (!trackStats) { - return; - } - trackStatsReporter_1.TrackStatsReporter.buildFramerateResolution(trackStats, now); - trackStatsReporter_1.TrackStatsReporter.calculateSimulcastFramerate(trackStats, now, before, this.trackStats.mediaTrackHandler.getActiveSimulcastStreams()); - } - }); - this.emitter.emitByteSendReport(byteSentStats); - this.processAndEmitReport(); - } - setActive(isActive) { - this.isActive = isActive; - } - getActive() { - return this.isActive; - } - handleError(_) { - this.isActive = false; - } - processAndEmitReport() { - const report = statsReportBuilder_1.StatsReportBuilder.build(this.trackStats.getTrack2stats()); - this.connectionStats.bandwidth = report.bandwidth; - this.connectionStats.bitrate = report.bitrate; - this.connectionStats.packetLoss = report.packetLoss; - this.emitter.emitConnectionStatsReport(Object.assign(Object.assign({}, 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"); - } - } - } -} -exports.StatsReportGatherer = StatsReportGatherer; - -},{"./connectionStats":425,"./connectionStatsReporter":426,"./media/mediaSsrcHandler":428,"./media/mediaTrackHandler":429,"./media/mediaTrackStatsHandler":431,"./statsReportBuilder":433,"./statsValueFormatter":436,"./trackStatsReporter":437,"./transportStatsReporter":438}],436:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.StatsValueFormatter = void 0; -/* -Copyright 2023 The Matrix.org Foundation C.I.C. -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ -class StatsValueFormatter { - static getNonNegativeValue(imput) { - let value = imput; - if (typeof value !== "number") { - value = Number(value); - } - if (isNaN(value)) { - return 0; - } - return Math.max(0, value); - } -} -exports.StatsValueFormatter = StatsValueFormatter; - -},{}],437:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TrackStatsReporter = void 0; -const statsValueFormatter_1 = require("./statsValueFormatter"); -class TrackStatsReporter { - static buildFramerateResolution(trackStats, now) { - const resolution = { - height: now.frameHeight, - width: now.frameWidth, - }; - const frameRate = now.framesPerSecond; - if (resolution.height && resolution.width) { - trackStats.setResolution(resolution); - } - trackStats.setFramerate(Math.round(frameRate || 0)); - } - static calculateSimulcastFramerate(trackStats, now, before, layer) { - let frameRate = trackStats.getFramerate(); - if (!frameRate) { - if (before) { - const timeMs = now.timestamp - before.timestamp; - if (timeMs > 0 && now.framesSent) { - const numberOfFramesSinceBefore = now.framesSent - before.framesSent; - frameRate = (numberOfFramesSinceBefore / timeMs) * 1000; - } - } - if (!frameRate) { - return; - } - } - // Reset frame rate to 0 when video is suspended as a result of endpoint falling out of last-n. - frameRate = layer ? Math.round(frameRate / layer) : 0; - trackStats.setFramerate(frameRate); - } - static buildCodec(report, trackStats, now) { - const 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. - */ - const codecShortType = codec.mimeType.split("/")[1]; - codecShortType && trackStats.setCodec(codecShortType); - } - } - static buildBitrateReceived(trackStats, now, before) { - trackStats.setBitrate({ - download: TrackStatsReporter.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) { - const key = now.type === "outbound-rtp" ? "packetsSent" : "packetsReceived"; - let packetsNow = now[key]; - if (!packetsNow || packetsNow < 0) { - packetsNow = 0; - } - const packetsBefore = statsValueFormatter_1.StatsValueFormatter.getNonNegativeValue(before[key]); - const packetsDiff = Math.max(0, packetsNow - packetsBefore); - const packetsLostNow = statsValueFormatter_1.StatsValueFormatter.getNonNegativeValue(now.packetsLost); - const packetsLostBefore = statsValueFormatter_1.StatsValueFormatter.getNonNegativeValue(before.packetsLost); - const packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore); - trackStats.setLoss({ - packetsTotal: packetsDiff + packetsLostDiff, - packetsLost: packetsLostDiff, - isDownloadStream: now.type !== "outbound-rtp", - }); - } - static calculateBitrate(bytesNowAny, bytesBeforeAny, nowTimestamp, beforeTimestamp) { - const bytesNow = statsValueFormatter_1.StatsValueFormatter.getNonNegativeValue(bytesNowAny); - const bytesBefore = statsValueFormatter_1.StatsValueFormatter.getNonNegativeValue(bytesBeforeAny); - const bytesProcessed = Math.max(0, bytesNow - bytesBefore); - const timeMs = nowTimestamp - beforeTimestamp; - let bitrateKbps = 0; - if (timeMs > 0) { - // TODO is there any reason to round here? - bitrateKbps = Math.round((bytesProcessed * 8) / timeMs); - } - return bitrateKbps; - } -} -exports.TrackStatsReporter = TrackStatsReporter; - -},{"./statsValueFormatter":436}],438:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TransportStatsReporter = void 0; -class TransportStatsReporter { - static buildReport(report, now, conferenceStatsTransport, isFocus) { - const localUsedCandidate = report === null || report === void 0 ? void 0 : report.get(now.localCandidateId); - const remoteUsedCandidate = report === null || report === void 0 ? void 0 : report.get(now.remoteCandidateId); - // RTCIceCandidateStats - // https://w3c.github.io/webrtc-stats/#icecandidate-dict* - if (remoteUsedCandidate && localUsedCandidate) { - const remoteIpAddress = remoteUsedCandidate.ip !== undefined ? remoteUsedCandidate.ip : remoteUsedCandidate.address; - const remotePort = remoteUsedCandidate.port; - const ip = `${remoteIpAddress}:${remotePort}`; - const localIpAddress = localUsedCandidate.ip !== undefined ? localUsedCandidate.ip : localUsedCandidate.address; - const localPort = localUsedCandidate.port; - const localIp = `${localIpAddress}:${localPort}`; - const type = remoteUsedCandidate.protocol; - // Save the address unless it has been saved already. - 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 * 1000 : NaN, - }); - } - } - return conferenceStatsTransport; - } -} -exports.TransportStatsReporter = TransportStatsReporter; - -},{}]},{},[320]) -//# sourceMappingURL=browser-matrix.js.map diff --git a/includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.js.map b/includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.js.map deleted file mode 100644 index 540a28d..0000000 --- a/includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.js.map +++ /dev/null @@ -1,801 +0,0 @@ -{ - "version": 3, - "sources": [ - "node_modules/browser-pack/_prelude.js", - "node_modules/another-json/another-json.js", - "node_modules/asn1.js/lib/asn1.js", - "node_modules/asn1.js/lib/asn1/api.js", - "node_modules/asn1.js/lib/asn1/base/buffer.js", - "node_modules/asn1.js/lib/asn1/base/index.js", - "node_modules/asn1.js/lib/asn1/base/node.js", - "node_modules/asn1.js/lib/asn1/base/reporter.js", - "node_modules/asn1.js/lib/asn1/constants/der.js", - "node_modules/asn1.js/lib/asn1/constants/index.js", - "node_modules/asn1.js/lib/asn1/decoders/der.js", - "node_modules/asn1.js/lib/asn1/decoders/index.js", - "node_modules/asn1.js/lib/asn1/decoders/pem.js", - "node_modules/asn1.js/lib/asn1/encoders/der.js", - "node_modules/asn1.js/lib/asn1/encoders/index.js", - "node_modules/asn1.js/lib/asn1/encoders/pem.js", - "node_modules/available-typed-arrays/index.js", - "node_modules/base64-js/index.js", - "node_modules/bn.js/lib/bn.js", - "node_modules/brorand/index.js", - "node_modules/browser-resolve/empty.js", - "node_modules/browserify-aes/aes.js", - "node_modules/browserify-aes/authCipher.js", - "node_modules/browserify-aes/browser.js", - "node_modules/browserify-aes/decrypter.js", - "node_modules/browserify-aes/encrypter.js", - "node_modules/browserify-aes/ghash.js", - "node_modules/browserify-aes/incr32.js", - "node_modules/browserify-aes/modes/cbc.js", - "node_modules/browserify-aes/modes/cfb.js", - "node_modules/browserify-aes/modes/cfb1.js", - "node_modules/browserify-aes/modes/cfb8.js", - "node_modules/browserify-aes/modes/ctr.js", - "node_modules/browserify-aes/modes/ecb.js", - "node_modules/browserify-aes/modes/index.js", - "node_modules/browserify-aes/modes/list.json", - "node_modules/browserify-aes/modes/ofb.js", - "node_modules/browserify-aes/streamCipher.js", - "node_modules/browserify-cipher/browser.js", - "node_modules/browserify-des/index.js", - "node_modules/browserify-des/modes.js", - "node_modules/browserify-rsa/index.js", - "node_modules/browserify-rsa/node_modules/bn.js/lib/bn.js", - "node_modules/browserify-sign/algos.js", - "node_modules/browserify-sign/browser/algorithms.json", - "node_modules/browserify-sign/browser/curves.json", - "node_modules/browserify-sign/browser/index.js", - "node_modules/browserify-sign/browser/sign.js", - "node_modules/browserify-sign/browser/verify.js", - "node_modules/browserify-sign/node_modules/readable-stream/errors-browser.js", - "node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_duplex.js", - "node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_passthrough.js", - "node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_readable.js", - "node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_transform.js", - "node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_writable.js", - "node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/async_iterator.js", - "node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/buffer_list.js", - "node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/destroy.js", - "node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/end-of-stream.js", - "node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/from-browser.js", - "node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/pipeline.js", - "node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/state.js", - "node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/stream-browser.js", - "node_modules/browserify-sign/node_modules/readable-stream/readable-browser.js", - "node_modules/bs58/index.js", - "node_modules/bs58/node_modules/base-x/src/index.js", - "node_modules/buffer-xor/index.js", - "node_modules/buffer/index.js", - "node_modules/call-bind/callBound.js", - "node_modules/call-bind/index.js", - "node_modules/cipher-base/index.js", - "node_modules/content-type/index.js", - "node_modules/create-ecdh/browser.js", - "node_modules/create-hash/browser.js", - "node_modules/create-hash/md5.js", - "node_modules/create-hmac/browser.js", - "node_modules/create-hmac/legacy.js", - "node_modules/crypto-browserify/index.js", - "node_modules/des.js/lib/des.js", - "node_modules/des.js/lib/des/cbc.js", - "node_modules/des.js/lib/des/cipher.js", - "node_modules/des.js/lib/des/des.js", - "node_modules/des.js/lib/des/ede.js", - "node_modules/des.js/lib/des/utils.js", - "node_modules/diffie-hellman/browser.js", - "node_modules/diffie-hellman/lib/dh.js", - "node_modules/diffie-hellman/lib/generatePrime.js", - "node_modules/diffie-hellman/lib/primes.json", - "node_modules/elliptic/lib/elliptic.js", - "node_modules/elliptic/lib/elliptic/curve/base.js", - "node_modules/elliptic/lib/elliptic/curve/edwards.js", - "node_modules/elliptic/lib/elliptic/curve/index.js", - "node_modules/elliptic/lib/elliptic/curve/mont.js", - "node_modules/elliptic/lib/elliptic/curve/short.js", - "node_modules/elliptic/lib/elliptic/curves.js", - "node_modules/elliptic/lib/elliptic/ec/index.js", - "node_modules/elliptic/lib/elliptic/ec/key.js", - "node_modules/elliptic/lib/elliptic/ec/signature.js", - "node_modules/elliptic/lib/elliptic/eddsa/index.js", - "node_modules/elliptic/lib/elliptic/eddsa/key.js", - "node_modules/elliptic/lib/elliptic/eddsa/signature.js", - "node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js", - "node_modules/elliptic/lib/elliptic/utils.js", - "node_modules/elliptic/package.json", - "node_modules/events/events.js", - "node_modules/evp_bytestokey/index.js", - "node_modules/for-each/index.js", - "node_modules/function-bind/implementation.js", - "node_modules/function-bind/index.js", - "node_modules/get-intrinsic/index.js", - "node_modules/gopd/index.js", - "node_modules/has-symbols/index.js", - "node_modules/has-symbols/shams.js", - "node_modules/has-tostringtag/shams.js", - "node_modules/has/src/index.js", - "node_modules/hash-base/index.js", - "node_modules/hash-base/node_modules/readable-stream/lib/_stream_duplex.js", - "node_modules/hash-base/node_modules/readable-stream/lib/_stream_readable.js", - "node_modules/hash-base/node_modules/readable-stream/lib/_stream_writable.js", - "node_modules/hash-base/node_modules/readable-stream/lib/internal/streams/async_iterator.js", - "node_modules/hash-base/node_modules/readable-stream/lib/internal/streams/destroy.js", - "node_modules/hash.js/lib/hash.js", - "node_modules/hash.js/lib/hash/common.js", - "node_modules/hash.js/lib/hash/hmac.js", - "node_modules/hash.js/lib/hash/ripemd.js", - "node_modules/hash.js/lib/hash/sha.js", - "node_modules/hash.js/lib/hash/sha/1.js", - "node_modules/hash.js/lib/hash/sha/224.js", - "node_modules/hash.js/lib/hash/sha/256.js", - "node_modules/hash.js/lib/hash/sha/384.js", - "node_modules/hash.js/lib/hash/sha/512.js", - "node_modules/hash.js/lib/hash/sha/common.js", - "node_modules/hash.js/lib/hash/utils.js", - "node_modules/hmac-drbg/lib/hmac-drbg.js", - "node_modules/ieee754/index.js", - "node_modules/inherits/inherits_browser.js", - "node_modules/is-arguments/index.js", - "node_modules/is-callable/index.js", - "node_modules/is-generator-function/index.js", - "node_modules/is-typed-array/index.js", - "node_modules/loglevel/lib/loglevel.js", - "node_modules/matrix-events-sdk/lib/ExtensibleEvents.js", - "node_modules/matrix-events-sdk/lib/IPartialEvent.js", - "node_modules/matrix-events-sdk/lib/InvalidEventError.js", - "node_modules/matrix-events-sdk/lib/NamespacedMap.js", - "node_modules/matrix-events-sdk/lib/NamespacedValue.js", - "node_modules/matrix-events-sdk/lib/events/EmoteEvent.js", - "node_modules/matrix-events-sdk/lib/events/ExtensibleEvent.js", - "node_modules/matrix-events-sdk/lib/events/MessageEvent.js", - "node_modules/matrix-events-sdk/lib/events/NoticeEvent.js", - "node_modules/matrix-events-sdk/lib/events/PollEndEvent.js", - "node_modules/matrix-events-sdk/lib/events/PollResponseEvent.js", - "node_modules/matrix-events-sdk/lib/events/PollStartEvent.js", - "node_modules/matrix-events-sdk/lib/events/message_types.js", - "node_modules/matrix-events-sdk/lib/events/poll_types.js", - "node_modules/matrix-events-sdk/lib/events/relationship_types.js", - "node_modules/matrix-events-sdk/lib/index.js", - "node_modules/matrix-events-sdk/lib/interpreters/legacy/MRoomMessage.js", - "node_modules/matrix-events-sdk/lib/interpreters/modern/MMessage.js", - "node_modules/matrix-events-sdk/lib/interpreters/modern/MPoll.js", - "node_modules/matrix-events-sdk/lib/types.js", - "node_modules/matrix-events-sdk/lib/utility/MessageMatchers.js", - "node_modules/matrix-events-sdk/lib/utility/events.js", - "node_modules/matrix-widget-api/lib/ClientWidgetApi.js", - "node_modules/matrix-widget-api/lib/Symbols.js", - "node_modules/matrix-widget-api/lib/WidgetApi.js", - "node_modules/matrix-widget-api/lib/driver/WidgetDriver.js", - "node_modules/matrix-widget-api/lib/index.js", - "node_modules/matrix-widget-api/lib/interfaces/ApiVersion.js", - "node_modules/matrix-widget-api/lib/interfaces/Capabilities.js", - "node_modules/matrix-widget-api/lib/interfaces/GetOpenIDAction.js", - "node_modules/matrix-widget-api/lib/interfaces/IWidgetApiErrorResponse.js", - "node_modules/matrix-widget-api/lib/interfaces/ModalButtonKind.js", - "node_modules/matrix-widget-api/lib/interfaces/ModalWidgetActions.js", - "node_modules/matrix-widget-api/lib/interfaces/WidgetApiAction.js", - "node_modules/matrix-widget-api/lib/interfaces/WidgetApiDirection.js", - "node_modules/matrix-widget-api/lib/interfaces/WidgetKind.js", - "node_modules/matrix-widget-api/lib/interfaces/WidgetType.js", - "node_modules/matrix-widget-api/lib/models/Widget.js", - "node_modules/matrix-widget-api/lib/models/WidgetEventCapability.js", - "node_modules/matrix-widget-api/lib/models/WidgetParser.js", - "node_modules/matrix-widget-api/lib/models/validation/url.js", - "node_modules/matrix-widget-api/lib/models/validation/utils.js", - "node_modules/matrix-widget-api/lib/templating/url-template.js", - "node_modules/matrix-widget-api/lib/transport/PostmessageTransport.js", - "node_modules/matrix-widget-api/lib/util/SimpleObservable.js", - "node_modules/md5.js/index.js", - "node_modules/miller-rabin/lib/mr.js", - "node_modules/minimalistic-assert/index.js", - "node_modules/minimalistic-crypto-utils/lib/utils.js", - "node_modules/p-retry/index.js", - "node_modules/parse-asn1/aesid.json", - "node_modules/parse-asn1/asn1.js", - "node_modules/parse-asn1/certificate.js", - "node_modules/parse-asn1/fixProc.js", - "node_modules/parse-asn1/index.js", - "node_modules/pbkdf2/browser.js", - "node_modules/pbkdf2/lib/async.js", - "node_modules/pbkdf2/lib/default-encoding.js", - "node_modules/pbkdf2/lib/precondition.js", - "node_modules/pbkdf2/lib/sync-browser.js", - "node_modules/pbkdf2/lib/to-buffer.js", - "node_modules/process/browser.js", - "node_modules/public-encrypt/browser.js", - "node_modules/public-encrypt/mgf.js", - "node_modules/public-encrypt/privateDecrypt.js", - "node_modules/public-encrypt/publicEncrypt.js", - "node_modules/public-encrypt/withPublic.js", - "node_modules/public-encrypt/xor.js", - "node_modules/randombytes/browser.js", - "node_modules/randomfill/browser.js", - "node_modules/retry/index.js", - "node_modules/retry/lib/retry.js", - "node_modules/retry/lib/retry_operation.js", - "node_modules/ripemd160/index.js", - "node_modules/safe-buffer/index.js", - "node_modules/safer-buffer/safer.js", - "node_modules/sdp-transform/lib/grammar.js", - "node_modules/sdp-transform/lib/index.js", - "node_modules/sdp-transform/lib/parser.js", - "node_modules/sdp-transform/lib/writer.js", - "node_modules/sha.js/hash.js", - "node_modules/sha.js/index.js", - "node_modules/sha.js/sha.js", - "node_modules/sha.js/sha1.js", - "node_modules/sha.js/sha224.js", - "node_modules/sha.js/sha256.js", - "node_modules/sha.js/sha384.js", - "node_modules/sha.js/sha512.js", - "node_modules/stream-browserify/index.js", - "node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_duplex.js", - "node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_readable.js", - "node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_writable.js", - "node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/async_iterator.js", - "node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/destroy.js", - "node_modules/string_decoder/lib/string_decoder.js", - "node_modules/timers-browserify/main.js", - "node_modules/unhomoglyph/data.json", - "node_modules/unhomoglyph/index.js", - "node_modules/util-deprecate/browser.js", - "node_modules/util/support/isBufferBrowser.js", - "node_modules/util/support/types.js", - "node_modules/util/util.js", - "node_modules/uuid/dist/index.js", - "node_modules/uuid/dist/md5-browser.js", - "node_modules/uuid/dist/native-browser.js", - "node_modules/uuid/dist/nil.js", - "node_modules/uuid/dist/parse.js", - "node_modules/uuid/dist/regex.js", - "node_modules/uuid/dist/rng-browser.js", - "node_modules/uuid/dist/sha1-browser.js", - "node_modules/uuid/dist/stringify.js", - "node_modules/uuid/dist/v1.js", - "node_modules/uuid/dist/v3.js", - "node_modules/uuid/dist/v35.js", - "node_modules/uuid/dist/v4.js", - "node_modules/uuid/dist/v5.js", - "node_modules/uuid/dist/validate.js", - "node_modules/uuid/dist/version.js", - "node_modules/which-typed-array/index.js", - "src/@types/PushRules.ts", - "src/@types/beacon.ts", - "src/@types/event.ts", - "src/@types/extensible_events.ts", - "src/@types/location.ts", - "src/@types/partials.ts", - "src/@types/polls.ts", - "src/@types/read_receipts.ts", - "src/@types/requests.ts", - "src/@types/search.ts", - "src/@types/sync.ts", - "src/@types/topic.ts", - "src/NamespacedValue.ts", - "src/ReEmitter.ts", - "src/ToDeviceMessageQueue.ts", - "src/autodiscovery.ts", - "src/browser-index.ts", - "src/client.ts", - "src/content-helpers.ts", - "src/content-repo.ts", - "src/crypto/CrossSigning.ts", - "src/crypto/DeviceList.ts", - "src/crypto/EncryptionSetup.ts", - "src/crypto/OlmDevice.ts", - "src/crypto/OutgoingRoomKeyRequestManager.ts", - "src/crypto/RoomList.ts", - "src/crypto/SecretStorage.ts", - "src/crypto/aes.ts", - "src/crypto/algorithms/base.ts", - "src/crypto/algorithms/index.ts", - "src/crypto/algorithms/megolm.ts", - "src/crypto/algorithms/olm.ts", - "src/crypto/api.ts", - "src/crypto/backup.ts", - "src/crypto/crypto.ts", - "src/crypto/dehydration.ts", - "src/crypto/deviceinfo.ts", - "src/crypto/index.ts", - "src/crypto/key_passphrase.ts", - "src/crypto/olmlib.ts", - "src/crypto/recoverykey.ts", - "src/crypto/store/indexeddb-crypto-store-backend.ts", - "src/crypto/store/indexeddb-crypto-store.ts", - "src/crypto/store/localStorage-crypto-store.ts", - "src/crypto/store/memory-crypto-store.ts", - "src/crypto/verification/Base.ts", - "src/crypto/verification/Error.ts", - "src/crypto/verification/IllegalMethod.ts", - "src/crypto/verification/QRCode.ts", - "src/crypto/verification/SAS.ts", - "src/crypto/verification/SASDecimal.ts", - "src/crypto/verification/request/InRoomChannel.ts", - "src/crypto/verification/request/ToDeviceChannel.ts", - "src/crypto/verification/request/VerificationRequest.ts", - "src/embedded.ts", - "src/errors.ts", - "src/event-mapper.ts", - "src/extensible_events_v1/utilities.ts", - "src/feature.ts", - "src/filter-component.ts", - "src/filter.ts", - "src/http-api/errors.ts", - "src/http-api/fetch.ts", - "src/http-api/index.ts", - "src/http-api/interface.ts", - "src/http-api/method.ts", - "src/http-api/prefix.ts", - "src/http-api/utils.ts", - "src/indexeddb-helpers.ts", - "src/interactive-auth.ts", - "src/logger.ts", - "src/matrix.ts", - "src/models/MSC3089Branch.ts", - "src/models/MSC3089TreeSpace.ts", - "src/models/beacon.ts", - "src/models/event-context.ts", - "src/models/event-status.ts", - "src/models/event-timeline-set.ts", - "src/models/event-timeline.ts", - "src/models/event.ts", - "src/models/invites-ignorer.ts", - "src/models/poll.ts", - "src/models/read-receipt.ts", - "src/models/relations-container.ts", - "src/models/relations.ts", - "src/models/room-member.ts", - "src/models/room-state.ts", - "src/models/room-summary.ts", - "src/models/room.ts", - "src/models/search-result.ts", - "src/models/thread.ts", - "src/models/typed-event-emitter.ts", - "src/models/user.ts", - "src/pushprocessor.ts", - "src/randomstring.ts", - "src/realtime-callbacks.ts", - "src/rust-crypto/browserify-index.ts", - "src/rust-crypto/constants.ts", - "src/rust-crypto/index.ts", - "src/scheduler.ts", - "src/secret-storage.ts", - "src/service-types.ts", - "src/sliding-sync-sdk.ts", - "src/sliding-sync.ts", - "src/store/indexeddb-local-backend.ts", - "src/store/indexeddb-remote-backend.ts", - "src/store/indexeddb.ts", - "src/store/memory.ts", - "src/store/stub.ts", - "src/sync-accumulator.ts", - "src/sync.ts", - "src/timeline-window.ts", - "src/utils.ts", - "src/webrtc/audioContext.ts", - "src/webrtc/call.ts", - "src/webrtc/callEventHandler.ts", - "src/webrtc/callEventTypes.ts", - "src/webrtc/callFeed.ts", - "src/webrtc/groupCall.ts", - "src/webrtc/groupCallEventHandler.ts", - "src/webrtc/mediaHandler.ts", - "src/webrtc/stats/connectionStats.ts", - "src/webrtc/stats/connectionStatsReporter.ts", - "src/webrtc/stats/groupCallStats.ts", - "src/webrtc/stats/media/mediaSsrcHandler.ts", - "src/webrtc/stats/media/mediaTrackHandler.ts", - "src/webrtc/stats/media/mediaTrackStats.ts", - "src/webrtc/stats/media/mediaTrackStatsHandler.ts", - "src/webrtc/stats/statsReport.ts", - "src/webrtc/stats/statsReportBuilder.ts", - "src/webrtc/stats/statsReportEmitter.ts", - "src/webrtc/stats/statsReportGatherer.ts", - "src/webrtc/stats/statsValueFormatter.ts", - "src/webrtc/stats/trackStatsReporter.ts", - "src/webrtc/stats/transportStatsReporter.ts" - ], - "names": [], - "mappings": "AAAA;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9nBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/UA;AACA;AACA;AACA;AACA;AACA;AACA;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvSA;AACA;AACA;AACA;AACA;AACA;AACA;;ACNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACvBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AC3BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACt3GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjEA;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC/LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACxBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC39GA;AACA;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACpFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC/HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AC1IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACtCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACnmCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACxMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACxrBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AC9MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACjNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACxGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvGA;AACA;AACA;AACA;;ACHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1BA;AACA;;ACDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA;AACA;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACzHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACjvDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACjOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AC5HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9BA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AChQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;AC1CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACpKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7XA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC16BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5wBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpDA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACPA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;AC/FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC1IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACnmCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACxrBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC9MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;ACxGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACtCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AC5DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5LA;AACA;AACA;AACA;AACA;;ACJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9RA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9zCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACz5BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1lBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;ACzEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;AC7BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;AC7BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC3BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5PA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AC3DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9PA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3GA;AACA;AACA;;;ACFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACtHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;AClDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AC5GA;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACjEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AC7EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9eA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9FA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACrDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpQA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACjIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC1IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACnmCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACxrBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;AC9MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;;;;;;;;;;ACxGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACvSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AC3EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxqMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACnEA;AACA;AACA;AACA;AACA;AACA;;ACLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AC9UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;AC3sBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACVA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1GA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;;ACvDA;;;;;;;;;;;;;;EAcE;;;AAEF,4DAA4D;AAC5D,8BAA8B;AAE9B,IAAY,kBAIX;AAJD,WAAY,kBAAkB;IAC1B,gDAA0B,CAAA;IAC1B,uCAAiB,CAAA;IACjB,2CAAqB,CAAA;AACzB,CAAC,EAJW,kBAAkB,GAAlB,0BAAkB,KAAlB,0BAAkB,QAI7B;AAED,IAAY,SAGX;AAHD,WAAY,SAAS;IACjB,oCAAuB,CAAA;IACvB,4BAAe,CAAA;AACnB,CAAC,EAHW,SAAS,GAAT,iBAAS,KAAT,iBAAS,QAGpB;AAYD,IAAY,iBAMX;AAND,WAAY,iBAAiB;IACzB,uCAAkB,CAAA;IAClB,mCAAc,CAAA;IACd,sCAAiB,CAAA;IACjB,8CAAyB,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pD,mBAAmB,EAAE,mBAAmB,CAAC,aAAa;oBACtD,WAAW,EAAE,kBAAkB,CAAC,WAAW;oBAC3C,GAAG,EAAE,GAAG,CAAC,oBAAoB,CAAC,CAAC,CAAC,GAAG,CAAC,oBAAoB,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG;iBACtD,CAAC,CAAC;aACxB;SACJ;QACD,OAAO,wBAAwB,CAAC;IACpC,CAAC;CACJ;AA7CD,wDA6CC", - "file": "generated.js", - "sourceRoot": "", - "sourcesContent": [ - "(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c=\"function\"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error(\"Cannot find module '\"+i+\"'\");throw a.code=\"MODULE_NOT_FOUND\",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u=\"function\"==typeof require&&require,i=0;i> 6];\n const primitive = (tag & 0x20) === 0;\n\n // Multi-octet tag - load\n if ((tag & 0x1f) === 0x1f) {\n let oct = tag;\n tag = 0;\n while ((oct & 0x80) === 0x80) {\n oct = buf.readUInt8(fail);\n if (buf.isError(oct))\n return oct;\n\n tag <<= 7;\n tag |= oct & 0x7f;\n }\n } else {\n tag &= 0x1f;\n }\n const tagStr = der.tag[tag];\n\n return {\n cls: cls,\n primitive: primitive,\n tag: tag,\n tagStr: tagStr\n };\n}\n\nfunction derDecodeLen(buf, primitive, fail) {\n let len = buf.readUInt8(fail);\n if (buf.isError(len))\n return len;\n\n // Indefinite form\n if (!primitive && len === 0x80)\n return null;\n\n // Definite form\n if ((len & 0x80) === 0) {\n // Short form\n return len;\n }\n\n // Long form\n const num = len & 0x7f;\n if (num > 4)\n return buf.error('length octect is too long');\n\n len = 0;\n for (let i = 0; i < num; i++) {\n len <<= 8;\n const j = buf.readUInt8(fail);\n if (buf.isError(j))\n return j;\n len |= j;\n }\n\n return len;\n}\n", - "'use strict';\n\nconst decoders = exports;\n\ndecoders.der = require('./der');\ndecoders.pem = require('./pem');\n", - "'use strict';\n\nconst inherits = require('inherits');\nconst Buffer = require('safer-buffer').Buffer;\n\nconst DERDecoder = require('./der');\n\nfunction PEMDecoder(entity) {\n DERDecoder.call(this, entity);\n this.enc = 'pem';\n}\ninherits(PEMDecoder, DERDecoder);\nmodule.exports = PEMDecoder;\n\nPEMDecoder.prototype.decode = function decode(data, options) {\n const lines = data.toString().split(/[\\r\\n]+/g);\n\n const label = options.label.toUpperCase();\n\n const re = /^-----(BEGIN|END) ([^-]+)-----$/;\n let start = -1;\n let end = -1;\n for (let i = 0; i < lines.length; i++) {\n const match = lines[i].match(re);\n if (match === null)\n continue;\n\n if (match[2] !== label)\n continue;\n\n if (start === -1) {\n if (match[1] !== 'BEGIN')\n break;\n start = i;\n } else {\n if (match[1] !== 'END')\n break;\n end = i;\n break;\n }\n }\n if (start === -1 || end === -1)\n throw new Error('PEM section not found for: ' + label);\n\n const base64 = lines.slice(start + 1, end).join('');\n // Remove excessive symbols\n base64.replace(/[^a-z0-9+/=]+/gi, '');\n\n const input = Buffer.from(base64, 'base64');\n return DERDecoder.prototype.decode.call(this, input, options);\n};\n", - "'use strict';\n\nconst inherits = require('inherits');\nconst Buffer = require('safer-buffer').Buffer;\nconst Node = require('../base/node');\n\n// Import DER constants\nconst der = require('../constants/der');\n\nfunction DEREncoder(entity) {\n this.enc = 'der';\n this.name = entity.name;\n this.entity = entity;\n\n // Construct base tree\n this.tree = new DERNode();\n this.tree._init(entity.body);\n}\nmodule.exports = DEREncoder;\n\nDEREncoder.prototype.encode = function encode(data, reporter) {\n return this.tree._encode(data, reporter).join();\n};\n\n// Tree methods\n\nfunction DERNode(parent) {\n Node.call(this, 'der', parent);\n}\ninherits(DERNode, Node);\n\nDERNode.prototype._encodeComposite = function encodeComposite(tag,\n primitive,\n cls,\n content) {\n const encodedTag = encodeTag(tag, primitive, cls, this.reporter);\n\n // Short form\n if (content.length < 0x80) {\n const header = Buffer.alloc(2);\n header[0] = encodedTag;\n header[1] = content.length;\n return this._createEncoderBuffer([ header, content ]);\n }\n\n // Long form\n // Count octets required to store length\n let lenOctets = 1;\n for (let i = content.length; i >= 0x100; i >>= 8)\n lenOctets++;\n\n const header = Buffer.alloc(1 + 1 + lenOctets);\n header[0] = encodedTag;\n header[1] = 0x80 | lenOctets;\n\n for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8)\n header[i] = j & 0xff;\n\n return this._createEncoderBuffer([ header, content ]);\n};\n\nDERNode.prototype._encodeStr = function encodeStr(str, tag) {\n if (tag === 'bitstr') {\n return this._createEncoderBuffer([ str.unused | 0, str.data ]);\n } else if (tag === 'bmpstr') {\n const buf = Buffer.alloc(str.length * 2);\n for (let i = 0; i < str.length; i++) {\n buf.writeUInt16BE(str.charCodeAt(i), i * 2);\n }\n return this._createEncoderBuffer(buf);\n } else if (tag === 'numstr') {\n if (!this._isNumstr(str)) {\n return this.reporter.error('Encoding of string type: numstr supports ' +\n 'only digits and space');\n }\n return this._createEncoderBuffer(str);\n } else if (tag === 'printstr') {\n if (!this._isPrintstr(str)) {\n return this.reporter.error('Encoding of string type: printstr supports ' +\n 'only latin upper and lower case letters, ' +\n 'digits, space, apostrophe, left and rigth ' +\n 'parenthesis, plus sign, comma, hyphen, ' +\n 'dot, slash, colon, equal sign, ' +\n 'question mark');\n }\n return this._createEncoderBuffer(str);\n } else if (/str$/.test(tag)) {\n return this._createEncoderBuffer(str);\n } else if (tag === 'objDesc') {\n return this._createEncoderBuffer(str);\n } else {\n return this.reporter.error('Encoding of string type: ' + tag +\n ' unsupported');\n }\n};\n\nDERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {\n if (typeof id === 'string') {\n if (!values)\n return this.reporter.error('string objid given, but no values map found');\n if (!values.hasOwnProperty(id))\n return this.reporter.error('objid not found in values map');\n id = values[id].split(/[\\s.]+/g);\n for (let i = 0; i < id.length; i++)\n id[i] |= 0;\n } else if (Array.isArray(id)) {\n id = id.slice();\n for (let i = 0; i < id.length; i++)\n id[i] |= 0;\n }\n\n if (!Array.isArray(id)) {\n return this.reporter.error('objid() should be either array or string, ' +\n 'got: ' + JSON.stringify(id));\n }\n\n if (!relative) {\n if (id[1] >= 40)\n return this.reporter.error('Second objid identifier OOB');\n id.splice(0, 2, id[0] * 40 + id[1]);\n }\n\n // Count number of octets\n let size = 0;\n for (let i = 0; i < id.length; i++) {\n let ident = id[i];\n for (size++; ident >= 0x80; ident >>= 7)\n size++;\n }\n\n const objid = Buffer.alloc(size);\n let offset = objid.length - 1;\n for (let i = id.length - 1; i >= 0; i--) {\n let ident = id[i];\n objid[offset--] = ident & 0x7f;\n while ((ident >>= 7) > 0)\n objid[offset--] = 0x80 | (ident & 0x7f);\n }\n\n return this._createEncoderBuffer(objid);\n};\n\nfunction two(num) {\n if (num < 10)\n return '0' + num;\n else\n return num;\n}\n\nDERNode.prototype._encodeTime = function encodeTime(time, tag) {\n let str;\n const date = new Date(time);\n\n if (tag === 'gentime') {\n str = [\n two(date.getUTCFullYear()),\n two(date.getUTCMonth() + 1),\n two(date.getUTCDate()),\n two(date.getUTCHours()),\n two(date.getUTCMinutes()),\n two(date.getUTCSeconds()),\n 'Z'\n ].join('');\n } else if (tag === 'utctime') {\n str = [\n two(date.getUTCFullYear() % 100),\n two(date.getUTCMonth() + 1),\n two(date.getUTCDate()),\n two(date.getUTCHours()),\n two(date.getUTCMinutes()),\n two(date.getUTCSeconds()),\n 'Z'\n ].join('');\n } else {\n this.reporter.error('Encoding ' + tag + ' time is not supported yet');\n }\n\n return this._encodeStr(str, 'octstr');\n};\n\nDERNode.prototype._encodeNull = function encodeNull() {\n return this._createEncoderBuffer('');\n};\n\nDERNode.prototype._encodeInt = function encodeInt(num, values) {\n if (typeof num === 'string') {\n if (!values)\n return this.reporter.error('String int or enum given, but no values map');\n if (!values.hasOwnProperty(num)) {\n return this.reporter.error('Values map doesn\\'t contain: ' +\n JSON.stringify(num));\n }\n num = values[num];\n }\n\n // Bignum, assume big endian\n if (typeof num !== 'number' && !Buffer.isBuffer(num)) {\n const numArray = num.toArray();\n if (!num.sign && numArray[0] & 0x80) {\n numArray.unshift(0);\n }\n num = Buffer.from(numArray);\n }\n\n if (Buffer.isBuffer(num)) {\n let size = num.length;\n if (num.length === 0)\n size++;\n\n const out = Buffer.alloc(size);\n num.copy(out);\n if (num.length === 0)\n out[0] = 0;\n return this._createEncoderBuffer(out);\n }\n\n if (num < 0x80)\n return this._createEncoderBuffer(num);\n\n if (num < 0x100)\n return this._createEncoderBuffer([0, num]);\n\n let size = 1;\n for (let i = num; i >= 0x100; i >>= 8)\n size++;\n\n const out = new Array(size);\n for (let i = out.length - 1; i >= 0; i--) {\n out[i] = num & 0xff;\n num >>= 8;\n }\n if(out[0] & 0x80) {\n out.unshift(0);\n }\n\n return this._createEncoderBuffer(Buffer.from(out));\n};\n\nDERNode.prototype._encodeBool = function encodeBool(value) {\n return this._createEncoderBuffer(value ? 0xff : 0);\n};\n\nDERNode.prototype._use = function use(entity, obj) {\n if (typeof entity === 'function')\n entity = entity(obj);\n return entity._getEncoder('der').tree;\n};\n\nDERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) {\n const state = this._baseState;\n let i;\n if (state['default'] === null)\n return false;\n\n const data = dataBuffer.join();\n if (state.defaultBuffer === undefined)\n state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join();\n\n if (data.length !== state.defaultBuffer.length)\n return false;\n\n for (i=0; i < data.length; i++)\n if (data[i] !== state.defaultBuffer[i])\n return false;\n\n return true;\n};\n\n// Utility methods\n\nfunction encodeTag(tag, primitive, cls, reporter) {\n let res;\n\n if (tag === 'seqof')\n tag = 'seq';\n else if (tag === 'setof')\n tag = 'set';\n\n if (der.tagByName.hasOwnProperty(tag))\n res = der.tagByName[tag];\n else if (typeof tag === 'number' && (tag | 0) === tag)\n res = tag;\n else\n return reporter.error('Unknown tag: ' + tag);\n\n if (res >= 0x1f)\n return reporter.error('Multi-octet tag encoding unsupported');\n\n if (!primitive)\n res |= 0x20;\n\n res |= (der.tagClassByName[cls || 'universal'] << 6);\n\n return res;\n}\n", - "'use strict';\n\nconst encoders = exports;\n\nencoders.der = require('./der');\nencoders.pem = require('./pem');\n", - "'use strict';\n\nconst inherits = require('inherits');\n\nconst DEREncoder = require('./der');\n\nfunction PEMEncoder(entity) {\n DEREncoder.call(this, entity);\n this.enc = 'pem';\n}\ninherits(PEMEncoder, DEREncoder);\nmodule.exports = PEMEncoder;\n\nPEMEncoder.prototype.encode = function encode(data, options) {\n const buf = DEREncoder.prototype.encode.call(this, data);\n\n const p = buf.toString('base64');\n const out = [ '-----BEGIN ' + options.label + '-----' ];\n for (let i = 0; i < p.length; i += 64)\n out.push(p.slice(i, i + 64));\n out.push('-----END ' + options.label + '-----');\n return out.join('\\n');\n};\n", - "'use strict';\n\nvar possibleNames = [\n\t'BigInt64Array',\n\t'BigUint64Array',\n\t'Float32Array',\n\t'Float64Array',\n\t'Int16Array',\n\t'Int32Array',\n\t'Int8Array',\n\t'Uint16Array',\n\t'Uint32Array',\n\t'Uint8Array',\n\t'Uint8ClampedArray'\n];\n\nvar g = typeof globalThis === 'undefined' ? global : globalThis;\n\nmodule.exports = function availableTypedArrays() {\n\tvar out = [];\n\tfor (var i = 0; i < possibleNames.length; i++) {\n\t\tif (typeof g[possibleNames[i]] === 'function') {\n\t\t\tout[out.length] = possibleNames[i];\n\t\t}\n\t}\n\treturn out;\n};\n", - "'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n", - "(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {\n Buffer = window.Buffer;\n } else {\n Buffer = require('buffer').Buffer;\n }\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n this.negative = 1;\n }\n\n if (start < number.length) {\n if (base === 16) {\n this._parseHex(number, start, endian);\n } else {\n this._parseBase(number, base, start);\n if (endian === 'le') {\n this._initArray(this.toArray(), base, endian);\n }\n }\n }\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [ number & 0x3ffffff ];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [ 0 ];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this.strip();\n };\n\n function parseHex4Bits (string, index) {\n var c = string.charCodeAt(index);\n // 'A' - 'F'\n if (c >= 65 && c <= 70) {\n return c - 55;\n // 'a' - 'f'\n } else if (c >= 97 && c <= 102) {\n return c - 87;\n // '0' - '9'\n } else {\n return (c - 48) & 0xf;\n }\n }\n\n function parseHexByte (string, lowerBound, index) {\n var r = parseHex4Bits(string, index);\n if (index - 1 >= lowerBound) {\n r |= parseHex4Bits(string, index - 1) << 4;\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start, endian) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n // 24-bits chunks\n var off = 0;\n var j = 0;\n\n var w;\n if (endian === 'be') {\n for (i = number.length - 1; i >= start; i -= 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n } else {\n var parseLength = number.length - start;\n for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n }\n\n this.strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n r += c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n r += c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r += c;\n }\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [ 0 ];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n this.strip();\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype.strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n BN.prototype.inspect = function inspect () {\n return (this.red ? '';\n };\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16);\n };\n\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n assert(typeof Buffer !== 'undefined');\n return this.toArrayLike(Buffer, endian, length);\n };\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n this.strip();\n var littleEndian = endian === 'le';\n var res = new ArrayType(reqLength);\n\n var b, i;\n var q = this.clone();\n if (!littleEndian) {\n // Assume big-endian\n for (i = 0; i < reqLength - byteLength; i++) {\n res[i] = 0;\n }\n\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[reqLength - i - 1] = b;\n }\n } else {\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[i] = b;\n }\n\n for (; i < reqLength; i++) {\n res[i] = 0;\n }\n }\n\n return res;\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this.strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this.strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this.strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this.strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this.strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this.strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n function jumboMulTo (self, num, out) {\n var fftm = new FFTM();\n return fftm.mulp(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out.strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this.strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) < num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this.strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this.strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this.strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q.strip();\n }\n a.strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modn = function modn (num) {\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return acc;\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n return this.strip();\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this.strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n if (r.strip !== undefined) {\n // r is BN v4 instance\n r.strip();\n } else {\n // r is BN v5 instance\n r._strip();\n }\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n return a.umod(this.m)._forceRed(this);\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})(typeof module === 'undefined' || module, this);\n", - "var r;\n\nmodule.exports = function rand(len) {\n if (!r)\n r = new Rand(null);\n\n return r.generate(len);\n};\n\nfunction Rand(rand) {\n this.rand = rand;\n}\nmodule.exports.Rand = Rand;\n\nRand.prototype.generate = function generate(len) {\n return this._rand(len);\n};\n\n// Emulate crypto API using randy\nRand.prototype._rand = function _rand(n) {\n if (this.rand.getBytes)\n return this.rand.getBytes(n);\n\n var res = new Uint8Array(n);\n for (var i = 0; i < res.length; i++)\n res[i] = this.rand.getByte();\n return res;\n};\n\nif (typeof self === 'object') {\n if (self.crypto && self.crypto.getRandomValues) {\n // Modern browsers\n Rand.prototype._rand = function _rand(n) {\n var arr = new Uint8Array(n);\n self.crypto.getRandomValues(arr);\n return arr;\n };\n } else if (self.msCrypto && self.msCrypto.getRandomValues) {\n // IE\n Rand.prototype._rand = function _rand(n) {\n var arr = new Uint8Array(n);\n self.msCrypto.getRandomValues(arr);\n return arr;\n };\n\n // Safari's WebWorkers do not have `crypto`\n } else if (typeof window === 'object') {\n // Old junk\n Rand.prototype._rand = function() {\n throw new Error('Not implemented yet');\n };\n }\n} else {\n // Node.js or Web worker with no crypto support\n try {\n var crypto = require('crypto');\n if (typeof crypto.randomBytes !== 'function')\n throw new Error('Not supported');\n\n Rand.prototype._rand = function _rand(n) {\n return crypto.randomBytes(n);\n };\n } catch (e) {\n }\n}\n", - "", - "// based on the aes implimentation in triple sec\n// https://github.com/keybase/triplesec\n// which is in turn based on the one from crypto-js\n// https://code.google.com/p/crypto-js/\n\nvar Buffer = require('safe-buffer').Buffer\n\nfunction asUInt32Array (buf) {\n if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)\n\n var len = (buf.length / 4) | 0\n var out = new Array(len)\n\n for (var i = 0; i < len; i++) {\n out[i] = buf.readUInt32BE(i * 4)\n }\n\n return out\n}\n\nfunction scrubVec (v) {\n for (var i = 0; i < v.length; v++) {\n v[i] = 0\n }\n}\n\nfunction cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) {\n var SUB_MIX0 = SUB_MIX[0]\n var SUB_MIX1 = SUB_MIX[1]\n var SUB_MIX2 = SUB_MIX[2]\n var SUB_MIX3 = SUB_MIX[3]\n\n var s0 = M[0] ^ keySchedule[0]\n var s1 = M[1] ^ keySchedule[1]\n var s2 = M[2] ^ keySchedule[2]\n var s3 = M[3] ^ keySchedule[3]\n var t0, t1, t2, t3\n var ksRow = 4\n\n for (var round = 1; round < nRounds; round++) {\n t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++]\n t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++]\n t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++]\n t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++]\n s0 = t0\n s1 = t1\n s2 = t2\n s3 = t3\n }\n\n t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]\n t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]\n t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]\n t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]\n t0 = t0 >>> 0\n t1 = t1 >>> 0\n t2 = t2 >>> 0\n t3 = t3 >>> 0\n\n return [t0, t1, t2, t3]\n}\n\n// AES constants\nvar RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]\nvar G = (function () {\n // Compute double table\n var d = new Array(256)\n for (var j = 0; j < 256; j++) {\n if (j < 128) {\n d[j] = j << 1\n } else {\n d[j] = (j << 1) ^ 0x11b\n }\n }\n\n var SBOX = []\n var INV_SBOX = []\n var SUB_MIX = [[], [], [], []]\n var INV_SUB_MIX = [[], [], [], []]\n\n // Walk GF(2^8)\n var x = 0\n var xi = 0\n for (var i = 0; i < 256; ++i) {\n // Compute sbox\n var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)\n sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63\n SBOX[x] = sx\n INV_SBOX[sx] = x\n\n // Compute multiplication\n var x2 = d[x]\n var x4 = d[x2]\n var x8 = d[x4]\n\n // Compute sub bytes, mix columns tables\n var t = (d[sx] * 0x101) ^ (sx * 0x1010100)\n SUB_MIX[0][x] = (t << 24) | (t >>> 8)\n SUB_MIX[1][x] = (t << 16) | (t >>> 16)\n SUB_MIX[2][x] = (t << 8) | (t >>> 24)\n SUB_MIX[3][x] = t\n\n // Compute inv sub bytes, inv mix columns tables\n t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)\n INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)\n INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)\n INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)\n INV_SUB_MIX[3][sx] = t\n\n if (x === 0) {\n x = xi = 1\n } else {\n x = x2 ^ d[d[d[x8 ^ x2]]]\n xi ^= d[d[xi]]\n }\n }\n\n return {\n SBOX: SBOX,\n INV_SBOX: INV_SBOX,\n SUB_MIX: SUB_MIX,\n INV_SUB_MIX: INV_SUB_MIX\n }\n})()\n\nfunction AES (key) {\n this._key = asUInt32Array(key)\n this._reset()\n}\n\nAES.blockSize = 4 * 4\nAES.keySize = 256 / 8\nAES.prototype.blockSize = AES.blockSize\nAES.prototype.keySize = AES.keySize\nAES.prototype._reset = function () {\n var keyWords = this._key\n var keySize = keyWords.length\n var nRounds = keySize + 6\n var ksRows = (nRounds + 1) * 4\n\n var keySchedule = []\n for (var k = 0; k < keySize; k++) {\n keySchedule[k] = keyWords[k]\n }\n\n for (k = keySize; k < ksRows; k++) {\n var t = keySchedule[k - 1]\n\n if (k % keySize === 0) {\n t = (t << 8) | (t >>> 24)\n t =\n (G.SBOX[t >>> 24] << 24) |\n (G.SBOX[(t >>> 16) & 0xff] << 16) |\n (G.SBOX[(t >>> 8) & 0xff] << 8) |\n (G.SBOX[t & 0xff])\n\n t ^= RCON[(k / keySize) | 0] << 24\n } else if (keySize > 6 && k % keySize === 4) {\n t =\n (G.SBOX[t >>> 24] << 24) |\n (G.SBOX[(t >>> 16) & 0xff] << 16) |\n (G.SBOX[(t >>> 8) & 0xff] << 8) |\n (G.SBOX[t & 0xff])\n }\n\n keySchedule[k] = keySchedule[k - keySize] ^ t\n }\n\n var invKeySchedule = []\n for (var ik = 0; ik < ksRows; ik++) {\n var ksR = ksRows - ik\n var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]\n\n if (ik < 4 || ksR <= 4) {\n invKeySchedule[ik] = tt\n } else {\n invKeySchedule[ik] =\n G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^\n G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^\n G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^\n G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]]\n }\n }\n\n this._nRounds = nRounds\n this._keySchedule = keySchedule\n this._invKeySchedule = invKeySchedule\n}\n\nAES.prototype.encryptBlockRaw = function (M) {\n M = asUInt32Array(M)\n return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)\n}\n\nAES.prototype.encryptBlock = function (M) {\n var out = this.encryptBlockRaw(M)\n var buf = Buffer.allocUnsafe(16)\n buf.writeUInt32BE(out[0], 0)\n buf.writeUInt32BE(out[1], 4)\n buf.writeUInt32BE(out[2], 8)\n buf.writeUInt32BE(out[3], 12)\n return buf\n}\n\nAES.prototype.decryptBlock = function (M) {\n M = asUInt32Array(M)\n\n // swap\n var m1 = M[1]\n M[1] = M[3]\n M[3] = m1\n\n var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds)\n var buf = Buffer.allocUnsafe(16)\n buf.writeUInt32BE(out[0], 0)\n buf.writeUInt32BE(out[3], 4)\n buf.writeUInt32BE(out[2], 8)\n buf.writeUInt32BE(out[1], 12)\n return buf\n}\n\nAES.prototype.scrub = function () {\n scrubVec(this._keySchedule)\n scrubVec(this._invKeySchedule)\n scrubVec(this._key)\n}\n\nmodule.exports.AES = AES\n", - "var aes = require('./aes')\nvar Buffer = require('safe-buffer').Buffer\nvar Transform = require('cipher-base')\nvar inherits = require('inherits')\nvar GHASH = require('./ghash')\nvar xor = require('buffer-xor')\nvar incr32 = require('./incr32')\n\nfunction xorTest (a, b) {\n var out = 0\n if (a.length !== b.length) out++\n\n var len = Math.min(a.length, b.length)\n for (var i = 0; i < len; ++i) {\n out += (a[i] ^ b[i])\n }\n\n return out\n}\n\nfunction calcIv (self, iv, ck) {\n if (iv.length === 12) {\n self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])])\n return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])])\n }\n var ghash = new GHASH(ck)\n var len = iv.length\n var toPad = len % 16\n ghash.update(iv)\n if (toPad) {\n toPad = 16 - toPad\n ghash.update(Buffer.alloc(toPad, 0))\n }\n ghash.update(Buffer.alloc(8, 0))\n var ivBits = len * 8\n var tail = Buffer.alloc(8)\n tail.writeUIntBE(ivBits, 0, 8)\n ghash.update(tail)\n self._finID = ghash.state\n var out = Buffer.from(self._finID)\n incr32(out)\n return out\n}\nfunction StreamCipher (mode, key, iv, decrypt) {\n Transform.call(this)\n\n var h = Buffer.alloc(4, 0)\n\n this._cipher = new aes.AES(key)\n var ck = this._cipher.encryptBlock(h)\n this._ghash = new GHASH(ck)\n iv = calcIv(this, iv, ck)\n\n this._prev = Buffer.from(iv)\n this._cache = Buffer.allocUnsafe(0)\n this._secCache = Buffer.allocUnsafe(0)\n this._decrypt = decrypt\n this._alen = 0\n this._len = 0\n this._mode = mode\n\n this._authTag = null\n this._called = false\n}\n\ninherits(StreamCipher, Transform)\n\nStreamCipher.prototype._update = function (chunk) {\n if (!this._called && this._alen) {\n var rump = 16 - (this._alen % 16)\n if (rump < 16) {\n rump = Buffer.alloc(rump, 0)\n this._ghash.update(rump)\n }\n }\n\n this._called = true\n var out = this._mode.encrypt(this, chunk)\n if (this._decrypt) {\n this._ghash.update(chunk)\n } else {\n this._ghash.update(out)\n }\n this._len += chunk.length\n return out\n}\n\nStreamCipher.prototype._final = function () {\n if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data')\n\n var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))\n if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data')\n\n this._authTag = tag\n this._cipher.scrub()\n}\n\nStreamCipher.prototype.getAuthTag = function getAuthTag () {\n if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state')\n\n return this._authTag\n}\n\nStreamCipher.prototype.setAuthTag = function setAuthTag (tag) {\n if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state')\n\n this._authTag = tag\n}\n\nStreamCipher.prototype.setAAD = function setAAD (buf) {\n if (this._called) throw new Error('Attempting to set AAD in unsupported state')\n\n this._ghash.update(buf)\n this._alen += buf.length\n}\n\nmodule.exports = StreamCipher\n", - "var ciphers = require('./encrypter')\nvar deciphers = require('./decrypter')\nvar modes = require('./modes/list.json')\n\nfunction getCiphers () {\n return Object.keys(modes)\n}\n\nexports.createCipher = exports.Cipher = ciphers.createCipher\nexports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv\nexports.createDecipher = exports.Decipher = deciphers.createDecipher\nexports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv\nexports.listCiphers = exports.getCiphers = getCiphers\n", - "var AuthCipher = require('./authCipher')\nvar Buffer = require('safe-buffer').Buffer\nvar MODES = require('./modes')\nvar StreamCipher = require('./streamCipher')\nvar Transform = require('cipher-base')\nvar aes = require('./aes')\nvar ebtk = require('evp_bytestokey')\nvar inherits = require('inherits')\n\nfunction Decipher (mode, key, iv) {\n Transform.call(this)\n\n this._cache = new Splitter()\n this._last = void 0\n this._cipher = new aes.AES(key)\n this._prev = Buffer.from(iv)\n this._mode = mode\n this._autopadding = true\n}\n\ninherits(Decipher, Transform)\n\nDecipher.prototype._update = function (data) {\n this._cache.add(data)\n var chunk\n var thing\n var out = []\n while ((chunk = this._cache.get(this._autopadding))) {\n thing = this._mode.decrypt(this, chunk)\n out.push(thing)\n }\n return Buffer.concat(out)\n}\n\nDecipher.prototype._final = function () {\n var chunk = this._cache.flush()\n if (this._autopadding) {\n return unpad(this._mode.decrypt(this, chunk))\n } else if (chunk) {\n throw new Error('data not multiple of block length')\n }\n}\n\nDecipher.prototype.setAutoPadding = function (setTo) {\n this._autopadding = !!setTo\n return this\n}\n\nfunction Splitter () {\n this.cache = Buffer.allocUnsafe(0)\n}\n\nSplitter.prototype.add = function (data) {\n this.cache = Buffer.concat([this.cache, data])\n}\n\nSplitter.prototype.get = function (autoPadding) {\n var out\n if (autoPadding) {\n if (this.cache.length > 16) {\n out = this.cache.slice(0, 16)\n this.cache = this.cache.slice(16)\n return out\n }\n } else {\n if (this.cache.length >= 16) {\n out = this.cache.slice(0, 16)\n this.cache = this.cache.slice(16)\n return out\n }\n }\n\n return null\n}\n\nSplitter.prototype.flush = function () {\n if (this.cache.length) return this.cache\n}\n\nfunction unpad (last) {\n var padded = last[15]\n if (padded < 1 || padded > 16) {\n throw new Error('unable to decrypt data')\n }\n var i = -1\n while (++i < padded) {\n if (last[(i + (16 - padded))] !== padded) {\n throw new Error('unable to decrypt data')\n }\n }\n if (padded === 16) return\n\n return last.slice(0, 16 - padded)\n}\n\nfunction createDecipheriv (suite, password, iv) {\n var config = MODES[suite.toLowerCase()]\n if (!config) throw new TypeError('invalid suite type')\n\n if (typeof iv === 'string') iv = Buffer.from(iv)\n if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)\n\n if (typeof password === 'string') password = Buffer.from(password)\n if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)\n\n if (config.type === 'stream') {\n return new StreamCipher(config.module, password, iv, true)\n } else if (config.type === 'auth') {\n return new AuthCipher(config.module, password, iv, true)\n }\n\n return new Decipher(config.module, password, iv)\n}\n\nfunction createDecipher (suite, password) {\n var config = MODES[suite.toLowerCase()]\n if (!config) throw new TypeError('invalid suite type')\n\n var keys = ebtk(password, false, config.key, config.iv)\n return createDecipheriv(suite, keys.key, keys.iv)\n}\n\nexports.createDecipher = createDecipher\nexports.createDecipheriv = createDecipheriv\n", - "var MODES = require('./modes')\nvar AuthCipher = require('./authCipher')\nvar Buffer = require('safe-buffer').Buffer\nvar StreamCipher = require('./streamCipher')\nvar Transform = require('cipher-base')\nvar aes = require('./aes')\nvar ebtk = require('evp_bytestokey')\nvar inherits = require('inherits')\n\nfunction Cipher (mode, key, iv) {\n Transform.call(this)\n\n this._cache = new Splitter()\n this._cipher = new aes.AES(key)\n this._prev = Buffer.from(iv)\n this._mode = mode\n this._autopadding = true\n}\n\ninherits(Cipher, Transform)\n\nCipher.prototype._update = function (data) {\n this._cache.add(data)\n var chunk\n var thing\n var out = []\n\n while ((chunk = this._cache.get())) {\n thing = this._mode.encrypt(this, chunk)\n out.push(thing)\n }\n\n return Buffer.concat(out)\n}\n\nvar PADDING = Buffer.alloc(16, 0x10)\n\nCipher.prototype._final = function () {\n var chunk = this._cache.flush()\n if (this._autopadding) {\n chunk = this._mode.encrypt(this, chunk)\n this._cipher.scrub()\n return chunk\n }\n\n if (!chunk.equals(PADDING)) {\n this._cipher.scrub()\n throw new Error('data not multiple of block length')\n }\n}\n\nCipher.prototype.setAutoPadding = function (setTo) {\n this._autopadding = !!setTo\n return this\n}\n\nfunction Splitter () {\n this.cache = Buffer.allocUnsafe(0)\n}\n\nSplitter.prototype.add = function (data) {\n this.cache = Buffer.concat([this.cache, data])\n}\n\nSplitter.prototype.get = function () {\n if (this.cache.length > 15) {\n var out = this.cache.slice(0, 16)\n this.cache = this.cache.slice(16)\n return out\n }\n return null\n}\n\nSplitter.prototype.flush = function () {\n var len = 16 - this.cache.length\n var padBuff = Buffer.allocUnsafe(len)\n\n var i = -1\n while (++i < len) {\n padBuff.writeUInt8(len, i)\n }\n\n return Buffer.concat([this.cache, padBuff])\n}\n\nfunction createCipheriv (suite, password, iv) {\n var config = MODES[suite.toLowerCase()]\n if (!config) throw new TypeError('invalid suite type')\n\n if (typeof password === 'string') password = Buffer.from(password)\n if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)\n\n if (typeof iv === 'string') iv = Buffer.from(iv)\n if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)\n\n if (config.type === 'stream') {\n return new StreamCipher(config.module, password, iv)\n } else if (config.type === 'auth') {\n return new AuthCipher(config.module, password, iv)\n }\n\n return new Cipher(config.module, password, iv)\n}\n\nfunction createCipher (suite, password) {\n var config = MODES[suite.toLowerCase()]\n if (!config) throw new TypeError('invalid suite type')\n\n var keys = ebtk(password, false, config.key, config.iv)\n return createCipheriv(suite, keys.key, keys.iv)\n}\n\nexports.createCipheriv = createCipheriv\nexports.createCipher = createCipher\n", - "var Buffer = require('safe-buffer').Buffer\nvar ZEROES = Buffer.alloc(16, 0)\n\nfunction toArray (buf) {\n return [\n buf.readUInt32BE(0),\n buf.readUInt32BE(4),\n buf.readUInt32BE(8),\n buf.readUInt32BE(12)\n ]\n}\n\nfunction fromArray (out) {\n var buf = Buffer.allocUnsafe(16)\n buf.writeUInt32BE(out[0] >>> 0, 0)\n buf.writeUInt32BE(out[1] >>> 0, 4)\n buf.writeUInt32BE(out[2] >>> 0, 8)\n buf.writeUInt32BE(out[3] >>> 0, 12)\n return buf\n}\n\nfunction GHASH (key) {\n this.h = key\n this.state = Buffer.alloc(16, 0)\n this.cache = Buffer.allocUnsafe(0)\n}\n\n// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html\n// by Juho Vähä-Herttua\nGHASH.prototype.ghash = function (block) {\n var i = -1\n while (++i < block.length) {\n this.state[i] ^= block[i]\n }\n this._multiply()\n}\n\nGHASH.prototype._multiply = function () {\n var Vi = toArray(this.h)\n var Zi = [0, 0, 0, 0]\n var j, xi, lsbVi\n var i = -1\n while (++i < 128) {\n xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0\n if (xi) {\n // Z_i+1 = Z_i ^ V_i\n Zi[0] ^= Vi[0]\n Zi[1] ^= Vi[1]\n Zi[2] ^= Vi[2]\n Zi[3] ^= Vi[3]\n }\n\n // Store the value of LSB(V_i)\n lsbVi = (Vi[3] & 1) !== 0\n\n // V_i+1 = V_i >> 1\n for (j = 3; j > 0; j--) {\n Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)\n }\n Vi[0] = Vi[0] >>> 1\n\n // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R\n if (lsbVi) {\n Vi[0] = Vi[0] ^ (0xe1 << 24)\n }\n }\n this.state = fromArray(Zi)\n}\n\nGHASH.prototype.update = function (buf) {\n this.cache = Buffer.concat([this.cache, buf])\n var chunk\n while (this.cache.length >= 16) {\n chunk = this.cache.slice(0, 16)\n this.cache = this.cache.slice(16)\n this.ghash(chunk)\n }\n}\n\nGHASH.prototype.final = function (abl, bl) {\n if (this.cache.length) {\n this.ghash(Buffer.concat([this.cache, ZEROES], 16))\n }\n\n this.ghash(fromArray([0, abl, 0, bl]))\n return this.state\n}\n\nmodule.exports = GHASH\n", - "function incr32 (iv) {\n var len = iv.length\n var item\n while (len--) {\n item = iv.readUInt8(len)\n if (item === 255) {\n iv.writeUInt8(0, len)\n } else {\n item++\n iv.writeUInt8(item, len)\n break\n }\n }\n}\nmodule.exports = incr32\n", - "var xor = require('buffer-xor')\n\nexports.encrypt = function (self, block) {\n var data = xor(block, self._prev)\n\n self._prev = self._cipher.encryptBlock(data)\n return self._prev\n}\n\nexports.decrypt = function (self, block) {\n var pad = self._prev\n\n self._prev = block\n var out = self._cipher.decryptBlock(block)\n\n return xor(out, pad)\n}\n", - "var Buffer = require('safe-buffer').Buffer\nvar xor = require('buffer-xor')\n\nfunction encryptStart (self, data, decrypt) {\n var len = data.length\n var out = xor(data, self._cache)\n self._cache = self._cache.slice(len)\n self._prev = Buffer.concat([self._prev, decrypt ? data : out])\n return out\n}\n\nexports.encrypt = function (self, data, decrypt) {\n var out = Buffer.allocUnsafe(0)\n var len\n\n while (data.length) {\n if (self._cache.length === 0) {\n self._cache = self._cipher.encryptBlock(self._prev)\n self._prev = Buffer.allocUnsafe(0)\n }\n\n if (self._cache.length <= data.length) {\n len = self._cache.length\n out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])\n data = data.slice(len)\n } else {\n out = Buffer.concat([out, encryptStart(self, data, decrypt)])\n break\n }\n }\n\n return out\n}\n", - "var Buffer = require('safe-buffer').Buffer\n\nfunction encryptByte (self, byteParam, decrypt) {\n var pad\n var i = -1\n var len = 8\n var out = 0\n var bit, value\n while (++i < len) {\n pad = self._cipher.encryptBlock(self._prev)\n bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0\n value = pad[0] ^ bit\n out += ((value & 0x80) >> (i % 8))\n self._prev = shiftIn(self._prev, decrypt ? bit : value)\n }\n return out\n}\n\nfunction shiftIn (buffer, value) {\n var len = buffer.length\n var i = -1\n var out = Buffer.allocUnsafe(buffer.length)\n buffer = Buffer.concat([buffer, Buffer.from([value])])\n\n while (++i < len) {\n out[i] = buffer[i] << 1 | buffer[i + 1] >> (7)\n }\n\n return out\n}\n\nexports.encrypt = function (self, chunk, decrypt) {\n var len = chunk.length\n var out = Buffer.allocUnsafe(len)\n var i = -1\n\n while (++i < len) {\n out[i] = encryptByte(self, chunk[i], decrypt)\n }\n\n return out\n}\n", - "var Buffer = require('safe-buffer').Buffer\n\nfunction encryptByte (self, byteParam, decrypt) {\n var pad = self._cipher.encryptBlock(self._prev)\n var out = pad[0] ^ byteParam\n\n self._prev = Buffer.concat([\n self._prev.slice(1),\n Buffer.from([decrypt ? byteParam : out])\n ])\n\n return out\n}\n\nexports.encrypt = function (self, chunk, decrypt) {\n var len = chunk.length\n var out = Buffer.allocUnsafe(len)\n var i = -1\n\n while (++i < len) {\n out[i] = encryptByte(self, chunk[i], decrypt)\n }\n\n return out\n}\n", - "var xor = require('buffer-xor')\nvar Buffer = require('safe-buffer').Buffer\nvar incr32 = require('../incr32')\n\nfunction getBlock (self) {\n var out = self._cipher.encryptBlockRaw(self._prev)\n incr32(self._prev)\n return out\n}\n\nvar blockSize = 16\nexports.encrypt = function (self, chunk) {\n var chunkNum = Math.ceil(chunk.length / blockSize)\n var start = self._cache.length\n self._cache = Buffer.concat([\n self._cache,\n Buffer.allocUnsafe(chunkNum * blockSize)\n ])\n for (var i = 0; i < chunkNum; i++) {\n var out = getBlock(self)\n var offset = start + i * blockSize\n self._cache.writeUInt32BE(out[0], offset + 0)\n self._cache.writeUInt32BE(out[1], offset + 4)\n self._cache.writeUInt32BE(out[2], offset + 8)\n self._cache.writeUInt32BE(out[3], offset + 12)\n }\n var pad = self._cache.slice(0, chunk.length)\n self._cache = self._cache.slice(chunk.length)\n return xor(chunk, pad)\n}\n", - "exports.encrypt = function (self, block) {\n return self._cipher.encryptBlock(block)\n}\n\nexports.decrypt = function (self, block) {\n return self._cipher.decryptBlock(block)\n}\n", - "var modeModules = {\n ECB: require('./ecb'),\n CBC: require('./cbc'),\n CFB: require('./cfb'),\n CFB8: require('./cfb8'),\n CFB1: require('./cfb1'),\n OFB: require('./ofb'),\n CTR: require('./ctr'),\n GCM: require('./ctr')\n}\n\nvar modes = require('./list.json')\n\nfor (var key in modes) {\n modes[key].module = modeModules[modes[key].mode]\n}\n\nmodule.exports = modes\n", - "module.exports={\n \"aes-128-ecb\": {\n \"cipher\": \"AES\",\n \"key\": 128,\n \"iv\": 0,\n \"mode\": \"ECB\",\n \"type\": \"block\"\n },\n \"aes-192-ecb\": {\n \"cipher\": \"AES\",\n \"key\": 192,\n \"iv\": 0,\n \"mode\": \"ECB\",\n \"type\": \"block\"\n },\n \"aes-256-ecb\": {\n \"cipher\": \"AES\",\n \"key\": 256,\n \"iv\": 0,\n \"mode\": \"ECB\",\n \"type\": \"block\"\n },\n \"aes-128-cbc\": {\n \"cipher\": \"AES\",\n \"key\": 128,\n \"iv\": 16,\n \"mode\": \"CBC\",\n \"type\": \"block\"\n },\n \"aes-192-cbc\": {\n \"cipher\": \"AES\",\n \"key\": 192,\n \"iv\": 16,\n \"mode\": \"CBC\",\n \"type\": \"block\"\n },\n \"aes-256-cbc\": {\n \"cipher\": \"AES\",\n \"key\": 256,\n \"iv\": 16,\n \"mode\": \"CBC\",\n \"type\": \"block\"\n },\n \"aes128\": {\n \"cipher\": \"AES\",\n \"key\": 128,\n \"iv\": 16,\n \"mode\": \"CBC\",\n \"type\": \"block\"\n },\n \"aes192\": {\n \"cipher\": \"AES\",\n \"key\": 192,\n \"iv\": 16,\n \"mode\": \"CBC\",\n \"type\": \"block\"\n },\n \"aes256\": {\n \"cipher\": \"AES\",\n \"key\": 256,\n \"iv\": 16,\n \"mode\": \"CBC\",\n \"type\": \"block\"\n },\n \"aes-128-cfb\": {\n \"cipher\": \"AES\",\n \"key\": 128,\n \"iv\": 16,\n \"mode\": \"CFB\",\n \"type\": \"stream\"\n },\n \"aes-192-cfb\": {\n \"cipher\": \"AES\",\n \"key\": 192,\n \"iv\": 16,\n \"mode\": \"CFB\",\n \"type\": \"stream\"\n },\n \"aes-256-cfb\": {\n \"cipher\": \"AES\",\n \"key\": 256,\n \"iv\": 16,\n \"mode\": \"CFB\",\n \"type\": \"stream\"\n },\n \"aes-128-cfb8\": {\n \"cipher\": \"AES\",\n \"key\": 128,\n \"iv\": 16,\n \"mode\": \"CFB8\",\n \"type\": \"stream\"\n },\n \"aes-192-cfb8\": {\n \"cipher\": \"AES\",\n \"key\": 192,\n \"iv\": 16,\n \"mode\": \"CFB8\",\n \"type\": \"stream\"\n },\n \"aes-256-cfb8\": {\n \"cipher\": \"AES\",\n \"key\": 256,\n \"iv\": 16,\n \"mode\": \"CFB8\",\n \"type\": \"stream\"\n },\n \"aes-128-cfb1\": {\n \"cipher\": \"AES\",\n \"key\": 128,\n \"iv\": 16,\n \"mode\": \"CFB1\",\n \"type\": \"stream\"\n },\n \"aes-192-cfb1\": {\n \"cipher\": \"AES\",\n \"key\": 192,\n \"iv\": 16,\n \"mode\": \"CFB1\",\n \"type\": \"stream\"\n },\n \"aes-256-cfb1\": {\n \"cipher\": \"AES\",\n \"key\": 256,\n \"iv\": 16,\n \"mode\": \"CFB1\",\n \"type\": \"stream\"\n },\n \"aes-128-ofb\": {\n \"cipher\": \"AES\",\n \"key\": 128,\n \"iv\": 16,\n \"mode\": \"OFB\",\n \"type\": \"stream\"\n },\n \"aes-192-ofb\": {\n \"cipher\": \"AES\",\n \"key\": 192,\n \"iv\": 16,\n \"mode\": \"OFB\",\n \"type\": \"stream\"\n },\n \"aes-256-ofb\": {\n \"cipher\": \"AES\",\n \"key\": 256,\n \"iv\": 16,\n \"mode\": \"OFB\",\n \"type\": \"stream\"\n },\n \"aes-128-ctr\": {\n \"cipher\": \"AES\",\n \"key\": 128,\n \"iv\": 16,\n \"mode\": \"CTR\",\n \"type\": \"stream\"\n },\n \"aes-192-ctr\": {\n \"cipher\": \"AES\",\n \"key\": 192,\n \"iv\": 16,\n \"mode\": \"CTR\",\n \"type\": \"stream\"\n },\n \"aes-256-ctr\": {\n \"cipher\": \"AES\",\n \"key\": 256,\n \"iv\": 16,\n \"mode\": \"CTR\",\n \"type\": \"stream\"\n },\n \"aes-128-gcm\": {\n \"cipher\": \"AES\",\n \"key\": 128,\n \"iv\": 12,\n \"mode\": \"GCM\",\n \"type\": \"auth\"\n },\n \"aes-192-gcm\": {\n \"cipher\": \"AES\",\n \"key\": 192,\n \"iv\": 12,\n \"mode\": \"GCM\",\n \"type\": \"auth\"\n },\n \"aes-256-gcm\": {\n \"cipher\": \"AES\",\n \"key\": 256,\n \"iv\": 12,\n \"mode\": \"GCM\",\n \"type\": \"auth\"\n }\n}\n", - "var xor = require('buffer-xor')\n\nfunction getBlock (self) {\n self._prev = self._cipher.encryptBlock(self._prev)\n return self._prev\n}\n\nexports.encrypt = function (self, chunk) {\n while (self._cache.length < chunk.length) {\n self._cache = Buffer.concat([self._cache, getBlock(self)])\n }\n\n var pad = self._cache.slice(0, chunk.length)\n self._cache = self._cache.slice(chunk.length)\n return xor(chunk, pad)\n}\n", - "var aes = require('./aes')\nvar Buffer = require('safe-buffer').Buffer\nvar Transform = require('cipher-base')\nvar inherits = require('inherits')\n\nfunction StreamCipher (mode, key, iv, decrypt) {\n Transform.call(this)\n\n this._cipher = new aes.AES(key)\n this._prev = Buffer.from(iv)\n this._cache = Buffer.allocUnsafe(0)\n this._secCache = Buffer.allocUnsafe(0)\n this._decrypt = decrypt\n this._mode = mode\n}\n\ninherits(StreamCipher, Transform)\n\nStreamCipher.prototype._update = function (chunk) {\n return this._mode.encrypt(this, chunk, this._decrypt)\n}\n\nStreamCipher.prototype._final = function () {\n this._cipher.scrub()\n}\n\nmodule.exports = StreamCipher\n", - "var DES = require('browserify-des')\nvar aes = require('browserify-aes/browser')\nvar aesModes = require('browserify-aes/modes')\nvar desModes = require('browserify-des/modes')\nvar ebtk = require('evp_bytestokey')\n\nfunction createCipher (suite, password) {\n suite = suite.toLowerCase()\n\n var keyLen, ivLen\n if (aesModes[suite]) {\n keyLen = aesModes[suite].key\n ivLen = aesModes[suite].iv\n } else if (desModes[suite]) {\n keyLen = desModes[suite].key * 8\n ivLen = desModes[suite].iv\n } else {\n throw new TypeError('invalid suite type')\n }\n\n var keys = ebtk(password, false, keyLen, ivLen)\n return createCipheriv(suite, keys.key, keys.iv)\n}\n\nfunction createDecipher (suite, password) {\n suite = suite.toLowerCase()\n\n var keyLen, ivLen\n if (aesModes[suite]) {\n keyLen = aesModes[suite].key\n ivLen = aesModes[suite].iv\n } else if (desModes[suite]) {\n keyLen = desModes[suite].key * 8\n ivLen = desModes[suite].iv\n } else {\n throw new TypeError('invalid suite type')\n }\n\n var keys = ebtk(password, false, keyLen, ivLen)\n return createDecipheriv(suite, keys.key, keys.iv)\n}\n\nfunction createCipheriv (suite, key, iv) {\n suite = suite.toLowerCase()\n if (aesModes[suite]) return aes.createCipheriv(suite, key, iv)\n if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite })\n\n throw new TypeError('invalid suite type')\n}\n\nfunction createDecipheriv (suite, key, iv) {\n suite = suite.toLowerCase()\n if (aesModes[suite]) return aes.createDecipheriv(suite, key, iv)\n if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite, decrypt: true })\n\n throw new TypeError('invalid suite type')\n}\n\nfunction getCiphers () {\n return Object.keys(desModes).concat(aes.getCiphers())\n}\n\nexports.createCipher = exports.Cipher = createCipher\nexports.createCipheriv = exports.Cipheriv = createCipheriv\nexports.createDecipher = exports.Decipher = createDecipher\nexports.createDecipheriv = exports.Decipheriv = createDecipheriv\nexports.listCiphers = exports.getCiphers = getCiphers\n", - "var CipherBase = require('cipher-base')\nvar des = require('des.js')\nvar inherits = require('inherits')\nvar Buffer = require('safe-buffer').Buffer\n\nvar modes = {\n 'des-ede3-cbc': des.CBC.instantiate(des.EDE),\n 'des-ede3': des.EDE,\n 'des-ede-cbc': des.CBC.instantiate(des.EDE),\n 'des-ede': des.EDE,\n 'des-cbc': des.CBC.instantiate(des.DES),\n 'des-ecb': des.DES\n}\nmodes.des = modes['des-cbc']\nmodes.des3 = modes['des-ede3-cbc']\nmodule.exports = DES\ninherits(DES, CipherBase)\nfunction DES (opts) {\n CipherBase.call(this)\n var modeName = opts.mode.toLowerCase()\n var mode = modes[modeName]\n var type\n if (opts.decrypt) {\n type = 'decrypt'\n } else {\n type = 'encrypt'\n }\n var key = opts.key\n if (!Buffer.isBuffer(key)) {\n key = Buffer.from(key)\n }\n if (modeName === 'des-ede' || modeName === 'des-ede-cbc') {\n key = Buffer.concat([key, key.slice(0, 8)])\n }\n var iv = opts.iv\n if (!Buffer.isBuffer(iv)) {\n iv = Buffer.from(iv)\n }\n this._des = mode.create({\n key: key,\n iv: iv,\n type: type\n })\n}\nDES.prototype._update = function (data) {\n return Buffer.from(this._des.update(data))\n}\nDES.prototype._final = function () {\n return Buffer.from(this._des.final())\n}\n", - "exports['des-ecb'] = {\n key: 8,\n iv: 0\n}\nexports['des-cbc'] = exports.des = {\n key: 8,\n iv: 8\n}\nexports['des-ede3-cbc'] = exports.des3 = {\n key: 24,\n iv: 8\n}\nexports['des-ede3'] = {\n key: 24,\n iv: 0\n}\nexports['des-ede-cbc'] = {\n key: 16,\n iv: 8\n}\nexports['des-ede'] = {\n key: 16,\n iv: 0\n}\n", - "var BN = require('bn.js')\nvar randomBytes = require('randombytes')\n\nfunction blind (priv) {\n var r = getr(priv)\n var blinder = r.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed()\n return { blinder: blinder, unblinder: r.invm(priv.modulus) }\n}\n\nfunction getr (priv) {\n var len = priv.modulus.byteLength()\n var r\n do {\n r = new BN(randomBytes(len))\n } while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2))\n return r\n}\n\nfunction crt (msg, priv) {\n var blinds = blind(priv)\n var len = priv.modulus.byteLength()\n var blinded = new BN(msg).mul(blinds.blinder).umod(priv.modulus)\n var c1 = blinded.toRed(BN.mont(priv.prime1))\n var c2 = blinded.toRed(BN.mont(priv.prime2))\n var qinv = priv.coefficient\n var p = priv.prime1\n var q = priv.prime2\n var m1 = c1.redPow(priv.exponent1).fromRed()\n var m2 = c2.redPow(priv.exponent2).fromRed()\n var h = m1.isub(m2).imul(qinv).umod(p).imul(q)\n return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer, 'be', len)\n}\ncrt.getr = getr\n\nmodule.exports = crt\n", - "(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {\n Buffer = window.Buffer;\n } else {\n Buffer = require('buffer').Buffer;\n }\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n this.negative = 1;\n }\n\n if (start < number.length) {\n if (base === 16) {\n this._parseHex(number, start, endian);\n } else {\n this._parseBase(number, base, start);\n if (endian === 'le') {\n this._initArray(this.toArray(), base, endian);\n }\n }\n }\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [number & 0x3ffffff];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [0];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this._strip();\n };\n\n function parseHex4Bits (string, index) {\n var c = string.charCodeAt(index);\n // '0' - '9'\n if (c >= 48 && c <= 57) {\n return c - 48;\n // 'A' - 'F'\n } else if (c >= 65 && c <= 70) {\n return c - 55;\n // 'a' - 'f'\n } else if (c >= 97 && c <= 102) {\n return c - 87;\n } else {\n assert(false, 'Invalid character in ' + string);\n }\n }\n\n function parseHexByte (string, lowerBound, index) {\n var r = parseHex4Bits(string, index);\n if (index - 1 >= lowerBound) {\n r |= parseHex4Bits(string, index - 1) << 4;\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start, endian) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n // 24-bits chunks\n var off = 0;\n var j = 0;\n\n var w;\n if (endian === 'be') {\n for (i = number.length - 1; i >= start; i -= 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n } else {\n var parseLength = number.length - start;\n for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n }\n\n this._strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var b = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n b = c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n b = c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n b = c;\n }\n assert(c >= 0 && b < mul, 'Invalid character');\n r += b;\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [0];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n this._strip();\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n function move (dest, src) {\n dest.words = src.words;\n dest.length = src.length;\n dest.negative = src.negative;\n dest.red = src.red;\n }\n\n BN.prototype._move = function _move (dest) {\n move(dest, this);\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype._strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n // Check Symbol.for because not everywhere where Symbol defined\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility\n if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') {\n try {\n BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect;\n } catch (e) {\n BN.prototype.inspect = inspect;\n }\n } else {\n BN.prototype.inspect = inspect;\n }\n\n function inspect () {\n return (this.red ? '';\n }\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modrn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16, 2);\n };\n\n if (Buffer) {\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n return this.toArrayLike(Buffer, endian, length);\n };\n }\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n var allocate = function allocate (ArrayType, size) {\n if (ArrayType.allocUnsafe) {\n return ArrayType.allocUnsafe(size);\n }\n return new ArrayType(size);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n this._strip();\n\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n var res = allocate(ArrayType, reqLength);\n var postfix = endian === 'le' ? 'LE' : 'BE';\n this['_toArrayLike' + postfix](res, byteLength);\n return res;\n };\n\n BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) {\n var position = 0;\n var carry = 0;\n\n for (var i = 0, shift = 0; i < this.length; i++) {\n var word = (this.words[i] << shift) | carry;\n\n res[position++] = word & 0xff;\n if (position < res.length) {\n res[position++] = (word >> 8) & 0xff;\n }\n if (position < res.length) {\n res[position++] = (word >> 16) & 0xff;\n }\n\n if (shift === 6) {\n if (position < res.length) {\n res[position++] = (word >> 24) & 0xff;\n }\n carry = 0;\n shift = 0;\n } else {\n carry = word >>> 24;\n shift += 2;\n }\n }\n\n if (position < res.length) {\n res[position++] = carry;\n\n while (position < res.length) {\n res[position++] = 0;\n }\n }\n };\n\n BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) {\n var position = res.length - 1;\n var carry = 0;\n\n for (var i = 0, shift = 0; i < this.length; i++) {\n var word = (this.words[i] << shift) | carry;\n\n res[position--] = word & 0xff;\n if (position >= 0) {\n res[position--] = (word >> 8) & 0xff;\n }\n if (position >= 0) {\n res[position--] = (word >> 16) & 0xff;\n }\n\n if (shift === 6) {\n if (position >= 0) {\n res[position--] = (word >> 24) & 0xff;\n }\n carry = 0;\n shift = 0;\n } else {\n carry = word >>> 24;\n shift += 2;\n }\n }\n\n if (position >= 0) {\n res[position--] = carry;\n\n while (position >= 0) {\n res[position--] = 0;\n }\n }\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] >>> wbit) & 0x01;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this._strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this._strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this._strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this._strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this._strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this._strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out._strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out._strip();\n }\n\n function jumboMulTo (self, num, out) {\n // Temporary disable, see https://github.com/indutny/bn.js/issues/211\n // var fftm = new FFTM();\n // return fftm.mulp(self, num, out);\n return bigMulTo(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out._strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return isNegNum ? this.ineg() : this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this._strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this._strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this._strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) <= num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this._strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this._strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this._strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q._strip();\n }\n a._strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modrn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modrn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modrn = function modrn (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return isNegNum ? -acc : acc;\n };\n\n // WARNING: DEPRECATED\n BN.prototype.modn = function modn (num) {\n return this.modrn(num);\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n var isNegNum = num < 0;\n if (isNegNum) num = -num;\n\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n this._strip();\n return isNegNum ? this.ineg() : this;\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this._strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n if (r.strip !== undefined) {\n // r is a BN v4 instance\n r.strip();\n } else {\n // r is a BN v5 instance\n r._strip();\n }\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n\n move(a, a.umod(this.m)._forceRed(this));\n return a;\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})(typeof module === 'undefined' || module, this);\n", - "module.exports = require('./browser/algorithms.json')\n", - "module.exports={\n \"sha224WithRSAEncryption\": {\n \"sign\": \"rsa\",\n \"hash\": \"sha224\",\n \"id\": \"302d300d06096086480165030402040500041c\"\n },\n \"RSA-SHA224\": {\n \"sign\": \"ecdsa/rsa\",\n \"hash\": \"sha224\",\n \"id\": \"302d300d06096086480165030402040500041c\"\n },\n \"sha256WithRSAEncryption\": {\n \"sign\": \"rsa\",\n \"hash\": \"sha256\",\n \"id\": \"3031300d060960864801650304020105000420\"\n },\n \"RSA-SHA256\": {\n \"sign\": \"ecdsa/rsa\",\n \"hash\": \"sha256\",\n \"id\": \"3031300d060960864801650304020105000420\"\n },\n \"sha384WithRSAEncryption\": {\n \"sign\": \"rsa\",\n \"hash\": \"sha384\",\n \"id\": \"3041300d060960864801650304020205000430\"\n },\n \"RSA-SHA384\": {\n \"sign\": \"ecdsa/rsa\",\n \"hash\": \"sha384\",\n \"id\": \"3041300d060960864801650304020205000430\"\n },\n \"sha512WithRSAEncryption\": {\n \"sign\": \"rsa\",\n \"hash\": \"sha512\",\n \"id\": \"3051300d060960864801650304020305000440\"\n },\n \"RSA-SHA512\": {\n \"sign\": \"ecdsa/rsa\",\n \"hash\": \"sha512\",\n \"id\": \"3051300d060960864801650304020305000440\"\n },\n \"RSA-SHA1\": {\n \"sign\": \"rsa\",\n \"hash\": \"sha1\",\n \"id\": \"3021300906052b0e03021a05000414\"\n },\n \"ecdsa-with-SHA1\": {\n \"sign\": \"ecdsa\",\n \"hash\": \"sha1\",\n \"id\": \"\"\n },\n \"sha256\": {\n \"sign\": \"ecdsa\",\n \"hash\": \"sha256\",\n \"id\": \"\"\n },\n \"sha224\": {\n \"sign\": \"ecdsa\",\n \"hash\": \"sha224\",\n \"id\": \"\"\n },\n \"sha384\": {\n \"sign\": \"ecdsa\",\n \"hash\": \"sha384\",\n \"id\": \"\"\n },\n \"sha512\": {\n \"sign\": \"ecdsa\",\n \"hash\": \"sha512\",\n \"id\": \"\"\n },\n \"DSA-SHA\": {\n \"sign\": \"dsa\",\n \"hash\": \"sha1\",\n \"id\": \"\"\n },\n \"DSA-SHA1\": {\n \"sign\": \"dsa\",\n \"hash\": \"sha1\",\n \"id\": \"\"\n },\n \"DSA\": {\n \"sign\": \"dsa\",\n \"hash\": \"sha1\",\n \"id\": \"\"\n },\n \"DSA-WITH-SHA224\": {\n \"sign\": \"dsa\",\n \"hash\": \"sha224\",\n \"id\": \"\"\n },\n \"DSA-SHA224\": {\n \"sign\": \"dsa\",\n \"hash\": \"sha224\",\n \"id\": \"\"\n },\n \"DSA-WITH-SHA256\": {\n \"sign\": \"dsa\",\n \"hash\": \"sha256\",\n \"id\": \"\"\n },\n \"DSA-SHA256\": {\n \"sign\": \"dsa\",\n \"hash\": \"sha256\",\n \"id\": \"\"\n },\n \"DSA-WITH-SHA384\": {\n \"sign\": \"dsa\",\n \"hash\": \"sha384\",\n \"id\": \"\"\n },\n \"DSA-SHA384\": {\n \"sign\": \"dsa\",\n \"hash\": \"sha384\",\n \"id\": \"\"\n },\n \"DSA-WITH-SHA512\": {\n \"sign\": \"dsa\",\n \"hash\": \"sha512\",\n \"id\": \"\"\n },\n \"DSA-SHA512\": {\n \"sign\": \"dsa\",\n \"hash\": \"sha512\",\n \"id\": \"\"\n },\n \"DSA-RIPEMD160\": {\n \"sign\": \"dsa\",\n \"hash\": \"rmd160\",\n \"id\": \"\"\n },\n \"ripemd160WithRSA\": {\n \"sign\": \"rsa\",\n \"hash\": \"rmd160\",\n \"id\": \"3021300906052b2403020105000414\"\n },\n \"RSA-RIPEMD160\": {\n \"sign\": \"rsa\",\n \"hash\": \"rmd160\",\n \"id\": \"3021300906052b2403020105000414\"\n },\n \"md5WithRSAEncryption\": {\n \"sign\": \"rsa\",\n \"hash\": \"md5\",\n \"id\": \"3020300c06082a864886f70d020505000410\"\n },\n \"RSA-MD5\": {\n \"sign\": \"rsa\",\n \"hash\": \"md5\",\n \"id\": \"3020300c06082a864886f70d020505000410\"\n }\n}\n", - "module.exports={\n \"1.3.132.0.10\": \"secp256k1\",\n \"1.3.132.0.33\": \"p224\",\n \"1.2.840.10045.3.1.1\": \"p192\",\n \"1.2.840.10045.3.1.7\": \"p256\",\n \"1.3.132.0.34\": \"p384\",\n \"1.3.132.0.35\": \"p521\"\n}\n", - "var Buffer = require('safe-buffer').Buffer\nvar createHash = require('create-hash')\nvar stream = require('readable-stream')\nvar inherits = require('inherits')\nvar sign = require('./sign')\nvar verify = require('./verify')\n\nvar algorithms = require('./algorithms.json')\nObject.keys(algorithms).forEach(function (key) {\n algorithms[key].id = Buffer.from(algorithms[key].id, 'hex')\n algorithms[key.toLowerCase()] = algorithms[key]\n})\n\nfunction Sign (algorithm) {\n stream.Writable.call(this)\n\n var data = algorithms[algorithm]\n if (!data) throw new Error('Unknown message digest')\n\n this._hashType = data.hash\n this._hash = createHash(data.hash)\n this._tag = data.id\n this._signType = data.sign\n}\ninherits(Sign, stream.Writable)\n\nSign.prototype._write = function _write (data, _, done) {\n this._hash.update(data)\n done()\n}\n\nSign.prototype.update = function update (data, enc) {\n if (typeof data === 'string') data = Buffer.from(data, enc)\n\n this._hash.update(data)\n return this\n}\n\nSign.prototype.sign = function signMethod (key, enc) {\n this.end()\n var hash = this._hash.digest()\n var sig = sign(hash, key, this._hashType, this._signType, this._tag)\n\n return enc ? sig.toString(enc) : sig\n}\n\nfunction Verify (algorithm) {\n stream.Writable.call(this)\n\n var data = algorithms[algorithm]\n if (!data) throw new Error('Unknown message digest')\n\n this._hash = createHash(data.hash)\n this._tag = data.id\n this._signType = data.sign\n}\ninherits(Verify, stream.Writable)\n\nVerify.prototype._write = function _write (data, _, done) {\n this._hash.update(data)\n done()\n}\n\nVerify.prototype.update = function update (data, enc) {\n if (typeof data === 'string') data = Buffer.from(data, enc)\n\n this._hash.update(data)\n return this\n}\n\nVerify.prototype.verify = function verifyMethod (key, sig, enc) {\n if (typeof sig === 'string') sig = Buffer.from(sig, enc)\n\n this.end()\n var hash = this._hash.digest()\n return verify(sig, hash, key, this._signType, this._tag)\n}\n\nfunction createSign (algorithm) {\n return new Sign(algorithm)\n}\n\nfunction createVerify (algorithm) {\n return new Verify(algorithm)\n}\n\nmodule.exports = {\n Sign: createSign,\n Verify: createVerify,\n createSign: createSign,\n createVerify: createVerify\n}\n", - "// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js\nvar Buffer = require('safe-buffer').Buffer\nvar createHmac = require('create-hmac')\nvar crt = require('browserify-rsa')\nvar EC = require('elliptic').ec\nvar BN = require('bn.js')\nvar parseKeys = require('parse-asn1')\nvar curves = require('./curves.json')\n\nfunction sign (hash, key, hashType, signType, tag) {\n var priv = parseKeys(key)\n if (priv.curve) {\n // rsa keys can be interpreted as ecdsa ones in openssl\n if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')\n return ecSign(hash, priv)\n } else if (priv.type === 'dsa') {\n if (signType !== 'dsa') throw new Error('wrong private key type')\n return dsaSign(hash, priv, hashType)\n } else {\n if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')\n }\n hash = Buffer.concat([tag, hash])\n var len = priv.modulus.byteLength()\n var pad = [0, 1]\n while (hash.length + pad.length + 1 < len) pad.push(0xff)\n pad.push(0x00)\n var i = -1\n while (++i < hash.length) pad.push(hash[i])\n\n var out = crt(pad, priv)\n return out\n}\n\nfunction ecSign (hash, priv) {\n var curveId = curves[priv.curve.join('.')]\n if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.'))\n\n var curve = new EC(curveId)\n var key = curve.keyFromPrivate(priv.privateKey)\n var out = key.sign(hash)\n\n return Buffer.from(out.toDER())\n}\n\nfunction dsaSign (hash, priv, algo) {\n var x = priv.params.priv_key\n var p = priv.params.p\n var q = priv.params.q\n var g = priv.params.g\n var r = new BN(0)\n var k\n var H = bits2int(hash, q).mod(q)\n var s = false\n var kv = getKey(x, q, hash, algo)\n while (s === false) {\n k = makeKey(q, kv, algo)\n r = makeR(g, k, p, q)\n s = k.invm(q).imul(H.add(x.mul(r))).mod(q)\n if (s.cmpn(0) === 0) {\n s = false\n r = new BN(0)\n }\n }\n return toDER(r, s)\n}\n\nfunction toDER (r, s) {\n r = r.toArray()\n s = s.toArray()\n\n // Pad values\n if (r[0] & 0x80) r = [0].concat(r)\n if (s[0] & 0x80) s = [0].concat(s)\n\n var total = r.length + s.length + 4\n var res = [0x30, total, 0x02, r.length]\n res = res.concat(r, [0x02, s.length], s)\n return Buffer.from(res)\n}\n\nfunction getKey (x, q, hash, algo) {\n x = Buffer.from(x.toArray())\n if (x.length < q.byteLength()) {\n var zeros = Buffer.alloc(q.byteLength() - x.length)\n x = Buffer.concat([zeros, x])\n }\n var hlen = hash.length\n var hbits = bits2octets(hash, q)\n var v = Buffer.alloc(hlen)\n v.fill(1)\n var k = Buffer.alloc(hlen)\n k = createHmac(algo, k).update(v).update(Buffer.from([0])).update(x).update(hbits).digest()\n v = createHmac(algo, k).update(v).digest()\n k = createHmac(algo, k).update(v).update(Buffer.from([1])).update(x).update(hbits).digest()\n v = createHmac(algo, k).update(v).digest()\n return { k: k, v: v }\n}\n\nfunction bits2int (obits, q) {\n var bits = new BN(obits)\n var shift = (obits.length << 3) - q.bitLength()\n if (shift > 0) bits.ishrn(shift)\n return bits\n}\n\nfunction bits2octets (bits, q) {\n bits = bits2int(bits, q)\n bits = bits.mod(q)\n var out = Buffer.from(bits.toArray())\n if (out.length < q.byteLength()) {\n var zeros = Buffer.alloc(q.byteLength() - out.length)\n out = Buffer.concat([zeros, out])\n }\n return out\n}\n\nfunction makeKey (q, kv, algo) {\n var t\n var k\n\n do {\n t = Buffer.alloc(0)\n\n while (t.length * 8 < q.bitLength()) {\n kv.v = createHmac(algo, kv.k).update(kv.v).digest()\n t = Buffer.concat([t, kv.v])\n }\n\n k = bits2int(t, q)\n kv.k = createHmac(algo, kv.k).update(kv.v).update(Buffer.from([0])).digest()\n kv.v = createHmac(algo, kv.k).update(kv.v).digest()\n } while (k.cmp(q) !== -1)\n\n return k\n}\n\nfunction makeR (g, k, p, q) {\n return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q)\n}\n\nmodule.exports = sign\nmodule.exports.getKey = getKey\nmodule.exports.makeKey = makeKey\n", - "// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js\nvar Buffer = require('safe-buffer').Buffer\nvar BN = require('bn.js')\nvar EC = require('elliptic').ec\nvar parseKeys = require('parse-asn1')\nvar curves = require('./curves.json')\n\nfunction verify (sig, hash, key, signType, tag) {\n var pub = parseKeys(key)\n if (pub.type === 'ec') {\n // rsa keys can be interpreted as ecdsa ones in openssl\n if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')\n return ecVerify(sig, hash, pub)\n } else if (pub.type === 'dsa') {\n if (signType !== 'dsa') throw new Error('wrong public key type')\n return dsaVerify(sig, hash, pub)\n } else {\n if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')\n }\n hash = Buffer.concat([tag, hash])\n var len = pub.modulus.byteLength()\n var pad = [1]\n var padNum = 0\n while (hash.length + pad.length + 2 < len) {\n pad.push(0xff)\n padNum++\n }\n pad.push(0x00)\n var i = -1\n while (++i < hash.length) {\n pad.push(hash[i])\n }\n pad = Buffer.from(pad)\n var red = BN.mont(pub.modulus)\n sig = new BN(sig).toRed(red)\n\n sig = sig.redPow(new BN(pub.publicExponent))\n sig = Buffer.from(sig.fromRed().toArray())\n var out = padNum < 8 ? 1 : 0\n len = Math.min(sig.length, pad.length)\n if (sig.length !== pad.length) out = 1\n\n i = -1\n while (++i < len) out |= sig[i] ^ pad[i]\n return out === 0\n}\n\nfunction ecVerify (sig, hash, pub) {\n var curveId = curves[pub.data.algorithm.curve.join('.')]\n if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.'))\n\n var curve = new EC(curveId)\n var pubkey = pub.data.subjectPrivateKey.data\n\n return curve.verify(hash, sig, pubkey)\n}\n\nfunction dsaVerify (sig, hash, pub) {\n var p = pub.data.p\n var q = pub.data.q\n var g = pub.data.g\n var y = pub.data.pub_key\n var unpacked = parseKeys.signature.decode(sig, 'der')\n var s = unpacked.s\n var r = unpacked.r\n checkValue(s, q)\n checkValue(r, q)\n var montp = BN.mont(p)\n var w = s.invm(q)\n var v = g.toRed(montp)\n .redPow(new BN(hash).mul(w).mod(q))\n .fromRed()\n .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed())\n .mod(p)\n .mod(q)\n return v.cmp(r) === 0\n}\n\nfunction checkValue (b, q) {\n if (b.cmpn(0) <= 0) throw new Error('invalid sig')\n if (b.cmp(q) >= q) throw new Error('invalid sig')\n}\n\nmodule.exports = verify\n", - "'use strict';\n\nfunction _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }\n\nvar codes = {};\n\nfunction createErrorType(code, message, Base) {\n if (!Base) {\n Base = Error;\n }\n\n function getMessage(arg1, arg2, arg3) {\n if (typeof message === 'string') {\n return message;\n } else {\n return message(arg1, arg2, arg3);\n }\n }\n\n var NodeError =\n /*#__PURE__*/\n function (_Base) {\n _inheritsLoose(NodeError, _Base);\n\n function NodeError(arg1, arg2, arg3) {\n return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;\n }\n\n return NodeError;\n }(Base);\n\n NodeError.prototype.name = Base.name;\n NodeError.prototype.code = code;\n codes[code] = NodeError;\n} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js\n\n\nfunction oneOf(expected, thing) {\n if (Array.isArray(expected)) {\n var len = expected.length;\n expected = expected.map(function (i) {\n return String(i);\n });\n\n if (len > 2) {\n return \"one of \".concat(thing, \" \").concat(expected.slice(0, len - 1).join(', '), \", or \") + expected[len - 1];\n } else if (len === 2) {\n return \"one of \".concat(thing, \" \").concat(expected[0], \" or \").concat(expected[1]);\n } else {\n return \"of \".concat(thing, \" \").concat(expected[0]);\n }\n } else {\n return \"of \".concat(thing, \" \").concat(String(expected));\n }\n} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith\n\n\nfunction startsWith(str, search, pos) {\n return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;\n} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\n\n\nfunction endsWith(str, search, this_len) {\n if (this_len === undefined || this_len > str.length) {\n this_len = str.length;\n }\n\n return str.substring(this_len - search.length, this_len) === search;\n} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\n\n\nfunction includes(str, search, start) {\n if (typeof start !== 'number') {\n start = 0;\n }\n\n if (start + search.length > str.length) {\n return false;\n } else {\n return str.indexOf(search, start) !== -1;\n }\n}\n\ncreateErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {\n return 'The value \"' + value + '\" is invalid for option \"' + name + '\"';\n}, TypeError);\ncreateErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {\n // determiner: 'must be' or 'must not be'\n var determiner;\n\n if (typeof expected === 'string' && startsWith(expected, 'not ')) {\n determiner = 'must not be';\n expected = expected.replace(/^not /, '');\n } else {\n determiner = 'must be';\n }\n\n var msg;\n\n if (endsWith(name, ' argument')) {\n // For cases like 'first argument'\n msg = \"The \".concat(name, \" \").concat(determiner, \" \").concat(oneOf(expected, 'type'));\n } else {\n var type = includes(name, '.') ? 'property' : 'argument';\n msg = \"The \\\"\".concat(name, \"\\\" \").concat(type, \" \").concat(determiner, \" \").concat(oneOf(expected, 'type'));\n }\n\n msg += \". Received type \".concat(typeof actual);\n return msg;\n}, TypeError);\ncreateErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');\ncreateErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {\n return 'The ' + name + ' method is not implemented';\n});\ncreateErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');\ncreateErrorType('ERR_STREAM_DESTROYED', function (name) {\n return 'Cannot call ' + name + ' after a stream was destroyed';\n});\ncreateErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');\ncreateErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');\ncreateErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');\ncreateErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);\ncreateErrorType('ERR_UNKNOWN_ENCODING', function (arg) {\n return 'Unknown encoding: ' + arg;\n}, TypeError);\ncreateErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');\nmodule.exports.codes = codes;\n", - "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n'use strict';\n/**/\n\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n\n for (var key in obj) {\n keys.push(key);\n }\n\n return keys;\n};\n/**/\n\n\nmodule.exports = Duplex;\n\nvar Readable = require('./_stream_readable');\n\nvar Writable = require('./_stream_writable');\n\nrequire('inherits')(Duplex, Readable);\n\n{\n // Allow the keys array to be GC'ed.\n var keys = objectKeys(Writable.prototype);\n\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n Readable.call(this, options);\n Writable.call(this, options);\n this.allowHalfOpen = true;\n\n if (options) {\n if (options.readable === false) this.readable = false;\n if (options.writable === false) this.writable = false;\n\n if (options.allowHalfOpen === false) {\n this.allowHalfOpen = false;\n this.once('end', onend);\n }\n }\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n}); // the no-half-open enforcer\n\nfunction onend() {\n // If the writable side ended, then we're ok.\n if (this._writableState.ended) return; // no more data can be written.\n // But allow more writes to happen in this tick.\n\n process.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});", - "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\nrequire('inherits')(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};", - "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n'use strict';\n\nmodule.exports = Readable;\n/**/\n\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n/**/\n\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function EElistenerCount(emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\n\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n/**/\n\n\nvar debugUtil = require('util');\n\nvar debug;\n\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function debug() {};\n}\n/**/\n\n\nvar BufferList = require('./internal/streams/buffer_list');\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.\n\n\nvar StringDecoder;\nvar createReadableStreamAsyncIterator;\nvar from;\n\nrequire('inherits')(Readable, Stream);\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n\n this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n\n this.sync = true; // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n this.paused = true; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')\n\n this.autoDestroy = !!options.autoDestroy; // has it been destroyed\n\n this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s\n\n this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled\n\n this.readingMore = false;\n this.decoder = null;\n this.encoding = null;\n\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside\n // the ReadableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n this._readableState = new ReadableState(options, this, isDuplex); // legacy\n\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n }\n});\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\n\nReadable.prototype._destroy = function (err, cb) {\n cb(err);\n}; // Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\n\n\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n}; // Unshift should *always* be something directly out of read()\n\n\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n debug('readableAddChunk', chunk);\n var state = stream._readableState;\n\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n\n if (er) {\n errorOrDestroy(stream, er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());\n } else if (state.destroyed) {\n return false;\n } else {\n state.reading = false;\n\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n maybeReadMore(stream, state);\n }\n } // We can push more data if we are below the highWaterMark.\n // Also, if we have no data yet, we can stand some more bytes.\n // This is to work around cases where hwm=0, such as the repl.\n\n\n return !state.ended && (state.length < state.highWaterMark || state.length === 0);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n state.awaitDrain = 0;\n stream.emit('data', chunk);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n if (state.needReadable) emitReadable(stream);\n }\n\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);\n }\n\n return er;\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n}; // backwards compatibility.\n\n\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n var decoder = new StringDecoder(enc);\n this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8\n\n this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:\n\n var p = this._readableState.buffer.head;\n var content = '';\n\n while (p !== null) {\n content += decoder.write(p.data);\n p = p.next;\n }\n\n this._readableState.buffer.clear();\n\n if (content !== '') this._readableState.buffer.push(content);\n this._readableState.length = content.length;\n return this;\n}; // Don't raise the hwm > 1GB\n\n\nvar MAX_HWM = 0x40000000;\n\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n\n return n;\n} // This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\n\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n } // If we're asking for more than the current hwm, then raise the hwm.\n\n\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n; // Don't have enough\n\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n\n return state.length;\n} // you can override either this method, or the async _read(n) below.\n\n\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n\n if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.\n\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n } // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n // if we need a readable event, then we need to do some reading.\n\n\n var doRead = state.needReadable;\n debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some\n\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n } // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n\n\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true; // if the length is currently zero, then we *need* a readable event.\n\n if (state.length === 0) state.needReadable = true; // call internal read method\n\n this._read(state.highWaterMark);\n\n state.sync = false; // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = state.length <= state.highWaterMark;\n n = 0;\n } else {\n state.length -= n;\n state.awaitDrain = 0;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.\n\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n debug('onEofChunk');\n if (state.ended) return;\n\n if (state.decoder) {\n var chunk = state.decoder.end();\n\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n\n state.ended = true;\n\n if (state.sync) {\n // if we are sync, wait until next tick to emit the data.\n // Otherwise we risk emitting data in the flow()\n // the readable code triggers during a read() call\n emitReadable(stream);\n } else {\n // emit 'readable' now to make sure it gets picked up.\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n state.emittedReadable = true;\n emitReadable_(stream);\n }\n }\n} // Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\n\n\nfunction emitReadable(stream) {\n var state = stream._readableState;\n debug('emitReadable', state.needReadable, state.emittedReadable);\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n process.nextTick(emitReadable_, stream);\n }\n}\n\nfunction emitReadable_(stream) {\n var state = stream._readableState;\n debug('emitReadable_', state.destroyed, state.length, state.ended);\n\n if (!state.destroyed && (state.length || state.ended)) {\n stream.emit('readable');\n state.emittedReadable = false;\n } // The stream needs another readable event if\n // 1. It is not flowing, as the flow mechanism will take\n // care of it.\n // 2. It is not ended.\n // 3. It is below the highWaterMark, so we can schedule\n // another readable later.\n\n\n state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;\n flow(stream);\n} // at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\n\n\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n process.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n // Attempt to read more data if we should.\n //\n // The conditions for reading more data are (one of):\n // - Not enough data buffered (state.length < state.highWaterMark). The loop\n // is responsible for filling the buffer with enough data if such data\n // is available. If highWaterMark is 0 and we are not in the flowing mode\n // we should _not_ attempt to buffer any extra data. We'll get more data\n // when the stream consumer calls read() instead.\n // - No data in the buffer, and the stream is in flowing mode. In this mode\n // the loop below is responsible for ensuring read() is called. Failing to\n // call read here would abort the flow and there's no other mechanism for\n // continuing the flow if the stream consumer has just subscribed to the\n // 'data' event.\n //\n // In addition to the above conditions to keep reading data, the following\n // conditions prevent the data from being read:\n // - The stream has ended (state.ended).\n // - There is already a pending 'read' operation (state.reading). This is a\n // case where the the stream has called the implementation defined _read()\n // method, but they are processing the call asynchronously and have _not_\n // called push() with new data. In this case we skip performing more\n // read()s. The execution ends in this method again after the _read() ends\n // up calling push() with more data.\n while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {\n var len = state.length;\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length) // didn't get any data, stop spinning.\n break;\n }\n\n state.readingMore = false;\n} // abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\n\n\nReadable.prototype._read = function (n) {\n errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n\n default:\n state.pipes.push(dest);\n break;\n }\n\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);\n dest.on('unpipe', onunpipe);\n\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n } // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n\n\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n var cleanedUp = false;\n\n function cleanup() {\n debug('cleanup'); // cleanup event handlers once the pipe is broken\n\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n cleanedUp = true; // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n src.on('data', ondata);\n\n function ondata(chunk) {\n debug('ondata');\n var ret = dest.write(chunk);\n debug('dest.write', ret);\n\n if (ret === false) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n }\n\n src.pause();\n }\n } // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n\n\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);\n } // Make sure our error handler is attached before userland ones.\n\n\n prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.\n\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n\n dest.once('close', onclose);\n\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n } // tell the dest that it's being piped to\n\n\n dest.emit('pipe', src); // start the flow if it hasn't been started already.\n\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function pipeOnDrainFunctionResult() {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = {\n hasUnpiped: false\n }; // if we're not piping anywhere, then do nothing.\n\n if (state.pipesCount === 0) return this; // just one destination. most common case.\n\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n if (!dest) dest = state.pipes; // got a match.\n\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n } // slow case. multiple pipe destinations.\n\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, {\n hasUnpiped: false\n });\n }\n\n return this;\n } // try to find the right one.\n\n\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n dest.emit('unpipe', this, unpipeInfo);\n return this;\n}; // set up data events if they are asked for\n// Ensure readable listeners eventually get something\n\n\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n var state = this._readableState;\n\n if (ev === 'data') {\n // update readableListening so that resume() may be a no-op\n // a few lines down. This is needed to support once('readable').\n state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused\n\n if (state.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.flowing = false;\n state.emittedReadable = false;\n debug('on readable', state.length, state.reading);\n\n if (state.length) {\n emitReadable(this);\n } else if (!state.reading) {\n process.nextTick(nReadingNextTick, this);\n }\n }\n }\n\n return res;\n};\n\nReadable.prototype.addListener = Readable.prototype.on;\n\nReadable.prototype.removeListener = function (ev, fn) {\n var res = Stream.prototype.removeListener.call(this, ev, fn);\n\n if (ev === 'readable') {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nReadable.prototype.removeAllListeners = function (ev) {\n var res = Stream.prototype.removeAllListeners.apply(this, arguments);\n\n if (ev === 'readable' || ev === undefined) {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nfunction updateReadableListening(self) {\n var state = self._readableState;\n state.readableListening = self.listenerCount('readable') > 0;\n\n if (state.resumeScheduled && !state.paused) {\n // flowing needs to be set to true now, otherwise\n // the upcoming resume will not flow.\n state.flowing = true; // crude way to check if we should resume\n } else if (self.listenerCount('data') > 0) {\n self.resume();\n }\n}\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n} // pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\n\n\nReadable.prototype.resume = function () {\n var state = this._readableState;\n\n if (!state.flowing) {\n debug('resume'); // we flow only if there is no one listening\n // for readable, but we still have to call\n // resume()\n\n state.flowing = !state.readableListening;\n resume(this, state);\n }\n\n state.paused = false;\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n process.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n debug('resume', state.reading);\n\n if (!state.reading) {\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n\n if (this._readableState.flowing !== false) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n\n this._readableState.paused = true;\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n\n while (state.flowing && stream.read() !== null) {\n ;\n }\n} // wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\n\n\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n stream.on('end', function () {\n debug('wrapped end');\n\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode\n\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n\n if (!ret) {\n paused = true;\n stream.pause();\n }\n }); // proxy all the other methods.\n // important when wrapping filters and duplexes.\n\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function methodWrap(method) {\n return function methodWrapReturnFunction() {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n } // proxy certain important events.\n\n\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n } // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n\n\n this._read = function (n) {\n debug('wrapped _read', n);\n\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nif (typeof Symbol === 'function') {\n Readable.prototype[Symbol.asyncIterator] = function () {\n if (createReadableStreamAsyncIterator === undefined) {\n createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');\n }\n\n return createReadableStreamAsyncIterator(this);\n };\n}\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.highWaterMark;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState && this._readableState.buffer;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableFlowing', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.flowing;\n },\n set: function set(state) {\n if (this._readableState) {\n this._readableState.flowing = state;\n }\n }\n}); // exposed for testing purposes only.\n\nReadable._fromList = fromList;\nObject.defineProperty(Readable.prototype, 'readableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.length;\n }\n}); // Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = state.buffer.consume(n, state.decoder);\n }\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n debug('endReadable', state.endEmitted);\n\n if (!state.endEmitted) {\n state.ended = true;\n process.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.\n\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the writable side is ready for autoDestroy as well\n var wState = stream._writableState;\n\n if (!wState || wState.autoDestroy && wState.finished) {\n stream.destroy();\n }\n }\n }\n}\n\nif (typeof Symbol === 'function') {\n Readable.from = function (iterable, opts) {\n if (from === undefined) {\n from = require('./internal/streams/from');\n }\n\n return from(Readable, iterable, opts);\n };\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n\n return -1;\n}", - "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n'use strict';\n\nmodule.exports = Transform;\n\nvar _require$codes = require('../errors').codes,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,\n ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;\n\nvar Duplex = require('./_stream_duplex');\n\nrequire('inherits')(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n var cb = ts.writecb;\n\n if (cb === null) {\n return this.emit('error', new ERR_MULTIPLE_CALLBACK());\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n cb(er);\n var rs = this._readableState;\n rs.reading = false;\n\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n Duplex.call(this, options);\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n }; // start out asking for a readable event once data is transformed.\n\n this._readableState.needReadable = true; // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n if (typeof options.flush === 'function') this._flush = options.flush;\n } // When the writable side finishes, then flush out anything remaining.\n\n\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function' && !this._readableState.destroyed) {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n}; // This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\n\n\nTransform.prototype._transform = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n}; // Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\n\n\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && !ts.transforming) {\n ts.transforming = true;\n\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data); // TODO(BridgeAR): Write a test for these two error cases\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n\n if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();\n if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();\n return stream.push(null);\n}", - "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n'use strict';\n\nmodule.exports = Writable;\n/* */\n\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n} // It seems a linked list but it is not\n// there will be only 2 of these for each stream\n\n\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\n\n\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n/**/\n\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/**/\n\n/**/\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,\n ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,\n ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,\n ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\n\nrequire('inherits')(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream,\n // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n\n this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called\n\n this.finalCalled = false; // drain event flag.\n\n this.needDrain = false; // at the start of calling end()\n\n this.ending = false; // when end() has been called, and returned\n\n this.ended = false; // when 'finish' is emitted\n\n this.finished = false; // has it been destroyed\n\n this.destroyed = false; // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n\n this.length = 0; // a flag to see when we're in the middle of a write.\n\n this.writing = false; // when true all writes will be buffered until .uncork() call\n\n this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n\n this.sync = true; // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n\n this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)\n\n this.onwrite = function (er) {\n onwrite(stream, er);\n }; // the callback that the user supplies to write(chunk,encoding,cb)\n\n\n this.writecb = null; // the amount that is being written when _write is called.\n\n this.writelen = 0;\n this.bufferedRequest = null;\n this.lastBufferedRequest = null; // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n\n this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n\n this.prefinished = false; // True if the error was already emitted and should not be thrown again\n\n this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')\n\n this.autoDestroy = !!options.autoDestroy; // count buffered requests\n\n this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n\n while (current) {\n out.push(current);\n current = current.next;\n }\n\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function writableStateBufferGetter() {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})(); // Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\n\n\nvar realHasInstance;\n\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function value(object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function realHasInstance(object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the WritableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);\n this._writableState = new WritableState(options, this, isDuplex); // legacy.\n\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n if (typeof options.writev === 'function') this._writev = options.writev;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n} // Otherwise people can pipe Writable streams, which is just wrong.\n\n\nWritable.prototype.pipe = function () {\n errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb\n\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n} // Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\n\n\nfunction validChunk(stream, state, chunk, cb) {\n var er;\n\n if (chunk === null) {\n er = new ERR_STREAM_NULL_VALUES();\n } else if (typeof chunk !== 'string' && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);\n }\n\n if (er) {\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n return false;\n }\n\n return true;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n if (typeof cb !== 'function') cb = nop;\n if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n return ret;\n};\n\nWritable.prototype.cork = function () {\n this._writableState.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n}); // if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\n\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n\n var len = state.objectMode ? 1 : chunk.length;\n state.length += len;\n var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.\n\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n process.nextTick(cb, er); // this can emit finish, and it will always happen\n // after error\n\n process.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er); // this can emit finish, but finish must\n // always follow error\n\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();\n onwriteStateUpdate(state);\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state) || stream.destroyed;\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n process.nextTick(afterWrite, stream, state, finished, cb);\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n} // Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\n\n\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n} // if there's something in the buffer waiting, then process it\n\n\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n var count = 0;\n var allBuffers = true;\n\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n\n buffer.allBuffers = allBuffers;\n doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n\n state.pendingcb++;\n state.lastBufferedRequest = null;\n\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks\n\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n } // ignore unnecessary end() calls.\n\n\n if (!state.ending) endWritable(this, state, cb);\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n});\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\n\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n\n if (err) {\n errorOrDestroy(stream, err);\n }\n\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\n\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function' && !state.destroyed) {\n state.pendingcb++;\n state.finalCalled = true;\n process.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n\n if (need) {\n prefinish(stream, state);\n\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the readable side is ready for autoDestroy as well\n var rState = stream._readableState;\n\n if (!rState || rState.autoDestroy && rState.endEmitted) {\n stream.destroy();\n }\n }\n }\n }\n\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n\n if (cb) {\n if (state.finished) process.nextTick(cb);else stream.once('finish', cb);\n }\n\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n } // reuse the free corkReq.\n\n\n state.corkedRequestsFree.next = corkReq;\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._writableState === undefined) {\n return false;\n }\n\n return this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._writableState.destroyed = value;\n }\n});\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\n\nWritable.prototype._destroy = function (err, cb) {\n cb(err);\n};", - "'use strict';\n\nvar _Object$setPrototypeO;\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar finished = require('./end-of-stream');\n\nvar kLastResolve = Symbol('lastResolve');\nvar kLastReject = Symbol('lastReject');\nvar kError = Symbol('error');\nvar kEnded = Symbol('ended');\nvar kLastPromise = Symbol('lastPromise');\nvar kHandlePromise = Symbol('handlePromise');\nvar kStream = Symbol('stream');\n\nfunction createIterResult(value, done) {\n return {\n value: value,\n done: done\n };\n}\n\nfunction readAndResolve(iter) {\n var resolve = iter[kLastResolve];\n\n if (resolve !== null) {\n var data = iter[kStream].read(); // we defer if data is null\n // we can be expecting either 'end' or\n // 'error'\n\n if (data !== null) {\n iter[kLastPromise] = null;\n iter[kLastResolve] = null;\n iter[kLastReject] = null;\n resolve(createIterResult(data, false));\n }\n }\n}\n\nfunction onReadable(iter) {\n // we wait for the next tick, because it might\n // emit an error with process.nextTick\n process.nextTick(readAndResolve, iter);\n}\n\nfunction wrapForNext(lastPromise, iter) {\n return function (resolve, reject) {\n lastPromise.then(function () {\n if (iter[kEnded]) {\n resolve(createIterResult(undefined, true));\n return;\n }\n\n iter[kHandlePromise](resolve, reject);\n }, reject);\n };\n}\n\nvar AsyncIteratorPrototype = Object.getPrototypeOf(function () {});\nvar ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {\n get stream() {\n return this[kStream];\n },\n\n next: function next() {\n var _this = this;\n\n // if we have detected an error in the meanwhile\n // reject straight away\n var error = this[kError];\n\n if (error !== null) {\n return Promise.reject(error);\n }\n\n if (this[kEnded]) {\n return Promise.resolve(createIterResult(undefined, true));\n }\n\n if (this[kStream].destroyed) {\n // We need to defer via nextTick because if .destroy(err) is\n // called, the error will be emitted via nextTick, and\n // we cannot guarantee that there is no error lingering around\n // waiting to be emitted.\n return new Promise(function (resolve, reject) {\n process.nextTick(function () {\n if (_this[kError]) {\n reject(_this[kError]);\n } else {\n resolve(createIterResult(undefined, true));\n }\n });\n });\n } // if we have multiple next() calls\n // we will wait for the previous Promise to finish\n // this logic is optimized to support for await loops,\n // where next() is only called once at a time\n\n\n var lastPromise = this[kLastPromise];\n var promise;\n\n if (lastPromise) {\n promise = new Promise(wrapForNext(lastPromise, this));\n } else {\n // fast path needed to support multiple this.push()\n // without triggering the next() queue\n var data = this[kStream].read();\n\n if (data !== null) {\n return Promise.resolve(createIterResult(data, false));\n }\n\n promise = new Promise(this[kHandlePromise]);\n }\n\n this[kLastPromise] = promise;\n return promise;\n }\n}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {\n return this;\n}), _defineProperty(_Object$setPrototypeO, \"return\", function _return() {\n var _this2 = this;\n\n // destroy(err, cb) is a private API\n // we can guarantee we have that here, because we control the\n // Readable class this is attached to\n return new Promise(function (resolve, reject) {\n _this2[kStream].destroy(null, function (err) {\n if (err) {\n reject(err);\n return;\n }\n\n resolve(createIterResult(undefined, true));\n });\n });\n}), _Object$setPrototypeO), AsyncIteratorPrototype);\n\nvar createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {\n var _Object$create;\n\n var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {\n value: stream,\n writable: true\n }), _defineProperty(_Object$create, kLastResolve, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kLastReject, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kError, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kEnded, {\n value: stream._readableState.endEmitted,\n writable: true\n }), _defineProperty(_Object$create, kHandlePromise, {\n value: function value(resolve, reject) {\n var data = iterator[kStream].read();\n\n if (data) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(data, false));\n } else {\n iterator[kLastResolve] = resolve;\n iterator[kLastReject] = reject;\n }\n },\n writable: true\n }), _Object$create));\n iterator[kLastPromise] = null;\n finished(stream, function (err) {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise\n // returned by next() and store the error\n\n if (reject !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n reject(err);\n }\n\n iterator[kError] = err;\n return;\n }\n\n var resolve = iterator[kLastResolve];\n\n if (resolve !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(undefined, true));\n }\n\n iterator[kEnded] = true;\n });\n stream.on('readable', onReadable.bind(null, iterator));\n return iterator;\n};\n\nmodule.exports = createReadableStreamAsyncIterator;", - "'use strict';\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nvar _require = require('buffer'),\n Buffer = _require.Buffer;\n\nvar _require2 = require('util'),\n inspect = _require2.inspect;\n\nvar custom = inspect && inspect.custom || 'inspect';\n\nfunction copyBuffer(src, target, offset) {\n Buffer.prototype.copy.call(src, target, offset);\n}\n\nmodule.exports =\n/*#__PURE__*/\nfunction () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n _createClass(BufferList, [{\n key: \"push\",\n value: function push(v) {\n var entry = {\n data: v,\n next: null\n };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n }\n }, {\n key: \"unshift\",\n value: function unshift(v) {\n var entry = {\n data: v,\n next: this.head\n };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n }\n }, {\n key: \"shift\",\n value: function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n }\n }, {\n key: \"clear\",\n value: function clear() {\n this.head = this.tail = null;\n this.length = 0;\n }\n }, {\n key: \"join\",\n value: function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n\n while (p = p.next) {\n ret += s + p.data;\n }\n\n return ret;\n }\n }, {\n key: \"concat\",\n value: function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n\n return ret;\n } // Consumes a specified amount of bytes or characters from the buffered data.\n\n }, {\n key: \"consume\",\n value: function consume(n, hasStrings) {\n var ret;\n\n if (n < this.head.data.length) {\n // `slice` is the same for buffers and strings.\n ret = this.head.data.slice(0, n);\n this.head.data = this.head.data.slice(n);\n } else if (n === this.head.data.length) {\n // First chunk is a perfect match.\n ret = this.shift();\n } else {\n // Result spans more than one buffer.\n ret = hasStrings ? this._getString(n) : this._getBuffer(n);\n }\n\n return ret;\n }\n }, {\n key: \"first\",\n value: function first() {\n return this.head.data;\n } // Consumes a specified amount of characters from the buffered data.\n\n }, {\n key: \"_getString\",\n value: function _getString(n) {\n var p = this.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = str.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Consumes a specified amount of bytes from the buffered data.\n\n }, {\n key: \"_getBuffer\",\n value: function _getBuffer(n) {\n var ret = Buffer.allocUnsafe(n);\n var p = this.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = buf.slice(nb);\n }\n\n break;\n }\n\n ++c;\n }\n\n this.length -= c;\n return ret;\n } // Make sure the linked list only shows the minimal necessary information.\n\n }, {\n key: custom,\n value: function value(_, options) {\n return inspect(this, _objectSpread({}, options, {\n // Only inspect one level.\n depth: 0,\n // It should not recurse.\n customInspect: false\n }));\n }\n }]);\n\n return BufferList;\n}();", - "'use strict'; // undocumented cb() API, needed for core, not for public API\n\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n process.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n process.nextTick(emitErrorNT, this, err);\n }\n }\n\n return this;\n } // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n } // if this is a duplex stream mark the writable part as destroyed as well\n\n\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n } else if (cb) {\n process.nextTick(emitCloseNT, _this);\n cb(err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n });\n\n return this;\n}\n\nfunction emitErrorAndCloseNT(self, err) {\n emitErrorNT(self, err);\n emitCloseNT(self);\n}\n\nfunction emitCloseNT(self) {\n if (self._writableState && !self._writableState.emitClose) return;\n if (self._readableState && !self._readableState.emitClose) return;\n self.emit('close');\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nfunction errorOrDestroy(stream, err) {\n // We have tests that rely on errors being emitted\n // in the same tick, so changing this is semver major.\n // For now when you opt-in to autoDestroy we allow\n // the error to be emitted nextTick. In a future\n // semver major update we should change the default to this.\n var rState = stream._readableState;\n var wState = stream._writableState;\n if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy,\n errorOrDestroy: errorOrDestroy\n};", - "// Ported from https://github.com/mafintosh/end-of-stream with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n callback.apply(this, args);\n };\n}\n\nfunction noop() {}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction eos(stream, opts, callback) {\n if (typeof opts === 'function') return eos(stream, null, opts);\n if (!opts) opts = {};\n callback = once(callback || noop);\n var readable = opts.readable || opts.readable !== false && stream.readable;\n var writable = opts.writable || opts.writable !== false && stream.writable;\n\n var onlegacyfinish = function onlegacyfinish() {\n if (!stream.writable) onfinish();\n };\n\n var writableEnded = stream._writableState && stream._writableState.finished;\n\n var onfinish = function onfinish() {\n writable = false;\n writableEnded = true;\n if (!readable) callback.call(stream);\n };\n\n var readableEnded = stream._readableState && stream._readableState.endEmitted;\n\n var onend = function onend() {\n readable = false;\n readableEnded = true;\n if (!writable) callback.call(stream);\n };\n\n var onerror = function onerror(err) {\n callback.call(stream, err);\n };\n\n var onclose = function onclose() {\n var err;\n\n if (readable && !readableEnded) {\n if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n\n if (writable && !writableEnded) {\n if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n };\n\n var onrequest = function onrequest() {\n stream.req.on('finish', onfinish);\n };\n\n if (isRequest(stream)) {\n stream.on('complete', onfinish);\n stream.on('abort', onclose);\n if (stream.req) onrequest();else stream.on('request', onrequest);\n } else if (writable && !stream._writableState) {\n // legacy streams\n stream.on('end', onlegacyfinish);\n stream.on('close', onlegacyfinish);\n }\n\n stream.on('end', onend);\n stream.on('finish', onfinish);\n if (opts.error !== false) stream.on('error', onerror);\n stream.on('close', onclose);\n return function () {\n stream.removeListener('complete', onfinish);\n stream.removeListener('abort', onclose);\n stream.removeListener('request', onrequest);\n if (stream.req) stream.req.removeListener('finish', onfinish);\n stream.removeListener('end', onlegacyfinish);\n stream.removeListener('close', onlegacyfinish);\n stream.removeListener('finish', onfinish);\n stream.removeListener('end', onend);\n stream.removeListener('error', onerror);\n stream.removeListener('close', onclose);\n };\n}\n\nmodule.exports = eos;", - "module.exports = function () {\n throw new Error('Readable.from is not available in the browser')\n};\n", - "// Ported from https://github.com/mafintosh/pump with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar eos;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n callback.apply(void 0, arguments);\n };\n}\n\nvar _require$codes = require('../../../errors').codes,\n ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;\n\nfunction noop(err) {\n // Rethrow the error if it exists to avoid swallowing it\n if (err) throw err;\n}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction destroyer(stream, reading, writing, callback) {\n callback = once(callback);\n var closed = false;\n stream.on('close', function () {\n closed = true;\n });\n if (eos === undefined) eos = require('./end-of-stream');\n eos(stream, {\n readable: reading,\n writable: writing\n }, function (err) {\n if (err) return callback(err);\n closed = true;\n callback();\n });\n var destroyed = false;\n return function (err) {\n if (closed) return;\n if (destroyed) return;\n destroyed = true; // request.destroy just do .end - .abort is what we want\n\n if (isRequest(stream)) return stream.abort();\n if (typeof stream.destroy === 'function') return stream.destroy();\n callback(err || new ERR_STREAM_DESTROYED('pipe'));\n };\n}\n\nfunction call(fn) {\n fn();\n}\n\nfunction pipe(from, to) {\n return from.pipe(to);\n}\n\nfunction popCallback(streams) {\n if (!streams.length) return noop;\n if (typeof streams[streams.length - 1] !== 'function') return noop;\n return streams.pop();\n}\n\nfunction pipeline() {\n for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {\n streams[_key] = arguments[_key];\n }\n\n var callback = popCallback(streams);\n if (Array.isArray(streams[0])) streams = streams[0];\n\n if (streams.length < 2) {\n throw new ERR_MISSING_ARGS('streams');\n }\n\n var error;\n var destroys = streams.map(function (stream, i) {\n var reading = i < streams.length - 1;\n var writing = i > 0;\n return destroyer(stream, reading, writing, function (err) {\n if (!error) error = err;\n if (err) destroys.forEach(call);\n if (reading) return;\n destroys.forEach(call);\n callback(error);\n });\n });\n return streams.reduce(pipe);\n}\n\nmodule.exports = pipeline;", - "'use strict';\n\nvar ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;\n\nfunction highWaterMarkFrom(options, isDuplex, duplexKey) {\n return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;\n}\n\nfunction getHighWaterMark(state, options, duplexKey, isDuplex) {\n var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);\n\n if (hwm != null) {\n if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {\n var name = isDuplex ? duplexKey : 'highWaterMark';\n throw new ERR_INVALID_OPT_VALUE(name, hwm);\n }\n\n return Math.floor(hwm);\n } // Default value\n\n\n return state.objectMode ? 16 : 16 * 1024;\n}\n\nmodule.exports = {\n getHighWaterMark: getHighWaterMark\n};", - "module.exports = require('events').EventEmitter;\n", - "exports = module.exports = require('./lib/_stream_readable.js');\nexports.Stream = exports;\nexports.Readable = exports;\nexports.Writable = require('./lib/_stream_writable.js');\nexports.Duplex = require('./lib/_stream_duplex.js');\nexports.Transform = require('./lib/_stream_transform.js');\nexports.PassThrough = require('./lib/_stream_passthrough.js');\nexports.finished = require('./lib/internal/streams/end-of-stream.js');\nexports.pipeline = require('./lib/internal/streams/pipeline.js');\n", - "const basex = require('base-x')\nconst ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\nmodule.exports = basex(ALPHABET)\n", - "'use strict'\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\nfunction base (ALPHABET) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256)\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i)\n var xc = x.charCodeAt(0)\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i\n }\n var BASE = ALPHABET.length\n var LEADER = ALPHABET.charAt(0)\n var FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n function encode (source) {\n if (source instanceof Uint8Array) {\n } else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength)\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source)\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0\n var length = 0\n var pbegin = 0\n var pend = source.length\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++\n zeroes++\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n var b58 = new Uint8Array(size)\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin]\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0\n b58[it1] = (carry % BASE) >>> 0\n carry = (carry / BASE) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n pbegin++\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length\n while (it2 !== size && b58[it2] === 0) {\n it2++\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes)\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0\n // Skip and count leading '1's.\n var zeroes = 0\n var length = 0\n while (source[psz] === LEADER) {\n zeroes++\n psz++\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size)\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)]\n // Invalid character\n if (carry === 255) { return }\n var i = 0\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0\n b256[it3] = (carry % 256) >>> 0\n carry = (carry / 256) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n psz++\n }\n // Skip leading zeroes in b256.\n var it4 = size - length\n while (it4 !== size && b256[it4] === 0) {\n it4++\n }\n var vch = new Uint8Array(zeroes + (size - it4))\n var j = zeroes\n while (it4 !== size) {\n vch[j++] = b256[it4++]\n }\n return vch\n }\n function decode (string) {\n var buffer = decodeUnsafe(string)\n if (buffer) { return buffer }\n throw new Error('Non-base' + BASE + ' character')\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nmodule.exports = base\n", - "module.exports = function xor (a, b) {\n var length = Math.min(a.length, b.length)\n var buffer = new Buffer(length)\n\n for (var i = 0; i < length; ++i) {\n buffer[i] = a[i] ^ b[i]\n }\n\n return buffer\n}\n", - "/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nvar K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n var buf = new Uint8Array(length)\n buf.__proto__ = Buffer.prototype\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\n// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\nif (typeof Symbol !== 'undefined' && Symbol.species != null &&\n Buffer[Symbol.species] === Buffer) {\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true,\n enumerable: false,\n writable: false\n })\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayLike(value)\n }\n\n if (value == null) {\n throw TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n var valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n var b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(\n value[Symbol.toPrimitive]('string'), encodingOrOffset, length\n )\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nBuffer.prototype.__proto__ = Uint8Array.prototype\nBuffer.__proto__ = Uint8Array\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n var length = byteLength(string, encoding) | 0\n var buf = createBuffer(length)\n\n var actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n var buf = createBuffer(length)\n for (var i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n var buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n buf.__proto__ = Buffer.prototype\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n var buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n buf = Buffer.from(buf)\n }\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n var len = string.length\n var mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n var strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n newBuf.__proto__ = Buffer.prototype\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (var i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n var len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n", - "'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar callBind = require('./');\n\nvar $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));\n\nmodule.exports = function callBoundIntrinsic(name, allowMissing) {\n\tvar intrinsic = GetIntrinsic(name, !!allowMissing);\n\tif (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {\n\t\treturn callBind(intrinsic);\n\t}\n\treturn intrinsic;\n};\n", - "'use strict';\n\nvar bind = require('function-bind');\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $apply = GetIntrinsic('%Function.prototype.apply%');\nvar $call = GetIntrinsic('%Function.prototype.call%');\nvar $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);\n\nvar $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);\nvar $defineProperty = GetIntrinsic('%Object.defineProperty%', true);\nvar $max = GetIntrinsic('%Math.max%');\n\nif ($defineProperty) {\n\ttry {\n\t\t$defineProperty({}, 'a', { value: 1 });\n\t} catch (e) {\n\t\t// IE 8 has a broken defineProperty\n\t\t$defineProperty = null;\n\t}\n}\n\nmodule.exports = function callBind(originalFunction) {\n\tvar func = $reflectApply(bind, $call, arguments);\n\tif ($gOPD && $defineProperty) {\n\t\tvar desc = $gOPD(func, 'length');\n\t\tif (desc.configurable) {\n\t\t\t// original length, plus the receiver, minus any additional arguments (after the receiver)\n\t\t\t$defineProperty(\n\t\t\t\tfunc,\n\t\t\t\t'length',\n\t\t\t\t{ value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) }\n\t\t\t);\n\t\t}\n\t}\n\treturn func;\n};\n\nvar applyBind = function applyBind() {\n\treturn $reflectApply(bind, $apply, arguments);\n};\n\nif ($defineProperty) {\n\t$defineProperty(module.exports, 'apply', { value: applyBind });\n} else {\n\tmodule.exports.apply = applyBind;\n}\n", - "var Buffer = require('safe-buffer').Buffer\nvar Transform = require('stream').Transform\nvar StringDecoder = require('string_decoder').StringDecoder\nvar inherits = require('inherits')\n\nfunction CipherBase (hashMode) {\n Transform.call(this)\n this.hashMode = typeof hashMode === 'string'\n if (this.hashMode) {\n this[hashMode] = this._finalOrDigest\n } else {\n this.final = this._finalOrDigest\n }\n if (this._final) {\n this.__final = this._final\n this._final = null\n }\n this._decoder = null\n this._encoding = null\n}\ninherits(CipherBase, Transform)\n\nCipherBase.prototype.update = function (data, inputEnc, outputEnc) {\n if (typeof data === 'string') {\n data = Buffer.from(data, inputEnc)\n }\n\n var outData = this._update(data)\n if (this.hashMode) return this\n\n if (outputEnc) {\n outData = this._toString(outData, outputEnc)\n }\n\n return outData\n}\n\nCipherBase.prototype.setAutoPadding = function () {}\nCipherBase.prototype.getAuthTag = function () {\n throw new Error('trying to get auth tag in unsupported state')\n}\n\nCipherBase.prototype.setAuthTag = function () {\n throw new Error('trying to set auth tag in unsupported state')\n}\n\nCipherBase.prototype.setAAD = function () {\n throw new Error('trying to set aad in unsupported state')\n}\n\nCipherBase.prototype._transform = function (data, _, next) {\n var err\n try {\n if (this.hashMode) {\n this._update(data)\n } else {\n this.push(this._update(data))\n }\n } catch (e) {\n err = e\n } finally {\n next(err)\n }\n}\nCipherBase.prototype._flush = function (done) {\n var err\n try {\n this.push(this.__final())\n } catch (e) {\n err = e\n }\n\n done(err)\n}\nCipherBase.prototype._finalOrDigest = function (outputEnc) {\n var outData = this.__final() || Buffer.alloc(0)\n if (outputEnc) {\n outData = this._toString(outData, outputEnc, true)\n }\n return outData\n}\n\nCipherBase.prototype._toString = function (value, enc, fin) {\n if (!this._decoder) {\n this._decoder = new StringDecoder(enc)\n this._encoding = enc\n }\n\n if (this._encoding !== enc) throw new Error('can\\'t switch encodings')\n\n var out = this._decoder.write(value)\n if (fin) {\n out += this._decoder.end()\n }\n\n return out\n}\n\nmodule.exports = CipherBase\n", - "/*!\n * content-type\n * Copyright(c) 2015 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict'\n\n/**\n * RegExp to match *( \";\" parameter ) in RFC 7231 sec 3.1.1.1\n *\n * parameter = token \"=\" ( token / quoted-string )\n * token = 1*tchar\n * tchar = \"!\" / \"#\" / \"$\" / \"%\" / \"&\" / \"'\" / \"*\"\n * / \"+\" / \"-\" / \".\" / \"^\" / \"_\" / \"`\" / \"|\" / \"~\"\n * / DIGIT / ALPHA\n * ; any VCHAR, except delimiters\n * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE\n * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text\n * obs-text = %x80-FF\n * quoted-pair = \"\\\" ( HTAB / SP / VCHAR / obs-text )\n */\nvar PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *(\"(?:[\\u000b\\u0020\\u0021\\u0023-\\u005b\\u005d-\\u007e\\u0080-\\u00ff]|\\\\[\\u000b\\u0020-\\u00ff])*\"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g // eslint-disable-line no-control-regex\nvar TEXT_REGEXP = /^[\\u000b\\u0020-\\u007e\\u0080-\\u00ff]+$/ // eslint-disable-line no-control-regex\nvar TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/\n\n/**\n * RegExp to match quoted-pair in RFC 7230 sec 3.2.6\n *\n * quoted-pair = \"\\\" ( HTAB / SP / VCHAR / obs-text )\n * obs-text = %x80-FF\n */\nvar QESC_REGEXP = /\\\\([\\u000b\\u0020-\\u00ff])/g // eslint-disable-line no-control-regex\n\n/**\n * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6\n */\nvar QUOTE_REGEXP = /([\\\\\"])/g\n\n/**\n * RegExp to match type in RFC 7231 sec 3.1.1.1\n *\n * media-type = type \"/\" subtype\n * type = token\n * subtype = token\n */\nvar TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/\n\n/**\n * Module exports.\n * @public\n */\n\nexports.format = format\nexports.parse = parse\n\n/**\n * Format object to media type.\n *\n * @param {object} obj\n * @return {string}\n * @public\n */\n\nfunction format (obj) {\n if (!obj || typeof obj !== 'object') {\n throw new TypeError('argument obj is required')\n }\n\n var parameters = obj.parameters\n var type = obj.type\n\n if (!type || !TYPE_REGEXP.test(type)) {\n throw new TypeError('invalid type')\n }\n\n var string = type\n\n // append parameters\n if (parameters && typeof parameters === 'object') {\n var param\n var params = Object.keys(parameters).sort()\n\n for (var i = 0; i < params.length; i++) {\n param = params[i]\n\n if (!TOKEN_REGEXP.test(param)) {\n throw new TypeError('invalid parameter name')\n }\n\n string += '; ' + param + '=' + qstring(parameters[param])\n }\n }\n\n return string\n}\n\n/**\n * Parse media type to object.\n *\n * @param {string|object} string\n * @return {Object}\n * @public\n */\n\nfunction parse (string) {\n if (!string) {\n throw new TypeError('argument string is required')\n }\n\n // support req/res-like objects as argument\n var header = typeof string === 'object'\n ? getcontenttype(string)\n : string\n\n if (typeof header !== 'string') {\n throw new TypeError('argument string is required to be a string')\n }\n\n var index = header.indexOf(';')\n var type = index !== -1\n ? header.slice(0, index).trim()\n : header.trim()\n\n if (!TYPE_REGEXP.test(type)) {\n throw new TypeError('invalid media type')\n }\n\n var obj = new ContentType(type.toLowerCase())\n\n // parse parameters\n if (index !== -1) {\n var key\n var match\n var value\n\n PARAM_REGEXP.lastIndex = index\n\n while ((match = PARAM_REGEXP.exec(header))) {\n if (match.index !== index) {\n throw new TypeError('invalid parameter format')\n }\n\n index += match[0].length\n key = match[1].toLowerCase()\n value = match[2]\n\n if (value.charCodeAt(0) === 0x22 /* \" */) {\n // remove quotes\n value = value.slice(1, -1)\n\n // remove escapes\n if (value.indexOf('\\\\') !== -1) {\n value = value.replace(QESC_REGEXP, '$1')\n }\n }\n\n obj.parameters[key] = value\n }\n\n if (index !== header.length) {\n throw new TypeError('invalid parameter format')\n }\n }\n\n return obj\n}\n\n/**\n * Get content-type from req/res objects.\n *\n * @param {object}\n * @return {Object}\n * @private\n */\n\nfunction getcontenttype (obj) {\n var header\n\n if (typeof obj.getHeader === 'function') {\n // res-like\n header = obj.getHeader('content-type')\n } else if (typeof obj.headers === 'object') {\n // req-like\n header = obj.headers && obj.headers['content-type']\n }\n\n if (typeof header !== 'string') {\n throw new TypeError('content-type header is missing from object')\n }\n\n return header\n}\n\n/**\n * Quote a string if necessary.\n *\n * @param {string} val\n * @return {string}\n * @private\n */\n\nfunction qstring (val) {\n var str = String(val)\n\n // no need to quote tokens\n if (TOKEN_REGEXP.test(str)) {\n return str\n }\n\n if (str.length > 0 && !TEXT_REGEXP.test(str)) {\n throw new TypeError('invalid parameter value')\n }\n\n return '\"' + str.replace(QUOTE_REGEXP, '\\\\$1') + '\"'\n}\n\n/**\n * Class to represent a content type.\n * @private\n */\nfunction ContentType (type) {\n this.parameters = Object.create(null)\n this.type = type\n}\n", - "var elliptic = require('elliptic')\nvar BN = require('bn.js')\n\nmodule.exports = function createECDH (curve) {\n return new ECDH(curve)\n}\n\nvar aliases = {\n secp256k1: {\n name: 'secp256k1',\n byteLength: 32\n },\n secp224r1: {\n name: 'p224',\n byteLength: 28\n },\n prime256v1: {\n name: 'p256',\n byteLength: 32\n },\n prime192v1: {\n name: 'p192',\n byteLength: 24\n },\n ed25519: {\n name: 'ed25519',\n byteLength: 32\n },\n secp384r1: {\n name: 'p384',\n byteLength: 48\n },\n secp521r1: {\n name: 'p521',\n byteLength: 66\n }\n}\n\naliases.p224 = aliases.secp224r1\naliases.p256 = aliases.secp256r1 = aliases.prime256v1\naliases.p192 = aliases.secp192r1 = aliases.prime192v1\naliases.p384 = aliases.secp384r1\naliases.p521 = aliases.secp521r1\n\nfunction ECDH (curve) {\n this.curveType = aliases[curve]\n if (!this.curveType) {\n this.curveType = {\n name: curve\n }\n }\n this.curve = new elliptic.ec(this.curveType.name) // eslint-disable-line new-cap\n this.keys = void 0\n}\n\nECDH.prototype.generateKeys = function (enc, format) {\n this.keys = this.curve.genKeyPair()\n return this.getPublicKey(enc, format)\n}\n\nECDH.prototype.computeSecret = function (other, inenc, enc) {\n inenc = inenc || 'utf8'\n if (!Buffer.isBuffer(other)) {\n other = new Buffer(other, inenc)\n }\n var otherPub = this.curve.keyFromPublic(other).getPublic()\n var out = otherPub.mul(this.keys.getPrivate()).getX()\n return formatReturnValue(out, enc, this.curveType.byteLength)\n}\n\nECDH.prototype.getPublicKey = function (enc, format) {\n var key = this.keys.getPublic(format === 'compressed', true)\n if (format === 'hybrid') {\n if (key[key.length - 1] % 2) {\n key[0] = 7\n } else {\n key[0] = 6\n }\n }\n return formatReturnValue(key, enc)\n}\n\nECDH.prototype.getPrivateKey = function (enc) {\n return formatReturnValue(this.keys.getPrivate(), enc)\n}\n\nECDH.prototype.setPublicKey = function (pub, enc) {\n enc = enc || 'utf8'\n if (!Buffer.isBuffer(pub)) {\n pub = new Buffer(pub, enc)\n }\n this.keys._importPublic(pub)\n return this\n}\n\nECDH.prototype.setPrivateKey = function (priv, enc) {\n enc = enc || 'utf8'\n if (!Buffer.isBuffer(priv)) {\n priv = new Buffer(priv, enc)\n }\n\n var _priv = new BN(priv)\n _priv = _priv.toString(16)\n this.keys = this.curve.genKeyPair()\n this.keys._importPrivate(_priv)\n return this\n}\n\nfunction formatReturnValue (bn, enc, len) {\n if (!Array.isArray(bn)) {\n bn = bn.toArray()\n }\n var buf = new Buffer(bn)\n if (len && buf.length < len) {\n var zeros = new Buffer(len - buf.length)\n zeros.fill(0)\n buf = Buffer.concat([zeros, buf])\n }\n if (!enc) {\n return buf\n } else {\n return buf.toString(enc)\n }\n}\n", - "'use strict'\nvar inherits = require('inherits')\nvar MD5 = require('md5.js')\nvar RIPEMD160 = require('ripemd160')\nvar sha = require('sha.js')\nvar Base = require('cipher-base')\n\nfunction Hash (hash) {\n Base.call(this, 'digest')\n\n this._hash = hash\n}\n\ninherits(Hash, Base)\n\nHash.prototype._update = function (data) {\n this._hash.update(data)\n}\n\nHash.prototype._final = function () {\n return this._hash.digest()\n}\n\nmodule.exports = function createHash (alg) {\n alg = alg.toLowerCase()\n if (alg === 'md5') return new MD5()\n if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160()\n\n return new Hash(sha(alg))\n}\n", - "var MD5 = require('md5.js')\n\nmodule.exports = function (buffer) {\n return new MD5().update(buffer).digest()\n}\n", - "'use strict'\nvar inherits = require('inherits')\nvar Legacy = require('./legacy')\nvar Base = require('cipher-base')\nvar Buffer = require('safe-buffer').Buffer\nvar md5 = require('create-hash/md5')\nvar RIPEMD160 = require('ripemd160')\n\nvar sha = require('sha.js')\n\nvar ZEROS = Buffer.alloc(128)\n\nfunction Hmac (alg, key) {\n Base.call(this, 'digest')\n if (typeof key === 'string') {\n key = Buffer.from(key)\n }\n\n var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64\n\n this._alg = alg\n this._key = key\n if (key.length > blocksize) {\n var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)\n key = hash.update(key).digest()\n } else if (key.length < blocksize) {\n key = Buffer.concat([key, ZEROS], blocksize)\n }\n\n var ipad = this._ipad = Buffer.allocUnsafe(blocksize)\n var opad = this._opad = Buffer.allocUnsafe(blocksize)\n\n for (var i = 0; i < blocksize; i++) {\n ipad[i] = key[i] ^ 0x36\n opad[i] = key[i] ^ 0x5C\n }\n this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)\n this._hash.update(ipad)\n}\n\ninherits(Hmac, Base)\n\nHmac.prototype._update = function (data) {\n this._hash.update(data)\n}\n\nHmac.prototype._final = function () {\n var h = this._hash.digest()\n var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)\n return hash.update(this._opad).update(h).digest()\n}\n\nmodule.exports = function createHmac (alg, key) {\n alg = alg.toLowerCase()\n if (alg === 'rmd160' || alg === 'ripemd160') {\n return new Hmac('rmd160', key)\n }\n if (alg === 'md5') {\n return new Legacy(md5, key)\n }\n return new Hmac(alg, key)\n}\n", - "'use strict'\nvar inherits = require('inherits')\nvar Buffer = require('safe-buffer').Buffer\n\nvar Base = require('cipher-base')\n\nvar ZEROS = Buffer.alloc(128)\nvar blocksize = 64\n\nfunction Hmac (alg, key) {\n Base.call(this, 'digest')\n if (typeof key === 'string') {\n key = Buffer.from(key)\n }\n\n this._alg = alg\n this._key = key\n\n if (key.length > blocksize) {\n key = alg(key)\n } else if (key.length < blocksize) {\n key = Buffer.concat([key, ZEROS], blocksize)\n }\n\n var ipad = this._ipad = Buffer.allocUnsafe(blocksize)\n var opad = this._opad = Buffer.allocUnsafe(blocksize)\n\n for (var i = 0; i < blocksize; i++) {\n ipad[i] = key[i] ^ 0x36\n opad[i] = key[i] ^ 0x5C\n }\n\n this._hash = [ipad]\n}\n\ninherits(Hmac, Base)\n\nHmac.prototype._update = function (data) {\n this._hash.push(data)\n}\n\nHmac.prototype._final = function () {\n var h = this._alg(Buffer.concat(this._hash))\n return this._alg(Buffer.concat([this._opad, h]))\n}\nmodule.exports = Hmac\n", - "'use strict'\n\nexports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes')\nexports.createHash = exports.Hash = require('create-hash')\nexports.createHmac = exports.Hmac = require('create-hmac')\n\nvar algos = require('browserify-sign/algos')\nvar algoKeys = Object.keys(algos)\nvar hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys)\nexports.getHashes = function () {\n return hashes\n}\n\nvar p = require('pbkdf2')\nexports.pbkdf2 = p.pbkdf2\nexports.pbkdf2Sync = p.pbkdf2Sync\n\nvar aes = require('browserify-cipher')\n\nexports.Cipher = aes.Cipher\nexports.createCipher = aes.createCipher\nexports.Cipheriv = aes.Cipheriv\nexports.createCipheriv = aes.createCipheriv\nexports.Decipher = aes.Decipher\nexports.createDecipher = aes.createDecipher\nexports.Decipheriv = aes.Decipheriv\nexports.createDecipheriv = aes.createDecipheriv\nexports.getCiphers = aes.getCiphers\nexports.listCiphers = aes.listCiphers\n\nvar dh = require('diffie-hellman')\n\nexports.DiffieHellmanGroup = dh.DiffieHellmanGroup\nexports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup\nexports.getDiffieHellman = dh.getDiffieHellman\nexports.createDiffieHellman = dh.createDiffieHellman\nexports.DiffieHellman = dh.DiffieHellman\n\nvar sign = require('browserify-sign')\n\nexports.createSign = sign.createSign\nexports.Sign = sign.Sign\nexports.createVerify = sign.createVerify\nexports.Verify = sign.Verify\n\nexports.createECDH = require('create-ecdh')\n\nvar publicEncrypt = require('public-encrypt')\n\nexports.publicEncrypt = publicEncrypt.publicEncrypt\nexports.privateEncrypt = publicEncrypt.privateEncrypt\nexports.publicDecrypt = publicEncrypt.publicDecrypt\nexports.privateDecrypt = publicEncrypt.privateDecrypt\n\n// the least I can do is make error messages for the rest of the node.js/crypto api.\n// ;[\n// 'createCredentials'\n// ].forEach(function (name) {\n// exports[name] = function () {\n// throw new Error([\n// 'sorry, ' + name + ' is not implemented yet',\n// 'we accept pull requests',\n// 'https://github.com/crypto-browserify/crypto-browserify'\n// ].join('\\n'))\n// }\n// })\n\nvar rf = require('randomfill')\n\nexports.randomFill = rf.randomFill\nexports.randomFillSync = rf.randomFillSync\n\nexports.createCredentials = function () {\n throw new Error([\n 'sorry, createCredentials is not implemented yet',\n 'we accept pull requests',\n 'https://github.com/crypto-browserify/crypto-browserify'\n ].join('\\n'))\n}\n\nexports.constants = {\n 'DH_CHECK_P_NOT_SAFE_PRIME': 2,\n 'DH_CHECK_P_NOT_PRIME': 1,\n 'DH_UNABLE_TO_CHECK_GENERATOR': 4,\n 'DH_NOT_SUITABLE_GENERATOR': 8,\n 'NPN_ENABLED': 1,\n 'ALPN_ENABLED': 1,\n 'RSA_PKCS1_PADDING': 1,\n 'RSA_SSLV23_PADDING': 2,\n 'RSA_NO_PADDING': 3,\n 'RSA_PKCS1_OAEP_PADDING': 4,\n 'RSA_X931_PADDING': 5,\n 'RSA_PKCS1_PSS_PADDING': 6,\n 'POINT_CONVERSION_COMPRESSED': 2,\n 'POINT_CONVERSION_UNCOMPRESSED': 4,\n 'POINT_CONVERSION_HYBRID': 6\n}\n", - "'use strict';\n\nexports.utils = require('./des/utils');\nexports.Cipher = require('./des/cipher');\nexports.DES = require('./des/des');\nexports.CBC = require('./des/cbc');\nexports.EDE = require('./des/ede');\n", - "'use strict';\n\nvar assert = require('minimalistic-assert');\nvar inherits = require('inherits');\n\nvar proto = {};\n\nfunction CBCState(iv) {\n assert.equal(iv.length, 8, 'Invalid IV length');\n\n this.iv = new Array(8);\n for (var i = 0; i < this.iv.length; i++)\n this.iv[i] = iv[i];\n}\n\nfunction instantiate(Base) {\n function CBC(options) {\n Base.call(this, options);\n this._cbcInit();\n }\n inherits(CBC, Base);\n\n var keys = Object.keys(proto);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n CBC.prototype[key] = proto[key];\n }\n\n CBC.create = function create(options) {\n return new CBC(options);\n };\n\n return CBC;\n}\n\nexports.instantiate = instantiate;\n\nproto._cbcInit = function _cbcInit() {\n var state = new CBCState(this.options.iv);\n this._cbcState = state;\n};\n\nproto._update = function _update(inp, inOff, out, outOff) {\n var state = this._cbcState;\n var superProto = this.constructor.super_.prototype;\n\n var iv = state.iv;\n if (this.type === 'encrypt') {\n for (var i = 0; i < this.blockSize; i++)\n iv[i] ^= inp[inOff + i];\n\n superProto._update.call(this, iv, 0, out, outOff);\n\n for (var i = 0; i < this.blockSize; i++)\n iv[i] = out[outOff + i];\n } else {\n superProto._update.call(this, inp, inOff, out, outOff);\n\n for (var i = 0; i < this.blockSize; i++)\n out[outOff + i] ^= iv[i];\n\n for (var i = 0; i < this.blockSize; i++)\n iv[i] = inp[inOff + i];\n }\n};\n", - "'use strict';\n\nvar assert = require('minimalistic-assert');\n\nfunction Cipher(options) {\n this.options = options;\n\n this.type = this.options.type;\n this.blockSize = 8;\n this._init();\n\n this.buffer = new Array(this.blockSize);\n this.bufferOff = 0;\n}\nmodule.exports = Cipher;\n\nCipher.prototype._init = function _init() {\n // Might be overrided\n};\n\nCipher.prototype.update = function update(data) {\n if (data.length === 0)\n return [];\n\n if (this.type === 'decrypt')\n return this._updateDecrypt(data);\n else\n return this._updateEncrypt(data);\n};\n\nCipher.prototype._buffer = function _buffer(data, off) {\n // Append data to buffer\n var min = Math.min(this.buffer.length - this.bufferOff, data.length - off);\n for (var i = 0; i < min; i++)\n this.buffer[this.bufferOff + i] = data[off + i];\n this.bufferOff += min;\n\n // Shift next\n return min;\n};\n\nCipher.prototype._flushBuffer = function _flushBuffer(out, off) {\n this._update(this.buffer, 0, out, off);\n this.bufferOff = 0;\n return this.blockSize;\n};\n\nCipher.prototype._updateEncrypt = function _updateEncrypt(data) {\n var inputOff = 0;\n var outputOff = 0;\n\n var count = ((this.bufferOff + data.length) / this.blockSize) | 0;\n var out = new Array(count * this.blockSize);\n\n if (this.bufferOff !== 0) {\n inputOff += this._buffer(data, inputOff);\n\n if (this.bufferOff === this.buffer.length)\n outputOff += this._flushBuffer(out, outputOff);\n }\n\n // Write blocks\n var max = data.length - ((data.length - inputOff) % this.blockSize);\n for (; inputOff < max; inputOff += this.blockSize) {\n this._update(data, inputOff, out, outputOff);\n outputOff += this.blockSize;\n }\n\n // Queue rest\n for (; inputOff < data.length; inputOff++, this.bufferOff++)\n this.buffer[this.bufferOff] = data[inputOff];\n\n return out;\n};\n\nCipher.prototype._updateDecrypt = function _updateDecrypt(data) {\n var inputOff = 0;\n var outputOff = 0;\n\n var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1;\n var out = new Array(count * this.blockSize);\n\n // TODO(indutny): optimize it, this is far from optimal\n for (; count > 0; count--) {\n inputOff += this._buffer(data, inputOff);\n outputOff += this._flushBuffer(out, outputOff);\n }\n\n // Buffer rest of the input\n inputOff += this._buffer(data, inputOff);\n\n return out;\n};\n\nCipher.prototype.final = function final(buffer) {\n var first;\n if (buffer)\n first = this.update(buffer);\n\n var last;\n if (this.type === 'encrypt')\n last = this._finalEncrypt();\n else\n last = this._finalDecrypt();\n\n if (first)\n return first.concat(last);\n else\n return last;\n};\n\nCipher.prototype._pad = function _pad(buffer, off) {\n if (off === 0)\n return false;\n\n while (off < buffer.length)\n buffer[off++] = 0;\n\n return true;\n};\n\nCipher.prototype._finalEncrypt = function _finalEncrypt() {\n if (!this._pad(this.buffer, this.bufferOff))\n return [];\n\n var out = new Array(this.blockSize);\n this._update(this.buffer, 0, out, 0);\n return out;\n};\n\nCipher.prototype._unpad = function _unpad(buffer) {\n return buffer;\n};\n\nCipher.prototype._finalDecrypt = function _finalDecrypt() {\n assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt');\n var out = new Array(this.blockSize);\n this._flushBuffer(out, 0);\n\n return this._unpad(out);\n};\n", - "'use strict';\n\nvar assert = require('minimalistic-assert');\nvar inherits = require('inherits');\n\nvar utils = require('./utils');\nvar Cipher = require('./cipher');\n\nfunction DESState() {\n this.tmp = new Array(2);\n this.keys = null;\n}\n\nfunction DES(options) {\n Cipher.call(this, options);\n\n var state = new DESState();\n this._desState = state;\n\n this.deriveKeys(state, options.key);\n}\ninherits(DES, Cipher);\nmodule.exports = DES;\n\nDES.create = function create(options) {\n return new DES(options);\n};\n\nvar shiftTable = [\n 1, 1, 2, 2, 2, 2, 2, 2,\n 1, 2, 2, 2, 2, 2, 2, 1\n];\n\nDES.prototype.deriveKeys = function deriveKeys(state, key) {\n state.keys = new Array(16 * 2);\n\n assert.equal(key.length, this.blockSize, 'Invalid key length');\n\n var kL = utils.readUInt32BE(key, 0);\n var kR = utils.readUInt32BE(key, 4);\n\n utils.pc1(kL, kR, state.tmp, 0);\n kL = state.tmp[0];\n kR = state.tmp[1];\n for (var i = 0; i < state.keys.length; i += 2) {\n var shift = shiftTable[i >>> 1];\n kL = utils.r28shl(kL, shift);\n kR = utils.r28shl(kR, shift);\n utils.pc2(kL, kR, state.keys, i);\n }\n};\n\nDES.prototype._update = function _update(inp, inOff, out, outOff) {\n var state = this._desState;\n\n var l = utils.readUInt32BE(inp, inOff);\n var r = utils.readUInt32BE(inp, inOff + 4);\n\n // Initial Permutation\n utils.ip(l, r, state.tmp, 0);\n l = state.tmp[0];\n r = state.tmp[1];\n\n if (this.type === 'encrypt')\n this._encrypt(state, l, r, state.tmp, 0);\n else\n this._decrypt(state, l, r, state.tmp, 0);\n\n l = state.tmp[0];\n r = state.tmp[1];\n\n utils.writeUInt32BE(out, l, outOff);\n utils.writeUInt32BE(out, r, outOff + 4);\n};\n\nDES.prototype._pad = function _pad(buffer, off) {\n var value = buffer.length - off;\n for (var i = off; i < buffer.length; i++)\n buffer[i] = value;\n\n return true;\n};\n\nDES.prototype._unpad = function _unpad(buffer) {\n var pad = buffer[buffer.length - 1];\n for (var i = buffer.length - pad; i < buffer.length; i++)\n assert.equal(buffer[i], pad);\n\n return buffer.slice(0, buffer.length - pad);\n};\n\nDES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) {\n var l = lStart;\n var r = rStart;\n\n // Apply f() x16 times\n for (var i = 0; i < state.keys.length; i += 2) {\n var keyL = state.keys[i];\n var keyR = state.keys[i + 1];\n\n // f(r, k)\n utils.expand(r, state.tmp, 0);\n\n keyL ^= state.tmp[0];\n keyR ^= state.tmp[1];\n var s = utils.substitute(keyL, keyR);\n var f = utils.permute(s);\n\n var t = r;\n r = (l ^ f) >>> 0;\n l = t;\n }\n\n // Reverse Initial Permutation\n utils.rip(r, l, out, off);\n};\n\nDES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) {\n var l = rStart;\n var r = lStart;\n\n // Apply f() x16 times\n for (var i = state.keys.length - 2; i >= 0; i -= 2) {\n var keyL = state.keys[i];\n var keyR = state.keys[i + 1];\n\n // f(r, k)\n utils.expand(l, state.tmp, 0);\n\n keyL ^= state.tmp[0];\n keyR ^= state.tmp[1];\n var s = utils.substitute(keyL, keyR);\n var f = utils.permute(s);\n\n var t = l;\n l = (r ^ f) >>> 0;\n r = t;\n }\n\n // Reverse Initial Permutation\n utils.rip(l, r, out, off);\n};\n", - "'use strict';\n\nvar assert = require('minimalistic-assert');\nvar inherits = require('inherits');\n\nvar Cipher = require('./cipher');\nvar DES = require('./des');\n\nfunction EDEState(type, key) {\n assert.equal(key.length, 24, 'Invalid key length');\n\n var k1 = key.slice(0, 8);\n var k2 = key.slice(8, 16);\n var k3 = key.slice(16, 24);\n\n if (type === 'encrypt') {\n this.ciphers = [\n DES.create({ type: 'encrypt', key: k1 }),\n DES.create({ type: 'decrypt', key: k2 }),\n DES.create({ type: 'encrypt', key: k3 })\n ];\n } else {\n this.ciphers = [\n DES.create({ type: 'decrypt', key: k3 }),\n DES.create({ type: 'encrypt', key: k2 }),\n DES.create({ type: 'decrypt', key: k1 })\n ];\n }\n}\n\nfunction EDE(options) {\n Cipher.call(this, options);\n\n var state = new EDEState(this.type, this.options.key);\n this._edeState = state;\n}\ninherits(EDE, Cipher);\n\nmodule.exports = EDE;\n\nEDE.create = function create(options) {\n return new EDE(options);\n};\n\nEDE.prototype._update = function _update(inp, inOff, out, outOff) {\n var state = this._edeState;\n\n state.ciphers[0]._update(inp, inOff, out, outOff);\n state.ciphers[1]._update(out, outOff, out, outOff);\n state.ciphers[2]._update(out, outOff, out, outOff);\n};\n\nEDE.prototype._pad = DES.prototype._pad;\nEDE.prototype._unpad = DES.prototype._unpad;\n", - "'use strict';\n\nexports.readUInt32BE = function readUInt32BE(bytes, off) {\n var res = (bytes[0 + off] << 24) |\n (bytes[1 + off] << 16) |\n (bytes[2 + off] << 8) |\n bytes[3 + off];\n return res >>> 0;\n};\n\nexports.writeUInt32BE = function writeUInt32BE(bytes, value, off) {\n bytes[0 + off] = value >>> 24;\n bytes[1 + off] = (value >>> 16) & 0xff;\n bytes[2 + off] = (value >>> 8) & 0xff;\n bytes[3 + off] = value & 0xff;\n};\n\nexports.ip = function ip(inL, inR, out, off) {\n var outL = 0;\n var outR = 0;\n\n for (var i = 6; i >= 0; i -= 2) {\n for (var j = 0; j <= 24; j += 8) {\n outL <<= 1;\n outL |= (inR >>> (j + i)) & 1;\n }\n for (var j = 0; j <= 24; j += 8) {\n outL <<= 1;\n outL |= (inL >>> (j + i)) & 1;\n }\n }\n\n for (var i = 6; i >= 0; i -= 2) {\n for (var j = 1; j <= 25; j += 8) {\n outR <<= 1;\n outR |= (inR >>> (j + i)) & 1;\n }\n for (var j = 1; j <= 25; j += 8) {\n outR <<= 1;\n outR |= (inL >>> (j + i)) & 1;\n }\n }\n\n out[off + 0] = outL >>> 0;\n out[off + 1] = outR >>> 0;\n};\n\nexports.rip = function rip(inL, inR, out, off) {\n var outL = 0;\n var outR = 0;\n\n for (var i = 0; i < 4; i++) {\n for (var j = 24; j >= 0; j -= 8) {\n outL <<= 1;\n outL |= (inR >>> (j + i)) & 1;\n outL <<= 1;\n outL |= (inL >>> (j + i)) & 1;\n }\n }\n for (var i = 4; i < 8; i++) {\n for (var j = 24; j >= 0; j -= 8) {\n outR <<= 1;\n outR |= (inR >>> (j + i)) & 1;\n outR <<= 1;\n outR |= (inL >>> (j + i)) & 1;\n }\n }\n\n out[off + 0] = outL >>> 0;\n out[off + 1] = outR >>> 0;\n};\n\nexports.pc1 = function pc1(inL, inR, out, off) {\n var outL = 0;\n var outR = 0;\n\n // 7, 15, 23, 31, 39, 47, 55, 63\n // 6, 14, 22, 30, 39, 47, 55, 63\n // 5, 13, 21, 29, 39, 47, 55, 63\n // 4, 12, 20, 28\n for (var i = 7; i >= 5; i--) {\n for (var j = 0; j <= 24; j += 8) {\n outL <<= 1;\n outL |= (inR >> (j + i)) & 1;\n }\n for (var j = 0; j <= 24; j += 8) {\n outL <<= 1;\n outL |= (inL >> (j + i)) & 1;\n }\n }\n for (var j = 0; j <= 24; j += 8) {\n outL <<= 1;\n outL |= (inR >> (j + i)) & 1;\n }\n\n // 1, 9, 17, 25, 33, 41, 49, 57\n // 2, 10, 18, 26, 34, 42, 50, 58\n // 3, 11, 19, 27, 35, 43, 51, 59\n // 36, 44, 52, 60\n for (var i = 1; i <= 3; i++) {\n for (var j = 0; j <= 24; j += 8) {\n outR <<= 1;\n outR |= (inR >> (j + i)) & 1;\n }\n for (var j = 0; j <= 24; j += 8) {\n outR <<= 1;\n outR |= (inL >> (j + i)) & 1;\n }\n }\n for (var j = 0; j <= 24; j += 8) {\n outR <<= 1;\n outR |= (inL >> (j + i)) & 1;\n }\n\n out[off + 0] = outL >>> 0;\n out[off + 1] = outR >>> 0;\n};\n\nexports.r28shl = function r28shl(num, shift) {\n return ((num << shift) & 0xfffffff) | (num >>> (28 - shift));\n};\n\nvar pc2table = [\n // inL => outL\n 14, 11, 17, 4, 27, 23, 25, 0,\n 13, 22, 7, 18, 5, 9, 16, 24,\n 2, 20, 12, 21, 1, 8, 15, 26,\n\n // inR => outR\n 15, 4, 25, 19, 9, 1, 26, 16,\n 5, 11, 23, 8, 12, 7, 17, 0,\n 22, 3, 10, 14, 6, 20, 27, 24\n];\n\nexports.pc2 = function pc2(inL, inR, out, off) {\n var outL = 0;\n var outR = 0;\n\n var len = pc2table.length >>> 1;\n for (var i = 0; i < len; i++) {\n outL <<= 1;\n outL |= (inL >>> pc2table[i]) & 0x1;\n }\n for (var i = len; i < pc2table.length; i++) {\n outR <<= 1;\n outR |= (inR >>> pc2table[i]) & 0x1;\n }\n\n out[off + 0] = outL >>> 0;\n out[off + 1] = outR >>> 0;\n};\n\nexports.expand = function expand(r, out, off) {\n var outL = 0;\n var outR = 0;\n\n outL = ((r & 1) << 5) | (r >>> 27);\n for (var i = 23; i >= 15; i -= 4) {\n outL <<= 6;\n outL |= (r >>> i) & 0x3f;\n }\n for (var i = 11; i >= 3; i -= 4) {\n outR |= (r >>> i) & 0x3f;\n outR <<= 6;\n }\n outR |= ((r & 0x1f) << 1) | (r >>> 31);\n\n out[off + 0] = outL >>> 0;\n out[off + 1] = outR >>> 0;\n};\n\nvar sTable = [\n 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1,\n 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8,\n 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7,\n 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13,\n\n 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14,\n 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5,\n 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2,\n 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9,\n\n 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10,\n 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1,\n 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7,\n 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12,\n\n 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3,\n 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9,\n 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8,\n 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14,\n\n 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1,\n 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6,\n 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13,\n 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3,\n\n 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5,\n 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8,\n 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10,\n 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13,\n\n 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10,\n 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6,\n 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7,\n 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12,\n\n 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4,\n 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2,\n 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13,\n 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11\n];\n\nexports.substitute = function substitute(inL, inR) {\n var out = 0;\n for (var i = 0; i < 4; i++) {\n var b = (inL >>> (18 - i * 6)) & 0x3f;\n var sb = sTable[i * 0x40 + b];\n\n out <<= 4;\n out |= sb;\n }\n for (var i = 0; i < 4; i++) {\n var b = (inR >>> (18 - i * 6)) & 0x3f;\n var sb = sTable[4 * 0x40 + i * 0x40 + b];\n\n out <<= 4;\n out |= sb;\n }\n return out >>> 0;\n};\n\nvar permuteTable = [\n 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22,\n 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7\n];\n\nexports.permute = function permute(num) {\n var out = 0;\n for (var i = 0; i < permuteTable.length; i++) {\n out <<= 1;\n out |= (num >>> permuteTable[i]) & 0x1;\n }\n return out >>> 0;\n};\n\nexports.padSplit = function padSplit(num, size, group) {\n var str = num.toString(2);\n while (str.length < size)\n str = '0' + str;\n\n var out = [];\n for (var i = 0; i < size; i += group)\n out.push(str.slice(i, i + group));\n return out.join(' ');\n};\n", - "var generatePrime = require('./lib/generatePrime')\nvar primes = require('./lib/primes.json')\n\nvar DH = require('./lib/dh')\n\nfunction getDiffieHellman (mod) {\n var prime = new Buffer(primes[mod].prime, 'hex')\n var gen = new Buffer(primes[mod].gen, 'hex')\n\n return new DH(prime, gen)\n}\n\nvar ENCODINGS = {\n 'binary': true, 'hex': true, 'base64': true\n}\n\nfunction createDiffieHellman (prime, enc, generator, genc) {\n if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) {\n return createDiffieHellman(prime, 'binary', enc, generator)\n }\n\n enc = enc || 'binary'\n genc = genc || 'binary'\n generator = generator || new Buffer([2])\n\n if (!Buffer.isBuffer(generator)) {\n generator = new Buffer(generator, genc)\n }\n\n if (typeof prime === 'number') {\n return new DH(generatePrime(prime, generator), generator, true)\n }\n\n if (!Buffer.isBuffer(prime)) {\n prime = new Buffer(prime, enc)\n }\n\n return new DH(prime, generator, true)\n}\n\nexports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman\nexports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman\n", - "var BN = require('bn.js');\nvar MillerRabin = require('miller-rabin');\nvar millerRabin = new MillerRabin();\nvar TWENTYFOUR = new BN(24);\nvar ELEVEN = new BN(11);\nvar TEN = new BN(10);\nvar THREE = new BN(3);\nvar SEVEN = new BN(7);\nvar primes = require('./generatePrime');\nvar randomBytes = require('randombytes');\nmodule.exports = DH;\n\nfunction setPublicKey(pub, enc) {\n enc = enc || 'utf8';\n if (!Buffer.isBuffer(pub)) {\n pub = new Buffer(pub, enc);\n }\n this._pub = new BN(pub);\n return this;\n}\n\nfunction setPrivateKey(priv, enc) {\n enc = enc || 'utf8';\n if (!Buffer.isBuffer(priv)) {\n priv = new Buffer(priv, enc);\n }\n this._priv = new BN(priv);\n return this;\n}\n\nvar primeCache = {};\nfunction checkPrime(prime, generator) {\n var gen = generator.toString('hex');\n var hex = [gen, prime.toString(16)].join('_');\n if (hex in primeCache) {\n return primeCache[hex];\n }\n var error = 0;\n\n if (prime.isEven() ||\n !primes.simpleSieve ||\n !primes.fermatTest(prime) ||\n !millerRabin.test(prime)) {\n //not a prime so +1\n error += 1;\n\n if (gen === '02' || gen === '05') {\n // we'd be able to check the generator\n // it would fail so +8\n error += 8;\n } else {\n //we wouldn't be able to test the generator\n // so +4\n error += 4;\n }\n primeCache[hex] = error;\n return error;\n }\n if (!millerRabin.test(prime.shrn(1))) {\n //not a safe prime\n error += 2;\n }\n var rem;\n switch (gen) {\n case '02':\n if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) {\n // unsuidable generator\n error += 8;\n }\n break;\n case '05':\n rem = prime.mod(TEN);\n if (rem.cmp(THREE) && rem.cmp(SEVEN)) {\n // prime mod 10 needs to equal 3 or 7\n error += 8;\n }\n break;\n default:\n error += 4;\n }\n primeCache[hex] = error;\n return error;\n}\n\nfunction DH(prime, generator, malleable) {\n this.setGenerator(generator);\n this.__prime = new BN(prime);\n this._prime = BN.mont(this.__prime);\n this._primeLen = prime.length;\n this._pub = undefined;\n this._priv = undefined;\n this._primeCode = undefined;\n if (malleable) {\n this.setPublicKey = setPublicKey;\n this.setPrivateKey = setPrivateKey;\n } else {\n this._primeCode = 8;\n }\n}\nObject.defineProperty(DH.prototype, 'verifyError', {\n enumerable: true,\n get: function () {\n if (typeof this._primeCode !== 'number') {\n this._primeCode = checkPrime(this.__prime, this.__gen);\n }\n return this._primeCode;\n }\n});\nDH.prototype.generateKeys = function () {\n if (!this._priv) {\n this._priv = new BN(randomBytes(this._primeLen));\n }\n this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed();\n return this.getPublicKey();\n};\n\nDH.prototype.computeSecret = function (other) {\n other = new BN(other);\n other = other.toRed(this._prime);\n var secret = other.redPow(this._priv).fromRed();\n var out = new Buffer(secret.toArray());\n var prime = this.getPrime();\n if (out.length < prime.length) {\n var front = new Buffer(prime.length - out.length);\n front.fill(0);\n out = Buffer.concat([front, out]);\n }\n return out;\n};\n\nDH.prototype.getPublicKey = function getPublicKey(enc) {\n return formatReturnValue(this._pub, enc);\n};\n\nDH.prototype.getPrivateKey = function getPrivateKey(enc) {\n return formatReturnValue(this._priv, enc);\n};\n\nDH.prototype.getPrime = function (enc) {\n return formatReturnValue(this.__prime, enc);\n};\n\nDH.prototype.getGenerator = function (enc) {\n return formatReturnValue(this._gen, enc);\n};\n\nDH.prototype.setGenerator = function (gen, enc) {\n enc = enc || 'utf8';\n if (!Buffer.isBuffer(gen)) {\n gen = new Buffer(gen, enc);\n }\n this.__gen = gen;\n this._gen = new BN(gen);\n return this;\n};\n\nfunction formatReturnValue(bn, enc) {\n var buf = new Buffer(bn.toArray());\n if (!enc) {\n return buf;\n } else {\n return buf.toString(enc);\n }\n}\n", - "var randomBytes = require('randombytes');\nmodule.exports = findPrime;\nfindPrime.simpleSieve = simpleSieve;\nfindPrime.fermatTest = fermatTest;\nvar BN = require('bn.js');\nvar TWENTYFOUR = new BN(24);\nvar MillerRabin = require('miller-rabin');\nvar millerRabin = new MillerRabin();\nvar ONE = new BN(1);\nvar TWO = new BN(2);\nvar FIVE = new BN(5);\nvar SIXTEEN = new BN(16);\nvar EIGHT = new BN(8);\nvar TEN = new BN(10);\nvar THREE = new BN(3);\nvar SEVEN = new BN(7);\nvar ELEVEN = new BN(11);\nvar FOUR = new BN(4);\nvar TWELVE = new BN(12);\nvar primes = null;\n\nfunction _getPrimes() {\n if (primes !== null)\n return primes;\n\n var limit = 0x100000;\n var res = [];\n res[0] = 2;\n for (var i = 1, k = 3; k < limit; k += 2) {\n var sqrt = Math.ceil(Math.sqrt(k));\n for (var j = 0; j < i && res[j] <= sqrt; j++)\n if (k % res[j] === 0)\n break;\n\n if (i !== j && res[j] <= sqrt)\n continue;\n\n res[i++] = k;\n }\n primes = res;\n return res;\n}\n\nfunction simpleSieve(p) {\n var primes = _getPrimes();\n\n for (var i = 0; i < primes.length; i++)\n if (p.modn(primes[i]) === 0) {\n if (p.cmpn(primes[i]) === 0) {\n return true;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\nfunction fermatTest(p) {\n var red = BN.mont(p);\n return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0;\n}\n\nfunction findPrime(bits, gen) {\n if (bits < 16) {\n // this is what openssl does\n if (gen === 2 || gen === 5) {\n return new BN([0x8c, 0x7b]);\n } else {\n return new BN([0x8c, 0x27]);\n }\n }\n gen = new BN(gen);\n\n var num, n2;\n\n while (true) {\n num = new BN(randomBytes(Math.ceil(bits / 8)));\n while (num.bitLength() > bits) {\n num.ishrn(1);\n }\n if (num.isEven()) {\n num.iadd(ONE);\n }\n if (!num.testn(1)) {\n num.iadd(TWO);\n }\n if (!gen.cmp(TWO)) {\n while (num.mod(TWENTYFOUR).cmp(ELEVEN)) {\n num.iadd(FOUR);\n }\n } else if (!gen.cmp(FIVE)) {\n while (num.mod(TEN).cmp(THREE)) {\n num.iadd(FOUR);\n }\n }\n n2 = num.shrn(1);\n if (simpleSieve(n2) && simpleSieve(num) &&\n fermatTest(n2) && fermatTest(num) &&\n millerRabin.test(n2) && millerRabin.test(num)) {\n return num;\n }\n }\n\n}\n", - "module.exports={\n \"modp1\": {\n \"gen\": \"02\",\n \"prime\": \"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff\"\n },\n \"modp2\": {\n \"gen\": \"02\",\n \"prime\": \"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff\"\n },\n \"modp5\": {\n \"gen\": \"02\",\n \"prime\": \"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff\"\n },\n \"modp14\": {\n \"gen\": \"02\",\n \"prime\": \"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff\"\n },\n \"modp15\": {\n \"gen\": \"02\",\n \"prime\": \"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff\"\n },\n \"modp16\": {\n \"gen\": \"02\",\n \"prime\": \"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff\"\n },\n \"modp17\": {\n \"gen\": \"02\",\n \"prime\": \"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff\"\n },\n \"modp18\": {\n \"gen\": \"02\",\n \"prime\": \"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff\"\n }\n}", - "'use strict';\n\nvar elliptic = exports;\n\nelliptic.version = require('../package.json').version;\nelliptic.utils = require('./elliptic/utils');\nelliptic.rand = require('brorand');\nelliptic.curve = require('./elliptic/curve');\nelliptic.curves = require('./elliptic/curves');\n\n// Protocols\nelliptic.ec = require('./elliptic/ec');\nelliptic.eddsa = require('./elliptic/eddsa');\n", - "'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar getNAF = utils.getNAF;\nvar getJSF = utils.getJSF;\nvar assert = utils.assert;\n\nfunction BaseCurve(type, conf) {\n this.type = type;\n this.p = new BN(conf.p, 16);\n\n // Use Montgomery, when there is no fast reduction for the prime\n this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);\n\n // Useful for many curves\n this.zero = new BN(0).toRed(this.red);\n this.one = new BN(1).toRed(this.red);\n this.two = new BN(2).toRed(this.red);\n\n // Curve configuration, optional\n this.n = conf.n && new BN(conf.n, 16);\n this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);\n\n // Temporary arrays\n this._wnafT1 = new Array(4);\n this._wnafT2 = new Array(4);\n this._wnafT3 = new Array(4);\n this._wnafT4 = new Array(4);\n\n this._bitLength = this.n ? this.n.bitLength() : 0;\n\n // Generalized Greg Maxwell's trick\n var adjustCount = this.n && this.p.div(this.n);\n if (!adjustCount || adjustCount.cmpn(100) > 0) {\n this.redN = null;\n } else {\n this._maxwellTrick = true;\n this.redN = this.n.toRed(this.red);\n }\n}\nmodule.exports = BaseCurve;\n\nBaseCurve.prototype.point = function point() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype.validate = function validate() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {\n assert(p.precomputed);\n var doubles = p._getDoubles();\n\n var naf = getNAF(k, 1, this._bitLength);\n var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);\n I /= 3;\n\n // Translate into more windowed form\n var repr = [];\n var j;\n var nafW;\n for (j = 0; j < naf.length; j += doubles.step) {\n nafW = 0;\n for (var l = j + doubles.step - 1; l >= j; l--)\n nafW = (nafW << 1) + naf[l];\n repr.push(nafW);\n }\n\n var a = this.jpoint(null, null, null);\n var b = this.jpoint(null, null, null);\n for (var i = I; i > 0; i--) {\n for (j = 0; j < repr.length; j++) {\n nafW = repr[j];\n if (nafW === i)\n b = b.mixedAdd(doubles.points[j]);\n else if (nafW === -i)\n b = b.mixedAdd(doubles.points[j].neg());\n }\n a = a.add(b);\n }\n return a.toP();\n};\n\nBaseCurve.prototype._wnafMul = function _wnafMul(p, k) {\n var w = 4;\n\n // Precompute window\n var nafPoints = p._getNAFPoints(w);\n w = nafPoints.wnd;\n var wnd = nafPoints.points;\n\n // Get NAF form\n var naf = getNAF(k, w, this._bitLength);\n\n // Add `this`*(N+1) for every w-NAF index\n var acc = this.jpoint(null, null, null);\n for (var i = naf.length - 1; i >= 0; i--) {\n // Count zeroes\n for (var l = 0; i >= 0 && naf[i] === 0; i--)\n l++;\n if (i >= 0)\n l++;\n acc = acc.dblp(l);\n\n if (i < 0)\n break;\n var z = naf[i];\n assert(z !== 0);\n if (p.type === 'affine') {\n // J +- P\n if (z > 0)\n acc = acc.mixedAdd(wnd[(z - 1) >> 1]);\n else\n acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());\n } else {\n // J +- J\n if (z > 0)\n acc = acc.add(wnd[(z - 1) >> 1]);\n else\n acc = acc.add(wnd[(-z - 1) >> 1].neg());\n }\n }\n return p.type === 'affine' ? acc.toP() : acc;\n};\n\nBaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,\n points,\n coeffs,\n len,\n jacobianResult) {\n var wndWidth = this._wnafT1;\n var wnd = this._wnafT2;\n var naf = this._wnafT3;\n\n // Fill all arrays\n var max = 0;\n var i;\n var j;\n var p;\n for (i = 0; i < len; i++) {\n p = points[i];\n var nafPoints = p._getNAFPoints(defW);\n wndWidth[i] = nafPoints.wnd;\n wnd[i] = nafPoints.points;\n }\n\n // Comb small window NAFs\n for (i = len - 1; i >= 1; i -= 2) {\n var a = i - 1;\n var b = i;\n if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {\n naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength);\n naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength);\n max = Math.max(naf[a].length, max);\n max = Math.max(naf[b].length, max);\n continue;\n }\n\n var comb = [\n points[a], /* 1 */\n null, /* 3 */\n null, /* 5 */\n points[b], /* 7 */\n ];\n\n // Try to avoid Projective points, if possible\n if (points[a].y.cmp(points[b].y) === 0) {\n comb[1] = points[a].add(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].add(points[b].neg());\n } else {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n }\n\n var index = [\n -3, /* -1 -1 */\n -1, /* -1 0 */\n -5, /* -1 1 */\n -7, /* 0 -1 */\n 0, /* 0 0 */\n 7, /* 0 1 */\n 5, /* 1 -1 */\n 1, /* 1 0 */\n 3, /* 1 1 */\n ];\n\n var jsf = getJSF(coeffs[a], coeffs[b]);\n max = Math.max(jsf[0].length, max);\n naf[a] = new Array(max);\n naf[b] = new Array(max);\n for (j = 0; j < max; j++) {\n var ja = jsf[0][j] | 0;\n var jb = jsf[1][j] | 0;\n\n naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];\n naf[b][j] = 0;\n wnd[a] = comb;\n }\n }\n\n var acc = this.jpoint(null, null, null);\n var tmp = this._wnafT4;\n for (i = max; i >= 0; i--) {\n var k = 0;\n\n while (i >= 0) {\n var zero = true;\n for (j = 0; j < len; j++) {\n tmp[j] = naf[j][i] | 0;\n if (tmp[j] !== 0)\n zero = false;\n }\n if (!zero)\n break;\n k++;\n i--;\n }\n if (i >= 0)\n k++;\n acc = acc.dblp(k);\n if (i < 0)\n break;\n\n for (j = 0; j < len; j++) {\n var z = tmp[j];\n p;\n if (z === 0)\n continue;\n else if (z > 0)\n p = wnd[j][(z - 1) >> 1];\n else if (z < 0)\n p = wnd[j][(-z - 1) >> 1].neg();\n\n if (p.type === 'affine')\n acc = acc.mixedAdd(p);\n else\n acc = acc.add(p);\n }\n }\n // Zeroify references\n for (i = 0; i < len; i++)\n wnd[i] = null;\n\n if (jacobianResult)\n return acc;\n else\n return acc.toP();\n};\n\nfunction BasePoint(curve, type) {\n this.curve = curve;\n this.type = type;\n this.precomputed = null;\n}\nBaseCurve.BasePoint = BasePoint;\n\nBasePoint.prototype.eq = function eq(/*other*/) {\n throw new Error('Not implemented');\n};\n\nBasePoint.prototype.validate = function validate() {\n return this.curve.validate(this);\n};\n\nBaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {\n bytes = utils.toArray(bytes, enc);\n\n var len = this.p.byteLength();\n\n // uncompressed, hybrid-odd, hybrid-even\n if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&\n bytes.length - 1 === 2 * len) {\n if (bytes[0] === 0x06)\n assert(bytes[bytes.length - 1] % 2 === 0);\n else if (bytes[0] === 0x07)\n assert(bytes[bytes.length - 1] % 2 === 1);\n\n var res = this.point(bytes.slice(1, 1 + len),\n bytes.slice(1 + len, 1 + 2 * len));\n\n return res;\n } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&\n bytes.length - 1 === len) {\n return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);\n }\n throw new Error('Unknown point format');\n};\n\nBasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {\n return this.encode(enc, true);\n};\n\nBasePoint.prototype._encode = function _encode(compact) {\n var len = this.curve.p.byteLength();\n var x = this.getX().toArray('be', len);\n\n if (compact)\n return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);\n\n return [ 0x04 ].concat(x, this.getY().toArray('be', len));\n};\n\nBasePoint.prototype.encode = function encode(enc, compact) {\n return utils.encode(this._encode(compact), enc);\n};\n\nBasePoint.prototype.precompute = function precompute(power) {\n if (this.precomputed)\n return this;\n\n var precomputed = {\n doubles: null,\n naf: null,\n beta: null,\n };\n precomputed.naf = this._getNAFPoints(8);\n precomputed.doubles = this._getDoubles(4, power);\n precomputed.beta = this._getBeta();\n this.precomputed = precomputed;\n\n return this;\n};\n\nBasePoint.prototype._hasDoubles = function _hasDoubles(k) {\n if (!this.precomputed)\n return false;\n\n var doubles = this.precomputed.doubles;\n if (!doubles)\n return false;\n\n return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);\n};\n\nBasePoint.prototype._getDoubles = function _getDoubles(step, power) {\n if (this.precomputed && this.precomputed.doubles)\n return this.precomputed.doubles;\n\n var doubles = [ this ];\n var acc = this;\n for (var i = 0; i < power; i += step) {\n for (var j = 0; j < step; j++)\n acc = acc.dbl();\n doubles.push(acc);\n }\n return {\n step: step,\n points: doubles,\n };\n};\n\nBasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {\n if (this.precomputed && this.precomputed.naf)\n return this.precomputed.naf;\n\n var res = [ this ];\n var max = (1 << wnd) - 1;\n var dbl = max === 1 ? null : this.dbl();\n for (var i = 1; i < max; i++)\n res[i] = res[i - 1].add(dbl);\n return {\n wnd: wnd,\n points: res,\n };\n};\n\nBasePoint.prototype._getBeta = function _getBeta() {\n return null;\n};\n\nBasePoint.prototype.dblp = function dblp(k) {\n var r = this;\n for (var i = 0; i < k; i++)\n r = r.dbl();\n return r;\n};\n", - "'use strict';\n\nvar utils = require('../utils');\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar assert = utils.assert;\n\nfunction EdwardsCurve(conf) {\n // NOTE: Important as we are creating point in Base.call()\n this.twisted = (conf.a | 0) !== 1;\n this.mOneA = this.twisted && (conf.a | 0) === -1;\n this.extended = this.mOneA;\n\n Base.call(this, 'edwards', conf);\n\n this.a = new BN(conf.a, 16).umod(this.red.m);\n this.a = this.a.toRed(this.red);\n this.c = new BN(conf.c, 16).toRed(this.red);\n this.c2 = this.c.redSqr();\n this.d = new BN(conf.d, 16).toRed(this.red);\n this.dd = this.d.redAdd(this.d);\n\n assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);\n this.oneC = (conf.c | 0) === 1;\n}\ninherits(EdwardsCurve, Base);\nmodule.exports = EdwardsCurve;\n\nEdwardsCurve.prototype._mulA = function _mulA(num) {\n if (this.mOneA)\n return num.redNeg();\n else\n return this.a.redMul(num);\n};\n\nEdwardsCurve.prototype._mulC = function _mulC(num) {\n if (this.oneC)\n return num;\n else\n return this.c.redMul(num);\n};\n\n// Just for compatibility with Short curve\nEdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {\n return this.point(x, y, z, t);\n};\n\nEdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {\n x = new BN(x, 16);\n if (!x.red)\n x = x.toRed(this.red);\n\n var x2 = x.redSqr();\n var rhs = this.c2.redSub(this.a.redMul(x2));\n var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));\n\n var y2 = rhs.redMul(lhs.redInvm());\n var y = y2.redSqrt();\n if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n var isOdd = y.fromRed().isOdd();\n if (odd && !isOdd || !odd && isOdd)\n y = y.redNeg();\n\n return this.point(x, y);\n};\n\nEdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {\n y = new BN(y, 16);\n if (!y.red)\n y = y.toRed(this.red);\n\n // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)\n var y2 = y.redSqr();\n var lhs = y2.redSub(this.c2);\n var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);\n var x2 = lhs.redMul(rhs.redInvm());\n\n if (x2.cmp(this.zero) === 0) {\n if (odd)\n throw new Error('invalid point');\n else\n return this.point(this.zero, y);\n }\n\n var x = x2.redSqrt();\n if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n if (x.fromRed().isOdd() !== odd)\n x = x.redNeg();\n\n return this.point(x, y);\n};\n\nEdwardsCurve.prototype.validate = function validate(point) {\n if (point.isInfinity())\n return true;\n\n // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)\n point.normalize();\n\n var x2 = point.x.redSqr();\n var y2 = point.y.redSqr();\n var lhs = x2.redMul(this.a).redAdd(y2);\n var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));\n\n return lhs.cmp(rhs) === 0;\n};\n\nfunction Point(curve, x, y, z, t) {\n Base.BasePoint.call(this, curve, 'projective');\n if (x === null && y === null && z === null) {\n this.x = this.curve.zero;\n this.y = this.curve.one;\n this.z = this.curve.one;\n this.t = this.curve.zero;\n this.zOne = true;\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n this.z = z ? new BN(z, 16) : this.curve.one;\n this.t = t && new BN(t, 16);\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n if (this.t && !this.t.red)\n this.t = this.t.toRed(this.curve.red);\n this.zOne = this.z === this.curve.one;\n\n // Use extended coordinates\n if (this.curve.extended && !this.t) {\n this.t = this.x.redMul(this.y);\n if (!this.zOne)\n this.t = this.t.redMul(this.z.redInvm());\n }\n }\n}\ninherits(Point, Base.BasePoint);\n\nEdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {\n return Point.fromJSON(this, obj);\n};\n\nEdwardsCurve.prototype.point = function point(x, y, z, t) {\n return new Point(this, x, y, z, t);\n};\n\nPoint.fromJSON = function fromJSON(curve, obj) {\n return new Point(curve, obj[0], obj[1], obj[2]);\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.x.cmpn(0) === 0 &&\n (this.y.cmp(this.z) === 0 ||\n (this.zOne && this.y.cmp(this.curve.c) === 0));\n};\n\nPoint.prototype._extDbl = function _extDbl() {\n // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html\n // #doubling-dbl-2008-hwcd\n // 4M + 4S\n\n // A = X1^2\n var a = this.x.redSqr();\n // B = Y1^2\n var b = this.y.redSqr();\n // C = 2 * Z1^2\n var c = this.z.redSqr();\n c = c.redIAdd(c);\n // D = a * A\n var d = this.curve._mulA(a);\n // E = (X1 + Y1)^2 - A - B\n var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);\n // G = D + B\n var g = d.redAdd(b);\n // F = G - C\n var f = g.redSub(c);\n // H = D - B\n var h = d.redSub(b);\n // X3 = E * F\n var nx = e.redMul(f);\n // Y3 = G * H\n var ny = g.redMul(h);\n // T3 = E * H\n var nt = e.redMul(h);\n // Z3 = F * G\n var nz = f.redMul(g);\n return this.curve.point(nx, ny, nz, nt);\n};\n\nPoint.prototype._projDbl = function _projDbl() {\n // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html\n // #doubling-dbl-2008-bbjlp\n // #doubling-dbl-2007-bl\n // and others\n // Generally 3M + 4S or 2M + 4S\n\n // B = (X1 + Y1)^2\n var b = this.x.redAdd(this.y).redSqr();\n // C = X1^2\n var c = this.x.redSqr();\n // D = Y1^2\n var d = this.y.redSqr();\n\n var nx;\n var ny;\n var nz;\n var e;\n var h;\n var j;\n if (this.curve.twisted) {\n // E = a * C\n e = this.curve._mulA(c);\n // F = E + D\n var f = e.redAdd(d);\n if (this.zOne) {\n // X3 = (B - C - D) * (F - 2)\n nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));\n // Y3 = F * (E - D)\n ny = f.redMul(e.redSub(d));\n // Z3 = F^2 - 2 * F\n nz = f.redSqr().redSub(f).redSub(f);\n } else {\n // H = Z1^2\n h = this.z.redSqr();\n // J = F - 2 * H\n j = f.redSub(h).redISub(h);\n // X3 = (B-C-D)*J\n nx = b.redSub(c).redISub(d).redMul(j);\n // Y3 = F * (E - D)\n ny = f.redMul(e.redSub(d));\n // Z3 = F * J\n nz = f.redMul(j);\n }\n } else {\n // E = C + D\n e = c.redAdd(d);\n // H = (c * Z1)^2\n h = this.curve._mulC(this.z).redSqr();\n // J = E - 2 * H\n j = e.redSub(h).redSub(h);\n // X3 = c * (B - E) * J\n nx = this.curve._mulC(b.redISub(e)).redMul(j);\n // Y3 = c * E * (C - D)\n ny = this.curve._mulC(e).redMul(c.redISub(d));\n // Z3 = E * J\n nz = e.redMul(j);\n }\n return this.curve.point(nx, ny, nz);\n};\n\nPoint.prototype.dbl = function dbl() {\n if (this.isInfinity())\n return this;\n\n // Double in extended coordinates\n if (this.curve.extended)\n return this._extDbl();\n else\n return this._projDbl();\n};\n\nPoint.prototype._extAdd = function _extAdd(p) {\n // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html\n // #addition-add-2008-hwcd-3\n // 8M\n\n // A = (Y1 - X1) * (Y2 - X2)\n var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));\n // B = (Y1 + X1) * (Y2 + X2)\n var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));\n // C = T1 * k * T2\n var c = this.t.redMul(this.curve.dd).redMul(p.t);\n // D = Z1 * 2 * Z2\n var d = this.z.redMul(p.z.redAdd(p.z));\n // E = B - A\n var e = b.redSub(a);\n // F = D - C\n var f = d.redSub(c);\n // G = D + C\n var g = d.redAdd(c);\n // H = B + A\n var h = b.redAdd(a);\n // X3 = E * F\n var nx = e.redMul(f);\n // Y3 = G * H\n var ny = g.redMul(h);\n // T3 = E * H\n var nt = e.redMul(h);\n // Z3 = F * G\n var nz = f.redMul(g);\n return this.curve.point(nx, ny, nz, nt);\n};\n\nPoint.prototype._projAdd = function _projAdd(p) {\n // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html\n // #addition-add-2008-bbjlp\n // #addition-add-2007-bl\n // 10M + 1S\n\n // A = Z1 * Z2\n var a = this.z.redMul(p.z);\n // B = A^2\n var b = a.redSqr();\n // C = X1 * X2\n var c = this.x.redMul(p.x);\n // D = Y1 * Y2\n var d = this.y.redMul(p.y);\n // E = d * C * D\n var e = this.curve.d.redMul(c).redMul(d);\n // F = B - E\n var f = b.redSub(e);\n // G = B + E\n var g = b.redAdd(e);\n // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)\n var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);\n var nx = a.redMul(f).redMul(tmp);\n var ny;\n var nz;\n if (this.curve.twisted) {\n // Y3 = A * G * (D - a * C)\n ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));\n // Z3 = F * G\n nz = f.redMul(g);\n } else {\n // Y3 = A * G * (D - C)\n ny = a.redMul(g).redMul(d.redSub(c));\n // Z3 = c * F * G\n nz = this.curve._mulC(f).redMul(g);\n }\n return this.curve.point(nx, ny, nz);\n};\n\nPoint.prototype.add = function add(p) {\n if (this.isInfinity())\n return p;\n if (p.isInfinity())\n return this;\n\n if (this.curve.extended)\n return this._extAdd(p);\n else\n return this._projAdd(p);\n};\n\nPoint.prototype.mul = function mul(k) {\n if (this._hasDoubles(k))\n return this.curve._fixedNafMul(this, k);\n else\n return this.curve._wnafMul(this, k);\n};\n\nPoint.prototype.mulAdd = function mulAdd(k1, p, k2) {\n return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);\n};\n\nPoint.prototype.jmulAdd = function jmulAdd(k1, p, k2) {\n return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);\n};\n\nPoint.prototype.normalize = function normalize() {\n if (this.zOne)\n return this;\n\n // Normalize coordinates\n var zi = this.z.redInvm();\n this.x = this.x.redMul(zi);\n this.y = this.y.redMul(zi);\n if (this.t)\n this.t = this.t.redMul(zi);\n this.z = this.curve.one;\n this.zOne = true;\n return this;\n};\n\nPoint.prototype.neg = function neg() {\n return this.curve.point(this.x.redNeg(),\n this.y,\n this.z,\n this.t && this.t.redNeg());\n};\n\nPoint.prototype.getX = function getX() {\n this.normalize();\n return this.x.fromRed();\n};\n\nPoint.prototype.getY = function getY() {\n this.normalize();\n return this.y.fromRed();\n};\n\nPoint.prototype.eq = function eq(other) {\n return this === other ||\n this.getX().cmp(other.getX()) === 0 &&\n this.getY().cmp(other.getY()) === 0;\n};\n\nPoint.prototype.eqXToP = function eqXToP(x) {\n var rx = x.toRed(this.curve.red).redMul(this.z);\n if (this.x.cmp(rx) === 0)\n return true;\n\n var xc = x.clone();\n var t = this.curve.redN.redMul(this.z);\n for (;;) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0)\n return false;\n\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0)\n return true;\n }\n};\n\n// Compatibility with BaseCurve\nPoint.prototype.toP = Point.prototype.normalize;\nPoint.prototype.mixedAdd = Point.prototype.add;\n", - "'use strict';\n\nvar curve = exports;\n\ncurve.base = require('./base');\ncurve.short = require('./short');\ncurve.mont = require('./mont');\ncurve.edwards = require('./edwards');\n", - "'use strict';\n\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar utils = require('../utils');\n\nfunction MontCurve(conf) {\n Base.call(this, 'mont', conf);\n\n this.a = new BN(conf.a, 16).toRed(this.red);\n this.b = new BN(conf.b, 16).toRed(this.red);\n this.i4 = new BN(4).toRed(this.red).redInvm();\n this.two = new BN(2).toRed(this.red);\n this.a24 = this.i4.redMul(this.a.redAdd(this.two));\n}\ninherits(MontCurve, Base);\nmodule.exports = MontCurve;\n\nMontCurve.prototype.validate = function validate(point) {\n var x = point.normalize().x;\n var x2 = x.redSqr();\n var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);\n var y = rhs.redSqrt();\n\n return y.redSqr().cmp(rhs) === 0;\n};\n\nfunction Point(curve, x, z) {\n Base.BasePoint.call(this, curve, 'projective');\n if (x === null && z === null) {\n this.x = this.curve.one;\n this.z = this.curve.zero;\n } else {\n this.x = new BN(x, 16);\n this.z = new BN(z, 16);\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n }\n}\ninherits(Point, Base.BasePoint);\n\nMontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {\n return this.point(utils.toArray(bytes, enc), 1);\n};\n\nMontCurve.prototype.point = function point(x, z) {\n return new Point(this, x, z);\n};\n\nMontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {\n return Point.fromJSON(this, obj);\n};\n\nPoint.prototype.precompute = function precompute() {\n // No-op\n};\n\nPoint.prototype._encode = function _encode() {\n return this.getX().toArray('be', this.curve.p.byteLength());\n};\n\nPoint.fromJSON = function fromJSON(curve, obj) {\n return new Point(curve, obj[0], obj[1] || curve.one);\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.z.cmpn(0) === 0;\n};\n\nPoint.prototype.dbl = function dbl() {\n // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3\n // 2M + 2S + 4A\n\n // A = X1 + Z1\n var a = this.x.redAdd(this.z);\n // AA = A^2\n var aa = a.redSqr();\n // B = X1 - Z1\n var b = this.x.redSub(this.z);\n // BB = B^2\n var bb = b.redSqr();\n // C = AA - BB\n var c = aa.redSub(bb);\n // X3 = AA * BB\n var nx = aa.redMul(bb);\n // Z3 = C * (BB + A24 * C)\n var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));\n return this.curve.point(nx, nz);\n};\n\nPoint.prototype.add = function add() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.diffAdd = function diffAdd(p, diff) {\n // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3\n // 4M + 2S + 6A\n\n // A = X2 + Z2\n var a = this.x.redAdd(this.z);\n // B = X2 - Z2\n var b = this.x.redSub(this.z);\n // C = X3 + Z3\n var c = p.x.redAdd(p.z);\n // D = X3 - Z3\n var d = p.x.redSub(p.z);\n // DA = D * A\n var da = d.redMul(a);\n // CB = C * B\n var cb = c.redMul(b);\n // X5 = Z1 * (DA + CB)^2\n var nx = diff.z.redMul(da.redAdd(cb).redSqr());\n // Z5 = X1 * (DA - CB)^2\n var nz = diff.x.redMul(da.redISub(cb).redSqr());\n return this.curve.point(nx, nz);\n};\n\nPoint.prototype.mul = function mul(k) {\n var t = k.clone();\n var a = this; // (N / 2) * Q + Q\n var b = this.curve.point(null, null); // (N / 2) * Q\n var c = this; // Q\n\n for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))\n bits.push(t.andln(1));\n\n for (var i = bits.length - 1; i >= 0; i--) {\n if (bits[i] === 0) {\n // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q\n a = a.diffAdd(b, c);\n // N * Q = 2 * ((N / 2) * Q + Q))\n b = b.dbl();\n } else {\n // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)\n b = a.diffAdd(b, c);\n // N * Q + Q = 2 * ((N / 2) * Q + Q)\n a = a.dbl();\n }\n }\n return b;\n};\n\nPoint.prototype.mulAdd = function mulAdd() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.jumlAdd = function jumlAdd() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.eq = function eq(other) {\n return this.getX().cmp(other.getX()) === 0;\n};\n\nPoint.prototype.normalize = function normalize() {\n this.x = this.x.redMul(this.z.redInvm());\n this.z = this.curve.one;\n return this;\n};\n\nPoint.prototype.getX = function getX() {\n // Normalize coordinates\n this.normalize();\n\n return this.x.fromRed();\n};\n", - "'use strict';\n\nvar utils = require('../utils');\nvar BN = require('bn.js');\nvar inherits = require('inherits');\nvar Base = require('./base');\n\nvar assert = utils.assert;\n\nfunction ShortCurve(conf) {\n Base.call(this, 'short', conf);\n\n this.a = new BN(conf.a, 16).toRed(this.red);\n this.b = new BN(conf.b, 16).toRed(this.red);\n this.tinv = this.two.redInvm();\n\n this.zeroA = this.a.fromRed().cmpn(0) === 0;\n this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;\n\n // If the curve is endomorphic, precalculate beta and lambda\n this.endo = this._getEndomorphism(conf);\n this._endoWnafT1 = new Array(4);\n this._endoWnafT2 = new Array(4);\n}\ninherits(ShortCurve, Base);\nmodule.exports = ShortCurve;\n\nShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {\n // No efficient endomorphism\n if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)\n return;\n\n // Compute beta and lambda, that lambda * P = (beta * Px; Py)\n var beta;\n var lambda;\n if (conf.beta) {\n beta = new BN(conf.beta, 16).toRed(this.red);\n } else {\n var betas = this._getEndoRoots(this.p);\n // Choose the smallest beta\n beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];\n beta = beta.toRed(this.red);\n }\n if (conf.lambda) {\n lambda = new BN(conf.lambda, 16);\n } else {\n // Choose the lambda that is matching selected beta\n var lambdas = this._getEndoRoots(this.n);\n if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {\n lambda = lambdas[0];\n } else {\n lambda = lambdas[1];\n assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);\n }\n }\n\n // Get basis vectors, used for balanced length-two representation\n var basis;\n if (conf.basis) {\n basis = conf.basis.map(function(vec) {\n return {\n a: new BN(vec.a, 16),\n b: new BN(vec.b, 16),\n };\n });\n } else {\n basis = this._getEndoBasis(lambda);\n }\n\n return {\n beta: beta,\n lambda: lambda,\n basis: basis,\n };\n};\n\nShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {\n // Find roots of for x^2 + x + 1 in F\n // Root = (-1 +- Sqrt(-3)) / 2\n //\n var red = num === this.p ? this.red : BN.mont(num);\n var tinv = new BN(2).toRed(red).redInvm();\n var ntinv = tinv.redNeg();\n\n var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);\n\n var l1 = ntinv.redAdd(s).fromRed();\n var l2 = ntinv.redSub(s).fromRed();\n return [ l1, l2 ];\n};\n\nShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {\n // aprxSqrt >= sqrt(this.n)\n var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));\n\n // 3.74\n // Run EGCD, until r(L + 1) < aprxSqrt\n var u = lambda;\n var v = this.n.clone();\n var x1 = new BN(1);\n var y1 = new BN(0);\n var x2 = new BN(0);\n var y2 = new BN(1);\n\n // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)\n var a0;\n var b0;\n // First vector\n var a1;\n var b1;\n // Second vector\n var a2;\n var b2;\n\n var prevR;\n var i = 0;\n var r;\n var x;\n while (u.cmpn(0) !== 0) {\n var q = v.div(u);\n r = v.sub(q.mul(u));\n x = x2.sub(q.mul(x1));\n var y = y2.sub(q.mul(y1));\n\n if (!a1 && r.cmp(aprxSqrt) < 0) {\n a0 = prevR.neg();\n b0 = x1;\n a1 = r.neg();\n b1 = x;\n } else if (a1 && ++i === 2) {\n break;\n }\n prevR = r;\n\n v = u;\n u = r;\n x2 = x1;\n x1 = x;\n y2 = y1;\n y1 = y;\n }\n a2 = r.neg();\n b2 = x;\n\n var len1 = a1.sqr().add(b1.sqr());\n var len2 = a2.sqr().add(b2.sqr());\n if (len2.cmp(len1) >= 0) {\n a2 = a0;\n b2 = b0;\n }\n\n // Normalize signs\n if (a1.negative) {\n a1 = a1.neg();\n b1 = b1.neg();\n }\n if (a2.negative) {\n a2 = a2.neg();\n b2 = b2.neg();\n }\n\n return [\n { a: a1, b: b1 },\n { a: a2, b: b2 },\n ];\n};\n\nShortCurve.prototype._endoSplit = function _endoSplit(k) {\n var basis = this.endo.basis;\n var v1 = basis[0];\n var v2 = basis[1];\n\n var c1 = v2.b.mul(k).divRound(this.n);\n var c2 = v1.b.neg().mul(k).divRound(this.n);\n\n var p1 = c1.mul(v1.a);\n var p2 = c2.mul(v2.a);\n var q1 = c1.mul(v1.b);\n var q2 = c2.mul(v2.b);\n\n // Calculate answer\n var k1 = k.sub(p1).sub(p2);\n var k2 = q1.add(q2).neg();\n return { k1: k1, k2: k2 };\n};\n\nShortCurve.prototype.pointFromX = function pointFromX(x, odd) {\n x = new BN(x, 16);\n if (!x.red)\n x = x.toRed(this.red);\n\n var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);\n var y = y2.redSqrt();\n if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n // XXX Is there any way to tell if the number is odd without converting it\n // to non-red form?\n var isOdd = y.fromRed().isOdd();\n if (odd && !isOdd || !odd && isOdd)\n y = y.redNeg();\n\n return this.point(x, y);\n};\n\nShortCurve.prototype.validate = function validate(point) {\n if (point.inf)\n return true;\n\n var x = point.x;\n var y = point.y;\n\n var ax = this.a.redMul(x);\n var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);\n return y.redSqr().redISub(rhs).cmpn(0) === 0;\n};\n\nShortCurve.prototype._endoWnafMulAdd =\n function _endoWnafMulAdd(points, coeffs, jacobianResult) {\n var npoints = this._endoWnafT1;\n var ncoeffs = this._endoWnafT2;\n for (var i = 0; i < points.length; i++) {\n var split = this._endoSplit(coeffs[i]);\n var p = points[i];\n var beta = p._getBeta();\n\n if (split.k1.negative) {\n split.k1.ineg();\n p = p.neg(true);\n }\n if (split.k2.negative) {\n split.k2.ineg();\n beta = beta.neg(true);\n }\n\n npoints[i * 2] = p;\n npoints[i * 2 + 1] = beta;\n ncoeffs[i * 2] = split.k1;\n ncoeffs[i * 2 + 1] = split.k2;\n }\n var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);\n\n // Clean-up references to points and coefficients\n for (var j = 0; j < i * 2; j++) {\n npoints[j] = null;\n ncoeffs[j] = null;\n }\n return res;\n };\n\nfunction Point(curve, x, y, isRed) {\n Base.BasePoint.call(this, curve, 'affine');\n if (x === null && y === null) {\n this.x = null;\n this.y = null;\n this.inf = true;\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n // Force redgomery representation when loading from JSON\n if (isRed) {\n this.x.forceRed(this.curve.red);\n this.y.forceRed(this.curve.red);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n this.inf = false;\n }\n}\ninherits(Point, Base.BasePoint);\n\nShortCurve.prototype.point = function point(x, y, isRed) {\n return new Point(this, x, y, isRed);\n};\n\nShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {\n return Point.fromJSON(this, obj, red);\n};\n\nPoint.prototype._getBeta = function _getBeta() {\n if (!this.curve.endo)\n return;\n\n var pre = this.precomputed;\n if (pre && pre.beta)\n return pre.beta;\n\n var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);\n if (pre) {\n var curve = this.curve;\n var endoMul = function(p) {\n return curve.point(p.x.redMul(curve.endo.beta), p.y);\n };\n pre.beta = beta;\n beta.precomputed = {\n beta: null,\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(endoMul),\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(endoMul),\n },\n };\n }\n return beta;\n};\n\nPoint.prototype.toJSON = function toJSON() {\n if (!this.precomputed)\n return [ this.x, this.y ];\n\n return [ this.x, this.y, this.precomputed && {\n doubles: this.precomputed.doubles && {\n step: this.precomputed.doubles.step,\n points: this.precomputed.doubles.points.slice(1),\n },\n naf: this.precomputed.naf && {\n wnd: this.precomputed.naf.wnd,\n points: this.precomputed.naf.points.slice(1),\n },\n } ];\n};\n\nPoint.fromJSON = function fromJSON(curve, obj, red) {\n if (typeof obj === 'string')\n obj = JSON.parse(obj);\n var res = curve.point(obj[0], obj[1], red);\n if (!obj[2])\n return res;\n\n function obj2point(obj) {\n return curve.point(obj[0], obj[1], red);\n }\n\n var pre = obj[2];\n res.precomputed = {\n beta: null,\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: [ res ].concat(pre.doubles.points.map(obj2point)),\n },\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: [ res ].concat(pre.naf.points.map(obj2point)),\n },\n };\n return res;\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n return this.inf;\n};\n\nPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.inf)\n return p;\n\n // P + O = P\n if (p.inf)\n return this;\n\n // P + P = 2P\n if (this.eq(p))\n return this.dbl();\n\n // P + (-P) = O\n if (this.neg().eq(p))\n return this.curve.point(null, null);\n\n // P + Q = O\n if (this.x.cmp(p.x) === 0)\n return this.curve.point(null, null);\n\n var c = this.y.redSub(p.y);\n if (c.cmpn(0) !== 0)\n c = c.redMul(this.x.redSub(p.x).redInvm());\n var nx = c.redSqr().redISub(this.x).redISub(p.x);\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.dbl = function dbl() {\n if (this.inf)\n return this;\n\n // 2P = O\n var ys1 = this.y.redAdd(this.y);\n if (ys1.cmpn(0) === 0)\n return this.curve.point(null, null);\n\n var a = this.curve.a;\n\n var x2 = this.x.redSqr();\n var dyinv = ys1.redInvm();\n var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);\n\n var nx = c.redSqr().redISub(this.x.redAdd(this.x));\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.getX = function getX() {\n return this.x.fromRed();\n};\n\nPoint.prototype.getY = function getY() {\n return this.y.fromRed();\n};\n\nPoint.prototype.mul = function mul(k) {\n k = new BN(k, 16);\n if (this.isInfinity())\n return this;\n else if (this._hasDoubles(k))\n return this.curve._fixedNafMul(this, k);\n else if (this.curve.endo)\n return this.curve._endoWnafMulAdd([ this ], [ k ]);\n else\n return this.curve._wnafMul(this, k);\n};\n\nPoint.prototype.mulAdd = function mulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2);\n};\n\nPoint.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs, true);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2, true);\n};\n\nPoint.prototype.eq = function eq(p) {\n return this === p ||\n this.inf === p.inf &&\n (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);\n};\n\nPoint.prototype.neg = function neg(_precompute) {\n if (this.inf)\n return this;\n\n var res = this.curve.point(this.x, this.y.redNeg());\n if (_precompute && this.precomputed) {\n var pre = this.precomputed;\n var negate = function(p) {\n return p.neg();\n };\n res.precomputed = {\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(negate),\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(negate),\n },\n };\n }\n return res;\n};\n\nPoint.prototype.toJ = function toJ() {\n if (this.inf)\n return this.curve.jpoint(null, null, null);\n\n var res = this.curve.jpoint(this.x, this.y, this.curve.one);\n return res;\n};\n\nfunction JPoint(curve, x, y, z) {\n Base.BasePoint.call(this, curve, 'jacobian');\n if (x === null && y === null && z === null) {\n this.x = this.curve.one;\n this.y = this.curve.one;\n this.z = new BN(0);\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n this.z = new BN(z, 16);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n\n this.zOne = this.z === this.curve.one;\n}\ninherits(JPoint, Base.BasePoint);\n\nShortCurve.prototype.jpoint = function jpoint(x, y, z) {\n return new JPoint(this, x, y, z);\n};\n\nJPoint.prototype.toP = function toP() {\n if (this.isInfinity())\n return this.curve.point(null, null);\n\n var zinv = this.z.redInvm();\n var zinv2 = zinv.redSqr();\n var ax = this.x.redMul(zinv2);\n var ay = this.y.redMul(zinv2).redMul(zinv);\n\n return this.curve.point(ax, ay);\n};\n\nJPoint.prototype.neg = function neg() {\n return this.curve.jpoint(this.x, this.y.redNeg(), this.z);\n};\n\nJPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.isInfinity())\n return p;\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 12M + 4S + 7A\n var pz2 = p.z.redSqr();\n var z2 = this.z.redSqr();\n var u1 = this.x.redMul(pz2);\n var u2 = p.x.redMul(z2);\n var s1 = this.y.redMul(pz2.redMul(p.z));\n var s2 = p.y.redMul(z2.redMul(this.z));\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(p.z).redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mixedAdd = function mixedAdd(p) {\n // O + P = P\n if (this.isInfinity())\n return p.toJ();\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 8M + 3S + 7A\n var z2 = this.z.redSqr();\n var u1 = this.x;\n var u2 = p.x.redMul(z2);\n var s1 = this.y;\n var s2 = p.y.redMul(z2).redMul(this.z);\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.dblp = function dblp(pow) {\n if (pow === 0)\n return this;\n if (this.isInfinity())\n return this;\n if (!pow)\n return this.dbl();\n\n var i;\n if (this.curve.zeroA || this.curve.threeA) {\n var r = this;\n for (i = 0; i < pow; i++)\n r = r.dbl();\n return r;\n }\n\n // 1M + 2S + 1A + N * (4S + 5M + 8A)\n // N = 1 => 6M + 6S + 9A\n var a = this.curve.a;\n var tinv = this.curve.tinv;\n\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n // Reuse results\n var jyd = jy.redAdd(jy);\n for (i = 0; i < pow; i++) {\n var jx2 = jx.redSqr();\n var jyd2 = jyd.redSqr();\n var jyd4 = jyd2.redSqr();\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var t1 = jx.redMul(jyd2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n var dny = c.redMul(t2);\n dny = dny.redIAdd(dny).redISub(jyd4);\n var nz = jyd.redMul(jz);\n if (i + 1 < pow)\n jz4 = jz4.redMul(jyd4);\n\n jx = nx;\n jz = nz;\n jyd = dny;\n }\n\n return this.curve.jpoint(jx, jyd.redMul(tinv), jz);\n};\n\nJPoint.prototype.dbl = function dbl() {\n if (this.isInfinity())\n return this;\n\n if (this.curve.zeroA)\n return this._zeroDbl();\n else if (this.curve.threeA)\n return this._threeDbl();\n else\n return this._dbl();\n};\n\nJPoint.prototype._zeroDbl = function _zeroDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 14A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // T = M ^ 2 - 2*S\n var t = m.redSqr().redISub(s).redISub(s);\n\n // 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2*Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-dbl-2009-l\n // 2M + 5S + 13A\n\n // A = X1^2\n var a = this.x.redSqr();\n // B = Y1^2\n var b = this.y.redSqr();\n // C = B^2\n var c = b.redSqr();\n // D = 2 * ((X1 + B)^2 - A - C)\n var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);\n d = d.redIAdd(d);\n // E = 3 * A\n var e = a.redAdd(a).redIAdd(a);\n // F = E^2\n var f = e.redSqr();\n\n // 8 * C\n var c8 = c.redIAdd(c);\n c8 = c8.redIAdd(c8);\n c8 = c8.redIAdd(c8);\n\n // X3 = F - 2 * D\n nx = f.redISub(d).redISub(d);\n // Y3 = E * (D - X3) - 8 * C\n ny = e.redMul(d.redISub(nx)).redISub(c8);\n // Z3 = 2 * Y1 * Z1\n nz = this.y.redMul(this.z);\n nz = nz.redIAdd(nz);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._threeDbl = function _threeDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 15A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a\n var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);\n // T = M^2 - 2 * S\n var t = m.redSqr().redISub(s).redISub(s);\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2 * Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b\n // 3M + 5S\n\n // delta = Z1^2\n var delta = this.z.redSqr();\n // gamma = Y1^2\n var gamma = this.y.redSqr();\n // beta = X1 * gamma\n var beta = this.x.redMul(gamma);\n // alpha = 3 * (X1 - delta) * (X1 + delta)\n var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));\n alpha = alpha.redAdd(alpha).redIAdd(alpha);\n // X3 = alpha^2 - 8 * beta\n var beta4 = beta.redIAdd(beta);\n beta4 = beta4.redIAdd(beta4);\n var beta8 = beta4.redAdd(beta4);\n nx = alpha.redSqr().redISub(beta8);\n // Z3 = (Y1 + Z1)^2 - gamma - delta\n nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);\n // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2\n var ggamma8 = gamma.redSqr();\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._dbl = function _dbl() {\n var a = this.curve.a;\n\n // 4M + 6S + 10A\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n var jx2 = jx.redSqr();\n var jy2 = jy.redSqr();\n\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var jxd4 = jx.redAdd(jx);\n jxd4 = jxd4.redIAdd(jxd4);\n var t1 = jxd4.redMul(jy2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n\n var jyd8 = jy2.redSqr();\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n var ny = c.redMul(t2).redISub(jyd8);\n var nz = jy.redAdd(jy).redMul(jz);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.trpl = function trpl() {\n if (!this.curve.zeroA)\n return this.dbl().add(this);\n\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl\n // 5M + 10S + ...\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // ZZ = Z1^2\n var zz = this.z.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // M = 3 * XX + a * ZZ2; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // MM = M^2\n var mm = m.redSqr();\n // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM\n var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n e = e.redIAdd(e);\n e = e.redAdd(e).redIAdd(e);\n e = e.redISub(mm);\n // EE = E^2\n var ee = e.redSqr();\n // T = 16*YYYY\n var t = yyyy.redIAdd(yyyy);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n // U = (M + E)^2 - MM - EE - T\n var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);\n // X3 = 4 * (X1 * EE - 4 * YY * U)\n var yyu4 = yy.redMul(u);\n yyu4 = yyu4.redIAdd(yyu4);\n yyu4 = yyu4.redIAdd(yyu4);\n var nx = this.x.redMul(ee).redISub(yyu4);\n nx = nx.redIAdd(nx);\n nx = nx.redIAdd(nx);\n // Y3 = 8 * Y1 * (U * (T - U) - E * EE)\n var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n // Z3 = (Z1 + E)^2 - ZZ - EE\n var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mul = function mul(k, kbase) {\n k = new BN(k, kbase);\n\n return this.curve._wnafMul(this, k);\n};\n\nJPoint.prototype.eq = function eq(p) {\n if (p.type === 'affine')\n return this.eq(p.toJ());\n\n if (this === p)\n return true;\n\n // x1 * z2^2 == x2 * z1^2\n var z2 = this.z.redSqr();\n var pz2 = p.z.redSqr();\n if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)\n return false;\n\n // y1 * z2^3 == y2 * z1^3\n var z3 = z2.redMul(this.z);\n var pz3 = pz2.redMul(p.z);\n return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;\n};\n\nJPoint.prototype.eqXToP = function eqXToP(x) {\n var zs = this.z.redSqr();\n var rx = x.toRed(this.curve.red).redMul(zs);\n if (this.x.cmp(rx) === 0)\n return true;\n\n var xc = x.clone();\n var t = this.curve.redN.redMul(zs);\n for (;;) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0)\n return false;\n\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0)\n return true;\n }\n};\n\nJPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nJPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.z.cmpn(0) === 0;\n};\n", - "'use strict';\n\nvar curves = exports;\n\nvar hash = require('hash.js');\nvar curve = require('./curve');\nvar utils = require('./utils');\n\nvar assert = utils.assert;\n\nfunction PresetCurve(options) {\n if (options.type === 'short')\n this.curve = new curve.short(options);\n else if (options.type === 'edwards')\n this.curve = new curve.edwards(options);\n else\n this.curve = new curve.mont(options);\n this.g = this.curve.g;\n this.n = this.curve.n;\n this.hash = options.hash;\n\n assert(this.g.validate(), 'Invalid curve');\n assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');\n}\ncurves.PresetCurve = PresetCurve;\n\nfunction defineCurve(name, options) {\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n get: function() {\n var curve = new PresetCurve(options);\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n value: curve,\n });\n return curve;\n },\n });\n}\n\ndefineCurve('p192', {\n type: 'short',\n prime: 'p192',\n p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',\n b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',\n n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',\n hash: hash.sha256,\n gRed: false,\n g: [\n '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',\n '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811',\n ],\n});\n\ndefineCurve('p224', {\n type: 'short',\n prime: 'p224',\n p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',\n b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',\n n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',\n hash: hash.sha256,\n gRed: false,\n g: [\n 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',\n 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34',\n ],\n});\n\ndefineCurve('p256', {\n type: 'short',\n prime: null,\n p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',\n a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',\n b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',\n n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',\n hash: hash.sha256,\n gRed: false,\n g: [\n '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',\n '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5',\n ],\n});\n\ndefineCurve('p384', {\n type: 'short',\n prime: null,\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 ffffffff',\n a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 fffffffc',\n b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +\n '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',\n n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +\n 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',\n hash: hash.sha384,\n gRed: false,\n g: [\n 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +\n '5502f25d bf55296c 3a545e38 72760ab7',\n '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +\n '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f',\n ],\n});\n\ndefineCurve('p521', {\n type: 'short',\n prime: null,\n p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff',\n a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff fffffffc',\n b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +\n '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +\n '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',\n n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +\n 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',\n hash: hash.sha512,\n gRed: false,\n g: [\n '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +\n '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +\n 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',\n '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +\n '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +\n '3fad0761 353c7086 a272c240 88be9476 9fd16650',\n ],\n});\n\ndefineCurve('curve25519', {\n type: 'mont',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '76d06',\n b: '1',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n hash: hash.sha256,\n gRed: false,\n g: [\n '9',\n ],\n});\n\ndefineCurve('ed25519', {\n type: 'edwards',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '-1',\n c: '1',\n // -121665 * (121666^(-1)) (mod P)\n d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n hash: hash.sha256,\n gRed: false,\n g: [\n '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',\n\n // 4/5\n '6666666666666666666666666666666666666666666666666666666666666658',\n ],\n});\n\nvar pre;\ntry {\n pre = require('./precomputed/secp256k1');\n} catch (e) {\n pre = undefined;\n}\n\ndefineCurve('secp256k1', {\n type: 'short',\n prime: 'k256',\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',\n a: '0',\n b: '7',\n n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',\n h: '1',\n hash: hash.sha256,\n\n // Precomputed endomorphism\n beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',\n lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',\n basis: [\n {\n a: '3086d221a7d46bcde86c90e49284eb15',\n b: '-e4437ed6010e88286f547fa90abfe4c3',\n },\n {\n a: '114ca50f7a8e2f3f657c1108d9d44cfd8',\n b: '3086d221a7d46bcde86c90e49284eb15',\n },\n ],\n\n gRed: false,\n g: [\n '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',\n '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',\n pre,\n ],\n});\n", - "'use strict';\n\nvar BN = require('bn.js');\nvar HmacDRBG = require('hmac-drbg');\nvar utils = require('../utils');\nvar curves = require('../curves');\nvar rand = require('brorand');\nvar assert = utils.assert;\n\nvar KeyPair = require('./key');\nvar Signature = require('./signature');\n\nfunction EC(options) {\n if (!(this instanceof EC))\n return new EC(options);\n\n // Shortcut `elliptic.ec(curve-name)`\n if (typeof options === 'string') {\n assert(Object.prototype.hasOwnProperty.call(curves, options),\n 'Unknown curve ' + options);\n\n options = curves[options];\n }\n\n // Shortcut for `elliptic.ec(elliptic.curves.curveName)`\n if (options instanceof curves.PresetCurve)\n options = { curve: options };\n\n this.curve = options.curve.curve;\n this.n = this.curve.n;\n this.nh = this.n.ushrn(1);\n this.g = this.curve.g;\n\n // Point on curve\n this.g = options.curve.g;\n this.g.precompute(options.curve.n.bitLength() + 1);\n\n // Hash for function for DRBG\n this.hash = options.hash || options.curve.hash;\n}\nmodule.exports = EC;\n\nEC.prototype.keyPair = function keyPair(options) {\n return new KeyPair(this, options);\n};\n\nEC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {\n return KeyPair.fromPrivate(this, priv, enc);\n};\n\nEC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {\n return KeyPair.fromPublic(this, pub, enc);\n};\n\nEC.prototype.genKeyPair = function genKeyPair(options) {\n if (!options)\n options = {};\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n entropy: options.entropy || rand(this.hash.hmacStrength),\n entropyEnc: options.entropy && options.entropyEnc || 'utf8',\n nonce: this.n.toArray(),\n });\n\n var bytes = this.n.byteLength();\n var ns2 = this.n.sub(new BN(2));\n for (;;) {\n var priv = new BN(drbg.generate(bytes));\n if (priv.cmp(ns2) > 0)\n continue;\n\n priv.iaddn(1);\n return this.keyFromPrivate(priv);\n }\n};\n\nEC.prototype._truncateToN = function _truncateToN(msg, truncOnly) {\n var delta = msg.byteLength() * 8 - this.n.bitLength();\n if (delta > 0)\n msg = msg.ushrn(delta);\n if (!truncOnly && msg.cmp(this.n) >= 0)\n return msg.sub(this.n);\n else\n return msg;\n};\n\nEC.prototype.sign = function sign(msg, key, enc, options) {\n if (typeof enc === 'object') {\n options = enc;\n enc = null;\n }\n if (!options)\n options = {};\n\n key = this.keyFromPrivate(key, enc);\n msg = this._truncateToN(new BN(msg, 16));\n\n // Zero-extend key to provide enough entropy\n var bytes = this.n.byteLength();\n var bkey = key.getPrivate().toArray('be', bytes);\n\n // Zero-extend nonce to have the same byte size as N\n var nonce = msg.toArray('be', bytes);\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n entropy: bkey,\n nonce: nonce,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n });\n\n // Number of bytes to generate\n var ns1 = this.n.sub(new BN(1));\n\n for (var iter = 0; ; iter++) {\n var k = options.k ?\n options.k(iter) :\n new BN(drbg.generate(this.n.byteLength()));\n k = this._truncateToN(k, true);\n if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)\n continue;\n\n var kp = this.g.mul(k);\n if (kp.isInfinity())\n continue;\n\n var kpX = kp.getX();\n var r = kpX.umod(this.n);\n if (r.cmpn(0) === 0)\n continue;\n\n var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));\n s = s.umod(this.n);\n if (s.cmpn(0) === 0)\n continue;\n\n var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |\n (kpX.cmp(r) !== 0 ? 2 : 0);\n\n // Use complement of `s`, if it is > `n / 2`\n if (options.canonical && s.cmp(this.nh) > 0) {\n s = this.n.sub(s);\n recoveryParam ^= 1;\n }\n\n return new Signature({ r: r, s: s, recoveryParam: recoveryParam });\n }\n};\n\nEC.prototype.verify = function verify(msg, signature, key, enc) {\n msg = this._truncateToN(new BN(msg, 16));\n key = this.keyFromPublic(key, enc);\n signature = new Signature(signature, 'hex');\n\n // Perform primitive values validation\n var r = signature.r;\n var s = signature.s;\n if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)\n return false;\n if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)\n return false;\n\n // Validate signature\n var sinv = s.invm(this.n);\n var u1 = sinv.mul(msg).umod(this.n);\n var u2 = sinv.mul(r).umod(this.n);\n var p;\n\n if (!this.curve._maxwellTrick) {\n p = this.g.mulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n return p.getX().umod(this.n).cmp(r) === 0;\n }\n\n // NOTE: Greg Maxwell's trick, inspired by:\n // https://git.io/vad3K\n\n p = this.g.jmulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n // Compare `p.x` of Jacobian point with `r`,\n // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the\n // inverse of `p.z^2`\n return p.eqXToP(r);\n};\n\nEC.prototype.recoverPubKey = function(msg, signature, j, enc) {\n assert((3 & j) === j, 'The recovery param is more than two bits');\n signature = new Signature(signature, enc);\n\n var n = this.n;\n var e = new BN(msg);\n var r = signature.r;\n var s = signature.s;\n\n // A set LSB signifies that the y-coordinate is odd\n var isYOdd = j & 1;\n var isSecondKey = j >> 1;\n if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)\n throw new Error('Unable to find sencond key candinate');\n\n // 1.1. Let x = r + jn.\n if (isSecondKey)\n r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);\n else\n r = this.curve.pointFromX(r, isYOdd);\n\n var rInv = signature.r.invm(n);\n var s1 = n.sub(e).mul(rInv).umod(n);\n var s2 = s.mul(rInv).umod(n);\n\n // 1.6.1 Compute Q = r^-1 (sR - eG)\n // Q = r^-1 (sR + -eG)\n return this.g.mulAdd(s1, r, s2);\n};\n\nEC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {\n signature = new Signature(signature, enc);\n if (signature.recoveryParam !== null)\n return signature.recoveryParam;\n\n for (var i = 0; i < 4; i++) {\n var Qprime;\n try {\n Qprime = this.recoverPubKey(e, signature, i);\n } catch (e) {\n continue;\n }\n\n if (Qprime.eq(Q))\n return i;\n }\n throw new Error('Unable to find valid recovery factor');\n};\n", - "'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar assert = utils.assert;\n\nfunction KeyPair(ec, options) {\n this.ec = ec;\n this.priv = null;\n this.pub = null;\n\n // KeyPair(ec, { priv: ..., pub: ... })\n if (options.priv)\n this._importPrivate(options.priv, options.privEnc);\n if (options.pub)\n this._importPublic(options.pub, options.pubEnc);\n}\nmodule.exports = KeyPair;\n\nKeyPair.fromPublic = function fromPublic(ec, pub, enc) {\n if (pub instanceof KeyPair)\n return pub;\n\n return new KeyPair(ec, {\n pub: pub,\n pubEnc: enc,\n });\n};\n\nKeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {\n if (priv instanceof KeyPair)\n return priv;\n\n return new KeyPair(ec, {\n priv: priv,\n privEnc: enc,\n });\n};\n\nKeyPair.prototype.validate = function validate() {\n var pub = this.getPublic();\n\n if (pub.isInfinity())\n return { result: false, reason: 'Invalid public key' };\n if (!pub.validate())\n return { result: false, reason: 'Public key is not a point' };\n if (!pub.mul(this.ec.curve.n).isInfinity())\n return { result: false, reason: 'Public key * N != O' };\n\n return { result: true, reason: null };\n};\n\nKeyPair.prototype.getPublic = function getPublic(compact, enc) {\n // compact is optional argument\n if (typeof compact === 'string') {\n enc = compact;\n compact = null;\n }\n\n if (!this.pub)\n this.pub = this.ec.g.mul(this.priv);\n\n if (!enc)\n return this.pub;\n\n return this.pub.encode(enc, compact);\n};\n\nKeyPair.prototype.getPrivate = function getPrivate(enc) {\n if (enc === 'hex')\n return this.priv.toString(16, 2);\n else\n return this.priv;\n};\n\nKeyPair.prototype._importPrivate = function _importPrivate(key, enc) {\n this.priv = new BN(key, enc || 16);\n\n // Ensure that the priv won't be bigger than n, otherwise we may fail\n // in fixed multiplication method\n this.priv = this.priv.umod(this.ec.curve.n);\n};\n\nKeyPair.prototype._importPublic = function _importPublic(key, enc) {\n if (key.x || key.y) {\n // Montgomery points only have an `x` coordinate.\n // Weierstrass/Edwards points on the other hand have both `x` and\n // `y` coordinates.\n if (this.ec.curve.type === 'mont') {\n assert(key.x, 'Need x coordinate');\n } else if (this.ec.curve.type === 'short' ||\n this.ec.curve.type === 'edwards') {\n assert(key.x && key.y, 'Need both x and y coordinate');\n }\n this.pub = this.ec.curve.point(key.x, key.y);\n return;\n }\n this.pub = this.ec.curve.decodePoint(key, enc);\n};\n\n// ECDH\nKeyPair.prototype.derive = function derive(pub) {\n if(!pub.validate()) {\n assert(pub.validate(), 'public point not validated');\n }\n return pub.mul(this.priv).getX();\n};\n\n// ECDSA\nKeyPair.prototype.sign = function sign(msg, enc, options) {\n return this.ec.sign(msg, this, enc, options);\n};\n\nKeyPair.prototype.verify = function verify(msg, signature) {\n return this.ec.verify(msg, signature, this);\n};\n\nKeyPair.prototype.inspect = function inspect() {\n return '';\n};\n", - "'use strict';\n\nvar BN = require('bn.js');\n\nvar utils = require('../utils');\nvar assert = utils.assert;\n\nfunction Signature(options, enc) {\n if (options instanceof Signature)\n return options;\n\n if (this._importDER(options, enc))\n return;\n\n assert(options.r && options.s, 'Signature without r or s');\n this.r = new BN(options.r, 16);\n this.s = new BN(options.s, 16);\n if (options.recoveryParam === undefined)\n this.recoveryParam = null;\n else\n this.recoveryParam = options.recoveryParam;\n}\nmodule.exports = Signature;\n\nfunction Position() {\n this.place = 0;\n}\n\nfunction getLength(buf, p) {\n var initial = buf[p.place++];\n if (!(initial & 0x80)) {\n return initial;\n }\n var octetLen = initial & 0xf;\n\n // Indefinite length or overflow\n if (octetLen === 0 || octetLen > 4) {\n return false;\n }\n\n var val = 0;\n for (var i = 0, off = p.place; i < octetLen; i++, off++) {\n val <<= 8;\n val |= buf[off];\n val >>>= 0;\n }\n\n // Leading zeroes\n if (val <= 0x7f) {\n return false;\n }\n\n p.place = off;\n return val;\n}\n\nfunction rmPadding(buf) {\n var i = 0;\n var len = buf.length - 1;\n while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {\n i++;\n }\n if (i === 0) {\n return buf;\n }\n return buf.slice(i);\n}\n\nSignature.prototype._importDER = function _importDER(data, enc) {\n data = utils.toArray(data, enc);\n var p = new Position();\n if (data[p.place++] !== 0x30) {\n return false;\n }\n var len = getLength(data, p);\n if (len === false) {\n return false;\n }\n if ((len + p.place) !== data.length) {\n return false;\n }\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var rlen = getLength(data, p);\n if (rlen === false) {\n return false;\n }\n var r = data.slice(p.place, rlen + p.place);\n p.place += rlen;\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var slen = getLength(data, p);\n if (slen === false) {\n return false;\n }\n if (data.length !== slen + p.place) {\n return false;\n }\n var s = data.slice(p.place, slen + p.place);\n if (r[0] === 0) {\n if (r[1] & 0x80) {\n r = r.slice(1);\n } else {\n // Leading zeroes\n return false;\n }\n }\n if (s[0] === 0) {\n if (s[1] & 0x80) {\n s = s.slice(1);\n } else {\n // Leading zeroes\n return false;\n }\n }\n\n this.r = new BN(r);\n this.s = new BN(s);\n this.recoveryParam = null;\n\n return true;\n};\n\nfunction constructLength(arr, len) {\n if (len < 0x80) {\n arr.push(len);\n return;\n }\n var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);\n arr.push(octets | 0x80);\n while (--octets) {\n arr.push((len >>> (octets << 3)) & 0xff);\n }\n arr.push(len);\n}\n\nSignature.prototype.toDER = function toDER(enc) {\n var r = this.r.toArray();\n var s = this.s.toArray();\n\n // Pad values\n if (r[0] & 0x80)\n r = [ 0 ].concat(r);\n // Pad values\n if (s[0] & 0x80)\n s = [ 0 ].concat(s);\n\n r = rmPadding(r);\n s = rmPadding(s);\n\n while (!s[0] && !(s[1] & 0x80)) {\n s = s.slice(1);\n }\n var arr = [ 0x02 ];\n constructLength(arr, r.length);\n arr = arr.concat(r);\n arr.push(0x02);\n constructLength(arr, s.length);\n var backHalf = arr.concat(s);\n var res = [ 0x30 ];\n constructLength(res, backHalf.length);\n res = res.concat(backHalf);\n return utils.encode(res, enc);\n};\n", - "'use strict';\n\nvar hash = require('hash.js');\nvar curves = require('../curves');\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar parseBytes = utils.parseBytes;\nvar KeyPair = require('./key');\nvar Signature = require('./signature');\n\nfunction EDDSA(curve) {\n assert(curve === 'ed25519', 'only tested with ed25519 so far');\n\n if (!(this instanceof EDDSA))\n return new EDDSA(curve);\n\n curve = curves[curve].curve;\n this.curve = curve;\n this.g = curve.g;\n this.g.precompute(curve.n.bitLength() + 1);\n\n this.pointClass = curve.point().constructor;\n this.encodingLength = Math.ceil(curve.n.bitLength() / 8);\n this.hash = hash.sha512;\n}\n\nmodule.exports = EDDSA;\n\n/**\n* @param {Array|String} message - message bytes\n* @param {Array|String|KeyPair} secret - secret bytes or a keypair\n* @returns {Signature} - signature\n*/\nEDDSA.prototype.sign = function sign(message, secret) {\n message = parseBytes(message);\n var key = this.keyFromSecret(secret);\n var r = this.hashInt(key.messagePrefix(), message);\n var R = this.g.mul(r);\n var Rencoded = this.encodePoint(R);\n var s_ = this.hashInt(Rencoded, key.pubBytes(), message)\n .mul(key.priv());\n var S = r.add(s_).umod(this.curve.n);\n return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });\n};\n\n/**\n* @param {Array} message - message bytes\n* @param {Array|String|Signature} sig - sig bytes\n* @param {Array|String|Point|KeyPair} pub - public key\n* @returns {Boolean} - true if public key matches sig of message\n*/\nEDDSA.prototype.verify = function verify(message, sig, pub) {\n message = parseBytes(message);\n sig = this.makeSignature(sig);\n var key = this.keyFromPublic(pub);\n var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);\n var SG = this.g.mul(sig.S());\n var RplusAh = sig.R().add(key.pub().mul(h));\n return RplusAh.eq(SG);\n};\n\nEDDSA.prototype.hashInt = function hashInt() {\n var hash = this.hash();\n for (var i = 0; i < arguments.length; i++)\n hash.update(arguments[i]);\n return utils.intFromLE(hash.digest()).umod(this.curve.n);\n};\n\nEDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {\n return KeyPair.fromPublic(this, pub);\n};\n\nEDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {\n return KeyPair.fromSecret(this, secret);\n};\n\nEDDSA.prototype.makeSignature = function makeSignature(sig) {\n if (sig instanceof Signature)\n return sig;\n return new Signature(this, sig);\n};\n\n/**\n* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2\n*\n* EDDSA defines methods for encoding and decoding points and integers. These are\n* helper convenience methods, that pass along to utility functions implied\n* parameters.\n*\n*/\nEDDSA.prototype.encodePoint = function encodePoint(point) {\n var enc = point.getY().toArray('le', this.encodingLength);\n enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;\n return enc;\n};\n\nEDDSA.prototype.decodePoint = function decodePoint(bytes) {\n bytes = utils.parseBytes(bytes);\n\n var lastIx = bytes.length - 1;\n var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);\n var xIsOdd = (bytes[lastIx] & 0x80) !== 0;\n\n var y = utils.intFromLE(normed);\n return this.curve.pointFromY(y, xIsOdd);\n};\n\nEDDSA.prototype.encodeInt = function encodeInt(num) {\n return num.toArray('le', this.encodingLength);\n};\n\nEDDSA.prototype.decodeInt = function decodeInt(bytes) {\n return utils.intFromLE(bytes);\n};\n\nEDDSA.prototype.isPoint = function isPoint(val) {\n return val instanceof this.pointClass;\n};\n", - "'use strict';\n\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar parseBytes = utils.parseBytes;\nvar cachedProperty = utils.cachedProperty;\n\n/**\n* @param {EDDSA} eddsa - instance\n* @param {Object} params - public/private key parameters\n*\n* @param {Array} [params.secret] - secret seed bytes\n* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)\n* @param {Array} [params.pub] - public key point encoded as bytes\n*\n*/\nfunction KeyPair(eddsa, params) {\n this.eddsa = eddsa;\n this._secret = parseBytes(params.secret);\n if (eddsa.isPoint(params.pub))\n this._pub = params.pub;\n else\n this._pubBytes = parseBytes(params.pub);\n}\n\nKeyPair.fromPublic = function fromPublic(eddsa, pub) {\n if (pub instanceof KeyPair)\n return pub;\n return new KeyPair(eddsa, { pub: pub });\n};\n\nKeyPair.fromSecret = function fromSecret(eddsa, secret) {\n if (secret instanceof KeyPair)\n return secret;\n return new KeyPair(eddsa, { secret: secret });\n};\n\nKeyPair.prototype.secret = function secret() {\n return this._secret;\n};\n\ncachedProperty(KeyPair, 'pubBytes', function pubBytes() {\n return this.eddsa.encodePoint(this.pub());\n});\n\ncachedProperty(KeyPair, 'pub', function pub() {\n if (this._pubBytes)\n return this.eddsa.decodePoint(this._pubBytes);\n return this.eddsa.g.mul(this.priv());\n});\n\ncachedProperty(KeyPair, 'privBytes', function privBytes() {\n var eddsa = this.eddsa;\n var hash = this.hash();\n var lastIx = eddsa.encodingLength - 1;\n\n var a = hash.slice(0, eddsa.encodingLength);\n a[0] &= 248;\n a[lastIx] &= 127;\n a[lastIx] |= 64;\n\n return a;\n});\n\ncachedProperty(KeyPair, 'priv', function priv() {\n return this.eddsa.decodeInt(this.privBytes());\n});\n\ncachedProperty(KeyPair, 'hash', function hash() {\n return this.eddsa.hash().update(this.secret()).digest();\n});\n\ncachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {\n return this.hash().slice(this.eddsa.encodingLength);\n});\n\nKeyPair.prototype.sign = function sign(message) {\n assert(this._secret, 'KeyPair can only verify');\n return this.eddsa.sign(message, this);\n};\n\nKeyPair.prototype.verify = function verify(message, sig) {\n return this.eddsa.verify(message, sig, this);\n};\n\nKeyPair.prototype.getSecret = function getSecret(enc) {\n assert(this._secret, 'KeyPair is public only');\n return utils.encode(this.secret(), enc);\n};\n\nKeyPair.prototype.getPublic = function getPublic(enc) {\n return utils.encode(this.pubBytes(), enc);\n};\n\nmodule.exports = KeyPair;\n", - "'use strict';\n\nvar BN = require('bn.js');\nvar utils = require('../utils');\nvar assert = utils.assert;\nvar cachedProperty = utils.cachedProperty;\nvar parseBytes = utils.parseBytes;\n\n/**\n* @param {EDDSA} eddsa - eddsa instance\n* @param {Array|Object} sig -\n* @param {Array|Point} [sig.R] - R point as Point or bytes\n* @param {Array|bn} [sig.S] - S scalar as bn or bytes\n* @param {Array} [sig.Rencoded] - R point encoded\n* @param {Array} [sig.Sencoded] - S scalar encoded\n*/\nfunction Signature(eddsa, sig) {\n this.eddsa = eddsa;\n\n if (typeof sig !== 'object')\n sig = parseBytes(sig);\n\n if (Array.isArray(sig)) {\n sig = {\n R: sig.slice(0, eddsa.encodingLength),\n S: sig.slice(eddsa.encodingLength),\n };\n }\n\n assert(sig.R && sig.S, 'Signature without R or S');\n\n if (eddsa.isPoint(sig.R))\n this._R = sig.R;\n if (sig.S instanceof BN)\n this._S = sig.S;\n\n this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;\n this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;\n}\n\ncachedProperty(Signature, 'S', function S() {\n return this.eddsa.decodeInt(this.Sencoded());\n});\n\ncachedProperty(Signature, 'R', function R() {\n return this.eddsa.decodePoint(this.Rencoded());\n});\n\ncachedProperty(Signature, 'Rencoded', function Rencoded() {\n return this.eddsa.encodePoint(this.R());\n});\n\ncachedProperty(Signature, 'Sencoded', function Sencoded() {\n return this.eddsa.encodeInt(this.S());\n});\n\nSignature.prototype.toBytes = function toBytes() {\n return this.Rencoded().concat(this.Sencoded());\n};\n\nSignature.prototype.toHex = function toHex() {\n return utils.encode(this.toBytes(), 'hex').toUpperCase();\n};\n\nmodule.exports = Signature;\n", - "module.exports = {\n doubles: {\n step: 4,\n points: [\n [\n 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',\n 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821',\n ],\n [\n '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',\n '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf',\n ],\n [\n '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',\n 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695',\n ],\n [\n '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',\n '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9',\n ],\n [\n '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',\n '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36',\n ],\n [\n '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',\n '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f',\n ],\n [\n 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',\n '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999',\n ],\n [\n '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',\n 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09',\n ],\n [\n 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',\n '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d',\n ],\n [\n 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',\n 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088',\n ],\n [\n 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',\n '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d',\n ],\n [\n '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',\n '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8',\n ],\n [\n '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',\n '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a',\n ],\n [\n '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',\n '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453',\n ],\n [\n '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',\n '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160',\n ],\n [\n '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',\n '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0',\n ],\n [\n '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',\n '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6',\n ],\n [\n '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',\n '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589',\n ],\n [\n '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',\n 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17',\n ],\n [\n 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',\n '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda',\n ],\n [\n 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',\n '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd',\n ],\n [\n '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',\n '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2',\n ],\n [\n '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',\n '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6',\n ],\n [\n 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',\n '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f',\n ],\n [\n '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',\n 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01',\n ],\n [\n 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',\n '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3',\n ],\n [\n 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',\n 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f',\n ],\n [\n 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',\n '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7',\n ],\n [\n 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',\n 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78',\n ],\n [\n 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',\n '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1',\n ],\n [\n '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',\n 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150',\n ],\n [\n '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',\n '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82',\n ],\n [\n 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',\n '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc',\n ],\n [\n '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',\n 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b',\n ],\n [\n 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',\n '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51',\n ],\n [\n 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',\n '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45',\n ],\n [\n 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',\n 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120',\n ],\n [\n '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',\n '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84',\n ],\n [\n '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',\n '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d',\n ],\n [\n '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',\n 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d',\n ],\n [\n '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',\n '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8',\n ],\n [\n 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',\n '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8',\n ],\n [\n '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',\n '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac',\n ],\n [\n '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',\n 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f',\n ],\n [\n '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',\n '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962',\n ],\n [\n 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',\n '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907',\n ],\n [\n '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',\n 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec',\n ],\n [\n 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',\n 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d',\n ],\n [\n 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',\n '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414',\n ],\n [\n '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',\n 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd',\n ],\n [\n '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',\n 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0',\n ],\n [\n 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',\n '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811',\n ],\n [\n 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',\n '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1',\n ],\n [\n 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',\n '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c',\n ],\n [\n '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',\n 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73',\n ],\n [\n '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',\n '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd',\n ],\n [\n 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',\n 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405',\n ],\n [\n '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',\n 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589',\n ],\n [\n '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',\n '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e',\n ],\n [\n '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',\n '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27',\n ],\n [\n 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',\n 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1',\n ],\n [\n '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',\n '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482',\n ],\n [\n '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',\n '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945',\n ],\n [\n 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',\n '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573',\n ],\n [\n 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',\n 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82',\n ],\n ],\n },\n naf: {\n wnd: 7,\n points: [\n [\n 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',\n '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672',\n ],\n [\n '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',\n 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6',\n ],\n [\n '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',\n '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da',\n ],\n [\n 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',\n 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37',\n ],\n [\n '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',\n 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b',\n ],\n [\n 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',\n 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81',\n ],\n [\n 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',\n '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58',\n ],\n [\n 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',\n '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77',\n ],\n [\n '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',\n '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a',\n ],\n [\n '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',\n '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c',\n ],\n [\n '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',\n '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67',\n ],\n [\n '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',\n '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402',\n ],\n [\n 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',\n 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55',\n ],\n [\n 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',\n '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482',\n ],\n [\n '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',\n 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82',\n ],\n [\n '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',\n 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396',\n ],\n [\n '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',\n '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49',\n ],\n [\n '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',\n '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf',\n ],\n [\n '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',\n '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a',\n ],\n [\n '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',\n 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7',\n ],\n [\n 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',\n 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933',\n ],\n [\n '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',\n '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a',\n ],\n [\n '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',\n '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6',\n ],\n [\n 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',\n 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37',\n ],\n [\n '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',\n '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e',\n ],\n [\n 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',\n 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6',\n ],\n [\n 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',\n 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476',\n ],\n [\n '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',\n '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40',\n ],\n [\n '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',\n '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61',\n ],\n [\n '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',\n '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683',\n ],\n [\n 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',\n '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5',\n ],\n [\n '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',\n '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b',\n ],\n [\n 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',\n '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417',\n ],\n [\n '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',\n 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868',\n ],\n [\n '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',\n 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a',\n ],\n [\n 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',\n 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6',\n ],\n [\n '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',\n '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996',\n ],\n [\n '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',\n 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e',\n ],\n [\n 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',\n 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d',\n ],\n [\n '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',\n '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2',\n ],\n [\n '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',\n 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e',\n ],\n [\n '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',\n '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437',\n ],\n [\n '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',\n 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311',\n ],\n [\n 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',\n '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4',\n ],\n [\n '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',\n '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575',\n ],\n [\n '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',\n 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d',\n ],\n [\n '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',\n 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d',\n ],\n [\n 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',\n 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629',\n ],\n [\n 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',\n 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06',\n ],\n [\n '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',\n '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374',\n ],\n [\n '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',\n '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee',\n ],\n [\n 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',\n '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1',\n ],\n [\n 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',\n 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b',\n ],\n [\n '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',\n '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661',\n ],\n [\n '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',\n '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6',\n ],\n [\n 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',\n '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e',\n ],\n [\n '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',\n '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d',\n ],\n [\n 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',\n 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc',\n ],\n [\n '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',\n 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4',\n ],\n [\n '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',\n '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c',\n ],\n [\n 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',\n '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b',\n ],\n [\n 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',\n '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913',\n ],\n [\n '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',\n '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154',\n ],\n [\n '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',\n '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865',\n ],\n [\n '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',\n 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc',\n ],\n [\n '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',\n 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224',\n ],\n [\n '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',\n '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e',\n ],\n [\n '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',\n '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6',\n ],\n [\n '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',\n '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511',\n ],\n [\n '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',\n 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b',\n ],\n [\n 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',\n 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2',\n ],\n [\n '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',\n 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c',\n ],\n [\n 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',\n '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3',\n ],\n [\n 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',\n '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d',\n ],\n [\n 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',\n '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700',\n ],\n [\n 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',\n '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4',\n ],\n [\n '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',\n 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196',\n ],\n [\n '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',\n '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4',\n ],\n [\n '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',\n 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257',\n ],\n [\n 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',\n 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13',\n ],\n [\n 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',\n '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096',\n ],\n [\n 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',\n 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38',\n ],\n [\n 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',\n '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f',\n ],\n [\n '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',\n '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448',\n ],\n [\n 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',\n '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a',\n ],\n [\n 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',\n '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4',\n ],\n [\n '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',\n '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437',\n ],\n [\n '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',\n 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7',\n ],\n [\n 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',\n '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d',\n ],\n [\n 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',\n '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a',\n ],\n [\n 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',\n '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54',\n ],\n [\n '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',\n '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77',\n ],\n [\n 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',\n 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517',\n ],\n [\n '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',\n 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10',\n ],\n [\n 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',\n 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125',\n ],\n [\n 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',\n '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e',\n ],\n [\n '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',\n 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1',\n ],\n [\n 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',\n '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2',\n ],\n [\n 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',\n '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423',\n ],\n [\n 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',\n '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8',\n ],\n [\n '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',\n 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758',\n ],\n [\n '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',\n 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375',\n ],\n [\n 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',\n '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d',\n ],\n [\n '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',\n 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec',\n ],\n [\n '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',\n '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0',\n ],\n [\n '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',\n 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c',\n ],\n [\n 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',\n 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4',\n ],\n [\n '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',\n 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f',\n ],\n [\n '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',\n '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649',\n ],\n [\n '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',\n 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826',\n ],\n [\n '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',\n '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5',\n ],\n [\n 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',\n 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87',\n ],\n [\n '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',\n '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b',\n ],\n [\n 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',\n '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc',\n ],\n [\n '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',\n '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c',\n ],\n [\n 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',\n 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f',\n ],\n [\n 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',\n '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a',\n ],\n [\n 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',\n 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46',\n ],\n [\n '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',\n 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f',\n ],\n [\n '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',\n '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03',\n ],\n [\n '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',\n 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08',\n ],\n [\n '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',\n '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8',\n ],\n [\n '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',\n '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373',\n ],\n [\n '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',\n 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3',\n ],\n [\n '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',\n '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8',\n ],\n [\n '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',\n '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1',\n ],\n [\n '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',\n '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9',\n ],\n ],\n },\n};\n", - "'use strict';\n\nvar utils = exports;\nvar BN = require('bn.js');\nvar minAssert = require('minimalistic-assert');\nvar minUtils = require('minimalistic-crypto-utils');\n\nutils.assert = minAssert;\nutils.toArray = minUtils.toArray;\nutils.zero2 = minUtils.zero2;\nutils.toHex = minUtils.toHex;\nutils.encode = minUtils.encode;\n\n// Represent num in a w-NAF form\nfunction getNAF(num, w, bits) {\n var naf = new Array(Math.max(num.bitLength(), bits) + 1);\n naf.fill(0);\n\n var ws = 1 << (w + 1);\n var k = num.clone();\n\n for (var i = 0; i < naf.length; i++) {\n var z;\n var mod = k.andln(ws - 1);\n if (k.isOdd()) {\n if (mod > (ws >> 1) - 1)\n z = (ws >> 1) - mod;\n else\n z = mod;\n k.isubn(z);\n } else {\n z = 0;\n }\n\n naf[i] = z;\n k.iushrn(1);\n }\n\n return naf;\n}\nutils.getNAF = getNAF;\n\n// Represent k1, k2 in a Joint Sparse Form\nfunction getJSF(k1, k2) {\n var jsf = [\n [],\n [],\n ];\n\n k1 = k1.clone();\n k2 = k2.clone();\n var d1 = 0;\n var d2 = 0;\n var m8;\n while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {\n // First phase\n var m14 = (k1.andln(3) + d1) & 3;\n var m24 = (k2.andln(3) + d2) & 3;\n if (m14 === 3)\n m14 = -1;\n if (m24 === 3)\n m24 = -1;\n var u1;\n if ((m14 & 1) === 0) {\n u1 = 0;\n } else {\n m8 = (k1.andln(7) + d1) & 7;\n if ((m8 === 3 || m8 === 5) && m24 === 2)\n u1 = -m14;\n else\n u1 = m14;\n }\n jsf[0].push(u1);\n\n var u2;\n if ((m24 & 1) === 0) {\n u2 = 0;\n } else {\n m8 = (k2.andln(7) + d2) & 7;\n if ((m8 === 3 || m8 === 5) && m14 === 2)\n u2 = -m24;\n else\n u2 = m24;\n }\n jsf[1].push(u2);\n\n // Second phase\n if (2 * d1 === u1 + 1)\n d1 = 1 - d1;\n if (2 * d2 === u2 + 1)\n d2 = 1 - d2;\n k1.iushrn(1);\n k2.iushrn(1);\n }\n\n return jsf;\n}\nutils.getJSF = getJSF;\n\nfunction cachedProperty(obj, name, computer) {\n var key = '_' + name;\n obj.prototype[name] = function cachedProperty() {\n return this[key] !== undefined ? this[key] :\n this[key] = computer.call(this);\n };\n}\nutils.cachedProperty = cachedProperty;\n\nfunction parseBytes(bytes) {\n return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :\n bytes;\n}\nutils.parseBytes = parseBytes;\n\nfunction intFromLE(bytes) {\n return new BN(bytes, 'hex', 'le');\n}\nutils.intFromLE = intFromLE;\n\n", - "module.exports={\n \"name\": \"elliptic\",\n \"version\": \"6.5.4\",\n \"description\": \"EC cryptography\",\n \"main\": \"lib/elliptic.js\",\n \"files\": [\n \"lib\"\n ],\n \"scripts\": {\n \"lint\": \"eslint lib test\",\n \"lint:fix\": \"npm run lint -- --fix\",\n \"unit\": \"istanbul test _mocha --reporter=spec test/index.js\",\n \"test\": \"npm run lint && npm run unit\",\n \"version\": \"grunt dist && git add dist/\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git@github.com:indutny/elliptic\"\n },\n \"keywords\": [\n \"EC\",\n \"Elliptic\",\n \"curve\",\n \"Cryptography\"\n ],\n \"author\": \"Fedor Indutny \",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/indutny/elliptic/issues\"\n },\n \"homepage\": \"https://github.com/indutny/elliptic\",\n \"devDependencies\": {\n \"brfs\": \"^2.0.2\",\n \"coveralls\": \"^3.1.0\",\n \"eslint\": \"^7.6.0\",\n \"grunt\": \"^1.2.1\",\n \"grunt-browserify\": \"^5.3.0\",\n \"grunt-cli\": \"^1.3.2\",\n \"grunt-contrib-connect\": \"^3.0.0\",\n \"grunt-contrib-copy\": \"^1.0.0\",\n \"grunt-contrib-uglify\": \"^5.0.0\",\n \"grunt-mocha-istanbul\": \"^5.0.2\",\n \"grunt-saucelabs\": \"^9.0.1\",\n \"istanbul\": \"^0.4.5\",\n \"mocha\": \"^8.0.1\"\n },\n \"dependencies\": {\n \"bn.js\": \"^4.11.9\",\n \"brorand\": \"^1.1.0\",\n \"hash.js\": \"^1.0.0\",\n \"hmac-drbg\": \"^1.0.1\",\n \"inherits\": \"^2.0.4\",\n \"minimalistic-assert\": \"^1.0.1\",\n \"minimalistic-crypto-utils\": \"^1.0.1\"\n }\n}\n", - "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction _getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n checkListener(listener);\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = _getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n checkListener(listener);\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function errorListener(err) {\n emitter.removeListener(name, resolver);\n reject(err);\n }\n\n function resolver() {\n if (typeof emitter.removeListener === 'function') {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n\n eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n if (name !== 'error') {\n addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n }\n });\n}\n\nfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n if (typeof emitter.on === 'function') {\n eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n }\n}\n\nfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n if (typeof emitter.on === 'function') {\n if (flags.once) {\n emitter.once(name, listener);\n } else {\n emitter.on(name, listener);\n }\n } else if (typeof emitter.addEventListener === 'function') {\n // EventTarget does not have `error` event semantics like Node\n // EventEmitters, we do not listen for `error` events here.\n emitter.addEventListener(name, function wrapListener(arg) {\n // IE does not have builtin `{ once: true }` support so we\n // have to do it manually.\n if (flags.once) {\n emitter.removeEventListener(name, wrapListener);\n }\n listener(arg);\n });\n } else {\n throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n }\n}\n", - "var Buffer = require('safe-buffer').Buffer\nvar MD5 = require('md5.js')\n\n/* eslint-disable camelcase */\nfunction EVP_BytesToKey (password, salt, keyBits, ivLen) {\n if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary')\n if (salt) {\n if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary')\n if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length')\n }\n\n var keyLen = keyBits / 8\n var key = Buffer.alloc(keyLen)\n var iv = Buffer.alloc(ivLen || 0)\n var tmp = Buffer.alloc(0)\n\n while (keyLen > 0 || ivLen > 0) {\n var hash = new MD5()\n hash.update(tmp)\n hash.update(password)\n if (salt) hash.update(salt)\n tmp = hash.digest()\n\n var used = 0\n\n if (keyLen > 0) {\n var keyStart = key.length - keyLen\n used = Math.min(keyLen, tmp.length)\n tmp.copy(key, keyStart, 0, used)\n keyLen -= used\n }\n\n if (used < tmp.length && ivLen > 0) {\n var ivStart = iv.length - ivLen\n var length = Math.min(ivLen, tmp.length - used)\n tmp.copy(iv, ivStart, used, used + length)\n ivLen -= length\n }\n }\n\n tmp.fill(0)\n return { key: key, iv: iv }\n}\n\nmodule.exports = EVP_BytesToKey\n", - "'use strict';\n\nvar isCallable = require('is-callable');\n\nvar toStr = Object.prototype.toString;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nvar forEachArray = function forEachArray(array, iterator, receiver) {\n for (var i = 0, len = array.length; i < len; i++) {\n if (hasOwnProperty.call(array, i)) {\n if (receiver == null) {\n iterator(array[i], i, array);\n } else {\n iterator.call(receiver, array[i], i, array);\n }\n }\n }\n};\n\nvar forEachString = function forEachString(string, iterator, receiver) {\n for (var i = 0, len = string.length; i < len; i++) {\n // no such thing as a sparse string.\n if (receiver == null) {\n iterator(string.charAt(i), i, string);\n } else {\n iterator.call(receiver, string.charAt(i), i, string);\n }\n }\n};\n\nvar forEachObject = function forEachObject(object, iterator, receiver) {\n for (var k in object) {\n if (hasOwnProperty.call(object, k)) {\n if (receiver == null) {\n iterator(object[k], k, object);\n } else {\n iterator.call(receiver, object[k], k, object);\n }\n }\n }\n};\n\nvar forEach = function forEach(list, iterator, thisArg) {\n if (!isCallable(iterator)) {\n throw new TypeError('iterator must be a function');\n }\n\n var receiver;\n if (arguments.length >= 3) {\n receiver = thisArg;\n }\n\n if (toStr.call(list) === '[object Array]') {\n forEachArray(list, iterator, receiver);\n } else if (typeof list === 'string') {\n forEachString(list, iterator, receiver);\n } else {\n forEachObject(list, iterator, receiver);\n }\n};\n\nmodule.exports = forEach;\n", - "'use strict';\n\n/* eslint no-invalid-this: 1 */\n\nvar ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';\nvar slice = Array.prototype.slice;\nvar toStr = Object.prototype.toString;\nvar funcType = '[object Function]';\n\nmodule.exports = function bind(that) {\n var target = this;\n if (typeof target !== 'function' || toStr.call(target) !== funcType) {\n throw new TypeError(ERROR_MESSAGE + target);\n }\n var args = slice.call(arguments, 1);\n\n var bound;\n var binder = function () {\n if (this instanceof bound) {\n var result = target.apply(\n this,\n args.concat(slice.call(arguments))\n );\n if (Object(result) === result) {\n return result;\n }\n return this;\n } else {\n return target.apply(\n that,\n args.concat(slice.call(arguments))\n );\n }\n };\n\n var boundLength = Math.max(0, target.length - args.length);\n var boundArgs = [];\n for (var i = 0; i < boundLength; i++) {\n boundArgs.push('$' + i);\n }\n\n bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);\n\n if (target.prototype) {\n var Empty = function Empty() {};\n Empty.prototype = target.prototype;\n bound.prototype = new Empty();\n Empty.prototype = null;\n }\n\n return bound;\n};\n", - "'use strict';\n\nvar implementation = require('./implementation');\n\nmodule.exports = Function.prototype.bind || implementation;\n", - "'use strict';\n\nvar undefined;\n\nvar $SyntaxError = SyntaxError;\nvar $Function = Function;\nvar $TypeError = TypeError;\n\n// eslint-disable-next-line consistent-return\nvar getEvalledConstructor = function (expressionSyntax) {\n\ttry {\n\t\treturn $Function('\"use strict\"; return (' + expressionSyntax + ').constructor;')();\n\t} catch (e) {}\n};\n\nvar $gOPD = Object.getOwnPropertyDescriptor;\nif ($gOPD) {\n\ttry {\n\t\t$gOPD({}, '');\n\t} catch (e) {\n\t\t$gOPD = null; // this is IE 8, which has a broken gOPD\n\t}\n}\n\nvar throwTypeError = function () {\n\tthrow new $TypeError();\n};\nvar ThrowTypeError = $gOPD\n\t? (function () {\n\t\ttry {\n\t\t\t// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties\n\t\t\targuments.callee; // IE 8 does not throw here\n\t\t\treturn throwTypeError;\n\t\t} catch (calleeThrows) {\n\t\t\ttry {\n\t\t\t\t// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')\n\t\t\t\treturn $gOPD(arguments, 'callee').get;\n\t\t\t} catch (gOPDthrows) {\n\t\t\t\treturn throwTypeError;\n\t\t\t}\n\t\t}\n\t}())\n\t: throwTypeError;\n\nvar hasSymbols = require('has-symbols')();\n\nvar getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto\n\nvar needsEval = {};\n\nvar TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);\n\nvar INTRINSICS = {\n\t'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,\n\t'%Array%': Array,\n\t'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,\n\t'%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,\n\t'%AsyncFromSyncIteratorPrototype%': undefined,\n\t'%AsyncFunction%': needsEval,\n\t'%AsyncGenerator%': needsEval,\n\t'%AsyncGeneratorFunction%': needsEval,\n\t'%AsyncIteratorPrototype%': needsEval,\n\t'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,\n\t'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,\n\t'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,\n\t'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,\n\t'%Boolean%': Boolean,\n\t'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,\n\t'%Date%': Date,\n\t'%decodeURI%': decodeURI,\n\t'%decodeURIComponent%': decodeURIComponent,\n\t'%encodeURI%': encodeURI,\n\t'%encodeURIComponent%': encodeURIComponent,\n\t'%Error%': Error,\n\t'%eval%': eval, // eslint-disable-line no-eval\n\t'%EvalError%': EvalError,\n\t'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,\n\t'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,\n\t'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,\n\t'%Function%': $Function,\n\t'%GeneratorFunction%': needsEval,\n\t'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,\n\t'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,\n\t'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,\n\t'%isFinite%': isFinite,\n\t'%isNaN%': isNaN,\n\t'%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,\n\t'%JSON%': typeof JSON === 'object' ? JSON : undefined,\n\t'%Map%': typeof Map === 'undefined' ? undefined : Map,\n\t'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),\n\t'%Math%': Math,\n\t'%Number%': Number,\n\t'%Object%': Object,\n\t'%parseFloat%': parseFloat,\n\t'%parseInt%': parseInt,\n\t'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,\n\t'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,\n\t'%RangeError%': RangeError,\n\t'%ReferenceError%': ReferenceError,\n\t'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,\n\t'%RegExp%': RegExp,\n\t'%Set%': typeof Set === 'undefined' ? undefined : Set,\n\t'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),\n\t'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,\n\t'%String%': String,\n\t'%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,\n\t'%Symbol%': hasSymbols ? Symbol : undefined,\n\t'%SyntaxError%': $SyntaxError,\n\t'%ThrowTypeError%': ThrowTypeError,\n\t'%TypedArray%': TypedArray,\n\t'%TypeError%': $TypeError,\n\t'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,\n\t'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,\n\t'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,\n\t'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,\n\t'%URIError%': URIError,\n\t'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,\n\t'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,\n\t'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet\n};\n\ntry {\n\tnull.error; // eslint-disable-line no-unused-expressions\n} catch (e) {\n\t// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229\n\tvar errorProto = getProto(getProto(e));\n\tINTRINSICS['%Error.prototype%'] = errorProto;\n}\n\nvar doEval = function doEval(name) {\n\tvar value;\n\tif (name === '%AsyncFunction%') {\n\t\tvalue = getEvalledConstructor('async function () {}');\n\t} else if (name === '%GeneratorFunction%') {\n\t\tvalue = getEvalledConstructor('function* () {}');\n\t} else if (name === '%AsyncGeneratorFunction%') {\n\t\tvalue = getEvalledConstructor('async function* () {}');\n\t} else if (name === '%AsyncGenerator%') {\n\t\tvar fn = doEval('%AsyncGeneratorFunction%');\n\t\tif (fn) {\n\t\t\tvalue = fn.prototype;\n\t\t}\n\t} else if (name === '%AsyncIteratorPrototype%') {\n\t\tvar gen = doEval('%AsyncGenerator%');\n\t\tif (gen) {\n\t\t\tvalue = getProto(gen.prototype);\n\t\t}\n\t}\n\n\tINTRINSICS[name] = value;\n\n\treturn value;\n};\n\nvar LEGACY_ALIASES = {\n\t'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],\n\t'%ArrayPrototype%': ['Array', 'prototype'],\n\t'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],\n\t'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],\n\t'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],\n\t'%ArrayProto_values%': ['Array', 'prototype', 'values'],\n\t'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],\n\t'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],\n\t'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],\n\t'%BooleanPrototype%': ['Boolean', 'prototype'],\n\t'%DataViewPrototype%': ['DataView', 'prototype'],\n\t'%DatePrototype%': ['Date', 'prototype'],\n\t'%ErrorPrototype%': ['Error', 'prototype'],\n\t'%EvalErrorPrototype%': ['EvalError', 'prototype'],\n\t'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],\n\t'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],\n\t'%FunctionPrototype%': ['Function', 'prototype'],\n\t'%Generator%': ['GeneratorFunction', 'prototype'],\n\t'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],\n\t'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],\n\t'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],\n\t'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],\n\t'%JSONParse%': ['JSON', 'parse'],\n\t'%JSONStringify%': ['JSON', 'stringify'],\n\t'%MapPrototype%': ['Map', 'prototype'],\n\t'%NumberPrototype%': ['Number', 'prototype'],\n\t'%ObjectPrototype%': ['Object', 'prototype'],\n\t'%ObjProto_toString%': ['Object', 'prototype', 'toString'],\n\t'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],\n\t'%PromisePrototype%': ['Promise', 'prototype'],\n\t'%PromiseProto_then%': ['Promise', 'prototype', 'then'],\n\t'%Promise_all%': ['Promise', 'all'],\n\t'%Promise_reject%': ['Promise', 'reject'],\n\t'%Promise_resolve%': ['Promise', 'resolve'],\n\t'%RangeErrorPrototype%': ['RangeError', 'prototype'],\n\t'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],\n\t'%RegExpPrototype%': ['RegExp', 'prototype'],\n\t'%SetPrototype%': ['Set', 'prototype'],\n\t'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],\n\t'%StringPrototype%': ['String', 'prototype'],\n\t'%SymbolPrototype%': ['Symbol', 'prototype'],\n\t'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],\n\t'%TypedArrayPrototype%': ['TypedArray', 'prototype'],\n\t'%TypeErrorPrototype%': ['TypeError', 'prototype'],\n\t'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],\n\t'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],\n\t'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],\n\t'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],\n\t'%URIErrorPrototype%': ['URIError', 'prototype'],\n\t'%WeakMapPrototype%': ['WeakMap', 'prototype'],\n\t'%WeakSetPrototype%': ['WeakSet', 'prototype']\n};\n\nvar bind = require('function-bind');\nvar hasOwn = require('has');\nvar $concat = bind.call(Function.call, Array.prototype.concat);\nvar $spliceApply = bind.call(Function.apply, Array.prototype.splice);\nvar $replace = bind.call(Function.call, String.prototype.replace);\nvar $strSlice = bind.call(Function.call, String.prototype.slice);\nvar $exec = bind.call(Function.call, RegExp.prototype.exec);\n\n/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */\nvar rePropName = /[^%.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|%$))/g;\nvar reEscapeChar = /\\\\(\\\\)?/g; /** Used to match backslashes in property paths. */\nvar stringToPath = function stringToPath(string) {\n\tvar first = $strSlice(string, 0, 1);\n\tvar last = $strSlice(string, -1);\n\tif (first === '%' && last !== '%') {\n\t\tthrow new $SyntaxError('invalid intrinsic syntax, expected closing `%`');\n\t} else if (last === '%' && first !== '%') {\n\t\tthrow new $SyntaxError('invalid intrinsic syntax, expected opening `%`');\n\t}\n\tvar result = [];\n\t$replace(string, rePropName, function (match, number, quote, subString) {\n\t\tresult[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;\n\t});\n\treturn result;\n};\n/* end adaptation */\n\nvar getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {\n\tvar intrinsicName = name;\n\tvar alias;\n\tif (hasOwn(LEGACY_ALIASES, intrinsicName)) {\n\t\talias = LEGACY_ALIASES[intrinsicName];\n\t\tintrinsicName = '%' + alias[0] + '%';\n\t}\n\n\tif (hasOwn(INTRINSICS, intrinsicName)) {\n\t\tvar value = INTRINSICS[intrinsicName];\n\t\tif (value === needsEval) {\n\t\t\tvalue = doEval(intrinsicName);\n\t\t}\n\t\tif (typeof value === 'undefined' && !allowMissing) {\n\t\t\tthrow new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');\n\t\t}\n\n\t\treturn {\n\t\t\talias: alias,\n\t\t\tname: intrinsicName,\n\t\t\tvalue: value\n\t\t};\n\t}\n\n\tthrow new $SyntaxError('intrinsic ' + name + ' does not exist!');\n};\n\nmodule.exports = function GetIntrinsic(name, allowMissing) {\n\tif (typeof name !== 'string' || name.length === 0) {\n\t\tthrow new $TypeError('intrinsic name must be a non-empty string');\n\t}\n\tif (arguments.length > 1 && typeof allowMissing !== 'boolean') {\n\t\tthrow new $TypeError('\"allowMissing\" argument must be a boolean');\n\t}\n\n\tif ($exec(/^%?[^%]*%?$/, name) === null) {\n\t\tthrow new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');\n\t}\n\tvar parts = stringToPath(name);\n\tvar intrinsicBaseName = parts.length > 0 ? parts[0] : '';\n\n\tvar intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);\n\tvar intrinsicRealName = intrinsic.name;\n\tvar value = intrinsic.value;\n\tvar skipFurtherCaching = false;\n\n\tvar alias = intrinsic.alias;\n\tif (alias) {\n\t\tintrinsicBaseName = alias[0];\n\t\t$spliceApply(parts, $concat([0, 1], alias));\n\t}\n\n\tfor (var i = 1, isOwn = true; i < parts.length; i += 1) {\n\t\tvar part = parts[i];\n\t\tvar first = $strSlice(part, 0, 1);\n\t\tvar last = $strSlice(part, -1);\n\t\tif (\n\t\t\t(\n\t\t\t\t(first === '\"' || first === \"'\" || first === '`')\n\t\t\t\t|| (last === '\"' || last === \"'\" || last === '`')\n\t\t\t)\n\t\t\t&& first !== last\n\t\t) {\n\t\t\tthrow new $SyntaxError('property names with quotes must have matching quotes');\n\t\t}\n\t\tif (part === 'constructor' || !isOwn) {\n\t\t\tskipFurtherCaching = true;\n\t\t}\n\n\t\tintrinsicBaseName += '.' + part;\n\t\tintrinsicRealName = '%' + intrinsicBaseName + '%';\n\n\t\tif (hasOwn(INTRINSICS, intrinsicRealName)) {\n\t\t\tvalue = INTRINSICS[intrinsicRealName];\n\t\t} else if (value != null) {\n\t\t\tif (!(part in value)) {\n\t\t\t\tif (!allowMissing) {\n\t\t\t\t\tthrow new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');\n\t\t\t\t}\n\t\t\t\treturn void undefined;\n\t\t\t}\n\t\t\tif ($gOPD && (i + 1) >= parts.length) {\n\t\t\t\tvar desc = $gOPD(value, part);\n\t\t\t\tisOwn = !!desc;\n\n\t\t\t\t// By convention, when a data property is converted to an accessor\n\t\t\t\t// property to emulate a data property that does not suffer from\n\t\t\t\t// the override mistake, that accessor's getter is marked with\n\t\t\t\t// an `originalValue` property. Here, when we detect this, we\n\t\t\t\t// uphold the illusion by pretending to see that original data\n\t\t\t\t// property, i.e., returning the value rather than the getter\n\t\t\t\t// itself.\n\t\t\t\tif (isOwn && 'get' in desc && !('originalValue' in desc.get)) {\n\t\t\t\t\tvalue = desc.get;\n\t\t\t\t} else {\n\t\t\t\t\tvalue = value[part];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tisOwn = hasOwn(value, part);\n\t\t\t\tvalue = value[part];\n\t\t\t}\n\n\t\t\tif (isOwn && !skipFurtherCaching) {\n\t\t\t\tINTRINSICS[intrinsicRealName] = value;\n\t\t\t}\n\t\t}\n\t}\n\treturn value;\n};\n", - "'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);\n\nif ($gOPD) {\n\ttry {\n\t\t$gOPD([], 'length');\n\t} catch (e) {\n\t\t// IE 8 has a broken gOPD\n\t\t$gOPD = null;\n\t}\n}\n\nmodule.exports = $gOPD;\n", - "'use strict';\n\nvar origSymbol = typeof Symbol !== 'undefined' && Symbol;\nvar hasSymbolSham = require('./shams');\n\nmodule.exports = function hasNativeSymbols() {\n\tif (typeof origSymbol !== 'function') { return false; }\n\tif (typeof Symbol !== 'function') { return false; }\n\tif (typeof origSymbol('foo') !== 'symbol') { return false; }\n\tif (typeof Symbol('bar') !== 'symbol') { return false; }\n\n\treturn hasSymbolSham();\n};\n", - "'use strict';\n\n/* eslint complexity: [2, 18], max-statements: [2, 33] */\nmodule.exports = function hasSymbols() {\n\tif (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }\n\tif (typeof Symbol.iterator === 'symbol') { return true; }\n\n\tvar obj = {};\n\tvar sym = Symbol('test');\n\tvar symObj = Object(sym);\n\tif (typeof sym === 'string') { return false; }\n\n\tif (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }\n\tif (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }\n\n\t// temp disabled per https://github.com/ljharb/object.assign/issues/17\n\t// if (sym instanceof Symbol) { return false; }\n\t// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4\n\t// if (!(symObj instanceof Symbol)) { return false; }\n\n\t// if (typeof Symbol.prototype.toString !== 'function') { return false; }\n\t// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }\n\n\tvar symVal = 42;\n\tobj[sym] = symVal;\n\tfor (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop\n\tif (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }\n\n\tif (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }\n\n\tvar syms = Object.getOwnPropertySymbols(obj);\n\tif (syms.length !== 1 || syms[0] !== sym) { return false; }\n\n\tif (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }\n\n\tif (typeof Object.getOwnPropertyDescriptor === 'function') {\n\t\tvar descriptor = Object.getOwnPropertyDescriptor(obj, sym);\n\t\tif (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }\n\t}\n\n\treturn true;\n};\n", - "'use strict';\n\nvar hasSymbols = require('has-symbols/shams');\n\nmodule.exports = function hasToStringTagShams() {\n\treturn hasSymbols() && !!Symbol.toStringTag;\n};\n", - "'use strict';\n\nvar bind = require('function-bind');\n\nmodule.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);\n", - "'use strict'\nvar Buffer = require('safe-buffer').Buffer\nvar Transform = require('readable-stream').Transform\nvar inherits = require('inherits')\n\nfunction throwIfNotStringOrBuffer (val, prefix) {\n if (!Buffer.isBuffer(val) && typeof val !== 'string') {\n throw new TypeError(prefix + ' must be a string or a buffer')\n }\n}\n\nfunction HashBase (blockSize) {\n Transform.call(this)\n\n this._block = Buffer.allocUnsafe(blockSize)\n this._blockSize = blockSize\n this._blockOffset = 0\n this._length = [0, 0, 0, 0]\n\n this._finalized = false\n}\n\ninherits(HashBase, Transform)\n\nHashBase.prototype._transform = function (chunk, encoding, callback) {\n var error = null\n try {\n this.update(chunk, encoding)\n } catch (err) {\n error = err\n }\n\n callback(error)\n}\n\nHashBase.prototype._flush = function (callback) {\n var error = null\n try {\n this.push(this.digest())\n } catch (err) {\n error = err\n }\n\n callback(error)\n}\n\nHashBase.prototype.update = function (data, encoding) {\n throwIfNotStringOrBuffer(data, 'Data')\n if (this._finalized) throw new Error('Digest already called')\n if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)\n\n // consume data\n var block = this._block\n var offset = 0\n while (this._blockOffset + data.length - offset >= this._blockSize) {\n for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]\n this._update()\n this._blockOffset = 0\n }\n while (offset < data.length) block[this._blockOffset++] = data[offset++]\n\n // update length\n for (var j = 0, carry = data.length * 8; carry > 0; ++j) {\n this._length[j] += carry\n carry = (this._length[j] / 0x0100000000) | 0\n if (carry > 0) this._length[j] -= 0x0100000000 * carry\n }\n\n return this\n}\n\nHashBase.prototype._update = function () {\n throw new Error('_update is not implemented')\n}\n\nHashBase.prototype.digest = function (encoding) {\n if (this._finalized) throw new Error('Digest already called')\n this._finalized = true\n\n var digest = this._digest()\n if (encoding !== undefined) digest = digest.toString(encoding)\n\n // reset state\n this._block.fill(0)\n this._blockOffset = 0\n for (var i = 0; i < 4; ++i) this._length[i] = 0\n\n return digest\n}\n\nHashBase.prototype._digest = function () {\n throw new Error('_digest is not implemented')\n}\n\nmodule.exports = HashBase\n", - "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n'use strict';\n/**/\n\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n\n for (var key in obj) {\n keys.push(key);\n }\n\n return keys;\n};\n/**/\n\n\nmodule.exports = Duplex;\n\nvar Readable = require('./_stream_readable');\n\nvar Writable = require('./_stream_writable');\n\nrequire('inherits')(Duplex, Readable);\n\n{\n // Allow the keys array to be GC'ed.\n var keys = objectKeys(Writable.prototype);\n\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n Readable.call(this, options);\n Writable.call(this, options);\n this.allowHalfOpen = true;\n\n if (options) {\n if (options.readable === false) this.readable = false;\n if (options.writable === false) this.writable = false;\n\n if (options.allowHalfOpen === false) {\n this.allowHalfOpen = false;\n this.once('end', onend);\n }\n }\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n}); // the no-half-open enforcer\n\nfunction onend() {\n // If the writable side ended, then we're ok.\n if (this._writableState.ended) return; // no more data can be written.\n // But allow more writes to happen in this tick.\n\n process.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});", - "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n'use strict';\n\nmodule.exports = Readable;\n/**/\n\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n/**/\n\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function EElistenerCount(emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\n\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n/**/\n\n\nvar debugUtil = require('util');\n\nvar debug;\n\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function debug() {};\n}\n/**/\n\n\nvar BufferList = require('./internal/streams/buffer_list');\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.\n\n\nvar StringDecoder;\nvar createReadableStreamAsyncIterator;\nvar from;\n\nrequire('inherits')(Readable, Stream);\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n\n this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n\n this.sync = true; // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n this.paused = true; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')\n\n this.autoDestroy = !!options.autoDestroy; // has it been destroyed\n\n this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s\n\n this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled\n\n this.readingMore = false;\n this.decoder = null;\n this.encoding = null;\n\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside\n // the ReadableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n this._readableState = new ReadableState(options, this, isDuplex); // legacy\n\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n }\n});\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\n\nReadable.prototype._destroy = function (err, cb) {\n cb(err);\n}; // Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\n\n\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n}; // Unshift should *always* be something directly out of read()\n\n\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n debug('readableAddChunk', chunk);\n var state = stream._readableState;\n\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n\n if (er) {\n errorOrDestroy(stream, er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());\n } else if (state.destroyed) {\n return false;\n } else {\n state.reading = false;\n\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n maybeReadMore(stream, state);\n }\n } // We can push more data if we are below the highWaterMark.\n // Also, if we have no data yet, we can stand some more bytes.\n // This is to work around cases where hwm=0, such as the repl.\n\n\n return !state.ended && (state.length < state.highWaterMark || state.length === 0);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n state.awaitDrain = 0;\n stream.emit('data', chunk);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n if (state.needReadable) emitReadable(stream);\n }\n\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);\n }\n\n return er;\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n}; // backwards compatibility.\n\n\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n var decoder = new StringDecoder(enc);\n this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8\n\n this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:\n\n var p = this._readableState.buffer.head;\n var content = '';\n\n while (p !== null) {\n content += decoder.write(p.data);\n p = p.next;\n }\n\n this._readableState.buffer.clear();\n\n if (content !== '') this._readableState.buffer.push(content);\n this._readableState.length = content.length;\n return this;\n}; // Don't raise the hwm > 1GB\n\n\nvar MAX_HWM = 0x40000000;\n\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n\n return n;\n} // This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\n\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n } // If we're asking for more than the current hwm, then raise the hwm.\n\n\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n; // Don't have enough\n\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n\n return state.length;\n} // you can override either this method, or the async _read(n) below.\n\n\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n\n if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.\n\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n } // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n // if we need a readable event, then we need to do some reading.\n\n\n var doRead = state.needReadable;\n debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some\n\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n } // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n\n\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true; // if the length is currently zero, then we *need* a readable event.\n\n if (state.length === 0) state.needReadable = true; // call internal read method\n\n this._read(state.highWaterMark);\n\n state.sync = false; // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = state.length <= state.highWaterMark;\n n = 0;\n } else {\n state.length -= n;\n state.awaitDrain = 0;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.\n\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n debug('onEofChunk');\n if (state.ended) return;\n\n if (state.decoder) {\n var chunk = state.decoder.end();\n\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n\n state.ended = true;\n\n if (state.sync) {\n // if we are sync, wait until next tick to emit the data.\n // Otherwise we risk emitting data in the flow()\n // the readable code triggers during a read() call\n emitReadable(stream);\n } else {\n // emit 'readable' now to make sure it gets picked up.\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n state.emittedReadable = true;\n emitReadable_(stream);\n }\n }\n} // Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\n\n\nfunction emitReadable(stream) {\n var state = stream._readableState;\n debug('emitReadable', state.needReadable, state.emittedReadable);\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n process.nextTick(emitReadable_, stream);\n }\n}\n\nfunction emitReadable_(stream) {\n var state = stream._readableState;\n debug('emitReadable_', state.destroyed, state.length, state.ended);\n\n if (!state.destroyed && (state.length || state.ended)) {\n stream.emit('readable');\n state.emittedReadable = false;\n } // The stream needs another readable event if\n // 1. It is not flowing, as the flow mechanism will take\n // care of it.\n // 2. It is not ended.\n // 3. It is below the highWaterMark, so we can schedule\n // another readable later.\n\n\n state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;\n flow(stream);\n} // at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\n\n\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n process.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n // Attempt to read more data if we should.\n //\n // The conditions for reading more data are (one of):\n // - Not enough data buffered (state.length < state.highWaterMark). The loop\n // is responsible for filling the buffer with enough data if such data\n // is available. If highWaterMark is 0 and we are not in the flowing mode\n // we should _not_ attempt to buffer any extra data. We'll get more data\n // when the stream consumer calls read() instead.\n // - No data in the buffer, and the stream is in flowing mode. In this mode\n // the loop below is responsible for ensuring read() is called. Failing to\n // call read here would abort the flow and there's no other mechanism for\n // continuing the flow if the stream consumer has just subscribed to the\n // 'data' event.\n //\n // In addition to the above conditions to keep reading data, the following\n // conditions prevent the data from being read:\n // - The stream has ended (state.ended).\n // - There is already a pending 'read' operation (state.reading). This is a\n // case where the the stream has called the implementation defined _read()\n // method, but they are processing the call asynchronously and have _not_\n // called push() with new data. In this case we skip performing more\n // read()s. The execution ends in this method again after the _read() ends\n // up calling push() with more data.\n while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {\n var len = state.length;\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length) // didn't get any data, stop spinning.\n break;\n }\n\n state.readingMore = false;\n} // abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\n\n\nReadable.prototype._read = function (n) {\n errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n\n default:\n state.pipes.push(dest);\n break;\n }\n\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);\n dest.on('unpipe', onunpipe);\n\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n } // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n\n\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n var cleanedUp = false;\n\n function cleanup() {\n debug('cleanup'); // cleanup event handlers once the pipe is broken\n\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n cleanedUp = true; // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n src.on('data', ondata);\n\n function ondata(chunk) {\n debug('ondata');\n var ret = dest.write(chunk);\n debug('dest.write', ret);\n\n if (ret === false) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n }\n\n src.pause();\n }\n } // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n\n\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);\n } // Make sure our error handler is attached before userland ones.\n\n\n prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.\n\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n\n dest.once('close', onclose);\n\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n } // tell the dest that it's being piped to\n\n\n dest.emit('pipe', src); // start the flow if it hasn't been started already.\n\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function pipeOnDrainFunctionResult() {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = {\n hasUnpiped: false\n }; // if we're not piping anywhere, then do nothing.\n\n if (state.pipesCount === 0) return this; // just one destination. most common case.\n\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n if (!dest) dest = state.pipes; // got a match.\n\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n } // slow case. multiple pipe destinations.\n\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, {\n hasUnpiped: false\n });\n }\n\n return this;\n } // try to find the right one.\n\n\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n dest.emit('unpipe', this, unpipeInfo);\n return this;\n}; // set up data events if they are asked for\n// Ensure readable listeners eventually get something\n\n\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n var state = this._readableState;\n\n if (ev === 'data') {\n // update readableListening so that resume() may be a no-op\n // a few lines down. This is needed to support once('readable').\n state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused\n\n if (state.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.flowing = false;\n state.emittedReadable = false;\n debug('on readable', state.length, state.reading);\n\n if (state.length) {\n emitReadable(this);\n } else if (!state.reading) {\n process.nextTick(nReadingNextTick, this);\n }\n }\n }\n\n return res;\n};\n\nReadable.prototype.addListener = Readable.prototype.on;\n\nReadable.prototype.removeListener = function (ev, fn) {\n var res = Stream.prototype.removeListener.call(this, ev, fn);\n\n if (ev === 'readable') {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nReadable.prototype.removeAllListeners = function (ev) {\n var res = Stream.prototype.removeAllListeners.apply(this, arguments);\n\n if (ev === 'readable' || ev === undefined) {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nfunction updateReadableListening(self) {\n var state = self._readableState;\n state.readableListening = self.listenerCount('readable') > 0;\n\n if (state.resumeScheduled && !state.paused) {\n // flowing needs to be set to true now, otherwise\n // the upcoming resume will not flow.\n state.flowing = true; // crude way to check if we should resume\n } else if (self.listenerCount('data') > 0) {\n self.resume();\n }\n}\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n} // pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\n\n\nReadable.prototype.resume = function () {\n var state = this._readableState;\n\n if (!state.flowing) {\n debug('resume'); // we flow only if there is no one listening\n // for readable, but we still have to call\n // resume()\n\n state.flowing = !state.readableListening;\n resume(this, state);\n }\n\n state.paused = false;\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n process.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n debug('resume', state.reading);\n\n if (!state.reading) {\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n\n if (this._readableState.flowing !== false) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n\n this._readableState.paused = true;\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n\n while (state.flowing && stream.read() !== null) {\n ;\n }\n} // wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\n\n\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n stream.on('end', function () {\n debug('wrapped end');\n\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode\n\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n\n if (!ret) {\n paused = true;\n stream.pause();\n }\n }); // proxy all the other methods.\n // important when wrapping filters and duplexes.\n\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function methodWrap(method) {\n return function methodWrapReturnFunction() {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n } // proxy certain important events.\n\n\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n } // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n\n\n this._read = function (n) {\n debug('wrapped _read', n);\n\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nif (typeof Symbol === 'function') {\n Readable.prototype[Symbol.asyncIterator] = function () {\n if (createReadableStreamAsyncIterator === undefined) {\n createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');\n }\n\n return createReadableStreamAsyncIterator(this);\n };\n}\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.highWaterMark;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState && this._readableState.buffer;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableFlowing', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.flowing;\n },\n set: function set(state) {\n if (this._readableState) {\n this._readableState.flowing = state;\n }\n }\n}); // exposed for testing purposes only.\n\nReadable._fromList = fromList;\nObject.defineProperty(Readable.prototype, 'readableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.length;\n }\n}); // Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = state.buffer.consume(n, state.decoder);\n }\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n debug('endReadable', state.endEmitted);\n\n if (!state.endEmitted) {\n state.ended = true;\n process.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.\n\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the writable side is ready for autoDestroy as well\n var wState = stream._writableState;\n\n if (!wState || wState.autoDestroy && wState.finished) {\n stream.destroy();\n }\n }\n }\n}\n\nif (typeof Symbol === 'function') {\n Readable.from = function (iterable, opts) {\n if (from === undefined) {\n from = require('./internal/streams/from');\n }\n\n return from(Readable, iterable, opts);\n };\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n\n return -1;\n}", - "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n'use strict';\n\nmodule.exports = Writable;\n/* */\n\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n} // It seems a linked list but it is not\n// there will be only 2 of these for each stream\n\n\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\n\n\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n/**/\n\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/**/\n\n/**/\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,\n ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,\n ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,\n ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\n\nrequire('inherits')(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream,\n // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n\n this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called\n\n this.finalCalled = false; // drain event flag.\n\n this.needDrain = false; // at the start of calling end()\n\n this.ending = false; // when end() has been called, and returned\n\n this.ended = false; // when 'finish' is emitted\n\n this.finished = false; // has it been destroyed\n\n this.destroyed = false; // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n\n this.length = 0; // a flag to see when we're in the middle of a write.\n\n this.writing = false; // when true all writes will be buffered until .uncork() call\n\n this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n\n this.sync = true; // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n\n this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)\n\n this.onwrite = function (er) {\n onwrite(stream, er);\n }; // the callback that the user supplies to write(chunk,encoding,cb)\n\n\n this.writecb = null; // the amount that is being written when _write is called.\n\n this.writelen = 0;\n this.bufferedRequest = null;\n this.lastBufferedRequest = null; // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n\n this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n\n this.prefinished = false; // True if the error was already emitted and should not be thrown again\n\n this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')\n\n this.autoDestroy = !!options.autoDestroy; // count buffered requests\n\n this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n\n while (current) {\n out.push(current);\n current = current.next;\n }\n\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function writableStateBufferGetter() {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})(); // Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\n\n\nvar realHasInstance;\n\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function value(object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function realHasInstance(object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the WritableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);\n this._writableState = new WritableState(options, this, isDuplex); // legacy.\n\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n if (typeof options.writev === 'function') this._writev = options.writev;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n} // Otherwise people can pipe Writable streams, which is just wrong.\n\n\nWritable.prototype.pipe = function () {\n errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb\n\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n} // Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\n\n\nfunction validChunk(stream, state, chunk, cb) {\n var er;\n\n if (chunk === null) {\n er = new ERR_STREAM_NULL_VALUES();\n } else if (typeof chunk !== 'string' && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);\n }\n\n if (er) {\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n return false;\n }\n\n return true;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n if (typeof cb !== 'function') cb = nop;\n if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n return ret;\n};\n\nWritable.prototype.cork = function () {\n this._writableState.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n}); // if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\n\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n\n var len = state.objectMode ? 1 : chunk.length;\n state.length += len;\n var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.\n\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n process.nextTick(cb, er); // this can emit finish, and it will always happen\n // after error\n\n process.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er); // this can emit finish, but finish must\n // always follow error\n\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();\n onwriteStateUpdate(state);\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state) || stream.destroyed;\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n process.nextTick(afterWrite, stream, state, finished, cb);\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n} // Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\n\n\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n} // if there's something in the buffer waiting, then process it\n\n\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n var count = 0;\n var allBuffers = true;\n\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n\n buffer.allBuffers = allBuffers;\n doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n\n state.pendingcb++;\n state.lastBufferedRequest = null;\n\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks\n\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n } // ignore unnecessary end() calls.\n\n\n if (!state.ending) endWritable(this, state, cb);\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n});\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\n\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n\n if (err) {\n errorOrDestroy(stream, err);\n }\n\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\n\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function' && !state.destroyed) {\n state.pendingcb++;\n state.finalCalled = true;\n process.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n\n if (need) {\n prefinish(stream, state);\n\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the readable side is ready for autoDestroy as well\n var rState = stream._readableState;\n\n if (!rState || rState.autoDestroy && rState.endEmitted) {\n stream.destroy();\n }\n }\n }\n }\n\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n\n if (cb) {\n if (state.finished) process.nextTick(cb);else stream.once('finish', cb);\n }\n\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n } // reuse the free corkReq.\n\n\n state.corkedRequestsFree.next = corkReq;\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._writableState === undefined) {\n return false;\n }\n\n return this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._writableState.destroyed = value;\n }\n});\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\n\nWritable.prototype._destroy = function (err, cb) {\n cb(err);\n};", - "'use strict';\n\nvar _Object$setPrototypeO;\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar finished = require('./end-of-stream');\n\nvar kLastResolve = Symbol('lastResolve');\nvar kLastReject = Symbol('lastReject');\nvar kError = Symbol('error');\nvar kEnded = Symbol('ended');\nvar kLastPromise = Symbol('lastPromise');\nvar kHandlePromise = Symbol('handlePromise');\nvar kStream = Symbol('stream');\n\nfunction createIterResult(value, done) {\n return {\n value: value,\n done: done\n };\n}\n\nfunction readAndResolve(iter) {\n var resolve = iter[kLastResolve];\n\n if (resolve !== null) {\n var data = iter[kStream].read(); // we defer if data is null\n // we can be expecting either 'end' or\n // 'error'\n\n if (data !== null) {\n iter[kLastPromise] = null;\n iter[kLastResolve] = null;\n iter[kLastReject] = null;\n resolve(createIterResult(data, false));\n }\n }\n}\n\nfunction onReadable(iter) {\n // we wait for the next tick, because it might\n // emit an error with process.nextTick\n process.nextTick(readAndResolve, iter);\n}\n\nfunction wrapForNext(lastPromise, iter) {\n return function (resolve, reject) {\n lastPromise.then(function () {\n if (iter[kEnded]) {\n resolve(createIterResult(undefined, true));\n return;\n }\n\n iter[kHandlePromise](resolve, reject);\n }, reject);\n };\n}\n\nvar AsyncIteratorPrototype = Object.getPrototypeOf(function () {});\nvar ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {\n get stream() {\n return this[kStream];\n },\n\n next: function next() {\n var _this = this;\n\n // if we have detected an error in the meanwhile\n // reject straight away\n var error = this[kError];\n\n if (error !== null) {\n return Promise.reject(error);\n }\n\n if (this[kEnded]) {\n return Promise.resolve(createIterResult(undefined, true));\n }\n\n if (this[kStream].destroyed) {\n // We need to defer via nextTick because if .destroy(err) is\n // called, the error will be emitted via nextTick, and\n // we cannot guarantee that there is no error lingering around\n // waiting to be emitted.\n return new Promise(function (resolve, reject) {\n process.nextTick(function () {\n if (_this[kError]) {\n reject(_this[kError]);\n } else {\n resolve(createIterResult(undefined, true));\n }\n });\n });\n } // if we have multiple next() calls\n // we will wait for the previous Promise to finish\n // this logic is optimized to support for await loops,\n // where next() is only called once at a time\n\n\n var lastPromise = this[kLastPromise];\n var promise;\n\n if (lastPromise) {\n promise = new Promise(wrapForNext(lastPromise, this));\n } else {\n // fast path needed to support multiple this.push()\n // without triggering the next() queue\n var data = this[kStream].read();\n\n if (data !== null) {\n return Promise.resolve(createIterResult(data, false));\n }\n\n promise = new Promise(this[kHandlePromise]);\n }\n\n this[kLastPromise] = promise;\n return promise;\n }\n}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {\n return this;\n}), _defineProperty(_Object$setPrototypeO, \"return\", function _return() {\n var _this2 = this;\n\n // destroy(err, cb) is a private API\n // we can guarantee we have that here, because we control the\n // Readable class this is attached to\n return new Promise(function (resolve, reject) {\n _this2[kStream].destroy(null, function (err) {\n if (err) {\n reject(err);\n return;\n }\n\n resolve(createIterResult(undefined, true));\n });\n });\n}), _Object$setPrototypeO), AsyncIteratorPrototype);\n\nvar createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {\n var _Object$create;\n\n var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {\n value: stream,\n writable: true\n }), _defineProperty(_Object$create, kLastResolve, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kLastReject, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kError, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kEnded, {\n value: stream._readableState.endEmitted,\n writable: true\n }), _defineProperty(_Object$create, kHandlePromise, {\n value: function value(resolve, reject) {\n var data = iterator[kStream].read();\n\n if (data) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(data, false));\n } else {\n iterator[kLastResolve] = resolve;\n iterator[kLastReject] = reject;\n }\n },\n writable: true\n }), _Object$create));\n iterator[kLastPromise] = null;\n finished(stream, function (err) {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise\n // returned by next() and store the error\n\n if (reject !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n reject(err);\n }\n\n iterator[kError] = err;\n return;\n }\n\n var resolve = iterator[kLastResolve];\n\n if (resolve !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(undefined, true));\n }\n\n iterator[kEnded] = true;\n });\n stream.on('readable', onReadable.bind(null, iterator));\n return iterator;\n};\n\nmodule.exports = createReadableStreamAsyncIterator;", - "'use strict'; // undocumented cb() API, needed for core, not for public API\n\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n process.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n process.nextTick(emitErrorNT, this, err);\n }\n }\n\n return this;\n } // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n } // if this is a duplex stream mark the writable part as destroyed as well\n\n\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n } else if (cb) {\n process.nextTick(emitCloseNT, _this);\n cb(err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n });\n\n return this;\n}\n\nfunction emitErrorAndCloseNT(self, err) {\n emitErrorNT(self, err);\n emitCloseNT(self);\n}\n\nfunction emitCloseNT(self) {\n if (self._writableState && !self._writableState.emitClose) return;\n if (self._readableState && !self._readableState.emitClose) return;\n self.emit('close');\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nfunction errorOrDestroy(stream, err) {\n // We have tests that rely on errors being emitted\n // in the same tick, so changing this is semver major.\n // For now when you opt-in to autoDestroy we allow\n // the error to be emitted nextTick. In a future\n // semver major update we should change the default to this.\n var rState = stream._readableState;\n var wState = stream._writableState;\n if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy,\n errorOrDestroy: errorOrDestroy\n};", - "var hash = exports;\n\nhash.utils = require('./hash/utils');\nhash.common = require('./hash/common');\nhash.sha = require('./hash/sha');\nhash.ripemd = require('./hash/ripemd');\nhash.hmac = require('./hash/hmac');\n\n// Proxy hash functions to the main object\nhash.sha1 = hash.sha.sha1;\nhash.sha256 = hash.sha.sha256;\nhash.sha224 = hash.sha.sha224;\nhash.sha384 = hash.sha.sha384;\nhash.sha512 = hash.sha.sha512;\nhash.ripemd160 = hash.ripemd.ripemd160;\n", - "'use strict';\n\nvar utils = require('./utils');\nvar assert = require('minimalistic-assert');\n\nfunction BlockHash() {\n this.pending = null;\n this.pendingTotal = 0;\n this.blockSize = this.constructor.blockSize;\n this.outSize = this.constructor.outSize;\n this.hmacStrength = this.constructor.hmacStrength;\n this.padLength = this.constructor.padLength / 8;\n this.endian = 'big';\n\n this._delta8 = this.blockSize / 8;\n this._delta32 = this.blockSize / 32;\n}\nexports.BlockHash = BlockHash;\n\nBlockHash.prototype.update = function update(msg, enc) {\n // Convert message to array, pad it, and join into 32bit blocks\n msg = utils.toArray(msg, enc);\n if (!this.pending)\n this.pending = msg;\n else\n this.pending = this.pending.concat(msg);\n this.pendingTotal += msg.length;\n\n // Enough data, try updating\n if (this.pending.length >= this._delta8) {\n msg = this.pending;\n\n // Process pending data in blocks\n var r = msg.length % this._delta8;\n this.pending = msg.slice(msg.length - r, msg.length);\n if (this.pending.length === 0)\n this.pending = null;\n\n msg = utils.join32(msg, 0, msg.length - r, this.endian);\n for (var i = 0; i < msg.length; i += this._delta32)\n this._update(msg, i, i + this._delta32);\n }\n\n return this;\n};\n\nBlockHash.prototype.digest = function digest(enc) {\n this.update(this._pad());\n assert(this.pending === null);\n\n return this._digest(enc);\n};\n\nBlockHash.prototype._pad = function pad() {\n var len = this.pendingTotal;\n var bytes = this._delta8;\n var k = bytes - ((len + this.padLength) % bytes);\n var res = new Array(k + this.padLength);\n res[0] = 0x80;\n for (var i = 1; i < k; i++)\n res[i] = 0;\n\n // Append length\n len <<= 3;\n if (this.endian === 'big') {\n for (var t = 8; t < this.padLength; t++)\n res[i++] = 0;\n\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = (len >>> 24) & 0xff;\n res[i++] = (len >>> 16) & 0xff;\n res[i++] = (len >>> 8) & 0xff;\n res[i++] = len & 0xff;\n } else {\n res[i++] = len & 0xff;\n res[i++] = (len >>> 8) & 0xff;\n res[i++] = (len >>> 16) & 0xff;\n res[i++] = (len >>> 24) & 0xff;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n res[i++] = 0;\n\n for (t = 8; t < this.padLength; t++)\n res[i++] = 0;\n }\n\n return res;\n};\n", - "'use strict';\n\nvar utils = require('./utils');\nvar assert = require('minimalistic-assert');\n\nfunction Hmac(hash, key, enc) {\n if (!(this instanceof Hmac))\n return new Hmac(hash, key, enc);\n this.Hash = hash;\n this.blockSize = hash.blockSize / 8;\n this.outSize = hash.outSize / 8;\n this.inner = null;\n this.outer = null;\n\n this._init(utils.toArray(key, enc));\n}\nmodule.exports = Hmac;\n\nHmac.prototype._init = function init(key) {\n // Shorten key, if needed\n if (key.length > this.blockSize)\n key = new this.Hash().update(key).digest();\n assert(key.length <= this.blockSize);\n\n // Add padding to key\n for (var i = key.length; i < this.blockSize; i++)\n key.push(0);\n\n for (i = 0; i < key.length; i++)\n key[i] ^= 0x36;\n this.inner = new this.Hash().update(key);\n\n // 0x36 ^ 0x5c = 0x6a\n for (i = 0; i < key.length; i++)\n key[i] ^= 0x6a;\n this.outer = new this.Hash().update(key);\n};\n\nHmac.prototype.update = function update(msg, enc) {\n this.inner.update(msg, enc);\n return this;\n};\n\nHmac.prototype.digest = function digest(enc) {\n this.outer.update(this.inner.digest());\n return this.outer.digest(enc);\n};\n", - "'use strict';\n\nvar utils = require('./utils');\nvar common = require('./common');\n\nvar rotl32 = utils.rotl32;\nvar sum32 = utils.sum32;\nvar sum32_3 = utils.sum32_3;\nvar sum32_4 = utils.sum32_4;\nvar BlockHash = common.BlockHash;\n\nfunction RIPEMD160() {\n if (!(this instanceof RIPEMD160))\n return new RIPEMD160();\n\n BlockHash.call(this);\n\n this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];\n this.endian = 'little';\n}\nutils.inherits(RIPEMD160, BlockHash);\nexports.ripemd160 = RIPEMD160;\n\nRIPEMD160.blockSize = 512;\nRIPEMD160.outSize = 160;\nRIPEMD160.hmacStrength = 192;\nRIPEMD160.padLength = 64;\n\nRIPEMD160.prototype._update = function update(msg, start) {\n var A = this.h[0];\n var B = this.h[1];\n var C = this.h[2];\n var D = this.h[3];\n var E = this.h[4];\n var Ah = A;\n var Bh = B;\n var Ch = C;\n var Dh = D;\n var Eh = E;\n for (var j = 0; j < 80; j++) {\n var T = sum32(\n rotl32(\n sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),\n s[j]),\n E);\n A = E;\n E = D;\n D = rotl32(C, 10);\n C = B;\n B = T;\n T = sum32(\n rotl32(\n sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),\n sh[j]),\n Eh);\n Ah = Eh;\n Eh = Dh;\n Dh = rotl32(Ch, 10);\n Ch = Bh;\n Bh = T;\n }\n T = sum32_3(this.h[1], C, Dh);\n this.h[1] = sum32_3(this.h[2], D, Eh);\n this.h[2] = sum32_3(this.h[3], E, Ah);\n this.h[3] = sum32_3(this.h[4], A, Bh);\n this.h[4] = sum32_3(this.h[0], B, Ch);\n this.h[0] = T;\n};\n\nRIPEMD160.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'little');\n else\n return utils.split32(this.h, 'little');\n};\n\nfunction f(j, x, y, z) {\n if (j <= 15)\n return x ^ y ^ z;\n else if (j <= 31)\n return (x & y) | ((~x) & z);\n else if (j <= 47)\n return (x | (~y)) ^ z;\n else if (j <= 63)\n return (x & z) | (y & (~z));\n else\n return x ^ (y | (~z));\n}\n\nfunction K(j) {\n if (j <= 15)\n return 0x00000000;\n else if (j <= 31)\n return 0x5a827999;\n else if (j <= 47)\n return 0x6ed9eba1;\n else if (j <= 63)\n return 0x8f1bbcdc;\n else\n return 0xa953fd4e;\n}\n\nfunction Kh(j) {\n if (j <= 15)\n return 0x50a28be6;\n else if (j <= 31)\n return 0x5c4dd124;\n else if (j <= 47)\n return 0x6d703ef3;\n else if (j <= 63)\n return 0x7a6d76e9;\n else\n return 0x00000000;\n}\n\nvar r = [\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,\n 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,\n 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13\n];\n\nvar rh = [\n 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,\n 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,\n 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,\n 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,\n 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11\n];\n\nvar s = [\n 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,\n 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,\n 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,\n 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,\n 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6\n];\n\nvar sh = [\n 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,\n 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,\n 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,\n 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,\n 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11\n];\n", - "'use strict';\n\nexports.sha1 = require('./sha/1');\nexports.sha224 = require('./sha/224');\nexports.sha256 = require('./sha/256');\nexports.sha384 = require('./sha/384');\nexports.sha512 = require('./sha/512');\n", - "'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar shaCommon = require('./common');\n\nvar rotl32 = utils.rotl32;\nvar sum32 = utils.sum32;\nvar sum32_5 = utils.sum32_5;\nvar ft_1 = shaCommon.ft_1;\nvar BlockHash = common.BlockHash;\n\nvar sha1_K = [\n 0x5A827999, 0x6ED9EBA1,\n 0x8F1BBCDC, 0xCA62C1D6\n];\n\nfunction SHA1() {\n if (!(this instanceof SHA1))\n return new SHA1();\n\n BlockHash.call(this);\n this.h = [\n 0x67452301, 0xefcdab89, 0x98badcfe,\n 0x10325476, 0xc3d2e1f0 ];\n this.W = new Array(80);\n}\n\nutils.inherits(SHA1, BlockHash);\nmodule.exports = SHA1;\n\nSHA1.blockSize = 512;\nSHA1.outSize = 160;\nSHA1.hmacStrength = 80;\nSHA1.padLength = 64;\n\nSHA1.prototype._update = function _update(msg, start) {\n var W = this.W;\n\n for (var i = 0; i < 16; i++)\n W[i] = msg[start + i];\n\n for(; i < W.length; i++)\n W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);\n\n var a = this.h[0];\n var b = this.h[1];\n var c = this.h[2];\n var d = this.h[3];\n var e = this.h[4];\n\n for (i = 0; i < W.length; i++) {\n var s = ~~(i / 20);\n var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);\n e = d;\n d = c;\n c = rotl32(b, 30);\n b = a;\n a = t;\n }\n\n this.h[0] = sum32(this.h[0], a);\n this.h[1] = sum32(this.h[1], b);\n this.h[2] = sum32(this.h[2], c);\n this.h[3] = sum32(this.h[3], d);\n this.h[4] = sum32(this.h[4], e);\n};\n\nSHA1.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n", - "'use strict';\n\nvar utils = require('../utils');\nvar SHA256 = require('./256');\n\nfunction SHA224() {\n if (!(this instanceof SHA224))\n return new SHA224();\n\n SHA256.call(this);\n this.h = [\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,\n 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];\n}\nutils.inherits(SHA224, SHA256);\nmodule.exports = SHA224;\n\nSHA224.blockSize = 512;\nSHA224.outSize = 224;\nSHA224.hmacStrength = 192;\nSHA224.padLength = 64;\n\nSHA224.prototype._digest = function digest(enc) {\n // Just truncate output\n if (enc === 'hex')\n return utils.toHex32(this.h.slice(0, 7), 'big');\n else\n return utils.split32(this.h.slice(0, 7), 'big');\n};\n\n", - "'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar shaCommon = require('./common');\nvar assert = require('minimalistic-assert');\n\nvar sum32 = utils.sum32;\nvar sum32_4 = utils.sum32_4;\nvar sum32_5 = utils.sum32_5;\nvar ch32 = shaCommon.ch32;\nvar maj32 = shaCommon.maj32;\nvar s0_256 = shaCommon.s0_256;\nvar s1_256 = shaCommon.s1_256;\nvar g0_256 = shaCommon.g0_256;\nvar g1_256 = shaCommon.g1_256;\n\nvar BlockHash = common.BlockHash;\n\nvar sha256_K = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,\n 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,\n 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,\n 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,\n 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n];\n\nfunction SHA256() {\n if (!(this instanceof SHA256))\n return new SHA256();\n\n BlockHash.call(this);\n this.h = [\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,\n 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n ];\n this.k = sha256_K;\n this.W = new Array(64);\n}\nutils.inherits(SHA256, BlockHash);\nmodule.exports = SHA256;\n\nSHA256.blockSize = 512;\nSHA256.outSize = 256;\nSHA256.hmacStrength = 192;\nSHA256.padLength = 64;\n\nSHA256.prototype._update = function _update(msg, start) {\n var W = this.W;\n\n for (var i = 0; i < 16; i++)\n W[i] = msg[start + i];\n for (; i < W.length; i++)\n W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);\n\n var a = this.h[0];\n var b = this.h[1];\n var c = this.h[2];\n var d = this.h[3];\n var e = this.h[4];\n var f = this.h[5];\n var g = this.h[6];\n var h = this.h[7];\n\n assert(this.k.length === W.length);\n for (i = 0; i < W.length; i++) {\n var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);\n var T2 = sum32(s0_256(a), maj32(a, b, c));\n h = g;\n g = f;\n f = e;\n e = sum32(d, T1);\n d = c;\n c = b;\n b = a;\n a = sum32(T1, T2);\n }\n\n this.h[0] = sum32(this.h[0], a);\n this.h[1] = sum32(this.h[1], b);\n this.h[2] = sum32(this.h[2], c);\n this.h[3] = sum32(this.h[3], d);\n this.h[4] = sum32(this.h[4], e);\n this.h[5] = sum32(this.h[5], f);\n this.h[6] = sum32(this.h[6], g);\n this.h[7] = sum32(this.h[7], h);\n};\n\nSHA256.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n", - "'use strict';\n\nvar utils = require('../utils');\n\nvar SHA512 = require('./512');\n\nfunction SHA384() {\n if (!(this instanceof SHA384))\n return new SHA384();\n\n SHA512.call(this);\n this.h = [\n 0xcbbb9d5d, 0xc1059ed8,\n 0x629a292a, 0x367cd507,\n 0x9159015a, 0x3070dd17,\n 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31,\n 0x8eb44a87, 0x68581511,\n 0xdb0c2e0d, 0x64f98fa7,\n 0x47b5481d, 0xbefa4fa4 ];\n}\nutils.inherits(SHA384, SHA512);\nmodule.exports = SHA384;\n\nSHA384.blockSize = 1024;\nSHA384.outSize = 384;\nSHA384.hmacStrength = 192;\nSHA384.padLength = 128;\n\nSHA384.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h.slice(0, 12), 'big');\n else\n return utils.split32(this.h.slice(0, 12), 'big');\n};\n", - "'use strict';\n\nvar utils = require('../utils');\nvar common = require('../common');\nvar assert = require('minimalistic-assert');\n\nvar rotr64_hi = utils.rotr64_hi;\nvar rotr64_lo = utils.rotr64_lo;\nvar shr64_hi = utils.shr64_hi;\nvar shr64_lo = utils.shr64_lo;\nvar sum64 = utils.sum64;\nvar sum64_hi = utils.sum64_hi;\nvar sum64_lo = utils.sum64_lo;\nvar sum64_4_hi = utils.sum64_4_hi;\nvar sum64_4_lo = utils.sum64_4_lo;\nvar sum64_5_hi = utils.sum64_5_hi;\nvar sum64_5_lo = utils.sum64_5_lo;\n\nvar BlockHash = common.BlockHash;\n\nvar sha512_K = [\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n];\n\nfunction SHA512() {\n if (!(this instanceof SHA512))\n return new SHA512();\n\n BlockHash.call(this);\n this.h = [\n 0x6a09e667, 0xf3bcc908,\n 0xbb67ae85, 0x84caa73b,\n 0x3c6ef372, 0xfe94f82b,\n 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1,\n 0x9b05688c, 0x2b3e6c1f,\n 0x1f83d9ab, 0xfb41bd6b,\n 0x5be0cd19, 0x137e2179 ];\n this.k = sha512_K;\n this.W = new Array(160);\n}\nutils.inherits(SHA512, BlockHash);\nmodule.exports = SHA512;\n\nSHA512.blockSize = 1024;\nSHA512.outSize = 512;\nSHA512.hmacStrength = 192;\nSHA512.padLength = 128;\n\nSHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {\n var W = this.W;\n\n // 32 x 32bit words\n for (var i = 0; i < 32; i++)\n W[i] = msg[start + i];\n for (; i < W.length; i += 2) {\n var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2\n var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);\n var c1_hi = W[i - 14]; // i - 7\n var c1_lo = W[i - 13];\n var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15\n var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);\n var c3_hi = W[i - 32]; // i - 16\n var c3_lo = W[i - 31];\n\n W[i] = sum64_4_hi(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo);\n W[i + 1] = sum64_4_lo(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo);\n }\n};\n\nSHA512.prototype._update = function _update(msg, start) {\n this._prepareBlock(msg, start);\n\n var W = this.W;\n\n var ah = this.h[0];\n var al = this.h[1];\n var bh = this.h[2];\n var bl = this.h[3];\n var ch = this.h[4];\n var cl = this.h[5];\n var dh = this.h[6];\n var dl = this.h[7];\n var eh = this.h[8];\n var el = this.h[9];\n var fh = this.h[10];\n var fl = this.h[11];\n var gh = this.h[12];\n var gl = this.h[13];\n var hh = this.h[14];\n var hl = this.h[15];\n\n assert(this.k.length === W.length);\n for (var i = 0; i < W.length; i += 2) {\n var c0_hi = hh;\n var c0_lo = hl;\n var c1_hi = s1_512_hi(eh, el);\n var c1_lo = s1_512_lo(eh, el);\n var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);\n var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);\n var c3_hi = this.k[i];\n var c3_lo = this.k[i + 1];\n var c4_hi = W[i];\n var c4_lo = W[i + 1];\n\n var T1_hi = sum64_5_hi(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo,\n c4_hi, c4_lo);\n var T1_lo = sum64_5_lo(\n c0_hi, c0_lo,\n c1_hi, c1_lo,\n c2_hi, c2_lo,\n c3_hi, c3_lo,\n c4_hi, c4_lo);\n\n c0_hi = s0_512_hi(ah, al);\n c0_lo = s0_512_lo(ah, al);\n c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);\n c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);\n\n var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);\n var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);\n\n hh = gh;\n hl = gl;\n\n gh = fh;\n gl = fl;\n\n fh = eh;\n fl = el;\n\n eh = sum64_hi(dh, dl, T1_hi, T1_lo);\n el = sum64_lo(dl, dl, T1_hi, T1_lo);\n\n dh = ch;\n dl = cl;\n\n ch = bh;\n cl = bl;\n\n bh = ah;\n bl = al;\n\n ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);\n al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);\n }\n\n sum64(this.h, 0, ah, al);\n sum64(this.h, 2, bh, bl);\n sum64(this.h, 4, ch, cl);\n sum64(this.h, 6, dh, dl);\n sum64(this.h, 8, eh, el);\n sum64(this.h, 10, fh, fl);\n sum64(this.h, 12, gh, gl);\n sum64(this.h, 14, hh, hl);\n};\n\nSHA512.prototype._digest = function digest(enc) {\n if (enc === 'hex')\n return utils.toHex32(this.h, 'big');\n else\n return utils.split32(this.h, 'big');\n};\n\nfunction ch64_hi(xh, xl, yh, yl, zh) {\n var r = (xh & yh) ^ ((~xh) & zh);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction ch64_lo(xh, xl, yh, yl, zh, zl) {\n var r = (xl & yl) ^ ((~xl) & zl);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction maj64_hi(xh, xl, yh, yl, zh) {\n var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction maj64_lo(xh, xl, yh, yl, zh, zl) {\n var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s0_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 28);\n var c1_hi = rotr64_hi(xl, xh, 2); // 34\n var c2_hi = rotr64_hi(xl, xh, 7); // 39\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s0_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 28);\n var c1_lo = rotr64_lo(xl, xh, 2); // 34\n var c2_lo = rotr64_lo(xl, xh, 7); // 39\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s1_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 14);\n var c1_hi = rotr64_hi(xh, xl, 18);\n var c2_hi = rotr64_hi(xl, xh, 9); // 41\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction s1_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 14);\n var c1_lo = rotr64_lo(xh, xl, 18);\n var c2_lo = rotr64_lo(xl, xh, 9); // 41\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g0_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 1);\n var c1_hi = rotr64_hi(xh, xl, 8);\n var c2_hi = shr64_hi(xh, xl, 7);\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g0_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 1);\n var c1_lo = rotr64_lo(xh, xl, 8);\n var c2_lo = shr64_lo(xh, xl, 7);\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g1_512_hi(xh, xl) {\n var c0_hi = rotr64_hi(xh, xl, 19);\n var c1_hi = rotr64_hi(xl, xh, 29); // 61\n var c2_hi = shr64_hi(xh, xl, 6);\n\n var r = c0_hi ^ c1_hi ^ c2_hi;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n\nfunction g1_512_lo(xh, xl) {\n var c0_lo = rotr64_lo(xh, xl, 19);\n var c1_lo = rotr64_lo(xl, xh, 29); // 61\n var c2_lo = shr64_lo(xh, xl, 6);\n\n var r = c0_lo ^ c1_lo ^ c2_lo;\n if (r < 0)\n r += 0x100000000;\n return r;\n}\n", - "'use strict';\n\nvar utils = require('../utils');\nvar rotr32 = utils.rotr32;\n\nfunction ft_1(s, x, y, z) {\n if (s === 0)\n return ch32(x, y, z);\n if (s === 1 || s === 3)\n return p32(x, y, z);\n if (s === 2)\n return maj32(x, y, z);\n}\nexports.ft_1 = ft_1;\n\nfunction ch32(x, y, z) {\n return (x & y) ^ ((~x) & z);\n}\nexports.ch32 = ch32;\n\nfunction maj32(x, y, z) {\n return (x & y) ^ (x & z) ^ (y & z);\n}\nexports.maj32 = maj32;\n\nfunction p32(x, y, z) {\n return x ^ y ^ z;\n}\nexports.p32 = p32;\n\nfunction s0_256(x) {\n return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);\n}\nexports.s0_256 = s0_256;\n\nfunction s1_256(x) {\n return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);\n}\nexports.s1_256 = s1_256;\n\nfunction g0_256(x) {\n return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);\n}\nexports.g0_256 = g0_256;\n\nfunction g1_256(x) {\n return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);\n}\nexports.g1_256 = g1_256;\n", - "'use strict';\n\nvar assert = require('minimalistic-assert');\nvar inherits = require('inherits');\n\nexports.inherits = inherits;\n\nfunction isSurrogatePair(msg, i) {\n if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {\n return false;\n }\n if (i < 0 || i + 1 >= msg.length) {\n return false;\n }\n return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;\n}\n\nfunction toArray(msg, enc) {\n if (Array.isArray(msg))\n return msg.slice();\n if (!msg)\n return [];\n var res = [];\n if (typeof msg === 'string') {\n if (!enc) {\n // Inspired by stringToUtf8ByteArray() in closure-library by Google\n // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143\n // Apache License 2.0\n // https://github.com/google/closure-library/blob/master/LICENSE\n var p = 0;\n for (var i = 0; i < msg.length; i++) {\n var c = msg.charCodeAt(i);\n if (c < 128) {\n res[p++] = c;\n } else if (c < 2048) {\n res[p++] = (c >> 6) | 192;\n res[p++] = (c & 63) | 128;\n } else if (isSurrogatePair(msg, i)) {\n c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);\n res[p++] = (c >> 18) | 240;\n res[p++] = ((c >> 12) & 63) | 128;\n res[p++] = ((c >> 6) & 63) | 128;\n res[p++] = (c & 63) | 128;\n } else {\n res[p++] = (c >> 12) | 224;\n res[p++] = ((c >> 6) & 63) | 128;\n res[p++] = (c & 63) | 128;\n }\n }\n } else if (enc === 'hex') {\n msg = msg.replace(/[^a-z0-9]+/ig, '');\n if (msg.length % 2 !== 0)\n msg = '0' + msg;\n for (i = 0; i < msg.length; i += 2)\n res.push(parseInt(msg[i] + msg[i + 1], 16));\n }\n } else {\n for (i = 0; i < msg.length; i++)\n res[i] = msg[i] | 0;\n }\n return res;\n}\nexports.toArray = toArray;\n\nfunction toHex(msg) {\n var res = '';\n for (var i = 0; i < msg.length; i++)\n res += zero2(msg[i].toString(16));\n return res;\n}\nexports.toHex = toHex;\n\nfunction htonl(w) {\n var res = (w >>> 24) |\n ((w >>> 8) & 0xff00) |\n ((w << 8) & 0xff0000) |\n ((w & 0xff) << 24);\n return res >>> 0;\n}\nexports.htonl = htonl;\n\nfunction toHex32(msg, endian) {\n var res = '';\n for (var i = 0; i < msg.length; i++) {\n var w = msg[i];\n if (endian === 'little')\n w = htonl(w);\n res += zero8(w.toString(16));\n }\n return res;\n}\nexports.toHex32 = toHex32;\n\nfunction zero2(word) {\n if (word.length === 1)\n return '0' + word;\n else\n return word;\n}\nexports.zero2 = zero2;\n\nfunction zero8(word) {\n if (word.length === 7)\n return '0' + word;\n else if (word.length === 6)\n return '00' + word;\n else if (word.length === 5)\n return '000' + word;\n else if (word.length === 4)\n return '0000' + word;\n else if (word.length === 3)\n return '00000' + word;\n else if (word.length === 2)\n return '000000' + word;\n else if (word.length === 1)\n return '0000000' + word;\n else\n return word;\n}\nexports.zero8 = zero8;\n\nfunction join32(msg, start, end, endian) {\n var len = end - start;\n assert(len % 4 === 0);\n var res = new Array(len / 4);\n for (var i = 0, k = start; i < res.length; i++, k += 4) {\n var w;\n if (endian === 'big')\n w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];\n else\n w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];\n res[i] = w >>> 0;\n }\n return res;\n}\nexports.join32 = join32;\n\nfunction split32(msg, endian) {\n var res = new Array(msg.length * 4);\n for (var i = 0, k = 0; i < msg.length; i++, k += 4) {\n var m = msg[i];\n if (endian === 'big') {\n res[k] = m >>> 24;\n res[k + 1] = (m >>> 16) & 0xff;\n res[k + 2] = (m >>> 8) & 0xff;\n res[k + 3] = m & 0xff;\n } else {\n res[k + 3] = m >>> 24;\n res[k + 2] = (m >>> 16) & 0xff;\n res[k + 1] = (m >>> 8) & 0xff;\n res[k] = m & 0xff;\n }\n }\n return res;\n}\nexports.split32 = split32;\n\nfunction rotr32(w, b) {\n return (w >>> b) | (w << (32 - b));\n}\nexports.rotr32 = rotr32;\n\nfunction rotl32(w, b) {\n return (w << b) | (w >>> (32 - b));\n}\nexports.rotl32 = rotl32;\n\nfunction sum32(a, b) {\n return (a + b) >>> 0;\n}\nexports.sum32 = sum32;\n\nfunction sum32_3(a, b, c) {\n return (a + b + c) >>> 0;\n}\nexports.sum32_3 = sum32_3;\n\nfunction sum32_4(a, b, c, d) {\n return (a + b + c + d) >>> 0;\n}\nexports.sum32_4 = sum32_4;\n\nfunction sum32_5(a, b, c, d, e) {\n return (a + b + c + d + e) >>> 0;\n}\nexports.sum32_5 = sum32_5;\n\nfunction sum64(buf, pos, ah, al) {\n var bh = buf[pos];\n var bl = buf[pos + 1];\n\n var lo = (al + bl) >>> 0;\n var hi = (lo < al ? 1 : 0) + ah + bh;\n buf[pos] = hi >>> 0;\n buf[pos + 1] = lo;\n}\nexports.sum64 = sum64;\n\nfunction sum64_hi(ah, al, bh, bl) {\n var lo = (al + bl) >>> 0;\n var hi = (lo < al ? 1 : 0) + ah + bh;\n return hi >>> 0;\n}\nexports.sum64_hi = sum64_hi;\n\nfunction sum64_lo(ah, al, bh, bl) {\n var lo = al + bl;\n return lo >>> 0;\n}\nexports.sum64_lo = sum64_lo;\n\nfunction sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {\n var carry = 0;\n var lo = al;\n lo = (lo + bl) >>> 0;\n carry += lo < al ? 1 : 0;\n lo = (lo + cl) >>> 0;\n carry += lo < cl ? 1 : 0;\n lo = (lo + dl) >>> 0;\n carry += lo < dl ? 1 : 0;\n\n var hi = ah + bh + ch + dh + carry;\n return hi >>> 0;\n}\nexports.sum64_4_hi = sum64_4_hi;\n\nfunction sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {\n var lo = al + bl + cl + dl;\n return lo >>> 0;\n}\nexports.sum64_4_lo = sum64_4_lo;\n\nfunction sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {\n var carry = 0;\n var lo = al;\n lo = (lo + bl) >>> 0;\n carry += lo < al ? 1 : 0;\n lo = (lo + cl) >>> 0;\n carry += lo < cl ? 1 : 0;\n lo = (lo + dl) >>> 0;\n carry += lo < dl ? 1 : 0;\n lo = (lo + el) >>> 0;\n carry += lo < el ? 1 : 0;\n\n var hi = ah + bh + ch + dh + eh + carry;\n return hi >>> 0;\n}\nexports.sum64_5_hi = sum64_5_hi;\n\nfunction sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {\n var lo = al + bl + cl + dl + el;\n\n return lo >>> 0;\n}\nexports.sum64_5_lo = sum64_5_lo;\n\nfunction rotr64_hi(ah, al, num) {\n var r = (al << (32 - num)) | (ah >>> num);\n return r >>> 0;\n}\nexports.rotr64_hi = rotr64_hi;\n\nfunction rotr64_lo(ah, al, num) {\n var r = (ah << (32 - num)) | (al >>> num);\n return r >>> 0;\n}\nexports.rotr64_lo = rotr64_lo;\n\nfunction shr64_hi(ah, al, num) {\n return ah >>> num;\n}\nexports.shr64_hi = shr64_hi;\n\nfunction shr64_lo(ah, al, num) {\n var r = (ah << (32 - num)) | (al >>> num);\n return r >>> 0;\n}\nexports.shr64_lo = shr64_lo;\n", - "'use strict';\n\nvar hash = require('hash.js');\nvar utils = require('minimalistic-crypto-utils');\nvar assert = require('minimalistic-assert');\n\nfunction HmacDRBG(options) {\n if (!(this instanceof HmacDRBG))\n return new HmacDRBG(options);\n this.hash = options.hash;\n this.predResist = !!options.predResist;\n\n this.outLen = this.hash.outSize;\n this.minEntropy = options.minEntropy || this.hash.hmacStrength;\n\n this._reseed = null;\n this.reseedInterval = null;\n this.K = null;\n this.V = null;\n\n var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');\n var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');\n var pers = utils.toArray(options.pers, options.persEnc || 'hex');\n assert(entropy.length >= (this.minEntropy / 8),\n 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');\n this._init(entropy, nonce, pers);\n}\nmodule.exports = HmacDRBG;\n\nHmacDRBG.prototype._init = function init(entropy, nonce, pers) {\n var seed = entropy.concat(nonce).concat(pers);\n\n this.K = new Array(this.outLen / 8);\n this.V = new Array(this.outLen / 8);\n for (var i = 0; i < this.V.length; i++) {\n this.K[i] = 0x00;\n this.V[i] = 0x01;\n }\n\n this._update(seed);\n this._reseed = 1;\n this.reseedInterval = 0x1000000000000; // 2^48\n};\n\nHmacDRBG.prototype._hmac = function hmac() {\n return new hash.hmac(this.hash, this.K);\n};\n\nHmacDRBG.prototype._update = function update(seed) {\n var kmac = this._hmac()\n .update(this.V)\n .update([ 0x00 ]);\n if (seed)\n kmac = kmac.update(seed);\n this.K = kmac.digest();\n this.V = this._hmac().update(this.V).digest();\n if (!seed)\n return;\n\n this.K = this._hmac()\n .update(this.V)\n .update([ 0x01 ])\n .update(seed)\n .digest();\n this.V = this._hmac().update(this.V).digest();\n};\n\nHmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {\n // Optional entropy enc\n if (typeof entropyEnc !== 'string') {\n addEnc = add;\n add = entropyEnc;\n entropyEnc = null;\n }\n\n entropy = utils.toArray(entropy, entropyEnc);\n add = utils.toArray(add, addEnc);\n\n assert(entropy.length >= (this.minEntropy / 8),\n 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');\n\n this._update(entropy.concat(add || []));\n this._reseed = 1;\n};\n\nHmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {\n if (this._reseed > this.reseedInterval)\n throw new Error('Reseed is required');\n\n // Optional encoding\n if (typeof enc !== 'string') {\n addEnc = add;\n add = enc;\n enc = null;\n }\n\n // Optional additional data\n if (add) {\n add = utils.toArray(add, addEnc || 'hex');\n this._update(add);\n }\n\n var temp = [];\n while (temp.length < len) {\n this.V = this._hmac().update(this.V).digest();\n temp = temp.concat(this.V);\n }\n\n var res = temp.slice(0, len);\n this._update(add);\n this._reseed++;\n return utils.encode(res, enc);\n};\n", - "/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n", - "if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n", - "'use strict';\n\nvar hasToStringTag = require('has-tostringtag/shams')();\nvar callBound = require('call-bind/callBound');\n\nvar $toString = callBound('Object.prototype.toString');\n\nvar isStandardArguments = function isArguments(value) {\n\tif (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) {\n\t\treturn false;\n\t}\n\treturn $toString(value) === '[object Arguments]';\n};\n\nvar isLegacyArguments = function isArguments(value) {\n\tif (isStandardArguments(value)) {\n\t\treturn true;\n\t}\n\treturn value !== null &&\n\t\ttypeof value === 'object' &&\n\t\ttypeof value.length === 'number' &&\n\t\tvalue.length >= 0 &&\n\t\t$toString(value) !== '[object Array]' &&\n\t\t$toString(value.callee) === '[object Function]';\n};\n\nvar supportsStandardArguments = (function () {\n\treturn isStandardArguments(arguments);\n}());\n\nisStandardArguments.isLegacyArguments = isLegacyArguments; // for tests\n\nmodule.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments;\n", - "'use strict';\n\nvar fnToStr = Function.prototype.toString;\nvar reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply;\nvar badArrayLike;\nvar isCallableMarker;\nif (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') {\n\ttry {\n\t\tbadArrayLike = Object.defineProperty({}, 'length', {\n\t\t\tget: function () {\n\t\t\t\tthrow isCallableMarker;\n\t\t\t}\n\t\t});\n\t\tisCallableMarker = {};\n\t\t// eslint-disable-next-line no-throw-literal\n\t\treflectApply(function () { throw 42; }, null, badArrayLike);\n\t} catch (_) {\n\t\tif (_ !== isCallableMarker) {\n\t\t\treflectApply = null;\n\t\t}\n\t}\n} else {\n\treflectApply = null;\n}\n\nvar constructorRegex = /^\\s*class\\b/;\nvar isES6ClassFn = function isES6ClassFunction(value) {\n\ttry {\n\t\tvar fnStr = fnToStr.call(value);\n\t\treturn constructorRegex.test(fnStr);\n\t} catch (e) {\n\t\treturn false; // not a function\n\t}\n};\n\nvar tryFunctionObject = function tryFunctionToStr(value) {\n\ttry {\n\t\tif (isES6ClassFn(value)) { return false; }\n\t\tfnToStr.call(value);\n\t\treturn true;\n\t} catch (e) {\n\t\treturn false;\n\t}\n};\nvar toStr = Object.prototype.toString;\nvar objectClass = '[object Object]';\nvar fnClass = '[object Function]';\nvar genClass = '[object GeneratorFunction]';\nvar ddaClass = '[object HTMLAllCollection]'; // IE 11\nvar ddaClass2 = '[object HTML document.all class]';\nvar ddaClass3 = '[object HTMLCollection]'; // IE 9-10\nvar hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag`\n\nvar isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing\n\nvar isDDA = function isDocumentDotAll() { return false; };\nif (typeof document === 'object') {\n\t// Firefox 3 canonicalizes DDA to undefined when it's not accessed directly\n\tvar all = document.all;\n\tif (toStr.call(all) === toStr.call(document.all)) {\n\t\tisDDA = function isDocumentDotAll(value) {\n\t\t\t/* globals document: false */\n\t\t\t// in IE 6-8, typeof document.all is \"object\" and it's truthy\n\t\t\tif ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) {\n\t\t\t\ttry {\n\t\t\t\t\tvar str = toStr.call(value);\n\t\t\t\t\treturn (\n\t\t\t\t\t\tstr === ddaClass\n\t\t\t\t\t\t|| str === ddaClass2\n\t\t\t\t\t\t|| str === ddaClass3 // opera 12.16\n\t\t\t\t\t\t|| str === objectClass // IE 6-8\n\t\t\t\t\t) && value('') == null; // eslint-disable-line eqeqeq\n\t\t\t\t} catch (e) { /**/ }\n\t\t\t}\n\t\t\treturn false;\n\t\t};\n\t}\n}\n\nmodule.exports = reflectApply\n\t? function isCallable(value) {\n\t\tif (isDDA(value)) { return true; }\n\t\tif (!value) { return false; }\n\t\tif (typeof value !== 'function' && typeof value !== 'object') { return false; }\n\t\ttry {\n\t\t\treflectApply(value, null, badArrayLike);\n\t\t} catch (e) {\n\t\t\tif (e !== isCallableMarker) { return false; }\n\t\t}\n\t\treturn !isES6ClassFn(value) && tryFunctionObject(value);\n\t}\n\t: function isCallable(value) {\n\t\tif (isDDA(value)) { return true; }\n\t\tif (!value) { return false; }\n\t\tif (typeof value !== 'function' && typeof value !== 'object') { return false; }\n\t\tif (hasToStringTag) { return tryFunctionObject(value); }\n\t\tif (isES6ClassFn(value)) { return false; }\n\t\tvar strClass = toStr.call(value);\n\t\tif (strClass !== fnClass && strClass !== genClass && !(/^\\[object HTML/).test(strClass)) { return false; }\n\t\treturn tryFunctionObject(value);\n\t};\n", - "'use strict';\n\nvar toStr = Object.prototype.toString;\nvar fnToStr = Function.prototype.toString;\nvar isFnRegex = /^\\s*(?:function)?\\*/;\nvar hasToStringTag = require('has-tostringtag/shams')();\nvar getProto = Object.getPrototypeOf;\nvar getGeneratorFunc = function () { // eslint-disable-line consistent-return\n\tif (!hasToStringTag) {\n\t\treturn false;\n\t}\n\ttry {\n\t\treturn Function('return function*() {}')();\n\t} catch (e) {\n\t}\n};\nvar GeneratorFunction;\n\nmodule.exports = function isGeneratorFunction(fn) {\n\tif (typeof fn !== 'function') {\n\t\treturn false;\n\t}\n\tif (isFnRegex.test(fnToStr.call(fn))) {\n\t\treturn true;\n\t}\n\tif (!hasToStringTag) {\n\t\tvar str = toStr.call(fn);\n\t\treturn str === '[object GeneratorFunction]';\n\t}\n\tif (!getProto) {\n\t\treturn false;\n\t}\n\tif (typeof GeneratorFunction === 'undefined') {\n\t\tvar generatorFunc = getGeneratorFunc();\n\t\tGeneratorFunction = generatorFunc ? getProto(generatorFunc) : false;\n\t}\n\treturn getProto(fn) === GeneratorFunction;\n};\n", - "'use strict';\n\nvar forEach = require('for-each');\nvar availableTypedArrays = require('available-typed-arrays');\nvar callBound = require('call-bind/callBound');\n\nvar $toString = callBound('Object.prototype.toString');\nvar hasToStringTag = require('has-tostringtag/shams')();\nvar gOPD = require('gopd');\n\nvar g = typeof globalThis === 'undefined' ? global : globalThis;\nvar typedArrays = availableTypedArrays();\n\nvar $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) {\n\tfor (var i = 0; i < array.length; i += 1) {\n\t\tif (array[i] === value) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n};\nvar $slice = callBound('String.prototype.slice');\nvar toStrTags = {};\nvar getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');\nif (hasToStringTag && gOPD && getPrototypeOf) {\n\tforEach(typedArrays, function (typedArray) {\n\t\tvar arr = new g[typedArray]();\n\t\tif (Symbol.toStringTag in arr) {\n\t\t\tvar proto = getPrototypeOf(arr);\n\t\t\tvar descriptor = gOPD(proto, Symbol.toStringTag);\n\t\t\tif (!descriptor) {\n\t\t\t\tvar superProto = getPrototypeOf(proto);\n\t\t\t\tdescriptor = gOPD(superProto, Symbol.toStringTag);\n\t\t\t}\n\t\t\ttoStrTags[typedArray] = descriptor.get;\n\t\t}\n\t});\n}\n\nvar tryTypedArrays = function tryAllTypedArrays(value) {\n\tvar anyTrue = false;\n\tforEach(toStrTags, function (getter, typedArray) {\n\t\tif (!anyTrue) {\n\t\t\ttry {\n\t\t\t\tanyTrue = getter.call(value) === typedArray;\n\t\t\t} catch (e) { /**/ }\n\t\t}\n\t});\n\treturn anyTrue;\n};\n\nmodule.exports = function isTypedArray(value) {\n\tif (!value || typeof value !== 'object') { return false; }\n\tif (!hasToStringTag || !(Symbol.toStringTag in value)) {\n\t\tvar tag = $slice($toString(value), 8, -1);\n\t\treturn $indexOf(typedArrays, tag) > -1;\n\t}\n\tif (!gOPD) { return false; }\n\treturn tryTypedArrays(value);\n};\n", - "/*\n* loglevel - https://github.com/pimterry/loglevel\n*\n* Copyright (c) 2013 Tim Perry\n* Licensed under the MIT license.\n*/\n(function (root, definition) {\n \"use strict\";\n if (typeof define === 'function' && define.amd) {\n define(definition);\n } else if (typeof module === 'object' && module.exports) {\n module.exports = definition();\n } else {\n root.log = definition();\n }\n}(this, function () {\n \"use strict\";\n\n // Slightly dubious tricks to cut down minimized file size\n var noop = function() {};\n var undefinedType = \"undefined\";\n var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && (\n /Trident\\/|MSIE /.test(window.navigator.userAgent)\n );\n\n var logMethods = [\n \"trace\",\n \"debug\",\n \"info\",\n \"warn\",\n \"error\"\n ];\n\n // Cross-browser bind equivalent that works at least back to IE6\n function bindMethod(obj, methodName) {\n var method = obj[methodName];\n if (typeof method.bind === 'function') {\n return method.bind(obj);\n } else {\n try {\n return Function.prototype.bind.call(method, obj);\n } catch (e) {\n // Missing bind shim or IE8 + Modernizr, fallback to wrapping\n return function() {\n return Function.prototype.apply.apply(method, [obj, arguments]);\n };\n }\n }\n }\n\n // Trace() doesn't print the message in IE, so for that case we need to wrap it\n function traceForIE() {\n if (console.log) {\n if (console.log.apply) {\n console.log.apply(console, arguments);\n } else {\n // In old IE, native console methods themselves don't have apply().\n Function.prototype.apply.apply(console.log, [console, arguments]);\n }\n }\n if (console.trace) console.trace();\n }\n\n // Build the best logging method possible for this env\n // Wherever possible we want to bind, not wrap, to preserve stack traces\n function realMethod(methodName) {\n if (methodName === 'debug') {\n methodName = 'log';\n }\n\n if (typeof console === undefinedType) {\n return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives\n } else if (methodName === 'trace' && isIE) {\n return traceForIE;\n } else if (console[methodName] !== undefined) {\n return bindMethod(console, methodName);\n } else if (console.log !== undefined) {\n return bindMethod(console, 'log');\n } else {\n return noop;\n }\n }\n\n // These private functions always need `this` to be set properly\n\n function replaceLoggingMethods(level, loggerName) {\n /*jshint validthis:true */\n for (var i = 0; i < logMethods.length; i++) {\n var methodName = logMethods[i];\n this[methodName] = (i < level) ?\n noop :\n this.methodFactory(methodName, level, loggerName);\n }\n\n // Define log.log as an alias for log.debug\n this.log = this.debug;\n }\n\n // In old IE versions, the console isn't present until you first open it.\n // We build realMethod() replacements here that regenerate logging methods\n function enableLoggingWhenConsoleArrives(methodName, level, loggerName) {\n return function () {\n if (typeof console !== undefinedType) {\n replaceLoggingMethods.call(this, level, loggerName);\n this[methodName].apply(this, arguments);\n }\n };\n }\n\n // By default, we use closely bound real methods wherever possible, and\n // otherwise we wait for a console to appear, and then try again.\n function defaultMethodFactory(methodName, level, loggerName) {\n /*jshint validthis:true */\n return realMethod(methodName) ||\n enableLoggingWhenConsoleArrives.apply(this, arguments);\n }\n\n function Logger(name, defaultLevel, factory) {\n var self = this;\n var currentLevel;\n defaultLevel = defaultLevel == null ? \"WARN\" : defaultLevel;\n\n var storageKey = \"loglevel\";\n if (typeof name === \"string\") {\n storageKey += \":\" + name;\n } else if (typeof name === \"symbol\") {\n storageKey = undefined;\n }\n\n function persistLevelIfPossible(levelNum) {\n var levelName = (logMethods[levelNum] || 'silent').toUpperCase();\n\n if (typeof window === undefinedType || !storageKey) return;\n\n // Use localStorage if available\n try {\n window.localStorage[storageKey] = levelName;\n return;\n } catch (ignore) {}\n\n // Use session cookie as fallback\n try {\n window.document.cookie =\n encodeURIComponent(storageKey) + \"=\" + levelName + \";\";\n } catch (ignore) {}\n }\n\n function getPersistedLevel() {\n var storedLevel;\n\n if (typeof window === undefinedType || !storageKey) return;\n\n try {\n storedLevel = window.localStorage[storageKey];\n } catch (ignore) {}\n\n // Fallback to cookies if local storage gives us nothing\n if (typeof storedLevel === undefinedType) {\n try {\n var cookie = window.document.cookie;\n var location = cookie.indexOf(\n encodeURIComponent(storageKey) + \"=\");\n if (location !== -1) {\n storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1];\n }\n } catch (ignore) {}\n }\n\n // If the stored level is not valid, treat it as if nothing was stored.\n if (self.levels[storedLevel] === undefined) {\n storedLevel = undefined;\n }\n\n return storedLevel;\n }\n\n function clearPersistedLevel() {\n if (typeof window === undefinedType || !storageKey) return;\n\n // Use localStorage if available\n try {\n window.localStorage.removeItem(storageKey);\n return;\n } catch (ignore) {}\n\n // Use session cookie as fallback\n try {\n window.document.cookie =\n encodeURIComponent(storageKey) + \"=; expires=Thu, 01 Jan 1970 00:00:00 UTC\";\n } catch (ignore) {}\n }\n\n /*\n *\n * Public logger API - see https://github.com/pimterry/loglevel for details\n *\n */\n\n self.name = name;\n\n self.levels = { \"TRACE\": 0, \"DEBUG\": 1, \"INFO\": 2, \"WARN\": 3,\n \"ERROR\": 4, \"SILENT\": 5};\n\n self.methodFactory = factory || defaultMethodFactory;\n\n self.getLevel = function () {\n return currentLevel;\n };\n\n self.setLevel = function (level, persist) {\n if (typeof level === \"string\" && self.levels[level.toUpperCase()] !== undefined) {\n level = self.levels[level.toUpperCase()];\n }\n if (typeof level === \"number\" && level >= 0 && level <= self.levels.SILENT) {\n currentLevel = level;\n if (persist !== false) { // defaults to true\n persistLevelIfPossible(level);\n }\n replaceLoggingMethods.call(self, level, name);\n if (typeof console === undefinedType && level < self.levels.SILENT) {\n return \"No console available for logging\";\n }\n } else {\n throw \"log.setLevel() called with invalid level: \" + level;\n }\n };\n\n self.setDefaultLevel = function (level) {\n defaultLevel = level;\n if (!getPersistedLevel()) {\n self.setLevel(level, false);\n }\n };\n\n self.resetLevel = function () {\n self.setLevel(defaultLevel, false);\n clearPersistedLevel();\n };\n\n self.enableAll = function(persist) {\n self.setLevel(self.levels.TRACE, persist);\n };\n\n self.disableAll = function(persist) {\n self.setLevel(self.levels.SILENT, persist);\n };\n\n // Initialize with the right level\n var initialLevel = getPersistedLevel();\n if (initialLevel == null) {\n initialLevel = defaultLevel;\n }\n self.setLevel(initialLevel, false);\n }\n\n /*\n *\n * Top-level API\n *\n */\n\n var defaultLogger = new Logger();\n\n var _loggersByName = {};\n defaultLogger.getLogger = function getLogger(name) {\n if ((typeof name !== \"symbol\" && typeof name !== \"string\") || name === \"\") {\n throw new TypeError(\"You must supply a name when creating a logger.\");\n }\n\n var logger = _loggersByName[name];\n if (!logger) {\n logger = _loggersByName[name] = new Logger(\n name, defaultLogger.getLevel(), defaultLogger.methodFactory);\n }\n return logger;\n };\n\n // Grab the current global log variable in case of overwrite\n var _log = (typeof window !== undefinedType) ? window.log : undefined;\n defaultLogger.noConflict = function() {\n if (typeof window !== undefinedType &&\n window.log === defaultLogger) {\n window.log = _log;\n }\n\n return defaultLogger;\n };\n\n defaultLogger.getLoggers = function getLoggers() {\n return _loggersByName;\n };\n\n // ES6 default export, for compatibility\n defaultLogger['default'] = defaultLogger;\n\n return defaultLogger;\n}));\n", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.ExtensibleEvents = void 0;\n\nvar _NamespacedMap = require(\"./NamespacedMap\");\n\nvar _InvalidEventError = require(\"./InvalidEventError\");\n\nvar _MRoomMessage = require(\"./interpreters/legacy/MRoomMessage\");\n\nvar _MMessage = require(\"./interpreters/modern/MMessage\");\n\nvar _message_types = require(\"./events/message_types\");\n\nvar _poll_types = require(\"./events/poll_types\");\n\nvar _MPoll = require(\"./interpreters/modern/MPoll\");\n\nfunction _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; } } }; }\n\nfunction _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); }\n\nfunction _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; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n/**\n * Utility class for parsing and identifying event types in a renderable form. An\n * instance of this class can be created to change rendering preference depending\n * on use-case.\n */\nvar ExtensibleEvents = /*#__PURE__*/function () {\n function ExtensibleEvents() {\n _classCallCheck(this, ExtensibleEvents);\n\n _defineProperty(this, \"interpreters\", new _NamespacedMap.NamespacedMap([// Remember to add your unit test when adding to this! (\"known events\" test description)\n [_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]]));\n\n _defineProperty(this, \"_unknownInterpretOrder\", [_message_types.M_MESSAGE]);\n }\n /**\n * Gets the default instance for all extensible event parsing.\n */\n\n\n _createClass(ExtensibleEvents, [{\n key: \"unknownInterpretOrder\",\n get:\n /**\n * Gets the order the internal processor will use for unknown primary\n * event types.\n */\n function get() {\n var _this$_unknownInterpr;\n\n return (_this$_unknownInterpr = this._unknownInterpretOrder) !== null && _this$_unknownInterpr !== void 0 ? _this$_unknownInterpr : [];\n }\n /**\n * Sets the order the internal processor will use for unknown primary\n * event types.\n * @param {NamespacedValue[]} val The parsing order.\n */\n ,\n set: function set(val) {\n this._unknownInterpretOrder = val;\n }\n /**\n * Gets the order the internal processor will use for unknown primary\n * event types.\n */\n\n }, {\n key: \"registerInterpreter\",\n value:\n /**\n * Registers a primary event type interpreter. Note that the interpreter might be\n * called with non-primary events if the event is being parsed as a fallback.\n * @param {NamespacedValue} wireEventType The event type.\n * @param {EventInterpreter} interpreter The interpreter.\n */\n function registerInterpreter(wireEventType, interpreter) {\n this.interpreters.set(wireEventType, interpreter);\n }\n /**\n * Registers a primary event type interpreter. Note that the interpreter might be\n * called with non-primary events if the event is being parsed as a fallback.\n * @param {NamespacedValue} wireEventType The event type.\n * @param {EventInterpreter} interpreter The interpreter.\n */\n\n }, {\n key: \"parse\",\n value:\n /**\n * Parses an event, trying the primary event type first. If the primary type is not known\n * then the content will be inspected to find the most suitable fallback.\n *\n * If the parsing failed or was a completely unknown type, this will return falsy.\n * @param {IPartialEvent} wireFormat The event to parse.\n * @returns {Optional} The parsed extensible event.\n */\n function parse(wireFormat) {\n try {\n if (this.interpreters.hasNamespaced(wireFormat.type)) {\n return this.interpreters.getNamespaced(wireFormat.type)(wireFormat);\n }\n\n var _iterator = _createForOfIteratorHelper(this.unknownInterpretOrder),\n _step;\n\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var tryType = _step.value;\n\n if (this.interpreters.has(tryType)) {\n var val = this.interpreters.get(tryType)(wireFormat);\n if (val) return val;\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n\n return null; // cannot be parsed\n } catch (e) {\n if (e instanceof _InvalidEventError.InvalidEventError) {\n return null; // fail parsing and move on\n }\n\n throw e; // re-throw everything else\n }\n }\n /**\n * Parses an event, trying the primary event type first. If the primary type is not known\n * then the content will be inspected to find the most suitable fallback.\n *\n * If the parsing failed or was a completely unknown type, this will return falsy.\n * @param {IPartialEvent} wireFormat The event to parse.\n * @returns {Optional} The parsed extensible event.\n */\n\n }], [{\n key: \"defaultInstance\",\n get: function get() {\n return ExtensibleEvents._defaultInstance;\n }\n }, {\n key: \"unknownInterpretOrder\",\n get: function get() {\n return ExtensibleEvents.defaultInstance.unknownInterpretOrder;\n }\n /**\n * Sets the order the internal processor will use for unknown primary\n * event types.\n * @param {NamespacedValue[]} val The parsing order.\n */\n ,\n set: function set(val) {\n ExtensibleEvents.defaultInstance.unknownInterpretOrder = val;\n }\n }, {\n key: \"registerInterpreter\",\n value: function registerInterpreter(wireEventType, interpreter) {\n ExtensibleEvents.defaultInstance.registerInterpreter(wireEventType, interpreter);\n }\n }, {\n key: \"parse\",\n value: function parse(wireFormat) {\n return ExtensibleEvents.defaultInstance.parse(wireFormat);\n }\n }]);\n\n return ExtensibleEvents;\n}();\n\nexports.ExtensibleEvents = ExtensibleEvents;\n\n_defineProperty(ExtensibleEvents, \"_defaultInstance\", new ExtensibleEvents());", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});", - "\"use strict\";\n\nfunction _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); }\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.InvalidEventError = void 0;\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); }\n\nfunction _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); }; }\n\nfunction _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); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _wrapNativeSuper(Class) { var _cache = typeof Map === \"function\" ? new Map() : undefined; _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); }\n\nfunction _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 Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }\n\nfunction _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; } }\n\nfunction _isNativeFunction(fn) { return Function.toString.call(fn).indexOf(\"[native code]\") !== -1; }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Thrown when an event is unforgivably unparsable.\n */\nvar InvalidEventError = /*#__PURE__*/function (_Error) {\n _inherits(InvalidEventError, _Error);\n\n var _super = _createSuper(InvalidEventError);\n\n function InvalidEventError(message) {\n _classCallCheck(this, InvalidEventError);\n\n return _super.call(this, message);\n }\n\n return _createClass(InvalidEventError);\n}( /*#__PURE__*/_wrapNativeSuper(Error));\n\nexports.InvalidEventError = InvalidEventError;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.NamespacedMap = void 0;\n\nfunction _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; } } }; }\n\nfunction _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); }\n\nfunction _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; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n/**\n * A `Map` implementation which accepts a NamespacedValue as a key, and arbitrary value. The\n * namespaced value must be a string type.\n */\nvar NamespacedMap = /*#__PURE__*/function () {\n // protected to make tests happy for access\n\n /**\n * Creates a new map with optional seed data.\n * @param {Array<[NS, V]>} initial The seed data.\n */\n function NamespacedMap(initial) {\n _classCallCheck(this, NamespacedMap);\n\n _defineProperty(this, \"internalMap\", new Map());\n\n if (initial) {\n var _iterator = _createForOfIteratorHelper(initial),\n _step;\n\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var val = _step.value;\n this.set(val[0], val[1]);\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n }\n }\n /**\n * Gets a value from the map. If the value does not exist under\n * either namespace option, falsy is returned.\n * @param {NS} key The key.\n * @returns {Optional} The value, or falsy.\n */\n\n\n _createClass(NamespacedMap, [{\n key: \"get\",\n value: function get(key) {\n if (key.name && this.internalMap.has(key.name)) {\n return this.internalMap.get(key.name);\n }\n\n if (key.altName && this.internalMap.has(key.altName)) {\n return this.internalMap.get(key.altName);\n }\n\n return null;\n }\n /**\n * Sets a value in the map.\n * @param {NS} key The key.\n * @param {V} val The value.\n */\n\n }, {\n key: \"set\",\n value: function set(key, val) {\n if (key.name) {\n this.internalMap.set(key.name, val);\n }\n\n if (key.altName) {\n this.internalMap.set(key.altName, val);\n }\n }\n /**\n * Determines if any of the valid namespaced values are present\n * in the map.\n * @param {NS} key The key.\n * @returns {boolean} True if present.\n */\n\n }, {\n key: \"has\",\n value: function has(key) {\n return !!this.get(key);\n }\n /**\n * Removes all the namespaced values from the map.\n * @param {NS} key The key.\n */\n\n }, {\n key: \"delete\",\n value: function _delete(key) {\n if (key.name) {\n this.internalMap[\"delete\"](key.name);\n }\n\n if (key.altName) {\n this.internalMap[\"delete\"](key.altName);\n }\n }\n /**\n * Determines if the map contains a specific namespaced value\n * instead of the parent NS type.\n * @param {string} key The key.\n * @returns {boolean} True if present.\n */\n\n }, {\n key: \"hasNamespaced\",\n value: function hasNamespaced(key) {\n return this.internalMap.has(key);\n }\n /**\n * Gets a specific namespaced value from the map instead of the\n * parent NS type. Returns falsy if not found.\n * @param {string} key The key.\n * @returns {Optional} The value, or falsy.\n */\n\n }, {\n key: \"getNamespaced\",\n value: function getNamespaced(key) {\n return this.internalMap.get(key);\n }\n }]);\n\n return NamespacedMap;\n}();\n\nexports.NamespacedMap = NamespacedMap;", - "\"use strict\";\n\nfunction _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); }\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.UnstableValue = exports.NamespacedValue = void 0;\n\nfunction _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); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _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); }; }\n\nfunction _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); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _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; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\n/*\nCopyright 2021 - 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Represents a simple Matrix namespaced value. This will assume that if a stable prefix\n * is provided that the stable prefix should be used when representing the identifier.\n */\nvar NamespacedValue = /*#__PURE__*/function () {\n // Stable is optional, but one of the two parameters is required, hence the weird-looking types.\n // Goal is to have developers explicitly say there is no stable value (if applicable).\n function NamespacedValue(stable, unstable) {\n _classCallCheck(this, NamespacedValue);\n\n this.stable = stable;\n this.unstable = unstable;\n\n if (!this.unstable && !this.stable) {\n throw new Error(\"One of stable or unstable values must be supplied\");\n }\n }\n\n _createClass(NamespacedValue, [{\n key: \"name\",\n get: function get() {\n if (this.stable) {\n return this.stable;\n }\n\n return this.unstable;\n }\n }, {\n key: \"altName\",\n get: function get() {\n if (!this.stable) {\n return null;\n }\n\n return this.unstable;\n }\n }, {\n key: \"matches\",\n value: function matches(val) {\n return !!this.name && this.name === val || !!this.altName && this.altName === val;\n } // this desperately wants https://github.com/microsoft/TypeScript/pull/26349 at the top level of the class\n // so we can instantiate `NamespacedValue` as a default type for that namespace.\n\n }, {\n key: \"findIn\",\n value: function findIn(obj) {\n var val;\n\n if (this.name) {\n val = obj === null || obj === void 0 ? void 0 : obj[this.name];\n }\n\n if (!val && this.altName) {\n val = obj === null || obj === void 0 ? void 0 : obj[this.altName];\n }\n\n return val;\n }\n }, {\n key: \"includedIn\",\n value: function includedIn(arr) {\n var included = false;\n\n if (this.name) {\n included = arr.includes(this.name);\n }\n\n if (!included && this.altName) {\n included = arr.includes(this.altName);\n }\n\n return included;\n }\n }]);\n\n return NamespacedValue;\n}();\n/**\n * Represents a namespaced value which prioritizes the unstable value over the stable\n * value.\n */\n\n\nexports.NamespacedValue = NamespacedValue;\n\nvar UnstableValue = /*#__PURE__*/function (_NamespacedValue) {\n _inherits(UnstableValue, _NamespacedValue);\n\n var _super = _createSuper(UnstableValue);\n\n // Note: Constructor difference is that `unstable` is *required*.\n function UnstableValue(stable, unstable) {\n var _this;\n\n _classCallCheck(this, UnstableValue);\n\n _this = _super.call(this, stable, unstable);\n\n if (!_this.unstable) {\n throw new Error(\"Unstable value must be supplied\");\n }\n\n return _this;\n }\n\n _createClass(UnstableValue, [{\n key: \"name\",\n get: function get() {\n return this.unstable;\n }\n }, {\n key: \"altName\",\n get: function get() {\n return this.stable;\n }\n }]);\n\n return UnstableValue;\n}(NamespacedValue);\n\nexports.UnstableValue = UnstableValue;", - "\"use strict\";\n\nfunction _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); }\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.EmoteEvent = void 0;\n\nvar _MessageEvent2 = require(\"./MessageEvent\");\n\nvar _message_types = require(\"./message_types\");\n\nvar _events = require(\"../utility/events\");\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _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); }\n\nfunction _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }\n\nfunction _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); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _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); }; }\n\nfunction _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); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _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; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n// Emote events are just decorated message events\n\n/**\n * Represents an emote. This is essentially a MessageEvent with\n * emote characteristics considered.\n */\nvar EmoteEvent = /*#__PURE__*/function (_MessageEvent) {\n _inherits(EmoteEvent, _MessageEvent);\n\n var _super = _createSuper(EmoteEvent);\n\n function EmoteEvent(wireFormat) {\n _classCallCheck(this, EmoteEvent);\n\n return _super.call(this, wireFormat);\n }\n\n _createClass(EmoteEvent, [{\n key: \"isEmote\",\n get: function get() {\n return true; // override\n }\n }, {\n key: \"isEquivalentTo\",\n value: function isEquivalentTo(primaryEventType) {\n return (0, _events.isEventTypeSame)(primaryEventType, _message_types.M_EMOTE) || _get(_getPrototypeOf(EmoteEvent.prototype), \"isEquivalentTo\", this).call(this, primaryEventType);\n }\n }, {\n key: \"serialize\",\n value: function serialize() {\n var message = _get(_getPrototypeOf(EmoteEvent.prototype), \"serialize\", this).call(this);\n\n message.content['msgtype'] = \"m.emote\";\n return message;\n }\n /**\n * Creates a new EmoteEvent from text and HTML.\n * @param {string} text The text.\n * @param {string} html Optional HTML.\n * @returns {MessageEvent} The representative message event.\n */\n\n }], [{\n key: \"from\",\n value: function from(text, html) {\n var _content;\n\n return new EmoteEvent({\n type: _message_types.M_EMOTE.name,\n content: (_content = {}, _defineProperty(_content, _message_types.M_TEXT.name, text), _defineProperty(_content, _message_types.M_HTML.name, html), _content)\n });\n }\n }]);\n\n return EmoteEvent;\n}(_MessageEvent2.MessageEvent);\n\nexports.EmoteEvent = EmoteEvent;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.ExtensibleEvent = void 0;\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\n/*\nCopyright 2021 - 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Represents an Extensible Event in Matrix.\n */\nvar ExtensibleEvent = /*#__PURE__*/function () {\n function ExtensibleEvent(wireFormat) {\n _classCallCheck(this, ExtensibleEvent);\n\n this.wireFormat = wireFormat;\n }\n /**\n * Shortcut to wireFormat.content\n */\n\n\n _createClass(ExtensibleEvent, [{\n key: \"wireContent\",\n get: function get() {\n return this.wireFormat.content;\n }\n /**\n * Serializes the event into a format which can be used to send the\n * event to the room.\n * @returns {IPartialEvent} The serialized event.\n */\n\n }]);\n\n return ExtensibleEvent;\n}();\n\nexports.ExtensibleEvent = ExtensibleEvent;", - "\"use strict\";\n\nfunction _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); }\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.MessageEvent = void 0;\n\nvar _ExtensibleEvent2 = require(\"./ExtensibleEvent\");\n\nvar _types = require(\"../types\");\n\nvar _InvalidEventError = require(\"../InvalidEventError\");\n\nvar _message_types = require(\"./message_types\");\n\nvar _events = require(\"../utility/events\");\n\nfunction 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; }\n\nfunction _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; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _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); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _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); }; }\n\nfunction _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); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _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; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n/**\n * Represents a message event. Message events are the simplest form of event with\n * just text (optionally of different mimetypes, like HTML).\n *\n * Message events can additionally be an Emote or Notice, though typically those\n * are represented as EmoteEvent and NoticeEvent respectively.\n */\nvar MessageEvent = /*#__PURE__*/function (_ExtensibleEvent) {\n _inherits(MessageEvent, _ExtensibleEvent);\n\n var _super = _createSuper(MessageEvent);\n\n /**\n * The default text for the event.\n */\n\n /**\n * The default HTML for the event, if provided.\n */\n\n /**\n * All the different renderings of the message. Note that this is the same\n * format as an m.message body but may contain elements not found directly\n * in the event content: this is because this is interpreted based off the\n * other information available in the event.\n */\n\n /**\n * Creates a new MessageEvent from a pure format. Note that the event is\n * *not* parsed here: it will be treated as a literal m.message primary\n * typed event.\n * @param {IPartialEvent} wireFormat The event.\n */\n function MessageEvent(wireFormat) {\n var _this;\n\n _classCallCheck(this, MessageEvent);\n\n _this = _super.call(this, wireFormat);\n\n _defineProperty(_assertThisInitialized(_this), \"text\", void 0);\n\n _defineProperty(_assertThisInitialized(_this), \"html\", void 0);\n\n _defineProperty(_assertThisInitialized(_this), \"renderings\", void 0);\n\n var mmessage = _message_types.M_MESSAGE.findIn(_this.wireContent);\n\n var mtext = _message_types.M_TEXT.findIn(_this.wireContent);\n\n var mhtml = _message_types.M_HTML.findIn(_this.wireContent);\n\n if ((0, _types.isProvided)(mmessage)) {\n if (!Array.isArray(mmessage)) {\n throw new _InvalidEventError.InvalidEventError(\"m.message contents must be an array\");\n }\n\n var text = mmessage.find(function (r) {\n return !(0, _types.isProvided)(r.mimetype) || r.mimetype === \"text/plain\";\n });\n var html = mmessage.find(function (r) {\n return r.mimetype === \"text/html\";\n });\n if (!text) throw new _InvalidEventError.InvalidEventError(\"m.message is missing a plain text representation\");\n _this.text = text.body;\n _this.html = html === null || html === void 0 ? void 0 : html.body;\n _this.renderings = mmessage;\n } else if ((0, _types.isOptionalAString)(mtext)) {\n _this.text = mtext;\n _this.html = mhtml;\n _this.renderings = [{\n body: mtext,\n mimetype: \"text/plain\"\n }];\n\n if (_this.html) {\n _this.renderings.push({\n body: _this.html,\n mimetype: \"text/html\"\n });\n }\n } else {\n throw new _InvalidEventError.InvalidEventError(\"Missing textual representation for event\");\n }\n\n return _this;\n }\n /**\n * Gets whether this message is considered an \"emote\". Note that a message\n * might be an emote and notice at the same time: while technically possible,\n * the event should be interpreted as one or the other.\n */\n\n\n _createClass(MessageEvent, [{\n key: \"isEmote\",\n get: function get() {\n return _message_types.M_EMOTE.matches(this.wireFormat.type) || (0, _types.isProvided)(_message_types.M_EMOTE.findIn(this.wireFormat.content));\n }\n /**\n * Gets whether this message is considered a \"notice\". Note that a message\n * might be an emote and notice at the same time: while technically possible,\n * the event should be interpreted as one or the other.\n */\n\n }, {\n key: \"isNotice\",\n get: function get() {\n return _message_types.M_NOTICE.matches(this.wireFormat.type) || (0, _types.isProvided)(_message_types.M_NOTICE.findIn(this.wireFormat.content));\n }\n }, {\n key: \"isEquivalentTo\",\n value: function isEquivalentTo(primaryEventType) {\n return (0, _events.isEventTypeSame)(primaryEventType, _message_types.M_MESSAGE);\n }\n }, {\n key: \"serializeMMessageOnly\",\n value: function serializeMMessageOnly() {\n var messageRendering = _defineProperty({}, _message_types.M_MESSAGE.name, this.renderings); // Use the shorthand if it's just a simple text event\n\n\n if (this.renderings.length === 1) {\n var mime = this.renderings[0].mimetype;\n\n if (mime === undefined || mime === \"text/plain\") {\n messageRendering = _defineProperty({}, _message_types.M_TEXT.name, this.renderings[0].body);\n }\n }\n\n return messageRendering;\n }\n }, {\n key: \"serialize\",\n value: function serialize() {\n var _this$html;\n\n return {\n type: \"m.room.message\",\n content: _objectSpread(_objectSpread({}, this.serializeMMessageOnly()), {}, {\n body: this.text,\n msgtype: \"m.text\",\n format: this.html ? \"org.matrix.custom.html\" : undefined,\n formatted_body: (_this$html = this.html) !== null && _this$html !== void 0 ? _this$html : undefined\n })\n };\n }\n /**\n * Creates a new MessageEvent from text and HTML.\n * @param {string} text The text.\n * @param {string} html Optional HTML.\n * @returns {MessageEvent} The representative message event.\n */\n\n }], [{\n key: \"from\",\n value: function from(text, html) {\n var _content;\n\n return new MessageEvent({\n type: _message_types.M_MESSAGE.name,\n content: (_content = {}, _defineProperty(_content, _message_types.M_TEXT.name, text), _defineProperty(_content, _message_types.M_HTML.name, html), _content)\n });\n }\n }]);\n\n return MessageEvent;\n}(_ExtensibleEvent2.ExtensibleEvent);\n\nexports.MessageEvent = MessageEvent;", - "\"use strict\";\n\nfunction _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); }\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.NoticeEvent = void 0;\n\nvar _MessageEvent2 = require(\"./MessageEvent\");\n\nvar _message_types = require(\"./message_types\");\n\nvar _events = require(\"../utility/events\");\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _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); }\n\nfunction _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }\n\nfunction _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); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _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); }; }\n\nfunction _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); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _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; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n// Notice events are just decorated message events\n\n/**\n * Represents a notice. This is essentially a MessageEvent with\n * notice characteristics considered.\n */\nvar NoticeEvent = /*#__PURE__*/function (_MessageEvent) {\n _inherits(NoticeEvent, _MessageEvent);\n\n var _super = _createSuper(NoticeEvent);\n\n function NoticeEvent(wireFormat) {\n _classCallCheck(this, NoticeEvent);\n\n return _super.call(this, wireFormat);\n }\n\n _createClass(NoticeEvent, [{\n key: \"isNotice\",\n get: function get() {\n return true; // override\n }\n }, {\n key: \"isEquivalentTo\",\n value: function isEquivalentTo(primaryEventType) {\n return (0, _events.isEventTypeSame)(primaryEventType, _message_types.M_NOTICE) || _get(_getPrototypeOf(NoticeEvent.prototype), \"isEquivalentTo\", this).call(this, primaryEventType);\n }\n }, {\n key: \"serialize\",\n value: function serialize() {\n var message = _get(_getPrototypeOf(NoticeEvent.prototype), \"serialize\", this).call(this);\n\n message.content['msgtype'] = \"m.notice\";\n return message;\n }\n /**\n * Creates a new NoticeEvent from text and HTML.\n * @param {string} text The text.\n * @param {string} html Optional HTML.\n * @returns {MessageEvent} The representative message event.\n */\n\n }], [{\n key: \"from\",\n value: function from(text, html) {\n var _content;\n\n return new NoticeEvent({\n type: _message_types.M_NOTICE.name,\n content: (_content = {}, _defineProperty(_content, _message_types.M_TEXT.name, text), _defineProperty(_content, _message_types.M_HTML.name, html), _content)\n });\n }\n }]);\n\n return NoticeEvent;\n}(_MessageEvent2.MessageEvent);\n\nexports.NoticeEvent = NoticeEvent;", - "\"use strict\";\n\nfunction _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); }\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.PollEndEvent = void 0;\n\nvar _poll_types = require(\"./poll_types\");\n\nvar _InvalidEventError = require(\"../InvalidEventError\");\n\nvar _relationship_types = require(\"./relationship_types\");\n\nvar _MessageEvent = require(\"./MessageEvent\");\n\nvar _message_types = require(\"./message_types\");\n\nvar _events = require(\"../utility/events\");\n\nvar _ExtensibleEvent2 = require(\"./ExtensibleEvent\");\n\nfunction 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; }\n\nfunction _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; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _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); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _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); }; }\n\nfunction _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); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _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; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n/**\n * Represents a poll end/closure event.\n */\nvar PollEndEvent = /*#__PURE__*/function (_ExtensibleEvent) {\n _inherits(PollEndEvent, _ExtensibleEvent);\n\n var _super = _createSuper(PollEndEvent);\n\n /**\n * The poll start event ID referenced by the response.\n */\n\n /**\n * The closing message for the event.\n */\n\n /**\n * Creates a new PollEndEvent from a pure format. Note that the event is *not*\n * parsed here: it will be treated as a literal m.poll.response primary typed event.\n * @param {IPartialEvent} wireFormat The event.\n */\n function PollEndEvent(wireFormat) {\n var _this;\n\n _classCallCheck(this, PollEndEvent);\n\n _this = _super.call(this, wireFormat);\n\n _defineProperty(_assertThisInitialized(_this), \"pollEventId\", void 0);\n\n _defineProperty(_assertThisInitialized(_this), \"closingMessage\", void 0);\n\n var rel = _this.wireContent[\"m.relates_to\"];\n\n 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\") {\n throw new _InvalidEventError.InvalidEventError(\"Relationship must be a reference to an event\");\n }\n\n _this.pollEventId = rel.event_id;\n _this.closingMessage = new _MessageEvent.MessageEvent(_this.wireFormat);\n return _this;\n }\n\n _createClass(PollEndEvent, [{\n key: \"isEquivalentTo\",\n value: function isEquivalentTo(primaryEventType) {\n return (0, _events.isEventTypeSame)(primaryEventType, _poll_types.M_POLL_END);\n }\n }, {\n key: \"serialize\",\n value: function serialize() {\n return {\n type: _poll_types.M_POLL_END.name,\n content: _objectSpread(_defineProperty({\n \"m.relates_to\": {\n rel_type: _relationship_types.REFERENCE_RELATION.name,\n event_id: this.pollEventId\n }\n }, _poll_types.M_POLL_END.name, {}), this.closingMessage.serialize().content)\n };\n }\n /**\n * Creates a new PollEndEvent from a poll event ID.\n * @param {string} pollEventId The poll start event ID.\n * @param {string} message A closing message, typically revealing the top answer.\n * @returns {PollStartEvent} The representative poll closure event.\n */\n\n }], [{\n key: \"from\",\n value: function from(pollEventId, message) {\n var _content;\n\n return new PollEndEvent({\n type: _poll_types.M_POLL_END.name,\n content: (_content = {\n \"m.relates_to\": {\n rel_type: _relationship_types.REFERENCE_RELATION.name,\n event_id: pollEventId\n }\n }, _defineProperty(_content, _poll_types.M_POLL_END.name, {}), _defineProperty(_content, _message_types.M_TEXT.name, message), _content)\n });\n }\n }]);\n\n return PollEndEvent;\n}(_ExtensibleEvent2.ExtensibleEvent);\n\nexports.PollEndEvent = PollEndEvent;", - "\"use strict\";\n\nfunction _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); }\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.PollResponseEvent = void 0;\n\nvar _ExtensibleEvent2 = require(\"./ExtensibleEvent\");\n\nvar _poll_types = require(\"./poll_types\");\n\nvar _InvalidEventError = require(\"../InvalidEventError\");\n\nvar _relationship_types = require(\"./relationship_types\");\n\nvar _events = require(\"../utility/events\");\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _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); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _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); }; }\n\nfunction _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); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _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; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n/**\n * Represents a poll response event.\n */\nvar PollResponseEvent = /*#__PURE__*/function (_ExtensibleEvent) {\n _inherits(PollResponseEvent, _ExtensibleEvent);\n\n var _super = _createSuper(PollResponseEvent);\n\n /**\n * Creates a new PollResponseEvent from a pure format. Note that the event is *not*\n * parsed here: it will be treated as a literal m.poll.response primary typed event.\n *\n * To validate the response against a poll, call `validateAgainst` after creation.\n * @param {IPartialEvent} wireFormat The event.\n */\n function PollResponseEvent(wireFormat) {\n var _this;\n\n _classCallCheck(this, PollResponseEvent);\n\n _this = _super.call(this, wireFormat);\n\n _defineProperty(_assertThisInitialized(_this), \"internalAnswerIds\", void 0);\n\n _defineProperty(_assertThisInitialized(_this), \"internalSpoiled\", void 0);\n\n _defineProperty(_assertThisInitialized(_this), \"pollEventId\", void 0);\n\n var rel = _this.wireContent[\"m.relates_to\"];\n\n 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\") {\n throw new _InvalidEventError.InvalidEventError(\"Relationship must be a reference to an event\");\n }\n\n _this.pollEventId = rel.event_id;\n\n _this.validateAgainst(null);\n\n return _this;\n }\n /**\n * Validates the poll response using the poll start event as a frame of reference. This\n * is used to determine if the vote is spoiled, whether the answers are valid, etc.\n * @param {PollStartEvent} poll The poll start event.\n */\n\n\n _createClass(PollResponseEvent, [{\n key: \"answerIds\",\n get:\n /**\n * The provided answers for the poll. Note that this may be falsy/unpredictable if\n * the `spoiled` property is true.\n */\n function get() {\n return this.internalAnswerIds;\n }\n /**\n * The poll start event ID referenced by the response.\n */\n\n }, {\n key: \"spoiled\",\n get:\n /**\n * Whether the vote is spoiled.\n */\n function get() {\n return this.internalSpoiled;\n }\n }, {\n key: \"validateAgainst\",\n value: function validateAgainst(poll) {\n var response = _poll_types.M_POLL_RESPONSE.findIn(this.wireContent);\n\n if (!Array.isArray(response === null || response === void 0 ? void 0 : response.answers)) {\n this.internalSpoiled = true;\n this.internalAnswerIds = [];\n return;\n }\n\n var answers = response.answers;\n\n if (answers.some(function (a) {\n return typeof a !== \"string\";\n }) || answers.length === 0) {\n this.internalSpoiled = true;\n this.internalAnswerIds = [];\n return;\n }\n\n if (poll) {\n if (answers.some(function (a) {\n return !poll.answers.some(function (pa) {\n return pa.id === a;\n });\n })) {\n this.internalSpoiled = true;\n this.internalAnswerIds = [];\n return;\n }\n\n answers = answers.slice(0, poll.maxSelections);\n }\n\n this.internalAnswerIds = answers;\n this.internalSpoiled = false;\n }\n }, {\n key: \"isEquivalentTo\",\n value: function isEquivalentTo(primaryEventType) {\n return (0, _events.isEventTypeSame)(primaryEventType, _poll_types.M_POLL_RESPONSE);\n }\n }, {\n key: \"serialize\",\n value: function serialize() {\n return {\n type: _poll_types.M_POLL_RESPONSE.name,\n content: _defineProperty({\n \"m.relates_to\": {\n rel_type: _relationship_types.REFERENCE_RELATION.name,\n event_id: this.pollEventId\n }\n }, _poll_types.M_POLL_RESPONSE.name, {\n answers: this.spoiled ? undefined : this.answerIds\n })\n };\n }\n /**\n * Creates a new PollResponseEvent from a set of answers. To spoil the vote, pass an empty\n * answers array.\n * @param {string} answers The user's answers. Should be valid from a poll's answer IDs.\n * @param {string} pollEventId The poll start event ID.\n * @returns {PollStartEvent} The representative poll response event.\n */\n\n }], [{\n key: \"from\",\n value: function from(answers, pollEventId) {\n return new PollResponseEvent({\n type: _poll_types.M_POLL_RESPONSE.name,\n content: _defineProperty({\n \"m.relates_to\": {\n rel_type: _relationship_types.REFERENCE_RELATION.name,\n event_id: pollEventId\n }\n }, _poll_types.M_POLL_RESPONSE.name, {\n answers: answers\n })\n });\n }\n }]);\n\n return PollResponseEvent;\n}(_ExtensibleEvent2.ExtensibleEvent);\n\nexports.PollResponseEvent = PollResponseEvent;", - "\"use strict\";\n\nfunction _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); }\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.PollStartEvent = exports.PollAnswerSubevent = void 0;\n\nvar _poll_types = require(\"./poll_types\");\n\nvar _MessageEvent2 = require(\"./MessageEvent\");\n\nvar _message_types = require(\"./message_types\");\n\nvar _InvalidEventError = require(\"../InvalidEventError\");\n\nvar _NamespacedValue = require(\"../NamespacedValue\");\n\nvar _events = require(\"../utility/events\");\n\nvar _ExtensibleEvent2 = require(\"./ExtensibleEvent\");\n\nfunction _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\n\nfunction _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.\"); }\n\nfunction _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); }\n\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && iter[Symbol.iterator] != null || iter[\"@@iterator\"] != null) return Array.from(iter); }\n\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\n\nfunction _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; }\n\nfunction 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; }\n\nfunction _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; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _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); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _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); }; }\n\nfunction _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); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _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; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n/**\n * Represents a poll answer. Note that this is represented as a subtype and is\n * not registered as a parsable event - it is implied for usage exclusively\n * within the PollStartEvent parsing.\n */\nvar PollAnswerSubevent = /*#__PURE__*/function (_MessageEvent) {\n _inherits(PollAnswerSubevent, _MessageEvent);\n\n var _super = _createSuper(PollAnswerSubevent);\n\n /**\n * The answer ID.\n */\n function PollAnswerSubevent(wireFormat) {\n var _this;\n\n _classCallCheck(this, PollAnswerSubevent);\n\n _this = _super.call(this, wireFormat);\n\n _defineProperty(_assertThisInitialized(_this), \"id\", void 0);\n\n var id = wireFormat.content.id;\n\n if (!id || typeof id !== \"string\") {\n throw new _InvalidEventError.InvalidEventError(\"Answer ID must be a non-empty string\");\n }\n\n _this.id = id;\n return _this;\n }\n\n _createClass(PollAnswerSubevent, [{\n key: \"serialize\",\n value: function serialize() {\n return {\n type: \"org.matrix.sdk.poll.answer\",\n content: _objectSpread({\n id: this.id\n }, this.serializeMMessageOnly())\n };\n }\n /**\n * Creates a new PollAnswerSubevent from ID and text.\n * @param {string} id The answer ID (unique within the poll).\n * @param {string} text The text.\n * @returns {PollAnswerSubevent} The representative answer.\n */\n\n }], [{\n key: \"from\",\n value: function from(id, text) {\n return new PollAnswerSubevent({\n type: \"org.matrix.sdk.poll.answer\",\n content: _defineProperty({\n id: id\n }, _message_types.M_TEXT.name, text)\n });\n }\n }]);\n\n return PollAnswerSubevent;\n}(_MessageEvent2.MessageEvent);\n/**\n * Represents a poll start event.\n */\n\n\nexports.PollAnswerSubevent = PollAnswerSubevent;\n\nvar PollStartEvent = /*#__PURE__*/function (_ExtensibleEvent) {\n _inherits(PollStartEvent, _ExtensibleEvent);\n\n var _super2 = _createSuper(PollStartEvent);\n\n /**\n * The question being asked, as a MessageEvent node.\n */\n\n /**\n * The interpreted kind of poll. Note that this will infer a value that is known to the\n * SDK rather than verbatim - this means unknown types will be represented as undisclosed\n * polls.\n *\n * To get the raw kind, use rawKind.\n */\n\n /**\n * The true kind as provided by the event sender. Might not be valid.\n */\n\n /**\n * The maximum number of selections a user is allowed to make.\n */\n\n /**\n * The possible answers for the poll.\n */\n\n /**\n * Creates a new PollStartEvent from a pure format. Note that the event is *not*\n * parsed here: it will be treated as a literal m.poll.start primary typed event.\n * @param {IPartialEvent} wireFormat The event.\n */\n function PollStartEvent(wireFormat) {\n var _this2;\n\n _classCallCheck(this, PollStartEvent);\n\n _this2 = _super2.call(this, wireFormat);\n\n _defineProperty(_assertThisInitialized(_this2), \"question\", void 0);\n\n _defineProperty(_assertThisInitialized(_this2), \"kind\", void 0);\n\n _defineProperty(_assertThisInitialized(_this2), \"rawKind\", void 0);\n\n _defineProperty(_assertThisInitialized(_this2), \"maxSelections\", void 0);\n\n _defineProperty(_assertThisInitialized(_this2), \"answers\", void 0);\n\n var poll = _poll_types.M_POLL_START.findIn(_this2.wireContent);\n\n if (!poll.question) {\n throw new _InvalidEventError.InvalidEventError(\"A question is required\");\n }\n\n _this2.question = new _MessageEvent2.MessageEvent({\n type: \"org.matrix.sdk.poll.question\",\n content: poll.question\n });\n _this2.rawKind = poll.kind;\n\n if (_poll_types.M_POLL_KIND_DISCLOSED.matches(_this2.rawKind)) {\n _this2.kind = _poll_types.M_POLL_KIND_DISCLOSED;\n } else {\n _this2.kind = _poll_types.M_POLL_KIND_UNDISCLOSED; // default & assumed value\n }\n\n _this2.maxSelections = Number.isFinite(poll.max_selections) && poll.max_selections > 0 ? poll.max_selections : 1;\n\n if (!Array.isArray(poll.answers)) {\n throw new _InvalidEventError.InvalidEventError(\"Poll answers must be an array\");\n }\n\n var answers = poll.answers.slice(0, 20).map(function (a) {\n return new PollAnswerSubevent({\n type: \"org.matrix.sdk.poll.answer\",\n content: a\n });\n });\n\n if (answers.length <= 0) {\n throw new _InvalidEventError.InvalidEventError(\"No answers available\");\n }\n\n _this2.answers = answers;\n return _this2;\n }\n\n _createClass(PollStartEvent, [{\n key: \"isEquivalentTo\",\n value: function isEquivalentTo(primaryEventType) {\n return (0, _events.isEventTypeSame)(primaryEventType, _poll_types.M_POLL_START);\n }\n }, {\n key: \"serialize\",\n value: function serialize() {\n var _content2;\n\n return {\n type: _poll_types.M_POLL_START.name,\n content: (_content2 = {}, _defineProperty(_content2, _poll_types.M_POLL_START.name, {\n question: this.question.serialize().content,\n kind: this.rawKind,\n max_selections: this.maxSelections,\n answers: this.answers.map(function (a) {\n return a.serialize().content;\n })\n }), _defineProperty(_content2, _message_types.M_TEXT.name, \"\".concat(this.question.text, \"\\n\").concat(this.answers.map(function (a, i) {\n return \"\".concat(i + 1, \". \").concat(a.text);\n }).join(\"\\n\"))), _content2)\n };\n }\n /**\n * Creates a new PollStartEvent from question, answers, and metadata.\n * @param {string} question The question to ask.\n * @param {string} answers The answers. Should be unique within each other.\n * @param {KNOWN_POLL_KIND|string} kind The kind of poll.\n * @param {number} maxSelections The maximum number of selections. Must be 1 or higher.\n * @returns {PollStartEvent} The representative poll start event.\n */\n\n }], [{\n key: \"from\",\n value: function from(question, answers, kind) {\n var _content3;\n\n var maxSelections = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1;\n return new PollStartEvent({\n type: _poll_types.M_POLL_START.name,\n content: (_content3 = {}, _defineProperty(_content3, _message_types.M_TEXT.name, question), _defineProperty(_content3, _poll_types.M_POLL_START.name, {\n question: _defineProperty({}, _message_types.M_TEXT.name, question),\n kind: kind instanceof _NamespacedValue.NamespacedValue ? kind.name : kind,\n max_selections: maxSelections,\n answers: answers.map(function (a) {\n return _defineProperty({\n id: makeId()\n }, _message_types.M_TEXT.name, a);\n })\n }), _content3)\n });\n }\n }]);\n\n return PollStartEvent;\n}(_ExtensibleEvent2.ExtensibleEvent);\n\nexports.PollStartEvent = PollStartEvent;\nvar LETTERS = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n\nfunction makeId() {\n return _toConsumableArray(Array(16)).map(function () {\n return LETTERS.charAt(Math.floor(Math.random() * LETTERS.length));\n }).join('');\n}", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.M_TEXT = exports.M_NOTICE = exports.M_MESSAGE = exports.M_HTML = exports.M_EMOTE = void 0;\n\nvar _NamespacedValue = require(\"../NamespacedValue\");\n\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * The namespaced value for m.message\n */\nvar M_MESSAGE = new _NamespacedValue.UnstableValue(\"m.message\", \"org.matrix.msc1767.message\");\n/**\n * An m.message event rendering\n */\n\nexports.M_MESSAGE = M_MESSAGE;\n\n/**\n * The namespaced value for m.text\n */\nvar M_TEXT = new _NamespacedValue.UnstableValue(\"m.text\", \"org.matrix.msc1767.text\");\n/**\n * The content for an m.text event\n */\n\nexports.M_TEXT = M_TEXT;\n\n/**\n * The namespaced value for m.html\n */\nvar M_HTML = new _NamespacedValue.UnstableValue(\"m.html\", \"org.matrix.msc1767.html\");\n/**\n * The content for an m.html event\n */\n\nexports.M_HTML = M_HTML;\n\n/**\n * The namespaced value for m.emote\n */\nvar M_EMOTE = new _NamespacedValue.UnstableValue(\"m.emote\", \"org.matrix.msc1767.emote\");\n/**\n * The event definition for an m.emote event (in content)\n */\n\nexports.M_EMOTE = M_EMOTE;\n\n/**\n * The namespaced value for m.notice\n */\nvar M_NOTICE = new _NamespacedValue.UnstableValue(\"m.notice\", \"org.matrix.msc1767.notice\");\n/**\n * The event definition for an m.notice event (in content)\n */\n\nexports.M_NOTICE = M_NOTICE;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.M_POLL_START = exports.M_POLL_RESPONSE = exports.M_POLL_KIND_UNDISCLOSED = exports.M_POLL_KIND_DISCLOSED = exports.M_POLL_END = void 0;\n\nvar _NamespacedValue = require(\"../NamespacedValue\");\n\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Identifier for a disclosed poll.\n */\nvar M_POLL_KIND_DISCLOSED = new _NamespacedValue.UnstableValue(\"m.poll.disclosed\", \"org.matrix.msc3381.poll.disclosed\");\n/**\n * Identifier for an undisclosed poll.\n */\n\nexports.M_POLL_KIND_DISCLOSED = M_POLL_KIND_DISCLOSED;\nvar M_POLL_KIND_UNDISCLOSED = new _NamespacedValue.UnstableValue(\"m.poll.undisclosed\", \"org.matrix.msc3381.poll.undisclosed\");\n/**\n * Any poll kind.\n */\n\nexports.M_POLL_KIND_UNDISCLOSED = M_POLL_KIND_UNDISCLOSED;\n\n/**\n * The namespaced value for m.poll.start\n */\nvar M_POLL_START = new _NamespacedValue.UnstableValue(\"m.poll.start\", \"org.matrix.msc3381.poll.start\");\n/**\n * The m.poll.start type within event content\n */\n\nexports.M_POLL_START = M_POLL_START;\n\n/**\n * The namespaced value for m.poll.response\n */\nvar M_POLL_RESPONSE = new _NamespacedValue.UnstableValue(\"m.poll.response\", \"org.matrix.msc3381.poll.response\");\n/**\n * The m.poll.response type within event content\n */\n\nexports.M_POLL_RESPONSE = M_POLL_RESPONSE;\n\n/**\n * The namespaced value for m.poll.end\n */\nvar M_POLL_END = new _NamespacedValue.UnstableValue(\"m.poll.end\", \"org.matrix.msc3381.poll.end\");\n/**\n * The event definition for an m.poll.end event (in content)\n */\n\nexports.M_POLL_END = M_POLL_END;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.REFERENCE_RELATION = void 0;\n\nvar _NamespacedValue = require(\"../NamespacedValue\");\n\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * The namespaced value for an m.reference relation\n */\nvar REFERENCE_RELATION = new _NamespacedValue.NamespacedValue(\"m.reference\");\n/**\n * Represents any relation type\n */\n\nexports.REFERENCE_RELATION = REFERENCE_RELATION;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _ExtensibleEvents = require(\"./ExtensibleEvents\");\n\nObject.keys(_ExtensibleEvents).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _ExtensibleEvents[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _ExtensibleEvents[key];\n }\n });\n});\n\nvar _IPartialEvent = require(\"./IPartialEvent\");\n\nObject.keys(_IPartialEvent).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _IPartialEvent[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _IPartialEvent[key];\n }\n });\n});\n\nvar _InvalidEventError = require(\"./InvalidEventError\");\n\nObject.keys(_InvalidEventError).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _InvalidEventError[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _InvalidEventError[key];\n }\n });\n});\n\nvar _NamespacedValue = require(\"./NamespacedValue\");\n\nObject.keys(_NamespacedValue).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _NamespacedValue[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _NamespacedValue[key];\n }\n });\n});\n\nvar _NamespacedMap = require(\"./NamespacedMap\");\n\nObject.keys(_NamespacedMap).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _NamespacedMap[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _NamespacedMap[key];\n }\n });\n});\n\nvar _types = require(\"./types\");\n\nObject.keys(_types).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _types[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _types[key];\n }\n });\n});\n\nvar _MessageMatchers = require(\"./utility/MessageMatchers\");\n\nObject.keys(_MessageMatchers).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _MessageMatchers[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _MessageMatchers[key];\n }\n });\n});\n\nvar _events = require(\"./utility/events\");\n\nObject.keys(_events).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _events[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _events[key];\n }\n });\n});\n\nvar _MRoomMessage = require(\"./interpreters/legacy/MRoomMessage\");\n\nObject.keys(_MRoomMessage).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _MRoomMessage[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _MRoomMessage[key];\n }\n });\n});\n\nvar _MMessage = require(\"./interpreters/modern/MMessage\");\n\nObject.keys(_MMessage).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _MMessage[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _MMessage[key];\n }\n });\n});\n\nvar _MPoll = require(\"./interpreters/modern/MPoll\");\n\nObject.keys(_MPoll).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _MPoll[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _MPoll[key];\n }\n });\n});\n\nvar _relationship_types = require(\"./events/relationship_types\");\n\nObject.keys(_relationship_types).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _relationship_types[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _relationship_types[key];\n }\n });\n});\n\nvar _ExtensibleEvent = require(\"./events/ExtensibleEvent\");\n\nObject.keys(_ExtensibleEvent).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _ExtensibleEvent[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _ExtensibleEvent[key];\n }\n });\n});\n\nvar _message_types = require(\"./events/message_types\");\n\nObject.keys(_message_types).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _message_types[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _message_types[key];\n }\n });\n});\n\nvar _MessageEvent = require(\"./events/MessageEvent\");\n\nObject.keys(_MessageEvent).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _MessageEvent[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _MessageEvent[key];\n }\n });\n});\n\nvar _EmoteEvent = require(\"./events/EmoteEvent\");\n\nObject.keys(_EmoteEvent).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _EmoteEvent[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _EmoteEvent[key];\n }\n });\n});\n\nvar _NoticeEvent = require(\"./events/NoticeEvent\");\n\nObject.keys(_NoticeEvent).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _NoticeEvent[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _NoticeEvent[key];\n }\n });\n});\n\nvar _poll_types = require(\"./events/poll_types\");\n\nObject.keys(_poll_types).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _poll_types[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _poll_types[key];\n }\n });\n});\n\nvar _PollStartEvent = require(\"./events/PollStartEvent\");\n\nObject.keys(_PollStartEvent).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _PollStartEvent[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _PollStartEvent[key];\n }\n });\n});\n\nvar _PollResponseEvent = require(\"./events/PollResponseEvent\");\n\nObject.keys(_PollResponseEvent).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _PollResponseEvent[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _PollResponseEvent[key];\n }\n });\n});\n\nvar _PollEndEvent = require(\"./events/PollEndEvent\");\n\nObject.keys(_PollEndEvent).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _PollEndEvent[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _PollEndEvent[key];\n }\n });\n});", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.LEGACY_M_ROOM_MESSAGE = void 0;\nexports.parseMRoomMessage = parseMRoomMessage;\n\nvar _MessageEvent = require(\"../../events/MessageEvent\");\n\nvar _NoticeEvent = require(\"../../events/NoticeEvent\");\n\nvar _EmoteEvent = require(\"../../events/EmoteEvent\");\n\nvar _NamespacedValue = require(\"../../NamespacedValue\");\n\nvar _message_types = require(\"../../events/message_types\");\n\nfunction 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; }\n\nfunction _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; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar LEGACY_M_ROOM_MESSAGE = new _NamespacedValue.NamespacedValue(\"m.room.message\");\nexports.LEGACY_M_ROOM_MESSAGE = LEGACY_M_ROOM_MESSAGE;\n\nfunction parseMRoomMessage(wireEvent) {\n var _wireEvent$content, _wireEvent$content2, _wireEvent$content3;\n\n if (_message_types.M_MESSAGE.findIn(wireEvent.content) || _message_types.M_TEXT.findIn(wireEvent.content)) {\n // We know enough about the event to coerce it into the right type\n return new _MessageEvent.MessageEvent(wireEvent);\n }\n\n var msgtype = (_wireEvent$content = wireEvent.content) === null || _wireEvent$content === void 0 ? void 0 : _wireEvent$content.msgtype;\n var text = (_wireEvent$content2 = wireEvent.content) === null || _wireEvent$content2 === void 0 ? void 0 : _wireEvent$content2.body;\n 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;\n\n if (msgtype === \"m.text\") {\n var _objectSpread2;\n\n return new _MessageEvent.MessageEvent(_objectSpread(_objectSpread({}, wireEvent), {}, {\n content: _objectSpread(_objectSpread({}, wireEvent.content), {}, (_objectSpread2 = {}, _defineProperty(_objectSpread2, _message_types.M_TEXT.name, text), _defineProperty(_objectSpread2, _message_types.M_HTML.name, html), _objectSpread2))\n }));\n } else if (msgtype === \"m.notice\") {\n var _objectSpread3;\n\n return new _NoticeEvent.NoticeEvent(_objectSpread(_objectSpread({}, wireEvent), {}, {\n content: _objectSpread(_objectSpread({}, wireEvent.content), {}, (_objectSpread3 = {}, _defineProperty(_objectSpread3, _message_types.M_TEXT.name, text), _defineProperty(_objectSpread3, _message_types.M_HTML.name, html), _objectSpread3))\n }));\n } else if (msgtype === \"m.emote\") {\n var _objectSpread4;\n\n return new _EmoteEvent.EmoteEvent(_objectSpread(_objectSpread({}, wireEvent), {}, {\n content: _objectSpread(_objectSpread({}, wireEvent.content), {}, (_objectSpread4 = {}, _defineProperty(_objectSpread4, _message_types.M_TEXT.name, text), _defineProperty(_objectSpread4, _message_types.M_HTML.name, html), _objectSpread4))\n }));\n } else {\n // TODO: Handle other types\n return null;\n }\n}", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.parseMMessage = parseMMessage;\n\nvar _MessageEvent = require(\"../../events/MessageEvent\");\n\nvar _message_types = require(\"../../events/message_types\");\n\nvar _EmoteEvent = require(\"../../events/EmoteEvent\");\n\nvar _NoticeEvent = require(\"../../events/NoticeEvent\");\n\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nfunction parseMMessage(wireEvent) {\n if (_message_types.M_EMOTE.matches(wireEvent.type)) {\n return new _EmoteEvent.EmoteEvent(wireEvent);\n } else if (_message_types.M_NOTICE.matches(wireEvent.type)) {\n return new _NoticeEvent.NoticeEvent(wireEvent);\n } // default: return a generic message\n\n\n return new _MessageEvent.MessageEvent(wireEvent);\n}", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.parseMPoll = parseMPoll;\n\nvar _poll_types = require(\"../../events/poll_types\");\n\nvar _PollStartEvent = require(\"../../events/PollStartEvent\");\n\nvar _PollResponseEvent = require(\"../../events/PollResponseEvent\");\n\nvar _PollEndEvent = require(\"../../events/PollEndEvent\");\n\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nfunction parseMPoll(wireEvent) {\n if (_poll_types.M_POLL_START.matches(wireEvent.type)) {\n return new _PollStartEvent.PollStartEvent(wireEvent);\n } else if (_poll_types.M_POLL_RESPONSE.matches(wireEvent.type)) {\n return new _PollResponseEvent.PollResponseEvent(wireEvent);\n } else if (_poll_types.M_POLL_END.matches(wireEvent.type)) {\n return new _PollEndEvent.PollEndEvent(wireEvent);\n }\n\n return null; // not a poll event\n}", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.isOptionalAString = isOptionalAString;\nexports.isProvided = isProvided;\n\n/*\nCopyright 2021 - 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Represents an optional type: can either be T or a falsy value.\n */\n\n/**\n * Determines if the given optional string is a defined string.\n * @param {Optional} s The input string.\n * @returns {boolean} True if the input is a defined string.\n */\nfunction isOptionalAString(s) {\n return isProvided(s) && typeof s === 'string';\n}\n/**\n * Determines if the given optional was provided a value.\n * @param {Optional} s The optional to test.\n * @returns {boolean} True if the value is defined.\n */\n\n\nfunction isProvided(s) {\n return s !== null && s !== undefined;\n}\n/**\n * Represents either just T1, just T2, or T1 and T2 mixed.\n */", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.LegacyMsgType = void 0;\nexports.isEventLike = isEventLike;\n\nvar _message_types = require(\"../events/message_types\");\n\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Represents a legacy m.room.message msgtype\n */\nvar LegacyMsgType;\n/**\n * Determines if the given partial event looks similar enough to the given legacy msgtype\n * to count as that message type.\n * @param {IPartialEvent>} event The event.\n * @param {LegacyMsgType} msgtype The message type to compare for.\n * @returns {boolean} True if the event appears to look similar enough to the msgtype.\n */\n\nexports.LegacyMsgType = LegacyMsgType;\n\n(function (LegacyMsgType) {\n LegacyMsgType[\"Text\"] = \"m.text\";\n LegacyMsgType[\"Notice\"] = \"m.notice\";\n LegacyMsgType[\"Emote\"] = \"m.emote\";\n})(LegacyMsgType || (exports.LegacyMsgType = LegacyMsgType = {}));\n\nfunction isEventLike(event, msgtype) {\n var content = event.content;\n\n if (msgtype === LegacyMsgType.Text) {\n return _message_types.M_MESSAGE.matches(event.type) || event.type === \"m.room.message\" && (content === null || content === void 0 ? void 0 : content['msgtype']) === \"m.text\";\n } else if (msgtype === LegacyMsgType.Emote) {\n return _message_types.M_EMOTE.matches(event.type) || event.type === \"m.room.message\" && (content === null || content === void 0 ? void 0 : content['msgtype']) === \"m.emote\";\n } else if (msgtype === LegacyMsgType.Notice) {\n return _message_types.M_NOTICE.matches(event.type) || event.type === \"m.room.message\" && (content === null || content === void 0 ? void 0 : content['msgtype']) === \"m.notice\";\n }\n\n return false;\n}", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.isEventTypeSame = isEventTypeSame;\n\n/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Represents a potentially namespaced event type.\n */\n\n/**\n * Determines if two event types are the same, including namespaces.\n * @param {EventType} given The given event type. This will be compared\n * against the expected type.\n * @param {EventType} expected The expected event type.\n * @returns {boolean} True if the given type matches the expected type.\n */\nfunction isEventTypeSame(given, expected) {\n if (typeof given === \"string\") {\n if (typeof expected === \"string\") {\n return expected === given;\n } else {\n return expected.matches(given);\n }\n } else {\n if (typeof expected === \"string\") {\n return given.matches(expected);\n } else {\n var expectedNs = expected;\n var givenNs = given;\n return expectedNs.matches(givenNs.name) || expectedNs.matches(givenNs.altName);\n }\n }\n}", - "\"use strict\";\n\nfunction _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); }\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.ClientWidgetApi = void 0;\n\nvar _events = require(\"events\");\n\nvar _PostmessageTransport = require(\"./transport/PostmessageTransport\");\n\nvar _WidgetApiDirection = require(\"./interfaces/WidgetApiDirection\");\n\nvar _WidgetApiAction = require(\"./interfaces/WidgetApiAction\");\n\nvar _Capabilities = require(\"./interfaces/Capabilities\");\n\nvar _ApiVersion = require(\"./interfaces/ApiVersion\");\n\nvar _WidgetEventCapability = require(\"./models/WidgetEventCapability\");\n\nvar _GetOpenIDAction = require(\"./interfaces/GetOpenIDAction\");\n\nvar _SimpleObservable = require(\"./util/SimpleObservable\");\n\nvar _Symbols = require(\"./Symbols\");\n\nfunction _regeneratorRuntime() { \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $Symbol = \"function\" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || \"@@iterator\", asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\", toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, \"\"); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return generator._invoke = function (innerFn, self, context) { var state = \"suspendedStart\"; return function (method, arg) { if (\"executing\" === state) throw new Error(\"Generator is already running\"); if (\"completed\" === state) { if (\"throw\" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) { if (\"suspendedStart\" === state) throw state = \"completed\", context.arg; context.dispatchException(context.arg); } else \"return\" === context.method && context.abrupt(\"return\", context.arg); state = \"executing\"; var record = tryCatch(innerFn, self, context); if (\"normal\" === record.type) { if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg); } }; }(innerFn, self, context), generator; } function tryCatch(fn, obj, arg) { try { return { type: \"normal\", arg: fn.call(obj, arg) }; } catch (err) { return { type: \"throw\", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { [\"next\", \"throw\", \"return\"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (\"throw\" !== record.type) { var result = record.arg, value = result.value; return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke(\"next\", value, resolve, reject); }, function (err) { invoke(\"throw\", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke(\"throw\", error, resolve, reject); }); } reject(record.arg); } var previousPromise; this._invoke = function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); }; } function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (undefined === method) { if (context.delegate = null, \"throw\" === context.method) { if (delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method)) return ContinueSentinel; context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a 'throw' method\"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = \"normal\", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: \"root\" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if (\"function\" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, \"constructor\", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, \"constructor\", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) { var ctor = \"function\" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, \"toString\", function () { return \"[object Generator]\"; }), exports.keys = function (object) { var keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if (\"throw\" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if (\"root\" === entry.tryLoc) return handle(\"end\"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, \"catchLoc\"), hasFinally = hasOwn.call(entry, \"finallyLoc\"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error(\"try statement without catch or finally\"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, \"finallyLoc\") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if (\"throw\" === record.type) throw record.arg; return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, \"catch\": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (\"throw\" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }\n\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }\n\nfunction _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err); } _next(undefined); }); }; }\n\nfunction _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; } } }; }\n\nfunction _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); }\n\nfunction _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; }\n\nfunction 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; }\n\nfunction _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; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _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); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _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); }; }\n\nfunction _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); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _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; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _asyncIterator(iterable) { var method, async, sync, retry = 2; for (\"undefined\" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;) { if (async && null != (method = iterable[async])) return method.call(iterable); if (sync && null != (method = iterable[sync])) return new AsyncFromSyncIterator(method.call(iterable)); async = \"@@asyncIterator\", sync = \"@@iterator\"; } throw new TypeError(\"Object is not async iterable\"); }\n\nfunction AsyncFromSyncIterator(s) { function AsyncFromSyncIteratorContinuation(r) { if (Object(r) !== r) return Promise.reject(new TypeError(r + \" is not an object.\")); var done = r.done; return Promise.resolve(r.value).then(function (value) { return { value: value, done: done }; }); } return AsyncFromSyncIterator = function AsyncFromSyncIterator(s) { this.s = s, this.n = s.next; }, AsyncFromSyncIterator.prototype = { s: null, n: null, next: function next() { return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments)); }, \"return\": function _return(value) { var ret = this.s[\"return\"]; return void 0 === ret ? Promise.resolve({ value: value, done: !0 }) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments)); }, \"throw\": function _throw(value) { var thr = this.s[\"return\"]; return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments)); } }, new AsyncFromSyncIterator(s); }\n\n/**\n * API handler for the client side of widgets. This raises events\n * for each action received as `action:${action}` (eg: \"action:screenshot\").\n * Default handling can be prevented by using preventDefault() on the\n * raised event. The default handling varies for each action: ones\n * which the SDK can handle safely are acknowledged appropriately and\n * ones which are unhandled (custom or require the client to do something)\n * are rejected with an error.\n *\n * Events which are preventDefault()ed must reply using the transport.\n * The events raised will have a default of an IWidgetApiRequest\n * interface.\n *\n * When the ClientWidgetApi is ready to start sending requests, it will\n * raise a \"ready\" CustomEvent. After the ready event fires, actions can\n * be sent and the transport will be ready.\n *\n * When the widget has indicated it has loaded, this class raises a\n * \"preparing\" CustomEvent. The preparing event does not indicate that\n * the widget is ready to receive communications - that is signified by\n * the ready event exclusively.\n *\n * This class only handles one widget at a time.\n */\nvar ClientWidgetApi = /*#__PURE__*/function (_EventEmitter) {\n _inherits(ClientWidgetApi, _EventEmitter);\n\n var _super = _createSuper(ClientWidgetApi);\n\n // contentLoadedActionSent is used to check that only one ContentLoaded request is send.\n\n /**\n * Creates a new client widget API. This will instantiate the transport\n * and start everything. When the iframe is loaded under the widget's\n * conditions, a \"ready\" event will be raised.\n * @param {Widget} widget The widget to communicate with.\n * @param {HTMLIFrameElement} iframe The iframe the widget is in.\n * @param {WidgetDriver} driver The driver for this widget/client.\n */\n function ClientWidgetApi(widget, iframe, driver) {\n var _this;\n\n _classCallCheck(this, ClientWidgetApi);\n\n _this = _super.call(this);\n _this.widget = widget;\n _this.iframe = iframe;\n _this.driver = driver;\n\n _defineProperty(_assertThisInitialized(_this), \"transport\", void 0);\n\n _defineProperty(_assertThisInitialized(_this), \"contentLoadedActionSent\", false);\n\n _defineProperty(_assertThisInitialized(_this), \"allowedCapabilities\", new Set());\n\n _defineProperty(_assertThisInitialized(_this), \"allowedEvents\", []);\n\n _defineProperty(_assertThisInitialized(_this), \"isStopped\", false);\n\n _defineProperty(_assertThisInitialized(_this), \"turnServers\", null);\n\n if (!(iframe !== null && iframe !== void 0 && iframe.contentWindow)) {\n throw new Error(\"No iframe supplied\");\n }\n\n if (!widget) {\n throw new Error(\"Invalid widget\");\n }\n\n if (!driver) {\n throw new Error(\"Invalid driver\");\n }\n\n _this.transport = new _PostmessageTransport.PostmessageTransport(_WidgetApiDirection.WidgetApiDirection.ToWidget, widget.id, iframe.contentWindow, window);\n _this.transport.targetOrigin = widget.origin;\n\n _this.transport.on(\"message\", _this.handleMessage.bind(_assertThisInitialized(_this)));\n\n iframe.addEventListener(\"load\", _this.onIframeLoad.bind(_assertThisInitialized(_this)));\n\n _this.transport.start();\n\n return _this;\n }\n\n _createClass(ClientWidgetApi, [{\n key: \"hasCapability\",\n value: function hasCapability(capability) {\n return this.allowedCapabilities.has(capability);\n }\n }, {\n key: \"canUseRoomTimeline\",\n value: function canUseRoomTimeline(roomId) {\n return this.hasCapability(\"org.matrix.msc2762.timeline:\".concat(_Symbols.Symbols.AnyRoom)) || this.hasCapability(\"org.matrix.msc2762.timeline:\".concat(roomId));\n }\n }, {\n key: \"canSendRoomEvent\",\n value: function canSendRoomEvent(eventType) {\n var msgtype = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n return this.allowedEvents.some(function (e) {\n return e.matchesAsRoomEvent(_WidgetEventCapability.EventDirection.Send, eventType, msgtype);\n });\n }\n }, {\n key: \"canSendStateEvent\",\n value: function canSendStateEvent(eventType, stateKey) {\n return this.allowedEvents.some(function (e) {\n return e.matchesAsStateEvent(_WidgetEventCapability.EventDirection.Send, eventType, stateKey);\n });\n }\n }, {\n key: \"canSendToDeviceEvent\",\n value: function canSendToDeviceEvent(eventType) {\n return this.allowedEvents.some(function (e) {\n return e.matchesAsToDeviceEvent(_WidgetEventCapability.EventDirection.Send, eventType);\n });\n }\n }, {\n key: \"canReceiveRoomEvent\",\n value: function canReceiveRoomEvent(eventType) {\n var msgtype = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n return this.allowedEvents.some(function (e) {\n return e.matchesAsRoomEvent(_WidgetEventCapability.EventDirection.Receive, eventType, msgtype);\n });\n }\n }, {\n key: \"canReceiveStateEvent\",\n value: function canReceiveStateEvent(eventType, stateKey) {\n return this.allowedEvents.some(function (e) {\n return e.matchesAsStateEvent(_WidgetEventCapability.EventDirection.Receive, eventType, stateKey);\n });\n }\n }, {\n key: \"canReceiveToDeviceEvent\",\n value: function canReceiveToDeviceEvent(eventType) {\n return this.allowedEvents.some(function (e) {\n return e.matchesAsToDeviceEvent(_WidgetEventCapability.EventDirection.Receive, eventType);\n });\n }\n }, {\n key: \"stop\",\n value: function stop() {\n this.isStopped = true;\n this.transport.stop();\n }\n }, {\n key: \"beginCapabilities\",\n value: function beginCapabilities() {\n var _this2 = this;\n\n // widget has loaded - tell all the listeners that\n this.emit(\"preparing\");\n var requestedCaps;\n this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.Capabilities, {}).then(function (caps) {\n requestedCaps = caps.capabilities;\n return _this2.driver.validateCapabilities(new Set(caps.capabilities));\n }).then(function (allowedCaps) {\n console.log(\"Widget \".concat(_this2.widget.id, \" is allowed capabilities:\"), Array.from(allowedCaps));\n _this2.allowedCapabilities = allowedCaps;\n _this2.allowedEvents = _WidgetEventCapability.WidgetEventCapability.findEventCapabilities(allowedCaps);\n\n _this2.notifyCapabilities(requestedCaps);\n\n _this2.emit(\"ready\");\n });\n }\n }, {\n key: \"notifyCapabilities\",\n value: function notifyCapabilities(requested) {\n var _this3 = this;\n\n this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.NotifyCapabilities, {\n requested: requested,\n approved: Array.from(this.allowedCapabilities)\n })[\"catch\"](function (e) {\n console.warn(\"non-fatal error notifying widget of approved capabilities:\", e);\n }).then(function () {\n _this3.emit(\"capabilitiesNotified\");\n });\n }\n }, {\n key: \"onIframeLoad\",\n value: function onIframeLoad(ev) {\n if (this.widget.waitForIframeLoad) {\n // If the widget is set to waitForIframeLoad the capabilities immediatly get setup after load.\n // The client does not wait for the ContentLoaded action.\n this.beginCapabilities();\n } else {\n // Reaching this means, that the Iframe got reloaded/loaded and\n // the clientApi is awaiting the FIRST ContentLoaded action.\n this.contentLoadedActionSent = false;\n }\n }\n }, {\n key: \"handleContentLoadedAction\",\n value: function handleContentLoadedAction(action) {\n if (this.contentLoadedActionSent) {\n throw new Error(\"Improper sequence: ContentLoaded Action can only be send once after the widget loaded \" + \"and should only be used if waitForIframeLoad is false (default=true)\");\n }\n\n if (this.widget.waitForIframeLoad) {\n this.transport.reply(action, {\n error: {\n message: \"Improper sequence: not expecting ContentLoaded event if \" + \"waitForIframLoad is true (default=true)\"\n }\n });\n } else {\n this.transport.reply(action, {});\n this.beginCapabilities();\n }\n\n this.contentLoadedActionSent = true;\n }\n }, {\n key: \"replyVersions\",\n value: function replyVersions(request) {\n this.transport.reply(request, {\n supported_versions: _ApiVersion.CurrentApiVersions\n });\n }\n }, {\n key: \"handleCapabilitiesRenegotiate\",\n value: function handleCapabilitiesRenegotiate(request) {\n var _request$data,\n _this4 = this;\n\n // acknowledge first\n this.transport.reply(request, {});\n var requested = ((_request$data = request.data) === null || _request$data === void 0 ? void 0 : _request$data.capabilities) || [];\n var newlyRequested = new Set(requested.filter(function (r) {\n return !_this4.hasCapability(r);\n }));\n\n if (newlyRequested.size === 0) {\n // Nothing to do - notify capabilities\n return this.notifyCapabilities([]);\n }\n\n this.driver.validateCapabilities(newlyRequested).then(function (allowed) {\n allowed.forEach(function (c) {\n return _this4.allowedCapabilities.add(c);\n });\n\n var allowedEvents = _WidgetEventCapability.WidgetEventCapability.findEventCapabilities(allowed);\n\n allowedEvents.forEach(function (c) {\n return _this4.allowedEvents.push(c);\n });\n return _this4.notifyCapabilities(Array.from(newlyRequested));\n });\n }\n }, {\n key: \"handleNavigate\",\n value: function handleNavigate(request) {\n var _request$data2,\n _request$data3,\n _this5 = this;\n\n if (!this.hasCapability(_Capabilities.MatrixCapabilities.MSC2931Navigate)) {\n return this.transport.reply(request, {\n error: {\n message: \"Missing capability\"\n }\n });\n }\n\n if (!((_request$data2 = request.data) !== null && _request$data2 !== void 0 && _request$data2.uri) || !((_request$data3 = request.data) !== null && _request$data3 !== void 0 && _request$data3.uri.toString().startsWith(\"https://matrix.to/#\"))) {\n return this.transport.reply(request, {\n error: {\n message: \"Invalid matrix.to URI\"\n }\n });\n }\n\n var onErr = function onErr(e) {\n console.error(\"[ClientWidgetApi] Failed to handle navigation: \", e);\n return _this5.transport.reply(request, {\n error: {\n message: \"Error handling navigation\"\n }\n });\n };\n\n try {\n this.driver.navigate(request.data.uri.toString())[\"catch\"](function (e) {\n return onErr(e);\n }).then(function () {\n return _this5.transport.reply(request, {});\n });\n } catch (e) {\n return onErr(e);\n }\n }\n }, {\n key: \"handleOIDC\",\n value: function handleOIDC(request) {\n var _this6 = this;\n\n var phase = 1; // 1 = initial request, 2 = after user manual confirmation\n\n var replyState = function replyState(state, credential) {\n credential = credential || {};\n\n if (phase > 1) {\n return _this6.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.OpenIDCredentials, _objectSpread({\n state: state,\n original_request_id: request.requestId\n }, credential));\n } else {\n return _this6.transport.reply(request, _objectSpread({\n state: state\n }, credential));\n }\n };\n\n var replyError = function replyError(msg) {\n console.error(\"[ClientWidgetApi] Failed to handle OIDC: \", msg);\n\n if (phase > 1) {\n // We don't have a way to indicate that a random error happened in this flow, so\n // just block the attempt.\n return replyState(_GetOpenIDAction.OpenIDRequestState.Blocked);\n } else {\n return _this6.transport.reply(request, {\n error: {\n message: msg\n }\n });\n }\n };\n\n var observer = new _SimpleObservable.SimpleObservable(function (update) {\n if (update.state === _GetOpenIDAction.OpenIDRequestState.PendingUserConfirmation && phase > 1) {\n observer.close();\n return replyError(\"client provided out-of-phase response to OIDC flow\");\n }\n\n if (update.state === _GetOpenIDAction.OpenIDRequestState.PendingUserConfirmation) {\n replyState(update.state);\n phase++;\n return;\n }\n\n if (update.state === _GetOpenIDAction.OpenIDRequestState.Allowed && !update.token) {\n return replyError(\"client provided invalid OIDC token for an allowed request\");\n }\n\n if (update.state === _GetOpenIDAction.OpenIDRequestState.Blocked) {\n update.token = undefined; // just in case the client did something weird\n }\n\n observer.close();\n return replyState(update.state, update.token);\n });\n this.driver.askOpenID(observer);\n }\n }, {\n key: \"handleReadEvents\",\n value: function handleReadEvents(request) {\n var _this7 = this;\n\n if (!request.data.type) {\n return this.transport.reply(request, {\n error: {\n message: \"Invalid request - missing event type\"\n }\n });\n }\n\n if (request.data.limit !== undefined && (!request.data.limit || request.data.limit < 0)) {\n return this.transport.reply(request, {\n error: {\n message: \"Invalid request - limit out of range\"\n }\n });\n }\n\n var askRoomIds = null; // null denotes current room only\n\n if (request.data.room_ids) {\n askRoomIds = request.data.room_ids;\n\n if (!Array.isArray(askRoomIds)) {\n askRoomIds = [askRoomIds];\n }\n\n var _iterator2 = _createForOfIteratorHelper(askRoomIds),\n _step2;\n\n try {\n for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {\n var roomId = _step2.value;\n\n if (!this.canUseRoomTimeline(roomId)) {\n return this.transport.reply(request, {\n error: {\n message: \"Unable to access room timeline: \".concat(roomId)\n }\n });\n }\n }\n } catch (err) {\n _iterator2.e(err);\n } finally {\n _iterator2.f();\n }\n }\n\n var limit = request.data.limit || 0;\n var events = Promise.resolve([]);\n\n if (request.data.state_key !== undefined) {\n var stateKey = request.data.state_key === true ? undefined : request.data.state_key.toString();\n\n if (!this.canReceiveStateEvent(request.data.type, stateKey !== null && stateKey !== void 0 ? stateKey : null)) {\n return this.transport.reply(request, {\n error: {\n message: \"Cannot read state events of this type\"\n }\n });\n }\n\n events = this.driver.readStateEvents(request.data.type, stateKey, limit, askRoomIds);\n } else {\n if (!this.canReceiveRoomEvent(request.data.type, request.data.msgtype)) {\n return this.transport.reply(request, {\n error: {\n message: \"Cannot read room events of this type\"\n }\n });\n }\n\n events = this.driver.readRoomEvents(request.data.type, request.data.msgtype, limit, askRoomIds);\n }\n\n return events.then(function (evs) {\n return _this7.transport.reply(request, {\n events: evs\n });\n });\n }\n }, {\n key: \"handleSendEvent\",\n value: function handleSendEvent(request) {\n var _this8 = this;\n\n if (!request.data.type) {\n return this.transport.reply(request, {\n error: {\n message: \"Invalid request - missing event type\"\n }\n });\n }\n\n if (!!request.data.room_id && !this.canUseRoomTimeline(request.data.room_id)) {\n return this.transport.reply(request, {\n error: {\n message: \"Unable to access room timeline: \".concat(request.data.room_id)\n }\n });\n }\n\n var isState = request.data.state_key !== null && request.data.state_key !== undefined;\n var sendEventPromise;\n\n if (isState) {\n if (!this.canSendStateEvent(request.data.type, request.data.state_key)) {\n return this.transport.reply(request, {\n error: {\n message: \"Cannot send state events of this type\"\n }\n });\n }\n\n sendEventPromise = this.driver.sendEvent(request.data.type, request.data.content || {}, request.data.state_key, request.data.room_id);\n } else {\n var content = request.data.content || {};\n var msgtype = content['msgtype'];\n\n if (!this.canSendRoomEvent(request.data.type, msgtype)) {\n return this.transport.reply(request, {\n error: {\n message: \"Cannot send room events of this type\"\n }\n });\n }\n\n sendEventPromise = this.driver.sendEvent(request.data.type, content, null, // not sending a state event\n request.data.room_id);\n }\n\n sendEventPromise.then(function (sentEvent) {\n return _this8.transport.reply(request, {\n room_id: sentEvent.roomId,\n event_id: sentEvent.eventId\n });\n })[\"catch\"](function (e) {\n console.error(\"error sending event: \", e);\n return _this8.transport.reply(request, {\n error: {\n message: \"Error sending event\"\n }\n });\n });\n }\n }, {\n key: \"handleSendToDevice\",\n value: function () {\n var _handleSendToDevice = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(request) {\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n if (request.data.type) {\n _context.next = 5;\n break;\n }\n\n _context.next = 3;\n return this.transport.reply(request, {\n error: {\n message: \"Invalid request - missing event type\"\n }\n });\n\n case 3:\n _context.next = 32;\n break;\n\n case 5:\n if (request.data.messages) {\n _context.next = 10;\n break;\n }\n\n _context.next = 8;\n return this.transport.reply(request, {\n error: {\n message: \"Invalid request - missing event contents\"\n }\n });\n\n case 8:\n _context.next = 32;\n break;\n\n case 10:\n if (!(typeof request.data.encrypted !== \"boolean\")) {\n _context.next = 15;\n break;\n }\n\n _context.next = 13;\n return this.transport.reply(request, {\n error: {\n message: \"Invalid request - missing encryption flag\"\n }\n });\n\n case 13:\n _context.next = 32;\n break;\n\n case 15:\n if (this.canSendToDeviceEvent(request.data.type)) {\n _context.next = 20;\n break;\n }\n\n _context.next = 18;\n return this.transport.reply(request, {\n error: {\n message: \"Cannot send to-device events of this type\"\n }\n });\n\n case 18:\n _context.next = 32;\n break;\n\n case 20:\n _context.prev = 20;\n _context.next = 23;\n return this.driver.sendToDevice(request.data.type, request.data.encrypted, request.data.messages);\n\n case 23:\n _context.next = 25;\n return this.transport.reply(request, {});\n\n case 25:\n _context.next = 32;\n break;\n\n case 27:\n _context.prev = 27;\n _context.t0 = _context[\"catch\"](20);\n console.error(\"error sending to-device event\", _context.t0);\n _context.next = 32;\n return this.transport.reply(request, {\n error: {\n message: \"Error sending event\"\n }\n });\n\n case 32:\n case \"end\":\n return _context.stop();\n }\n }\n }, _callee, this, [[20, 27]]);\n }));\n\n function handleSendToDevice(_x) {\n return _handleSendToDevice.apply(this, arguments);\n }\n\n return handleSendToDevice;\n }()\n }, {\n key: \"pollTurnServers\",\n value: function () {\n var _pollTurnServers = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(turnServers, initialServer) {\n var _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, server;\n\n return _regeneratorRuntime().wrap(function _callee2$(_context2) {\n while (1) {\n switch (_context2.prev = _context2.next) {\n case 0:\n _context2.prev = 0;\n _context2.next = 3;\n return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.UpdateTurnServers, initialServer // it's compatible, but missing the index signature\n );\n\n case 3:\n // Pick the generator up where we left off\n _iteratorAbruptCompletion = false;\n _didIteratorError = false;\n _context2.prev = 5;\n _iterator = _asyncIterator(turnServers);\n\n case 7:\n _context2.next = 9;\n return _iterator.next();\n\n case 9:\n if (!(_iteratorAbruptCompletion = !(_step = _context2.sent).done)) {\n _context2.next = 16;\n break;\n }\n\n server = _step.value;\n _context2.next = 13;\n return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.UpdateTurnServers, server // it's compatible, but missing the index signature\n );\n\n case 13:\n _iteratorAbruptCompletion = false;\n _context2.next = 7;\n break;\n\n case 16:\n _context2.next = 22;\n break;\n\n case 18:\n _context2.prev = 18;\n _context2.t0 = _context2[\"catch\"](5);\n _didIteratorError = true;\n _iteratorError = _context2.t0;\n\n case 22:\n _context2.prev = 22;\n _context2.prev = 23;\n\n if (!(_iteratorAbruptCompletion && _iterator[\"return\"] != null)) {\n _context2.next = 27;\n break;\n }\n\n _context2.next = 27;\n return _iterator[\"return\"]();\n\n case 27:\n _context2.prev = 27;\n\n if (!_didIteratorError) {\n _context2.next = 30;\n break;\n }\n\n throw _iteratorError;\n\n case 30:\n return _context2.finish(27);\n\n case 31:\n return _context2.finish(22);\n\n case 32:\n _context2.next = 37;\n break;\n\n case 34:\n _context2.prev = 34;\n _context2.t1 = _context2[\"catch\"](0);\n console.error(\"error polling for TURN servers\", _context2.t1);\n\n case 37:\n case \"end\":\n return _context2.stop();\n }\n }\n }, _callee2, this, [[0, 34], [5, 18, 22, 32], [23,, 27, 31]]);\n }));\n\n function pollTurnServers(_x2, _x3) {\n return _pollTurnServers.apply(this, arguments);\n }\n\n return pollTurnServers;\n }()\n }, {\n key: \"handleWatchTurnServers\",\n value: function () {\n var _handleWatchTurnServers = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(request) {\n var turnServers, _yield$turnServers$ne, done, value;\n\n return _regeneratorRuntime().wrap(function _callee3$(_context3) {\n while (1) {\n switch (_context3.prev = _context3.next) {\n case 0:\n if (this.hasCapability(_Capabilities.MatrixCapabilities.MSC3846TurnServers)) {\n _context3.next = 5;\n break;\n }\n\n _context3.next = 3;\n return this.transport.reply(request, {\n error: {\n message: \"Missing capability\"\n }\n });\n\n case 3:\n _context3.next = 30;\n break;\n\n case 5:\n if (!this.turnServers) {\n _context3.next = 10;\n break;\n }\n\n _context3.next = 8;\n return this.transport.reply(request, {});\n\n case 8:\n _context3.next = 30;\n break;\n\n case 10:\n _context3.prev = 10;\n turnServers = this.driver.getTurnServers(); // Peek at the first result, so we can at least verify that the\n // client isn't banned from getting TURN servers entirely\n\n _context3.next = 14;\n return turnServers.next();\n\n case 14:\n _yield$turnServers$ne = _context3.sent;\n done = _yield$turnServers$ne.done;\n value = _yield$turnServers$ne.value;\n\n if (!done) {\n _context3.next = 19;\n break;\n }\n\n throw new Error(\"Client refuses to provide any TURN servers\");\n\n case 19:\n _context3.next = 21;\n return this.transport.reply(request, {});\n\n case 21:\n // Start the poll loop, sending the widget the initial result\n this.pollTurnServers(turnServers, value);\n this.turnServers = turnServers;\n _context3.next = 30;\n break;\n\n case 25:\n _context3.prev = 25;\n _context3.t0 = _context3[\"catch\"](10);\n console.error(\"error getting first TURN server results\", _context3.t0);\n _context3.next = 30;\n return this.transport.reply(request, {\n error: {\n message: \"TURN servers not available\"\n }\n });\n\n case 30:\n case \"end\":\n return _context3.stop();\n }\n }\n }, _callee3, this, [[10, 25]]);\n }));\n\n function handleWatchTurnServers(_x4) {\n return _handleWatchTurnServers.apply(this, arguments);\n }\n\n return handleWatchTurnServers;\n }()\n }, {\n key: \"handleUnwatchTurnServers\",\n value: function () {\n var _handleUnwatchTurnServers = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(request) {\n return _regeneratorRuntime().wrap(function _callee4$(_context4) {\n while (1) {\n switch (_context4.prev = _context4.next) {\n case 0:\n if (this.hasCapability(_Capabilities.MatrixCapabilities.MSC3846TurnServers)) {\n _context4.next = 5;\n break;\n }\n\n _context4.next = 3;\n return this.transport.reply(request, {\n error: {\n message: \"Missing capability\"\n }\n });\n\n case 3:\n _context4.next = 15;\n break;\n\n case 5:\n if (this.turnServers) {\n _context4.next = 10;\n break;\n }\n\n _context4.next = 8;\n return this.transport.reply(request, {});\n\n case 8:\n _context4.next = 15;\n break;\n\n case 10:\n _context4.next = 12;\n return this.turnServers[\"return\"](undefined);\n\n case 12:\n this.turnServers = null;\n _context4.next = 15;\n return this.transport.reply(request, {});\n\n case 15:\n case \"end\":\n return _context4.stop();\n }\n }\n }, _callee4, this);\n }));\n\n function handleUnwatchTurnServers(_x5) {\n return _handleUnwatchTurnServers.apply(this, arguments);\n }\n\n return handleUnwatchTurnServers;\n }()\n }, {\n key: \"handleReadRelations\",\n value: function () {\n var _handleReadRelations = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(request) {\n var _this9 = this;\n\n var result, chunk;\n return _regeneratorRuntime().wrap(function _callee5$(_context5) {\n while (1) {\n switch (_context5.prev = _context5.next) {\n case 0:\n if (request.data.event_id) {\n _context5.next = 2;\n break;\n }\n\n return _context5.abrupt(\"return\", this.transport.reply(request, {\n error: {\n message: \"Invalid request - missing event ID\"\n }\n }));\n\n case 2:\n if (!(request.data.limit !== undefined && request.data.limit < 0)) {\n _context5.next = 4;\n break;\n }\n\n return _context5.abrupt(\"return\", this.transport.reply(request, {\n error: {\n message: \"Invalid request - limit out of range\"\n }\n }));\n\n case 4:\n if (!(request.data.room_id !== undefined && !this.canUseRoomTimeline(request.data.room_id))) {\n _context5.next = 6;\n break;\n }\n\n return _context5.abrupt(\"return\", this.transport.reply(request, {\n error: {\n message: \"Unable to access room timeline: \".concat(request.data.room_id)\n }\n }));\n\n case 6:\n _context5.prev = 6;\n _context5.next = 9;\n return this.driver.readEventRelations(request.data.event_id, request.data.room_id, request.data.rel_type, request.data.event_type, request.data.from, request.data.to, request.data.limit, request.data.direction);\n\n case 9:\n result = _context5.sent;\n // only return events that the user has the permission to receive\n chunk = result.chunk.filter(function (e) {\n if (e.state_key !== undefined) {\n return _this9.canReceiveStateEvent(e.type, e.state_key);\n } else {\n return _this9.canReceiveRoomEvent(e.type, e.content['msgtype']);\n }\n });\n return _context5.abrupt(\"return\", this.transport.reply(request, {\n chunk: chunk,\n prev_batch: result.prevBatch,\n next_batch: result.nextBatch\n }));\n\n case 14:\n _context5.prev = 14;\n _context5.t0 = _context5[\"catch\"](6);\n console.error(\"error getting the relations\", _context5.t0);\n _context5.next = 19;\n return this.transport.reply(request, {\n error: {\n message: \"Unexpected error while reading relations\"\n }\n });\n\n case 19:\n case \"end\":\n return _context5.stop();\n }\n }\n }, _callee5, this, [[6, 14]]);\n }));\n\n function handleReadRelations(_x6) {\n return _handleReadRelations.apply(this, arguments);\n }\n\n return handleReadRelations;\n }()\n }, {\n key: \"handleUserDirectorySearch\",\n value: function () {\n var _handleUserDirectorySearch = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(request) {\n var result;\n return _regeneratorRuntime().wrap(function _callee6$(_context6) {\n while (1) {\n switch (_context6.prev = _context6.next) {\n case 0:\n if (this.hasCapability(_Capabilities.MatrixCapabilities.MSC3973UserDirectorySearch)) {\n _context6.next = 2;\n break;\n }\n\n return _context6.abrupt(\"return\", this.transport.reply(request, {\n error: {\n message: \"Missing capability\"\n }\n }));\n\n case 2:\n if (!(typeof request.data.search_term !== 'string')) {\n _context6.next = 4;\n break;\n }\n\n return _context6.abrupt(\"return\", this.transport.reply(request, {\n error: {\n message: \"Invalid request - missing search term\"\n }\n }));\n\n case 4:\n if (!(request.data.limit !== undefined && request.data.limit < 0)) {\n _context6.next = 6;\n break;\n }\n\n return _context6.abrupt(\"return\", this.transport.reply(request, {\n error: {\n message: \"Invalid request - limit out of range\"\n }\n }));\n\n case 6:\n _context6.prev = 6;\n _context6.next = 9;\n return this.driver.searchUserDirectory(request.data.search_term, request.data.limit);\n\n case 9:\n result = _context6.sent;\n return _context6.abrupt(\"return\", this.transport.reply(request, {\n limited: result.limited,\n results: result.results.map(function (r) {\n return {\n user_id: r.userId,\n display_name: r.displayName,\n avatar_url: r.avatarUrl\n };\n })\n }));\n\n case 13:\n _context6.prev = 13;\n _context6.t0 = _context6[\"catch\"](6);\n console.error(\"error searching in the user directory\", _context6.t0);\n _context6.next = 18;\n return this.transport.reply(request, {\n error: {\n message: \"Unexpected error while searching in the user directory\"\n }\n });\n\n case 18:\n case \"end\":\n return _context6.stop();\n }\n }\n }, _callee6, this, [[6, 13]]);\n }));\n\n function handleUserDirectorySearch(_x7) {\n return _handleUserDirectorySearch.apply(this, arguments);\n }\n\n return handleUserDirectorySearch;\n }()\n }, {\n key: \"handleMessage\",\n value: function handleMessage(ev) {\n if (this.isStopped) return;\n var actionEv = new CustomEvent(\"action:\".concat(ev.detail.action), {\n detail: ev.detail,\n cancelable: true\n });\n this.emit(\"action:\".concat(ev.detail.action), actionEv);\n\n if (!actionEv.defaultPrevented) {\n switch (ev.detail.action) {\n case _WidgetApiAction.WidgetApiFromWidgetAction.ContentLoaded:\n return this.handleContentLoadedAction(ev.detail);\n\n case _WidgetApiAction.WidgetApiFromWidgetAction.SupportedApiVersions:\n return this.replyVersions(ev.detail);\n\n case _WidgetApiAction.WidgetApiFromWidgetAction.SendEvent:\n return this.handleSendEvent(ev.detail);\n\n case _WidgetApiAction.WidgetApiFromWidgetAction.SendToDevice:\n return this.handleSendToDevice(ev.detail);\n\n case _WidgetApiAction.WidgetApiFromWidgetAction.GetOpenIDCredentials:\n return this.handleOIDC(ev.detail);\n\n case _WidgetApiAction.WidgetApiFromWidgetAction.MSC2931Navigate:\n return this.handleNavigate(ev.detail);\n\n case _WidgetApiAction.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities:\n return this.handleCapabilitiesRenegotiate(ev.detail);\n\n case _WidgetApiAction.WidgetApiFromWidgetAction.MSC2876ReadEvents:\n return this.handleReadEvents(ev.detail);\n\n case _WidgetApiAction.WidgetApiFromWidgetAction.WatchTurnServers:\n return this.handleWatchTurnServers(ev.detail);\n\n case _WidgetApiAction.WidgetApiFromWidgetAction.UnwatchTurnServers:\n return this.handleUnwatchTurnServers(ev.detail);\n\n case _WidgetApiAction.WidgetApiFromWidgetAction.MSC3869ReadRelations:\n return this.handleReadRelations(ev.detail);\n\n case _WidgetApiAction.WidgetApiFromWidgetAction.MSC3973UserDirectorySearch:\n return this.handleUserDirectorySearch(ev.detail);\n\n default:\n return this.transport.reply(ev.detail, {\n error: {\n message: \"Unknown or unsupported action: \" + ev.detail.action\n }\n });\n }\n }\n }\n /**\n * Takes a screenshot of the widget.\n * @returns Resolves to the widget's screenshot.\n * @throws Throws if there is a problem.\n */\n\n }, {\n key: \"takeScreenshot\",\n value: function takeScreenshot() {\n return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.TakeScreenshot, {});\n }\n /**\n * Alerts the widget to whether or not it is currently visible.\n * @param {boolean} isVisible Whether the widget is visible or not.\n * @returns {Promise} Resolves when the widget acknowledges the update.\n */\n\n }, {\n key: \"updateVisibility\",\n value: function updateVisibility(isVisible) {\n return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.UpdateVisibility, {\n visible: isVisible\n });\n }\n }, {\n key: \"sendWidgetConfig\",\n value: function sendWidgetConfig(data) {\n return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.WidgetConfig, data).then();\n }\n }, {\n key: \"notifyModalWidgetButtonClicked\",\n value: function notifyModalWidgetButtonClicked(id) {\n return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.ButtonClicked, {\n id: id\n }).then();\n }\n }, {\n key: \"notifyModalWidgetClose\",\n value: function notifyModalWidgetClose(data) {\n return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.CloseModalWidget, data).then();\n }\n /**\n * Feeds an event to the widget. If the widget is not able to accept the event due to\n * permissions, this will no-op and return calmly. If the widget failed to handle the\n * event, this will raise an error.\n * @param {IRoomEvent} rawEvent The event to (try to) send to the widget.\n * @param {string} currentViewedRoomId The room ID the user is currently interacting with.\n * Not the room ID of the event.\n * @returns {Promise} Resolves when complete, rejects if there was an error sending.\n */\n\n }, {\n key: \"feedEvent\",\n value: function () {\n var _feedEvent = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(rawEvent, currentViewedRoomId) {\n var _rawEvent$content;\n\n return _regeneratorRuntime().wrap(function _callee7$(_context7) {\n while (1) {\n switch (_context7.prev = _context7.next) {\n case 0:\n if (!(rawEvent.room_id !== currentViewedRoomId && !this.canUseRoomTimeline(rawEvent.room_id))) {\n _context7.next = 2;\n break;\n }\n\n return _context7.abrupt(\"return\");\n\n case 2:\n if (!(rawEvent.state_key !== undefined && rawEvent.state_key !== null)) {\n _context7.next = 7;\n break;\n }\n\n if (this.canReceiveStateEvent(rawEvent.type, rawEvent.state_key)) {\n _context7.next = 5;\n break;\n }\n\n return _context7.abrupt(\"return\");\n\n case 5:\n _context7.next = 9;\n break;\n\n case 7:\n if (this.canReceiveRoomEvent(rawEvent.type, (_rawEvent$content = rawEvent.content) === null || _rawEvent$content === void 0 ? void 0 : _rawEvent$content[\"msgtype\"])) {\n _context7.next = 9;\n break;\n }\n\n return _context7.abrupt(\"return\");\n\n case 9:\n _context7.next = 11;\n return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.SendEvent, rawEvent // it's compatible, but missing the index signature\n );\n\n case 11:\n case \"end\":\n return _context7.stop();\n }\n }\n }, _callee7, this);\n }));\n\n function feedEvent(_x8, _x9) {\n return _feedEvent.apply(this, arguments);\n }\n\n return feedEvent;\n }()\n /**\n * Feeds a to-device event to the widget. If the widget is not able to accept the\n * event due to permissions, this will no-op and return calmly. If the widget failed\n * to handle the event, this will raise an error.\n * @param {IRoomEvent} rawEvent The event to (try to) send to the widget.\n * @param {boolean} encrypted Whether the event contents were encrypted.\n * @returns {Promise} Resolves when complete, rejects if there was an error sending.\n */\n\n }, {\n key: \"feedToDevice\",\n value: function () {\n var _feedToDevice = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(rawEvent, encrypted) {\n return _regeneratorRuntime().wrap(function _callee8$(_context8) {\n while (1) {\n switch (_context8.prev = _context8.next) {\n case 0:\n if (!this.canReceiveToDeviceEvent(rawEvent.type)) {\n _context8.next = 3;\n break;\n }\n\n _context8.next = 3;\n return this.transport.send(_WidgetApiAction.WidgetApiToWidgetAction.SendToDevice, // it's compatible, but missing the index signature\n _objectSpread(_objectSpread({}, rawEvent), {}, {\n encrypted: encrypted\n }));\n\n case 3:\n case \"end\":\n return _context8.stop();\n }\n }\n }, _callee8, this);\n }));\n\n function feedToDevice(_x10, _x11) {\n return _feedToDevice.apply(this, arguments);\n }\n\n return feedToDevice;\n }()\n }]);\n\n return ClientWidgetApi;\n}(_events.EventEmitter);\n\nexports.ClientWidgetApi = ClientWidgetApi;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.Symbols = void 0;\n\n/*\n * Copyright 2021 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar Symbols;\nexports.Symbols = Symbols;\n\n(function (Symbols) {\n Symbols[\"AnyRoom\"] = \"*\";\n})(Symbols || (exports.Symbols = Symbols = {}));", - "\"use strict\";\n\nfunction _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); }\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.WidgetApi = void 0;\n\nvar _events = require(\"events\");\n\nvar _WidgetApiDirection = require(\"./interfaces/WidgetApiDirection\");\n\nvar _ApiVersion = require(\"./interfaces/ApiVersion\");\n\nvar _PostmessageTransport = require(\"./transport/PostmessageTransport\");\n\nvar _WidgetApiAction = require(\"./interfaces/WidgetApiAction\");\n\nvar _GetOpenIDAction = require(\"./interfaces/GetOpenIDAction\");\n\nvar _WidgetType = require(\"./interfaces/WidgetType\");\n\nvar _ModalWidgetActions = require(\"./interfaces/ModalWidgetActions\");\n\nvar _WidgetEventCapability = require(\"./models/WidgetEventCapability\");\n\nvar _Symbols = require(\"./Symbols\");\n\nfunction _regeneratorRuntime() { \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $Symbol = \"function\" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || \"@@iterator\", asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\", toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, \"\"); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return generator._invoke = function (innerFn, self, context) { var state = \"suspendedStart\"; return function (method, arg) { if (\"executing\" === state) throw new Error(\"Generator is already running\"); if (\"completed\" === state) { if (\"throw\" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) { if (\"suspendedStart\" === state) throw state = \"completed\", context.arg; context.dispatchException(context.arg); } else \"return\" === context.method && context.abrupt(\"return\", context.arg); state = \"executing\"; var record = tryCatch(innerFn, self, context); if (\"normal\" === record.type) { if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg); } }; }(innerFn, self, context), generator; } function tryCatch(fn, obj, arg) { try { return { type: \"normal\", arg: fn.call(obj, arg) }; } catch (err) { return { type: \"throw\", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { [\"next\", \"throw\", \"return\"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (\"throw\" !== record.type) { var result = record.arg, value = result.value; return value && \"object\" == _typeof(value) && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke(\"next\", value, resolve, reject); }, function (err) { invoke(\"throw\", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke(\"throw\", error, resolve, reject); }); } reject(record.arg); } var previousPromise; this._invoke = function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); }; } function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (undefined === method) { if (context.delegate = null, \"throw\" === context.method) { if (delegate.iterator[\"return\"] && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method)) return ContinueSentinel; context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a 'throw' method\"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = \"normal\", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: \"root\" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if (\"function\" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, \"constructor\", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, \"constructor\", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) { var ctor = \"function\" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, \"toString\", function () { return \"[object Generator]\"; }), exports.keys = function (object) { var keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if (\"throw\" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if (\"root\" === entry.tryLoc) return handle(\"end\"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, \"catchLoc\"), hasFinally = hasOwn.call(entry, \"finallyLoc\"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error(\"try statement without catch or finally\"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, \"finallyLoc\") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if (\"throw\" === record.type) throw record.arg; return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, \"catch\": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (\"throw\" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }\n\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }\n\nfunction _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err); } _next(undefined); }); }; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _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); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _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); }; }\n\nfunction _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); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _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; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _awaitAsyncGenerator(value) { return new _AwaitValue(value); }\n\nfunction _wrapAsyncGenerator(fn) { return function () { return new _AsyncGenerator(fn.apply(this, arguments)); }; }\n\nfunction _AsyncGenerator(gen) { var front, back; function send(key, arg) { return new Promise(function (resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null }; if (back) { back = back.next = request; } else { front = back = request; resume(key, arg); } }); } function resume(key, arg) { try { var result = gen[key](arg); var value = result.value; var wrappedAwait = value instanceof _AwaitValue; Promise.resolve(wrappedAwait ? value.wrapped : value).then(function (arg) { if (wrappedAwait) { resume(key === \"return\" ? \"return\" : \"next\", arg); return; } settle(result.done ? \"return\" : \"normal\", arg); }, function (err) { resume(\"throw\", err); }); } catch (err) { settle(\"throw\", err); } } function settle(type, value) { switch (type) { case \"return\": front.resolve({ value: value, done: true }); break; case \"throw\": front.reject(value); break; default: front.resolve({ value: value, done: false }); break; } front = front.next; if (front) { resume(front.key, front.arg); } else { back = null; } } this._invoke = send; if (typeof gen[\"return\"] !== \"function\") { this[\"return\"] = undefined; } }\n\n_AsyncGenerator.prototype[typeof Symbol === \"function\" && Symbol.asyncIterator || \"@@asyncIterator\"] = function () { return this; };\n\n_AsyncGenerator.prototype.next = function (arg) { return this._invoke(\"next\", arg); };\n\n_AsyncGenerator.prototype[\"throw\"] = function (arg) { return this._invoke(\"throw\", arg); };\n\n_AsyncGenerator.prototype[\"return\"] = function (arg) { return this._invoke(\"return\", arg); };\n\nfunction _AwaitValue(value) { this.wrapped = value; }\n\n/**\n * API handler for widgets. This raises events for each action\n * received as `action:${action}` (eg: \"action:screenshot\").\n * Default handling can be prevented by using preventDefault()\n * on the raised event. The default handling varies for each\n * action: ones which the SDK can handle safely are acknowledged\n * appropriately and ones which are unhandled (custom or require\n * the widget to do something) are rejected with an error.\n *\n * Events which are preventDefault()ed must reply using the\n * transport. The events raised will have a detail of an\n * IWidgetApiRequest interface.\n *\n * When the WidgetApi is ready to start sending requests, it will\n * raise a \"ready\" CustomEvent. After the ready event fires, actions\n * can be sent and the transport will be ready.\n */\nvar WidgetApi = /*#__PURE__*/function (_EventEmitter) {\n _inherits(WidgetApi, _EventEmitter);\n\n var _super = _createSuper(WidgetApi);\n\n /**\n * Creates a new API handler for the given widget.\n * @param {string} widgetId The widget ID to listen for. If not supplied then\n * the API will use the widget ID from the first valid request it receives.\n * @param {string} clientOrigin The origin of the client, or null if not known.\n */\n function WidgetApi() {\n var _this2;\n\n var widgetId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n var clientOrigin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n\n _classCallCheck(this, WidgetApi);\n\n _this2 = _super.call(this);\n _this2.clientOrigin = clientOrigin;\n\n _defineProperty(_assertThisInitialized(_this2), \"transport\", void 0);\n\n _defineProperty(_assertThisInitialized(_this2), \"capabilitiesFinished\", false);\n\n _defineProperty(_assertThisInitialized(_this2), \"supportsMSC2974Renegotiate\", false);\n\n _defineProperty(_assertThisInitialized(_this2), \"requestedCapabilities\", []);\n\n _defineProperty(_assertThisInitialized(_this2), \"approvedCapabilities\", void 0);\n\n _defineProperty(_assertThisInitialized(_this2), \"cachedClientVersions\", void 0);\n\n _defineProperty(_assertThisInitialized(_this2), \"turnServerWatchers\", 0);\n\n if (!window.parent) {\n throw new Error(\"No parent window. This widget doesn't appear to be embedded properly.\");\n }\n\n _this2.transport = new _PostmessageTransport.PostmessageTransport(_WidgetApiDirection.WidgetApiDirection.FromWidget, widgetId, window.parent, window);\n _this2.transport.targetOrigin = clientOrigin;\n\n _this2.transport.on(\"message\", _this2.handleMessage.bind(_assertThisInitialized(_this2)));\n\n return _this2;\n }\n /**\n * Determines if the widget was granted a particular capability. Note that on\n * clients where the capabilities are not fed back to the widget this function\n * will rely on requested capabilities instead.\n * @param {Capability} capability The capability to check for approval of.\n * @returns {boolean} True if the widget has approval for the given capability.\n */\n\n\n _createClass(WidgetApi, [{\n key: \"hasCapability\",\n value: function hasCapability(capability) {\n if (Array.isArray(this.approvedCapabilities)) {\n return this.approvedCapabilities.includes(capability);\n }\n\n return this.requestedCapabilities.includes(capability);\n }\n /**\n * Request a capability from the client. It is not guaranteed to be allowed,\n * but will be asked for.\n * @param {Capability} capability The capability to request.\n * @throws Throws if the capabilities negotiation has already started and the\n * widget is unable to request additional capabilities.\n */\n\n }, {\n key: \"requestCapability\",\n value: function requestCapability(capability) {\n if (this.capabilitiesFinished && !this.supportsMSC2974Renegotiate) {\n throw new Error(\"Capabilities have already been negotiated\");\n }\n\n this.requestedCapabilities.push(capability);\n }\n /**\n * Request capabilities from the client. They are not guaranteed to be allowed,\n * but will be asked for if the negotiation has not already happened.\n * @param {Capability[]} capabilities The capabilities to request.\n * @throws Throws if the capabilities negotiation has already started.\n */\n\n }, {\n key: \"requestCapabilities\",\n value: function requestCapabilities(capabilities) {\n var _this3 = this;\n\n capabilities.forEach(function (cap) {\n return _this3.requestCapability(cap);\n });\n }\n /**\n * Requests the capability to interact with rooms other than the user's currently\n * viewed room. Applies to event receiving and sending.\n * @param {string | Symbols.AnyRoom} roomId The room ID, or `Symbols.AnyRoom` to\n * denote all known rooms.\n */\n\n }, {\n key: \"requestCapabilityForRoomTimeline\",\n value: function requestCapabilityForRoomTimeline(roomId) {\n this.requestCapability(\"org.matrix.msc2762.timeline:\".concat(roomId));\n }\n /**\n * Requests the capability to send a given state event with optional explicit\n * state key. It is not guaranteed to be allowed, but will be asked for if the\n * negotiation has not already happened.\n * @param {string} eventType The state event type to ask for.\n * @param {string} stateKey If specified, the specific state key to request.\n * Otherwise all state keys will be requested.\n */\n\n }, {\n key: \"requestCapabilityToSendState\",\n value: function requestCapabilityToSendState(eventType, stateKey) {\n this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forStateEvent(_WidgetEventCapability.EventDirection.Send, eventType, stateKey).raw);\n }\n /**\n * Requests the capability to receive a given state event with optional explicit\n * state key. It is not guaranteed to be allowed, but will be asked for if the\n * negotiation has not already happened.\n * @param {string} eventType The state event type to ask for.\n * @param {string} stateKey If specified, the specific state key to request.\n * Otherwise all state keys will be requested.\n */\n\n }, {\n key: \"requestCapabilityToReceiveState\",\n value: function requestCapabilityToReceiveState(eventType, stateKey) {\n this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forStateEvent(_WidgetEventCapability.EventDirection.Receive, eventType, stateKey).raw);\n }\n /**\n * Requests the capability to send a given to-device event. It is not\n * guaranteed to be allowed, but will be asked for if the negotiation has\n * not already happened.\n * @param {string} eventType The room event type to ask for.\n */\n\n }, {\n key: \"requestCapabilityToSendToDevice\",\n value: function requestCapabilityToSendToDevice(eventType) {\n this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forToDeviceEvent(_WidgetEventCapability.EventDirection.Send, eventType).raw);\n }\n /**\n * Requests the capability to receive a given to-device event. It is not\n * guaranteed to be allowed, but will be asked for if the negotiation has\n * not already happened.\n * @param {string} eventType The room event type to ask for.\n */\n\n }, {\n key: \"requestCapabilityToReceiveToDevice\",\n value: function requestCapabilityToReceiveToDevice(eventType) {\n this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forToDeviceEvent(_WidgetEventCapability.EventDirection.Receive, eventType).raw);\n }\n /**\n * Requests the capability to send a given room event. It is not guaranteed to be\n * allowed, but will be asked for if the negotiation has not already happened.\n * @param {string} eventType The room event type to ask for.\n */\n\n }, {\n key: \"requestCapabilityToSendEvent\",\n value: function requestCapabilityToSendEvent(eventType) {\n this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forRoomEvent(_WidgetEventCapability.EventDirection.Send, eventType).raw);\n }\n /**\n * Requests the capability to receive a given room event. It is not guaranteed to be\n * allowed, but will be asked for if the negotiation has not already happened.\n * @param {string} eventType The room event type to ask for.\n */\n\n }, {\n key: \"requestCapabilityToReceiveEvent\",\n value: function requestCapabilityToReceiveEvent(eventType) {\n this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forRoomEvent(_WidgetEventCapability.EventDirection.Receive, eventType).raw);\n }\n /**\n * Requests the capability to send a given message event with optional explicit\n * `msgtype`. It is not guaranteed to be allowed, but will be asked for if the\n * negotiation has not already happened.\n * @param {string} msgtype If specified, the specific msgtype to request.\n * Otherwise all message types will be requested.\n */\n\n }, {\n key: \"requestCapabilityToSendMessage\",\n value: function requestCapabilityToSendMessage(msgtype) {\n this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forRoomMessageEvent(_WidgetEventCapability.EventDirection.Send, msgtype).raw);\n }\n /**\n * Requests the capability to receive a given message event with optional explicit\n * `msgtype`. It is not guaranteed to be allowed, but will be asked for if the\n * negotiation has not already happened.\n * @param {string} msgtype If specified, the specific msgtype to request.\n * Otherwise all message types will be requested.\n */\n\n }, {\n key: \"requestCapabilityToReceiveMessage\",\n value: function requestCapabilityToReceiveMessage(msgtype) {\n this.requestCapability(_WidgetEventCapability.WidgetEventCapability.forRoomMessageEvent(_WidgetEventCapability.EventDirection.Receive, msgtype).raw);\n }\n /**\n * Requests an OpenID Connect token from the client for the currently logged in\n * user. This token can be validated server-side with the federation API. Note\n * that the widget is responsible for validating the token and caching any results\n * it needs.\n * @returns {Promise} Resolves to a token for verification.\n * @throws Throws if the user rejected the request or the request failed.\n */\n\n }, {\n key: \"requestOpenIDConnectToken\",\n value: function requestOpenIDConnectToken() {\n var _this4 = this;\n\n return new Promise(function (resolve, reject) {\n _this4.transport.sendComplete(_WidgetApiAction.WidgetApiFromWidgetAction.GetOpenIDCredentials, {}).then(function (response) {\n var rdata = response.response;\n\n if (rdata.state === _GetOpenIDAction.OpenIDRequestState.Allowed) {\n resolve(rdata);\n } else if (rdata.state === _GetOpenIDAction.OpenIDRequestState.Blocked) {\n reject(new Error(\"User declined to verify their identity\"));\n } else if (rdata.state === _GetOpenIDAction.OpenIDRequestState.PendingUserConfirmation) {\n var handlerFn = function handlerFn(ev) {\n ev.preventDefault();\n var request = ev.detail;\n if (request.data.original_request_id !== response.requestId) return;\n\n if (request.data.state === _GetOpenIDAction.OpenIDRequestState.Allowed) {\n resolve(request.data);\n\n _this4.transport.reply(request, {}); // ack\n\n } else if (request.data.state === _GetOpenIDAction.OpenIDRequestState.Blocked) {\n reject(new Error(\"User declined to verify their identity\"));\n\n _this4.transport.reply(request, {}); // ack\n\n } else {\n reject(new Error(\"Invalid state on reply: \" + rdata.state));\n\n _this4.transport.reply(request, {\n error: {\n message: \"Invalid state\"\n }\n });\n }\n\n _this4.off(\"action:\".concat(_WidgetApiAction.WidgetApiToWidgetAction.OpenIDCredentials), handlerFn);\n };\n\n _this4.on(\"action:\".concat(_WidgetApiAction.WidgetApiToWidgetAction.OpenIDCredentials), handlerFn);\n } else {\n reject(new Error(\"Invalid state: \" + rdata.state));\n }\n })[\"catch\"](reject);\n });\n }\n /**\n * Asks the client for additional capabilities. Capabilities can be queued for this\n * request with the requestCapability() functions.\n * @returns {Promise} Resolves when complete. Note that the promise resolves when\n * the capabilities request has gone through, not when the capabilities are approved/denied.\n * Use the WidgetApiToWidgetAction.NotifyCapabilities action to detect changes.\n */\n\n }, {\n key: \"updateRequestedCapabilities\",\n value: function updateRequestedCapabilities() {\n return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities, {\n capabilities: this.requestedCapabilities\n }).then();\n }\n /**\n * Tell the client that the content has been loaded.\n * @returns {Promise} Resolves when the client acknowledges the request.\n */\n\n }, {\n key: \"sendContentLoaded\",\n value: function sendContentLoaded() {\n return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.ContentLoaded, {}).then();\n }\n /**\n * Sends a sticker to the client.\n * @param {IStickerActionRequestData} sticker The sticker to send.\n * @returns {Promise} Resolves when the client acknowledges the request.\n */\n\n }, {\n key: \"sendSticker\",\n value: function sendSticker(sticker) {\n return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SendSticker, sticker).then();\n }\n /**\n * Asks the client to set the always-on-screen status for this widget.\n * @param {boolean} value The new state to request.\n * @returns {Promise} Resolve with true if the client was able to fulfill\n * the request, resolves to false otherwise. Rejects if an error occurred.\n */\n\n }, {\n key: \"setAlwaysOnScreen\",\n value: function setAlwaysOnScreen(value) {\n return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.UpdateAlwaysOnScreen, {\n value: value\n }).then(function (res) {\n return res.success;\n });\n }\n /**\n * Opens a modal widget.\n * @param {string} url The URL to the modal widget.\n * @param {string} name The name of the widget.\n * @param {IModalWidgetOpenRequestDataButton[]} buttons The buttons to have on the widget.\n * @param {IModalWidgetCreateData} data Data to supply to the modal widget.\n * @param {WidgetType} type The type of modal widget.\n * @returns {Promise} Resolves when the modal widget has been opened.\n */\n\n }, {\n key: \"openModalWidget\",\n value: function openModalWidget(url, name) {\n var buttons = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];\n var data = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n var type = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : _WidgetType.MatrixWidgetType.Custom;\n return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.OpenModalWidget, {\n type: type,\n url: url,\n name: name,\n buttons: buttons,\n data: data\n }).then();\n }\n /**\n * Closes the modal widget. The widget's session will be terminated shortly after.\n * @param {IModalWidgetReturnData} data Optional data to close the modal widget with.\n * @returns {Promise} Resolves when complete.\n */\n\n }, {\n key: \"closeModalWidget\",\n value: function closeModalWidget() {\n var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.CloseModalWidget, data).then();\n }\n }, {\n key: \"sendRoomEvent\",\n value: function sendRoomEvent(eventType, content, roomId) {\n return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SendEvent, {\n type: eventType,\n content: content,\n room_id: roomId\n });\n }\n }, {\n key: \"sendStateEvent\",\n value: function sendStateEvent(eventType, stateKey, content, roomId) {\n return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SendEvent, {\n type: eventType,\n content: content,\n state_key: stateKey,\n room_id: roomId\n });\n }\n /**\n * Sends a to-device event.\n * @param {string} eventType The type of events being sent.\n * @param {boolean} encrypted Whether to encrypt the message contents.\n * @param {Object} contentMap A map from user IDs to device IDs to message contents.\n * @returns {Promise} Resolves when complete.\n */\n\n }, {\n key: \"sendToDevice\",\n value: function sendToDevice(eventType, encrypted, contentMap) {\n return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SendToDevice, {\n type: eventType,\n encrypted: encrypted,\n messages: contentMap\n });\n }\n }, {\n key: \"readRoomEvents\",\n value: function readRoomEvents(eventType, limit, msgtype, roomIds) {\n var data = {\n type: eventType,\n msgtype: msgtype\n };\n\n if (limit !== undefined) {\n data.limit = limit;\n }\n\n if (roomIds) {\n if (roomIds.includes(_Symbols.Symbols.AnyRoom)) {\n data.room_ids = _Symbols.Symbols.AnyRoom;\n } else {\n data.room_ids = roomIds;\n }\n }\n\n return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC2876ReadEvents, data).then(function (r) {\n return r.events;\n });\n }\n /**\n * Reads all related events given a known eventId.\n * @param eventId The id of the parent event to be read.\n * @param roomId The room to look within. When undefined, the user's currently\n * viewed room.\n * @param relationType The relationship type of child events to search for.\n * When undefined, all relations are returned.\n * @param eventType The event type of child events to search for. When undefined,\n * all related events are returned.\n * @param limit The maximum number of events to retrieve per room. If not\n * supplied, the server will apply a default limit.\n * @param from The pagination token to start returning results from, as\n * received from a previous call. If not supplied, results start at the most\n * recent topological event known to the server.\n * @param to The pagination token to stop returning results at. If not\n * supplied, results continue up to limit or until there are no more events.\n * @param direction The direction to search for according to MSC3715.\n * @returns Resolves to the room relations.\n */\n\n }, {\n key: \"readEventRelations\",\n value: function () {\n var _readEventRelations = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(eventId, roomId, relationType, eventType, limit, from, to, direction) {\n var versions, data;\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n _context.next = 2;\n return this.getClientVersions();\n\n case 2:\n versions = _context.sent;\n\n if (versions.includes(_ApiVersion.UnstableApiVersion.MSC3869)) {\n _context.next = 5;\n break;\n }\n\n throw new Error(\"The read_relations action is not supported by the client.\");\n\n case 5:\n data = {\n event_id: eventId,\n rel_type: relationType,\n event_type: eventType,\n room_id: roomId,\n to: to,\n from: from,\n limit: limit,\n direction: direction\n };\n return _context.abrupt(\"return\", this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC3869ReadRelations, data));\n\n case 7:\n case \"end\":\n return _context.stop();\n }\n }\n }, _callee, this);\n }));\n\n function readEventRelations(_x, _x2, _x3, _x4, _x5, _x6, _x7, _x8) {\n return _readEventRelations.apply(this, arguments);\n }\n\n return readEventRelations;\n }()\n }, {\n key: \"readStateEvents\",\n value: function readStateEvents(eventType, limit, stateKey, roomIds) {\n var data = {\n type: eventType,\n state_key: stateKey === undefined ? true : stateKey\n };\n\n if (limit !== undefined) {\n data.limit = limit;\n }\n\n if (roomIds) {\n if (roomIds.includes(_Symbols.Symbols.AnyRoom)) {\n data.room_ids = _Symbols.Symbols.AnyRoom;\n } else {\n data.room_ids = roomIds;\n }\n }\n\n return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC2876ReadEvents, data).then(function (r) {\n return r.events;\n });\n }\n /**\n * Sets a button as disabled or enabled on the modal widget. Buttons are enabled by default.\n * @param {ModalButtonID} buttonId The button ID to enable/disable.\n * @param {boolean} isEnabled Whether or not the button is enabled.\n * @returns {Promise} Resolves when complete.\n * @throws Throws if the button cannot be disabled, or the client refuses to disable the button.\n */\n\n }, {\n key: \"setModalButtonEnabled\",\n value: function setModalButtonEnabled(buttonId, isEnabled) {\n if (buttonId === _ModalWidgetActions.BuiltInModalButtonID.Close) {\n throw new Error(\"The close button cannot be disabled\");\n }\n\n return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SetModalButtonEnabled, {\n button: buttonId,\n enabled: isEnabled\n }).then();\n }\n /**\n * Attempts to navigate the client to the given URI. This can only be called with Matrix URIs\n * (currently only matrix.to, but in future a Matrix URI scheme will be defined).\n * @param {string} uri The URI to navigate to.\n * @returns {Promise} Resolves when complete.\n * @throws Throws if the URI is invalid or cannot be processed.\n * @deprecated This currently relies on an unstable MSC (MSC2931).\n */\n\n }, {\n key: \"navigateTo\",\n value: function navigateTo(uri) {\n if (!uri || !uri.startsWith(\"https://matrix.to/#\")) {\n throw new Error(\"Invalid matrix.to URI\");\n }\n\n return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC2931Navigate, {\n uri: uri\n }).then();\n }\n /**\n * Starts watching for TURN servers, yielding an initial set of credentials as soon as possible,\n * and thereafter yielding new credentials whenever the previous ones expire.\n * @yields {ITurnServer} The TURN server URIs and credentials currently available to the widget.\n */\n\n }, {\n key: \"getTurnServers\",\n value: function getTurnServers() {\n var _this = this;\n\n return _wrapAsyncGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {\n var setTurnServer, onUpdateTurnServers;\n return _regeneratorRuntime().wrap(function _callee3$(_context3) {\n while (1) {\n switch (_context3.prev = _context3.next) {\n case 0:\n onUpdateTurnServers = /*#__PURE__*/function () {\n var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(ev) {\n return _regeneratorRuntime().wrap(function _callee2$(_context2) {\n while (1) {\n switch (_context2.prev = _context2.next) {\n case 0:\n ev.preventDefault();\n setTurnServer(ev.detail.data);\n _context2.next = 4;\n return _this.transport.reply(ev.detail, {});\n\n case 4:\n case \"end\":\n return _context2.stop();\n }\n }\n }, _callee2);\n }));\n\n return function onUpdateTurnServers(_x9) {\n return _ref.apply(this, arguments);\n };\n }(); // Start listening for updates before we even start watching, to catch\n // TURN data that is sent immediately\n\n\n _this.on(\"action:\".concat(_WidgetApiAction.WidgetApiToWidgetAction.UpdateTurnServers), onUpdateTurnServers); // Only send the 'watch' action if we aren't already watching\n\n\n if (!(_this.turnServerWatchers === 0)) {\n _context3.next = 12;\n break;\n }\n\n _context3.prev = 3;\n _context3.next = 6;\n return _awaitAsyncGenerator(_this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.WatchTurnServers, {}));\n\n case 6:\n _context3.next = 12;\n break;\n\n case 8:\n _context3.prev = 8;\n _context3.t0 = _context3[\"catch\"](3);\n\n _this.off(\"action:\".concat(_WidgetApiAction.WidgetApiToWidgetAction.UpdateTurnServers), onUpdateTurnServers);\n\n throw _context3.t0;\n\n case 12:\n _this.turnServerWatchers++;\n _context3.prev = 13;\n\n case 14:\n if (!true) {\n _context3.next = 21;\n break;\n }\n\n _context3.next = 17;\n return _awaitAsyncGenerator(new Promise(function (resolve) {\n return setTurnServer = resolve;\n }));\n\n case 17:\n _context3.next = 19;\n return _context3.sent;\n\n case 19:\n _context3.next = 14;\n break;\n\n case 21:\n _context3.prev = 21;\n\n // The loop was broken by the caller - clean up\n _this.off(\"action:\".concat(_WidgetApiAction.WidgetApiToWidgetAction.UpdateTurnServers), onUpdateTurnServers); // Since sending the 'unwatch' action will end updates for all other\n // consumers, only send it if we're the only consumer remaining\n\n\n _this.turnServerWatchers--;\n\n if (!(_this.turnServerWatchers === 0)) {\n _context3.next = 27;\n break;\n }\n\n _context3.next = 27;\n return _awaitAsyncGenerator(_this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.UnwatchTurnServers, {}));\n\n case 27:\n return _context3.finish(21);\n\n case 28:\n case \"end\":\n return _context3.stop();\n }\n }\n }, _callee3, null, [[3, 8], [13,, 21, 28]]);\n }))();\n }\n /**\n * Search for users in the user directory.\n * @param searchTerm The term to search for.\n * @param limit The maximum number of results to return. If not supplied, the\n * @returns Resolves to the search results.\n */\n\n }, {\n key: \"searchUserDirectory\",\n value: function () {\n var _searchUserDirectory = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(searchTerm, limit) {\n var versions, data;\n return _regeneratorRuntime().wrap(function _callee4$(_context4) {\n while (1) {\n switch (_context4.prev = _context4.next) {\n case 0:\n _context4.next = 2;\n return this.getClientVersions();\n\n case 2:\n versions = _context4.sent;\n\n if (versions.includes(_ApiVersion.UnstableApiVersion.MSC3973)) {\n _context4.next = 5;\n break;\n }\n\n throw new Error(\"The user_directory_search action is not supported by the client.\");\n\n case 5:\n data = {\n search_term: searchTerm,\n limit: limit\n };\n return _context4.abrupt(\"return\", this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.MSC3973UserDirectorySearch, data));\n\n case 7:\n case \"end\":\n return _context4.stop();\n }\n }\n }, _callee4, this);\n }));\n\n function searchUserDirectory(_x10, _x11) {\n return _searchUserDirectory.apply(this, arguments);\n }\n\n return searchUserDirectory;\n }()\n /**\n * Starts the communication channel. This should be done early to ensure\n * that messages are not missed. Communication can only be stopped by the client.\n */\n\n }, {\n key: \"start\",\n value: function start() {\n var _this5 = this;\n\n this.transport.start();\n this.getClientVersions().then(function (v) {\n if (v.includes(_ApiVersion.UnstableApiVersion.MSC2974)) {\n _this5.supportsMSC2974Renegotiate = true;\n }\n });\n }\n }, {\n key: \"handleMessage\",\n value: function handleMessage(ev) {\n var actionEv = new CustomEvent(\"action:\".concat(ev.detail.action), {\n detail: ev.detail,\n cancelable: true\n });\n this.emit(\"action:\".concat(ev.detail.action), actionEv);\n\n if (!actionEv.defaultPrevented) {\n switch (ev.detail.action) {\n case _WidgetApiAction.WidgetApiToWidgetAction.SupportedApiVersions:\n return this.replyVersions(ev.detail);\n\n case _WidgetApiAction.WidgetApiToWidgetAction.Capabilities:\n return this.handleCapabilities(ev.detail);\n\n case _WidgetApiAction.WidgetApiToWidgetAction.UpdateVisibility:\n return this.transport.reply(ev.detail, {});\n // ack to avoid error spam\n\n case _WidgetApiAction.WidgetApiToWidgetAction.NotifyCapabilities:\n return this.transport.reply(ev.detail, {});\n // ack to avoid error spam\n\n default:\n return this.transport.reply(ev.detail, {\n error: {\n message: \"Unknown or unsupported action: \" + ev.detail.action\n }\n });\n }\n }\n }\n }, {\n key: \"replyVersions\",\n value: function replyVersions(request) {\n this.transport.reply(request, {\n supported_versions: _ApiVersion.CurrentApiVersions\n });\n }\n }, {\n key: \"getClientVersions\",\n value: function getClientVersions() {\n var _this6 = this;\n\n if (Array.isArray(this.cachedClientVersions)) {\n return Promise.resolve(this.cachedClientVersions);\n }\n\n return this.transport.send(_WidgetApiAction.WidgetApiFromWidgetAction.SupportedApiVersions, {}).then(function (r) {\n _this6.cachedClientVersions = r.supported_versions;\n return r.supported_versions;\n })[\"catch\"](function (e) {\n console.warn(\"non-fatal error getting supported client versions: \", e);\n return [];\n });\n }\n }, {\n key: \"handleCapabilities\",\n value: function handleCapabilities(request) {\n var _this7 = this;\n\n if (this.capabilitiesFinished) {\n return this.transport.reply(request, {\n error: {\n message: \"Capability negotiation already completed\"\n }\n });\n } // See if we can expect a capabilities notification or not\n\n\n return this.getClientVersions().then(function (v) {\n if (v.includes(_ApiVersion.UnstableApiVersion.MSC2871)) {\n _this7.once(\"action:\".concat(_WidgetApiAction.WidgetApiToWidgetAction.NotifyCapabilities), function (ev) {\n _this7.approvedCapabilities = ev.detail.data.approved;\n\n _this7.emit(\"ready\");\n });\n } else {\n // if we can't expect notification, we're as done as we can be\n _this7.emit(\"ready\");\n } // in either case, reply to that capabilities request\n\n\n _this7.capabilitiesFinished = true;\n return _this7.transport.reply(request, {\n capabilities: _this7.requestedCapabilities\n });\n });\n }\n }]);\n\n return WidgetApi;\n}(_events.EventEmitter);\n\nexports.WidgetApi = WidgetApi;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.WidgetDriver = void 0;\n\nvar _ = require(\"..\");\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\n/**\n * Represents the functions and behaviour the widget-api is unable to\n * do, such as prompting the user for information or interacting with\n * the UI. Clients are expected to implement this class and override\n * any functions they need/want to support.\n *\n * This class assumes the client will have a context of a Widget\n * instance already.\n */\nvar WidgetDriver = /*#__PURE__*/function () {\n function WidgetDriver() {\n _classCallCheck(this, WidgetDriver);\n }\n\n _createClass(WidgetDriver, [{\n key: \"validateCapabilities\",\n value:\n /**\n * Verifies the widget's requested capabilities, returning the ones\n * it is approved to use. Mutating the requested capabilities will\n * have no effect.\n *\n * This SHOULD result in the user being prompted to approve/deny\n * capabilities.\n *\n * By default this rejects all capabilities (returns an empty set).\n * @param {Set} requested The set of requested capabilities.\n * @returns {Promise>} Resolves to the allowed capabilities.\n */\n function validateCapabilities(requested) {\n return Promise.resolve(new Set());\n }\n /**\n * Sends an event into a room. If `roomId` is falsy, the client should send the event\n * into the room the user is currently looking at. The widget API will have already\n * verified that the widget is capable of sending the event to that room.\n * @param {string} eventType The event type to be sent.\n * @param {*} content The content for the event.\n * @param {string|null} stateKey The state key if this is a state event, otherwise null.\n * May be an empty string.\n * @param {string|null} roomId The room ID to send the event to. If falsy, the room the\n * user is currently looking at.\n * @returns {Promise} Resolves when the event has been sent with\n * details of that event.\n * @throws Rejected when the event could not be sent.\n */\n\n }, {\n key: \"sendEvent\",\n value: function sendEvent(eventType, content) {\n var stateKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n var roomId = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;\n return Promise.reject(new Error(\"Failed to override function\"));\n }\n /**\n * Sends a to-device event. The widget API will have already verified that the widget\n * is capable of sending the event.\n * @param {string} eventType The event type to be sent.\n * @param {boolean} encrypted Whether to encrypt the message contents.\n * @param {Object} contentMap A map from user ID and device ID to event content.\n * @returns {Promise} Resolves when the event has been sent.\n * @throws Rejected when the event could not be sent.\n */\n\n }, {\n key: \"sendToDevice\",\n value: function sendToDevice(eventType, encrypted, contentMap) {\n return Promise.reject(new Error(\"Failed to override function\"));\n }\n /**\n * Reads all events of the given type, and optionally `msgtype` (if applicable/defined),\n * the user has access to. The widget API will have already verified that the widget is\n * capable of receiving the events. Less events than the limit are allowed to be returned,\n * but not more. If `roomIds` is supplied, it may contain `Symbols.AnyRoom` to denote that\n * `limit` in each of the client's known rooms should be returned. When `null`, only the\n * room the user is currently looking at should be considered.\n * @param eventType The event type to be read.\n * @param msgtype The msgtype of the events to be read, if applicable/defined.\n * @param limit The maximum number of events to retrieve per room. Will be zero to denote \"as many\n * as possible\".\n * @param roomIds When null, the user's currently viewed room. Otherwise, the list of room IDs\n * to look within, possibly containing Symbols.AnyRoom to denote all known rooms.\n * @returns {Promise} Resolves to the room events, or an empty array.\n */\n\n }, {\n key: \"readRoomEvents\",\n value: function readRoomEvents(eventType, msgtype, limit) {\n var roomIds = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;\n return Promise.resolve([]);\n }\n /**\n * Reads all events of the given type, and optionally state key (if applicable/defined),\n * the user has access to. The widget API will have already verified that the widget is\n * capable of receiving the events. Less events than the limit are allowed to be returned,\n * but not more. If `roomIds` is supplied, it may contain `Symbols.AnyRoom` to denote that\n * `limit` in each of the client's known rooms should be returned. When `null`, only the\n * room the user is currently looking at should be considered.\n * @param eventType The event type to be read.\n * @param stateKey The state key of the events to be read, if applicable/defined.\n * @param limit The maximum number of events to retrieve. Will be zero to denote \"as many\n * as possible\".\n * @param roomIds When null, the user's currently viewed room. Otherwise, the list of room IDs\n * to look within, possibly containing Symbols.AnyRoom to denote all known rooms.\n * @returns {Promise} Resolves to the state events, or an empty array.\n */\n\n }, {\n key: \"readStateEvents\",\n value: function readStateEvents(eventType, stateKey, limit) {\n var roomIds = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;\n return Promise.resolve([]);\n }\n /**\n * Reads all events that are related to a given event. The widget API will\n * have already verified that the widget is capable of receiving the event,\n * or will make sure to reject access to events which are returned from this\n * function, but are not capable of receiving. If `relationType` or `eventType`\n * are set, the returned events should already be filtered. Less events than\n * the limit are allowed to be returned, but not more.\n * @param eventId The id of the parent event to be read.\n * @param roomId The room to look within. When undefined, the user's\n * currently viewed room.\n * @param relationType The relationship type of child events to search for.\n * When undefined, all relations are returned.\n * @param eventType The event type of child events to search for. When undefined,\n * all related events are returned.\n * @param from The pagination token to start returning results from, as\n * received from a previous call. If not supplied, results start at the most\n * recent topological event known to the server.\n * @param to The pagination token to stop returning results at. If not\n * supplied, results continue up to limit or until there are no more events.\n * @param limit The maximum number of events to retrieve per room. If not\n * supplied, the server will apply a default limit.\n * @param direction The direction to search for according to MSC3715\n * @returns Resolves to the room relations.\n */\n\n }, {\n key: \"readEventRelations\",\n value: function readEventRelations(eventId, roomId, relationType, eventType, from, to, limit, direction) {\n return Promise.resolve({\n chunk: []\n });\n }\n /**\n * Asks the user for permission to validate their identity through OpenID Connect. The\n * interface for this function is an observable which accepts the state machine of the\n * OIDC exchange flow. For example, if the client/user blocks the request then it would\n * feed back a `{state: Blocked}` into the observable. Similarly, if the user already\n * approved the widget then a `{state: Allowed}` would be fed into the observable alongside\n * the token itself. If the client is asking for permission, it should feed in a\n * `{state: PendingUserConfirmation}` followed by the relevant Allowed or Blocked state.\n *\n * The widget API will reject the widget's request with an error if this contract is not\n * met properly. By default, the widget driver will block all OIDC requests.\n * @param {SimpleObservable} observer The observable to feed updates into.\n */\n\n }, {\n key: \"askOpenID\",\n value: function askOpenID(observer) {\n observer.update({\n state: _.OpenIDRequestState.Blocked\n });\n }\n /**\n * Navigates the client with a matrix.to URI. In future this function will also be provided\n * with the Matrix URIs once matrix.to is replaced. The given URI will have already been\n * lightly checked to ensure it looks like a valid URI, though the implementation is recommended\n * to do further checks on the URI.\n * @param {string} uri The URI to navigate to.\n * @returns {Promise} Resolves when complete.\n * @throws Throws if there's a problem with the navigation, such as invalid format.\n */\n\n }, {\n key: \"navigate\",\n value: function navigate(uri) {\n throw new Error(\"Navigation is not implemented\");\n }\n /**\n * Polls for TURN server data, yielding an initial set of credentials as soon as possible, and\n * thereafter yielding new credentials whenever the previous ones expire. The widget API will\n * have already verified that the widget has permission to access TURN servers.\n * @yields {ITurnServer} The TURN server URIs and credentials currently available to the client.\n */\n\n }, {\n key: \"getTurnServers\",\n value: function getTurnServers() {\n throw new Error(\"TURN server support is not implemented\");\n }\n /**\n * Search for users in the user directory.\n * @param searchTerm The term to search for.\n * @param limit The maximum number of results to return. If not supplied, the\n * @returns Resolves to the search results.\n */\n\n }, {\n key: \"searchUserDirectory\",\n value: function searchUserDirectory(searchTerm, limit) {\n return Promise.resolve({\n limited: false,\n results: []\n });\n }\n }]);\n\n return WidgetDriver;\n}();\n\nexports.WidgetDriver = WidgetDriver;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _WidgetApi = require(\"./WidgetApi\");\n\nObject.keys(_WidgetApi).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _WidgetApi[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _WidgetApi[key];\n }\n });\n});\n\nvar _ClientWidgetApi = require(\"./ClientWidgetApi\");\n\nObject.keys(_ClientWidgetApi).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _ClientWidgetApi[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _ClientWidgetApi[key];\n }\n });\n});\n\nvar _Symbols = require(\"./Symbols\");\n\nObject.keys(_Symbols).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _Symbols[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _Symbols[key];\n }\n });\n});\n\nvar _ITransport = require(\"./transport/ITransport\");\n\nObject.keys(_ITransport).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _ITransport[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _ITransport[key];\n }\n });\n});\n\nvar _PostmessageTransport = require(\"./transport/PostmessageTransport\");\n\nObject.keys(_PostmessageTransport).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _PostmessageTransport[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _PostmessageTransport[key];\n }\n });\n});\n\nvar _ICustomWidgetData = require(\"./interfaces/ICustomWidgetData\");\n\nObject.keys(_ICustomWidgetData).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _ICustomWidgetData[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _ICustomWidgetData[key];\n }\n });\n});\n\nvar _IJitsiWidgetData = require(\"./interfaces/IJitsiWidgetData\");\n\nObject.keys(_IJitsiWidgetData).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _IJitsiWidgetData[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _IJitsiWidgetData[key];\n }\n });\n});\n\nvar _IStickerpickerWidgetData = require(\"./interfaces/IStickerpickerWidgetData\");\n\nObject.keys(_IStickerpickerWidgetData).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _IStickerpickerWidgetData[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _IStickerpickerWidgetData[key];\n }\n });\n});\n\nvar _IWidget = require(\"./interfaces/IWidget\");\n\nObject.keys(_IWidget).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _IWidget[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _IWidget[key];\n }\n });\n});\n\nvar _WidgetType = require(\"./interfaces/WidgetType\");\n\nObject.keys(_WidgetType).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _WidgetType[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _WidgetType[key];\n }\n });\n});\n\nvar _IWidgetApiErrorResponse = require(\"./interfaces/IWidgetApiErrorResponse\");\n\nObject.keys(_IWidgetApiErrorResponse).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _IWidgetApiErrorResponse[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _IWidgetApiErrorResponse[key];\n }\n });\n});\n\nvar _IWidgetApiRequest = require(\"./interfaces/IWidgetApiRequest\");\n\nObject.keys(_IWidgetApiRequest).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _IWidgetApiRequest[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _IWidgetApiRequest[key];\n }\n });\n});\n\nvar _IWidgetApiResponse = require(\"./interfaces/IWidgetApiResponse\");\n\nObject.keys(_IWidgetApiResponse).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _IWidgetApiResponse[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _IWidgetApiResponse[key];\n }\n });\n});\n\nvar _WidgetApiAction = require(\"./interfaces/WidgetApiAction\");\n\nObject.keys(_WidgetApiAction).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _WidgetApiAction[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _WidgetApiAction[key];\n }\n });\n});\n\nvar _WidgetApiDirection = require(\"./interfaces/WidgetApiDirection\");\n\nObject.keys(_WidgetApiDirection).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _WidgetApiDirection[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _WidgetApiDirection[key];\n }\n });\n});\n\nvar _ApiVersion = require(\"./interfaces/ApiVersion\");\n\nObject.keys(_ApiVersion).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _ApiVersion[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _ApiVersion[key];\n }\n });\n});\n\nvar _Capabilities = require(\"./interfaces/Capabilities\");\n\nObject.keys(_Capabilities).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _Capabilities[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _Capabilities[key];\n }\n });\n});\n\nvar _CapabilitiesAction = require(\"./interfaces/CapabilitiesAction\");\n\nObject.keys(_CapabilitiesAction).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _CapabilitiesAction[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _CapabilitiesAction[key];\n }\n });\n});\n\nvar _ContentLoadedAction = require(\"./interfaces/ContentLoadedAction\");\n\nObject.keys(_ContentLoadedAction).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _ContentLoadedAction[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _ContentLoadedAction[key];\n }\n });\n});\n\nvar _ScreenshotAction = require(\"./interfaces/ScreenshotAction\");\n\nObject.keys(_ScreenshotAction).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _ScreenshotAction[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _ScreenshotAction[key];\n }\n });\n});\n\nvar _StickerAction = require(\"./interfaces/StickerAction\");\n\nObject.keys(_StickerAction).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _StickerAction[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _StickerAction[key];\n }\n });\n});\n\nvar _StickyAction = require(\"./interfaces/StickyAction\");\n\nObject.keys(_StickyAction).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _StickyAction[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _StickyAction[key];\n }\n });\n});\n\nvar _SupportedVersionsAction = require(\"./interfaces/SupportedVersionsAction\");\n\nObject.keys(_SupportedVersionsAction).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _SupportedVersionsAction[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _SupportedVersionsAction[key];\n }\n });\n});\n\nvar _VisibilityAction = require(\"./interfaces/VisibilityAction\");\n\nObject.keys(_VisibilityAction).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _VisibilityAction[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _VisibilityAction[key];\n }\n });\n});\n\nvar _GetOpenIDAction = require(\"./interfaces/GetOpenIDAction\");\n\nObject.keys(_GetOpenIDAction).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _GetOpenIDAction[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _GetOpenIDAction[key];\n }\n });\n});\n\nvar _OpenIDCredentialsAction = require(\"./interfaces/OpenIDCredentialsAction\");\n\nObject.keys(_OpenIDCredentialsAction).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _OpenIDCredentialsAction[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _OpenIDCredentialsAction[key];\n }\n });\n});\n\nvar _WidgetKind = require(\"./interfaces/WidgetKind\");\n\nObject.keys(_WidgetKind).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _WidgetKind[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _WidgetKind[key];\n }\n });\n});\n\nvar _ModalButtonKind = require(\"./interfaces/ModalButtonKind\");\n\nObject.keys(_ModalButtonKind).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _ModalButtonKind[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _ModalButtonKind[key];\n }\n });\n});\n\nvar _ModalWidgetActions = require(\"./interfaces/ModalWidgetActions\");\n\nObject.keys(_ModalWidgetActions).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _ModalWidgetActions[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _ModalWidgetActions[key];\n }\n });\n});\n\nvar _SetModalButtonEnabledAction = require(\"./interfaces/SetModalButtonEnabledAction\");\n\nObject.keys(_SetModalButtonEnabledAction).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _SetModalButtonEnabledAction[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _SetModalButtonEnabledAction[key];\n }\n });\n});\n\nvar _WidgetConfigAction = require(\"./interfaces/WidgetConfigAction\");\n\nObject.keys(_WidgetConfigAction).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _WidgetConfigAction[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _WidgetConfigAction[key];\n }\n });\n});\n\nvar _SendEventAction = require(\"./interfaces/SendEventAction\");\n\nObject.keys(_SendEventAction).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _SendEventAction[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _SendEventAction[key];\n }\n });\n});\n\nvar _SendToDeviceAction = require(\"./interfaces/SendToDeviceAction\");\n\nObject.keys(_SendToDeviceAction).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _SendToDeviceAction[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _SendToDeviceAction[key];\n }\n });\n});\n\nvar _ReadEventAction = require(\"./interfaces/ReadEventAction\");\n\nObject.keys(_ReadEventAction).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _ReadEventAction[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _ReadEventAction[key];\n }\n });\n});\n\nvar _IRoomEvent = require(\"./interfaces/IRoomEvent\");\n\nObject.keys(_IRoomEvent).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _IRoomEvent[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _IRoomEvent[key];\n }\n });\n});\n\nvar _NavigateAction = require(\"./interfaces/NavigateAction\");\n\nObject.keys(_NavigateAction).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _NavigateAction[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _NavigateAction[key];\n }\n });\n});\n\nvar _TurnServerActions = require(\"./interfaces/TurnServerActions\");\n\nObject.keys(_TurnServerActions).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _TurnServerActions[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _TurnServerActions[key];\n }\n });\n});\n\nvar _ReadRelationsAction = require(\"./interfaces/ReadRelationsAction\");\n\nObject.keys(_ReadRelationsAction).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _ReadRelationsAction[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _ReadRelationsAction[key];\n }\n });\n});\n\nvar _WidgetEventCapability = require(\"./models/WidgetEventCapability\");\n\nObject.keys(_WidgetEventCapability).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _WidgetEventCapability[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _WidgetEventCapability[key];\n }\n });\n});\n\nvar _url = require(\"./models/validation/url\");\n\nObject.keys(_url).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _url[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _url[key];\n }\n });\n});\n\nvar _utils = require(\"./models/validation/utils\");\n\nObject.keys(_utils).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _utils[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _utils[key];\n }\n });\n});\n\nvar _Widget = require(\"./models/Widget\");\n\nObject.keys(_Widget).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _Widget[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _Widget[key];\n }\n });\n});\n\nvar _WidgetParser = require(\"./models/WidgetParser\");\n\nObject.keys(_WidgetParser).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _WidgetParser[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _WidgetParser[key];\n }\n });\n});\n\nvar _urlTemplate = require(\"./templating/url-template\");\n\nObject.keys(_urlTemplate).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _urlTemplate[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _urlTemplate[key];\n }\n });\n});\n\nvar _SimpleObservable = require(\"./util/SimpleObservable\");\n\nObject.keys(_SimpleObservable).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _SimpleObservable[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _SimpleObservable[key];\n }\n });\n});\n\nvar _WidgetDriver = require(\"./driver/WidgetDriver\");\n\nObject.keys(_WidgetDriver).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n if (key in exports && exports[key] === _WidgetDriver[key]) return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function get() {\n return _WidgetDriver[key];\n }\n });\n});", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.UnstableApiVersion = exports.MatrixApiVersion = exports.CurrentApiVersions = void 0;\n\n/*\n * Copyright 2020 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar MatrixApiVersion;\nexports.MatrixApiVersion = MatrixApiVersion;\n\n(function (MatrixApiVersion) {\n MatrixApiVersion[\"Prerelease1\"] = \"0.0.1\";\n MatrixApiVersion[\"Prerelease2\"] = \"0.0.2\";\n})(MatrixApiVersion || (exports.MatrixApiVersion = MatrixApiVersion = {}));\n\nvar UnstableApiVersion;\nexports.UnstableApiVersion = UnstableApiVersion;\n\n(function (UnstableApiVersion) {\n UnstableApiVersion[\"MSC2762\"] = \"org.matrix.msc2762\";\n UnstableApiVersion[\"MSC2871\"] = \"org.matrix.msc2871\";\n UnstableApiVersion[\"MSC2931\"] = \"org.matrix.msc2931\";\n UnstableApiVersion[\"MSC2974\"] = \"org.matrix.msc2974\";\n UnstableApiVersion[\"MSC2876\"] = \"org.matrix.msc2876\";\n UnstableApiVersion[\"MSC3819\"] = \"org.matrix.msc3819\";\n UnstableApiVersion[\"MSC3846\"] = \"town.robin.msc3846\";\n UnstableApiVersion[\"MSC3869\"] = \"org.matrix.msc3869\";\n UnstableApiVersion[\"MSC3973\"] = \"org.matrix.msc3973\";\n})(UnstableApiVersion || (exports.UnstableApiVersion = UnstableApiVersion = {}));\n\nvar CurrentApiVersions = [MatrixApiVersion.Prerelease1, MatrixApiVersion.Prerelease2, //MatrixApiVersion.V010,\nUnstableApiVersion.MSC2762, UnstableApiVersion.MSC2871, UnstableApiVersion.MSC2931, UnstableApiVersion.MSC2974, UnstableApiVersion.MSC2876, UnstableApiVersion.MSC3819, UnstableApiVersion.MSC3846, UnstableApiVersion.MSC3869, UnstableApiVersion.MSC3973];\nexports.CurrentApiVersions = CurrentApiVersions;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.VideoConferenceCapabilities = exports.StickerpickerCapabilities = exports.MatrixCapabilities = void 0;\nexports.getTimelineRoomIDFromCapability = getTimelineRoomIDFromCapability;\nexports.isTimelineCapability = isTimelineCapability;\nexports.isTimelineCapabilityFor = isTimelineCapabilityFor;\n\n/*\n * Copyright 2020 - 2021 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar MatrixCapabilities;\nexports.MatrixCapabilities = MatrixCapabilities;\n\n(function (MatrixCapabilities) {\n MatrixCapabilities[\"Screenshots\"] = \"m.capability.screenshot\";\n MatrixCapabilities[\"StickerSending\"] = \"m.sticker\";\n MatrixCapabilities[\"AlwaysOnScreen\"] = \"m.always_on_screen\";\n MatrixCapabilities[\"RequiresClient\"] = \"io.element.requires_client\";\n MatrixCapabilities[\"MSC2931Navigate\"] = \"org.matrix.msc2931.navigate\";\n MatrixCapabilities[\"MSC3846TurnServers\"] = \"town.robin.msc3846.turn_servers\";\n MatrixCapabilities[\"MSC3973UserDirectorySearch\"] = \"org.matrix.msc3973.user_directory_search\";\n})(MatrixCapabilities || (exports.MatrixCapabilities = MatrixCapabilities = {}));\n\nvar StickerpickerCapabilities = [MatrixCapabilities.StickerSending];\nexports.StickerpickerCapabilities = StickerpickerCapabilities;\nvar VideoConferenceCapabilities = [MatrixCapabilities.AlwaysOnScreen];\n/**\n * Determines if a capability is a capability for a timeline.\n * @param {Capability} capability The capability to test.\n * @returns {boolean} True if a timeline capability, false otherwise.\n */\n\nexports.VideoConferenceCapabilities = VideoConferenceCapabilities;\n\nfunction isTimelineCapability(capability) {\n // TODO: Change when MSC2762 becomes stable.\n return capability === null || capability === void 0 ? void 0 : capability.startsWith(\"org.matrix.msc2762.timeline:\");\n}\n/**\n * Determines if a capability is a timeline capability for the given room.\n * @param {Capability} capability The capability to test.\n * @param {string | Symbols.AnyRoom} roomId The room ID, or `Symbols.AnyRoom` for that designation.\n * @returns {boolean} True if a matching capability, false otherwise.\n */\n\n\nfunction isTimelineCapabilityFor(capability, roomId) {\n return capability === \"org.matrix.msc2762.timeline:\".concat(roomId);\n}\n/**\n * Gets the room ID described by a timeline capability.\n * @param {string} capability The capability to parse.\n * @returns {string} The room ID.\n */\n\n\nfunction getTimelineRoomIDFromCapability(capability) {\n return capability.substring(capability.indexOf(\":\") + 1);\n}", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.OpenIDRequestState = void 0;\n\n/*\n * Copyright 2020 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar OpenIDRequestState;\nexports.OpenIDRequestState = OpenIDRequestState;\n\n(function (OpenIDRequestState) {\n OpenIDRequestState[\"Allowed\"] = \"allowed\";\n OpenIDRequestState[\"Blocked\"] = \"blocked\";\n OpenIDRequestState[\"PendingUserConfirmation\"] = \"request\";\n})(OpenIDRequestState || (exports.OpenIDRequestState = OpenIDRequestState = {}));", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.isErrorResponse = isErrorResponse;\n\n/*\n * Copyright 2020 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction isErrorResponse(responseData) {\n if (\"error\" in responseData) {\n var err = responseData;\n return !!err.error.message;\n }\n\n return false;\n}", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.ModalButtonKind = void 0;\n\n/*\n * Copyright 2020 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar ModalButtonKind;\nexports.ModalButtonKind = ModalButtonKind;\n\n(function (ModalButtonKind) {\n ModalButtonKind[\"Primary\"] = \"m.primary\";\n ModalButtonKind[\"Secondary\"] = \"m.secondary\";\n ModalButtonKind[\"Warning\"] = \"m.warning\";\n ModalButtonKind[\"Danger\"] = \"m.danger\";\n ModalButtonKind[\"Link\"] = \"m.link\";\n})(ModalButtonKind || (exports.ModalButtonKind = ModalButtonKind = {}));", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.BuiltInModalButtonID = void 0;\n\n/*\n * Copyright 2020 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar BuiltInModalButtonID;\nexports.BuiltInModalButtonID = BuiltInModalButtonID;\n\n(function (BuiltInModalButtonID) {\n BuiltInModalButtonID[\"Close\"] = \"m.close\";\n})(BuiltInModalButtonID || (exports.BuiltInModalButtonID = BuiltInModalButtonID = {}));", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.WidgetApiToWidgetAction = exports.WidgetApiFromWidgetAction = void 0;\n\n/*\n * Copyright 2020 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar WidgetApiToWidgetAction;\nexports.WidgetApiToWidgetAction = WidgetApiToWidgetAction;\n\n(function (WidgetApiToWidgetAction) {\n WidgetApiToWidgetAction[\"SupportedApiVersions\"] = \"supported_api_versions\";\n WidgetApiToWidgetAction[\"Capabilities\"] = \"capabilities\";\n WidgetApiToWidgetAction[\"NotifyCapabilities\"] = \"notify_capabilities\";\n WidgetApiToWidgetAction[\"TakeScreenshot\"] = \"screenshot\";\n WidgetApiToWidgetAction[\"UpdateVisibility\"] = \"visibility\";\n WidgetApiToWidgetAction[\"OpenIDCredentials\"] = \"openid_credentials\";\n WidgetApiToWidgetAction[\"WidgetConfig\"] = \"widget_config\";\n WidgetApiToWidgetAction[\"CloseModalWidget\"] = \"close_modal\";\n WidgetApiToWidgetAction[\"ButtonClicked\"] = \"button_clicked\";\n WidgetApiToWidgetAction[\"SendEvent\"] = \"send_event\";\n WidgetApiToWidgetAction[\"SendToDevice\"] = \"send_to_device\";\n WidgetApiToWidgetAction[\"UpdateTurnServers\"] = \"update_turn_servers\";\n})(WidgetApiToWidgetAction || (exports.WidgetApiToWidgetAction = WidgetApiToWidgetAction = {}));\n\nvar WidgetApiFromWidgetAction;\nexports.WidgetApiFromWidgetAction = WidgetApiFromWidgetAction;\n\n(function (WidgetApiFromWidgetAction) {\n WidgetApiFromWidgetAction[\"SupportedApiVersions\"] = \"supported_api_versions\";\n WidgetApiFromWidgetAction[\"ContentLoaded\"] = \"content_loaded\";\n WidgetApiFromWidgetAction[\"SendSticker\"] = \"m.sticker\";\n WidgetApiFromWidgetAction[\"UpdateAlwaysOnScreen\"] = \"set_always_on_screen\";\n WidgetApiFromWidgetAction[\"GetOpenIDCredentials\"] = \"get_openid\";\n WidgetApiFromWidgetAction[\"CloseModalWidget\"] = \"close_modal\";\n WidgetApiFromWidgetAction[\"OpenModalWidget\"] = \"open_modal\";\n WidgetApiFromWidgetAction[\"SetModalButtonEnabled\"] = \"set_button_enabled\";\n WidgetApiFromWidgetAction[\"SendEvent\"] = \"send_event\";\n WidgetApiFromWidgetAction[\"SendToDevice\"] = \"send_to_device\";\n WidgetApiFromWidgetAction[\"WatchTurnServers\"] = \"watch_turn_servers\";\n WidgetApiFromWidgetAction[\"UnwatchTurnServers\"] = \"unwatch_turn_servers\";\n WidgetApiFromWidgetAction[\"MSC2876ReadEvents\"] = \"org.matrix.msc2876.read_events\";\n WidgetApiFromWidgetAction[\"MSC2931Navigate\"] = \"org.matrix.msc2931.navigate\";\n WidgetApiFromWidgetAction[\"MSC2974RenegotiateCapabilities\"] = \"org.matrix.msc2974.request_capabilities\";\n WidgetApiFromWidgetAction[\"MSC3869ReadRelations\"] = \"org.matrix.msc3869.read_relations\";\n WidgetApiFromWidgetAction[\"MSC3973UserDirectorySearch\"] = \"org.matrix.msc3973.user_directory_search\";\n})(WidgetApiFromWidgetAction || (exports.WidgetApiFromWidgetAction = WidgetApiFromWidgetAction = {}));", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.WidgetApiDirection = void 0;\nexports.invertedDirection = invertedDirection;\n\n/*\n * Copyright 2020 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar WidgetApiDirection;\nexports.WidgetApiDirection = WidgetApiDirection;\n\n(function (WidgetApiDirection) {\n WidgetApiDirection[\"ToWidget\"] = \"toWidget\";\n WidgetApiDirection[\"FromWidget\"] = \"fromWidget\";\n})(WidgetApiDirection || (exports.WidgetApiDirection = WidgetApiDirection = {}));\n\nfunction invertedDirection(dir) {\n if (dir === WidgetApiDirection.ToWidget) {\n return WidgetApiDirection.FromWidget;\n } else if (dir === WidgetApiDirection.FromWidget) {\n return WidgetApiDirection.ToWidget;\n } else {\n throw new Error(\"Invalid direction\");\n }\n}", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.WidgetKind = void 0;\n\n/*\n * Copyright 2020 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar WidgetKind;\nexports.WidgetKind = WidgetKind;\n\n(function (WidgetKind) {\n WidgetKind[\"Room\"] = \"room\";\n WidgetKind[\"Account\"] = \"account\";\n WidgetKind[\"Modal\"] = \"modal\";\n})(WidgetKind || (exports.WidgetKind = WidgetKind = {}));", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.MatrixWidgetType = void 0;\n\n/*\n * Copyright 2020 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar MatrixWidgetType;\nexports.MatrixWidgetType = MatrixWidgetType;\n\n(function (MatrixWidgetType) {\n MatrixWidgetType[\"Custom\"] = \"m.custom\";\n MatrixWidgetType[\"JitsiMeet\"] = \"m.jitsi\";\n MatrixWidgetType[\"Stickerpicker\"] = \"m.stickerpicker\";\n})(MatrixWidgetType || (exports.MatrixWidgetType = MatrixWidgetType = {}));", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.Widget = void 0;\n\nvar _utils = require(\"./validation/utils\");\n\nvar _ = require(\"..\");\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\n/**\n * Represents the barest form of widget.\n */\nvar Widget = /*#__PURE__*/function () {\n function Widget(definition) {\n _classCallCheck(this, Widget);\n\n this.definition = definition;\n if (!this.definition) throw new Error(\"Definition is required\");\n (0, _utils.assertPresent)(definition, \"id\");\n (0, _utils.assertPresent)(definition, \"creatorUserId\");\n (0, _utils.assertPresent)(definition, \"type\");\n (0, _utils.assertPresent)(definition, \"url\");\n }\n /**\n * The user ID who created the widget.\n */\n\n\n _createClass(Widget, [{\n key: \"creatorUserId\",\n get: function get() {\n return this.definition.creatorUserId;\n }\n /**\n * The type of widget.\n */\n\n }, {\n key: \"type\",\n get: function get() {\n return this.definition.type;\n }\n /**\n * The ID of the widget.\n */\n\n }, {\n key: \"id\",\n get: function get() {\n return this.definition.id;\n }\n /**\n * The name of the widget, or null if not set.\n */\n\n }, {\n key: \"name\",\n get: function get() {\n return this.definition.name || null;\n }\n /**\n * The title for the widget, or null if not set.\n */\n\n }, {\n key: \"title\",\n get: function get() {\n return this.rawData.title || null;\n }\n /**\n * The templated URL for the widget.\n */\n\n }, {\n key: \"templateUrl\",\n get: function get() {\n return this.definition.url;\n }\n /**\n * The origin for this widget.\n */\n\n }, {\n key: \"origin\",\n get: function get() {\n return new URL(this.templateUrl).origin;\n }\n /**\n * Whether or not the client should wait for the iframe to load. Defaults\n * to true.\n */\n\n }, {\n key: \"waitForIframeLoad\",\n get: function get() {\n if (this.definition.waitForIframeLoad === false) return false;\n if (this.definition.waitForIframeLoad === true) return true;\n return true; // default true\n }\n /**\n * The raw data for the widget. This will always be defined, though\n * may be empty.\n */\n\n }, {\n key: \"rawData\",\n get: function get() {\n return this.definition.data || {};\n }\n /**\n * Gets a complete widget URL for the client to render.\n * @param {ITemplateParams} params The template parameters.\n * @returns {string} A templated URL.\n */\n\n }, {\n key: \"getCompleteUrl\",\n value: function getCompleteUrl(params) {\n return (0, _.runTemplate)(this.templateUrl, this.definition, params);\n }\n }]);\n\n return Widget;\n}();\n\nexports.Widget = Widget;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.WidgetEventCapability = exports.EventKind = exports.EventDirection = void 0;\n\nfunction _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; } } }; }\n\nfunction _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); }\n\nfunction _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; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\n/*\n * Copyright 2020 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar EventKind;\nexports.EventKind = EventKind;\n\n(function (EventKind) {\n EventKind[\"Event\"] = \"event\";\n EventKind[\"State\"] = \"state_event\";\n EventKind[\"ToDevice\"] = \"to_device\";\n})(EventKind || (exports.EventKind = EventKind = {}));\n\nvar EventDirection;\nexports.EventDirection = EventDirection;\n\n(function (EventDirection) {\n EventDirection[\"Send\"] = \"send\";\n EventDirection[\"Receive\"] = \"receive\";\n})(EventDirection || (exports.EventDirection = EventDirection = {}));\n\nvar WidgetEventCapability = /*#__PURE__*/function () {\n function WidgetEventCapability(direction, eventType, kind, keyStr, raw) {\n _classCallCheck(this, WidgetEventCapability);\n\n this.direction = direction;\n this.eventType = eventType;\n this.kind = kind;\n this.keyStr = keyStr;\n this.raw = raw;\n }\n\n _createClass(WidgetEventCapability, [{\n key: \"matchesAsStateEvent\",\n value: function matchesAsStateEvent(direction, eventType, stateKey) {\n if (this.kind !== EventKind.State) return false; // not a state event\n\n if (this.direction !== direction) return false; // direction mismatch\n\n if (this.eventType !== eventType) return false; // event type mismatch\n\n if (this.keyStr === null) return true; // all state keys are allowed\n\n if (this.keyStr === stateKey) return true; // this state key is allowed\n // Default not allowed\n\n return false;\n }\n }, {\n key: \"matchesAsToDeviceEvent\",\n value: function matchesAsToDeviceEvent(direction, eventType) {\n if (this.kind !== EventKind.ToDevice) return false; // not a to-device event\n\n if (this.direction !== direction) return false; // direction mismatch\n\n if (this.eventType !== eventType) return false; // event type mismatch\n // Checks passed, the event is allowed\n\n return true;\n }\n }, {\n key: \"matchesAsRoomEvent\",\n value: function matchesAsRoomEvent(direction, eventType) {\n var msgtype = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n if (this.kind !== EventKind.Event) return false; // not a room event\n\n if (this.direction !== direction) return false; // direction mismatch\n\n if (this.eventType !== eventType) return false; // event type mismatch\n\n if (this.eventType === \"m.room.message\") {\n if (this.keyStr === null) return true; // all message types are allowed\n\n if (this.keyStr === msgtype) return true; // this message type is allowed\n } else {\n return true; // already passed the check for if the event is allowed\n } // Default not allowed\n\n\n return false;\n }\n }], [{\n key: \"forStateEvent\",\n value: function forStateEvent(direction, eventType, stateKey) {\n // TODO: Enable support for m.* namespace once the MSC lands.\n // https://github.com/matrix-org/matrix-widget-api/issues/22\n eventType = eventType.replace(/#/g, '\\\\#');\n stateKey = stateKey !== null && stateKey !== undefined ? \"#\".concat(stateKey) : '';\n var str = \"org.matrix.msc2762.\".concat(direction, \".state_event:\").concat(eventType).concat(stateKey); // cheat by sending it through the processor\n\n return WidgetEventCapability.findEventCapabilities([str])[0];\n }\n }, {\n key: \"forToDeviceEvent\",\n value: function forToDeviceEvent(direction, eventType) {\n // TODO: Enable support for m.* namespace once the MSC lands.\n // https://github.com/matrix-org/matrix-widget-api/issues/56\n var str = \"org.matrix.msc3819.\".concat(direction, \".to_device:\").concat(eventType); // cheat by sending it through the processor\n\n return WidgetEventCapability.findEventCapabilities([str])[0];\n }\n }, {\n key: \"forRoomEvent\",\n value: function forRoomEvent(direction, eventType) {\n // TODO: Enable support for m.* namespace once the MSC lands.\n // https://github.com/matrix-org/matrix-widget-api/issues/22\n var str = \"org.matrix.msc2762.\".concat(direction, \".event:\").concat(eventType); // cheat by sending it through the processor\n\n return WidgetEventCapability.findEventCapabilities([str])[0];\n }\n }, {\n key: \"forRoomMessageEvent\",\n value: function forRoomMessageEvent(direction, msgtype) {\n // TODO: Enable support for m.* namespace once the MSC lands.\n // https://github.com/matrix-org/matrix-widget-api/issues/22\n msgtype = msgtype === null || msgtype === undefined ? '' : msgtype;\n var str = \"org.matrix.msc2762.\".concat(direction, \".event:m.room.message#\").concat(msgtype); // cheat by sending it through the processor\n\n return WidgetEventCapability.findEventCapabilities([str])[0];\n }\n /**\n * Parses a capabilities request to find all the event capability requests.\n * @param {Iterable} capabilities The capabilities requested/to parse.\n * @returns {WidgetEventCapability[]} An array of event capability requests. May be empty, but never null.\n */\n\n }, {\n key: \"findEventCapabilities\",\n value: function findEventCapabilities(capabilities) {\n var parsed = [];\n\n var _iterator = _createForOfIteratorHelper(capabilities),\n _step;\n\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var cap = _step.value;\n var _direction = null;\n var eventSegment = void 0;\n var _kind = null; // TODO: Enable support for m.* namespace once the MSCs land.\n // https://github.com/matrix-org/matrix-widget-api/issues/22\n // https://github.com/matrix-org/matrix-widget-api/issues/56\n\n if (cap.startsWith(\"org.matrix.msc2762.send.event:\")) {\n _direction = EventDirection.Send;\n _kind = EventKind.Event;\n eventSegment = cap.substring(\"org.matrix.msc2762.send.event:\".length);\n } else if (cap.startsWith(\"org.matrix.msc2762.send.state_event:\")) {\n _direction = EventDirection.Send;\n _kind = EventKind.State;\n eventSegment = cap.substring(\"org.matrix.msc2762.send.state_event:\".length);\n } else if (cap.startsWith(\"org.matrix.msc3819.send.to_device:\")) {\n _direction = EventDirection.Send;\n _kind = EventKind.ToDevice;\n eventSegment = cap.substring(\"org.matrix.msc3819.send.to_device:\".length);\n } else if (cap.startsWith(\"org.matrix.msc2762.receive.event:\")) {\n _direction = EventDirection.Receive;\n _kind = EventKind.Event;\n eventSegment = cap.substring(\"org.matrix.msc2762.receive.event:\".length);\n } else if (cap.startsWith(\"org.matrix.msc2762.receive.state_event:\")) {\n _direction = EventDirection.Receive;\n _kind = EventKind.State;\n eventSegment = cap.substring(\"org.matrix.msc2762.receive.state_event:\".length);\n } else if (cap.startsWith(\"org.matrix.msc3819.receive.to_device:\")) {\n _direction = EventDirection.Receive;\n _kind = EventKind.ToDevice;\n eventSegment = cap.substring(\"org.matrix.msc3819.receive.to_device:\".length);\n }\n\n if (_direction === null || _kind === null || eventSegment === undefined) continue; // The capability uses `#` as a separator between event type and state key/msgtype,\n // so we split on that. However, a # is also valid in either one of those so we\n // join accordingly.\n // Eg: `m.room.message##m.text` is \"m.room.message\" event with msgtype \"#m.text\".\n\n var expectingKeyStr = eventSegment.startsWith(\"m.room.message#\") || _kind === EventKind.State;\n\n var _keyStr = null;\n\n if (eventSegment.includes('#') && expectingKeyStr) {\n // Dev note: regex is difficult to write, so instead the rules are manually written\n // out. This is probably just as understandable as a boring regex though, so win-win?\n // Test cases:\n // str eventSegment keyStr\n // -------------------------------------------------------------\n // m.room.message# m.room.message \n // m.room.message#test m.room.message test\n // m.room.message\\# m.room.message# test\n // m.room.message##test m.room.message #test\n // m.room.message\\##test m.room.message# test\n // m.room.message\\\\##test m.room.message\\# test\n // m.room.message\\\\###test m.room.message\\# #test\n // First step: explode the string\n var parts = eventSegment.split('#'); // To form the eventSegment, we'll keep finding parts of the exploded string until\n // there's one that doesn't end with the escape character (\\). We'll then join those\n // segments together with the exploding character. We have to remember to consume the\n // escape character as well.\n\n var idx = parts.findIndex(function (p) {\n return !p.endsWith(\"\\\\\");\n });\n eventSegment = parts.slice(0, idx + 1).map(function (p) {\n return p.endsWith('\\\\') ? p.substring(0, p.length - 1) : p;\n }).join('#'); // The keyStr is whatever is left over.\n\n _keyStr = parts.slice(idx + 1).join('#');\n }\n\n parsed.push(new WidgetEventCapability(_direction, eventSegment, _kind, _keyStr, cap));\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n\n return parsed;\n }\n }]);\n\n return WidgetEventCapability;\n}();\n\nexports.WidgetEventCapability = WidgetEventCapability;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.WidgetParser = void 0;\n\nvar _Widget = require(\"./Widget\");\n\nvar _url = require(\"./validation/url\");\n\nfunction _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; } } }; }\n\nfunction _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); }\n\nfunction _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; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nvar WidgetParser = /*#__PURE__*/function () {\n function WidgetParser() {// private constructor because this is a util class\n\n _classCallCheck(this, WidgetParser);\n }\n /**\n * Parses widgets from the \"m.widgets\" account data event. This will always\n * return an array, though may be empty if no valid widgets were found.\n * @param {IAccountDataWidgets} content The content of the \"m.widgets\" account data.\n * @returns {Widget[]} The widgets in account data, or an empty array.\n */\n\n\n _createClass(WidgetParser, null, [{\n key: \"parseAccountData\",\n value: function parseAccountData(content) {\n if (!content) return [];\n var result = [];\n\n for (var _i = 0, _Object$keys = Object.keys(content); _i < _Object$keys.length; _i++) {\n var _widgetId = _Object$keys[_i];\n var roughWidget = content[_widgetId];\n if (!roughWidget) continue;\n if (roughWidget.type !== \"m.widget\" && roughWidget.type !== \"im.vector.modular.widgets\") continue;\n if (!roughWidget.sender) continue;\n var probableWidgetId = roughWidget.state_key || roughWidget.id;\n if (probableWidgetId !== _widgetId) continue;\n var asStateEvent = {\n content: roughWidget.content,\n sender: roughWidget.sender,\n type: \"m.widget\",\n state_key: _widgetId,\n event_id: \"$example\",\n room_id: \"!example\",\n origin_server_ts: 1\n };\n var widget = WidgetParser.parseRoomWidget(asStateEvent);\n if (widget) result.push(widget);\n }\n\n return result;\n }\n /**\n * Parses all the widgets possible in the given array. This will always return\n * an array, though may be empty if no widgets could be parsed.\n * @param {IStateEvent[]} currentState The room state to parse.\n * @returns {Widget[]} The widgets in the state, or an empty array.\n */\n\n }, {\n key: \"parseWidgetsFromRoomState\",\n value: function parseWidgetsFromRoomState(currentState) {\n if (!currentState) return [];\n var result = [];\n\n var _iterator = _createForOfIteratorHelper(currentState),\n _step;\n\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var state = _step.value;\n var widget = WidgetParser.parseRoomWidget(state);\n if (widget) result.push(widget);\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n\n return result;\n }\n /**\n * Parses a state event into a widget. If the state event does not represent\n * a widget (wrong event type, invalid widget, etc) then null is returned.\n * @param {IStateEvent} stateEvent The state event.\n * @returns {Widget|null} The widget, or null if invalid\n */\n\n }, {\n key: \"parseRoomWidget\",\n value: function parseRoomWidget(stateEvent) {\n if (!stateEvent) return null; // TODO: [Legacy] Remove legacy support\n\n if (stateEvent.type !== \"m.widget\" && stateEvent.type !== \"im.vector.modular.widgets\") {\n return null;\n } // Dev note: Throughout this function we have null safety to ensure that\n // if the caller did not supply something useful that we don't error. This\n // is done against the requirements of the interface because not everyone\n // will have an interface to validate against.\n\n\n var content = stateEvent.content || {}; // Form our best approximation of a widget with the information we have\n\n var estimatedWidget = {\n id: stateEvent.state_key,\n creatorUserId: content['creatorUserId'] || stateEvent.sender,\n name: content['name'],\n type: content['type'],\n url: content['url'],\n waitForIframeLoad: content['waitForIframeLoad'],\n data: content['data']\n }; // Finally, process that widget\n\n return WidgetParser.processEstimatedWidget(estimatedWidget);\n }\n }, {\n key: \"processEstimatedWidget\",\n value: function processEstimatedWidget(widget) {\n // Validate that the widget has the best chance of passing as a widget\n if (!widget.id || !widget.creatorUserId || !widget.type) {\n return null;\n }\n\n if (!(0, _url.isValidUrl)(widget.url)) {\n return null;\n } // TODO: Validate data for known widget types\n\n\n return new _Widget.Widget(widget);\n }\n }]);\n\n return WidgetParser;\n}();\n\nexports.WidgetParser = WidgetParser;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.isValidUrl = isValidUrl;\n\n/*\n * Copyright 2020 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction isValidUrl(val) {\n if (!val) return false; // easy: not valid if not present\n\n try {\n var parsed = new URL(val);\n\n if (parsed.protocol !== \"http\" && parsed.protocol !== \"https\") {\n return false;\n }\n\n return true;\n } catch (e) {\n if (e instanceof TypeError) {\n return false;\n }\n\n throw e;\n }\n}", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.assertPresent = assertPresent;\n\n/*\n * Copyright 2020 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction assertPresent(obj, key) {\n if (!obj[key]) {\n throw new Error(\"\".concat(key, \" is required\"));\n }\n}", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.runTemplate = runTemplate;\nexports.toString = toString;\n\n/*\n * Copyright 2020, 2021 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction runTemplate(url, widget, params) {\n // Always apply the supplied params over top of data to ensure the data can't lie about them.\n var variables = Object.assign({}, widget.data, {\n 'matrix_room_id': params.widgetRoomId || \"\",\n 'matrix_user_id': params.currentUserId,\n 'matrix_display_name': params.userDisplayName || params.currentUserId,\n 'matrix_avatar_url': params.userHttpAvatarUrl || \"\",\n 'matrix_widget_id': widget.id,\n // TODO: Convert to stable (https://github.com/matrix-org/matrix-doc/pull/2873)\n 'org.matrix.msc2873.client_id': params.clientId || \"\",\n 'org.matrix.msc2873.client_theme': params.clientTheme || \"\",\n 'org.matrix.msc2873.client_language': params.clientLanguage || \"\"\n });\n var result = url;\n\n for (var _i = 0, _Object$keys = Object.keys(variables); _i < _Object$keys.length; _i++) {\n var key = _Object$keys[_i];\n // Regex escape from https://stackoverflow.com/a/6969486/7037379\n var pattern = \"$\".concat(key).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); // $& means the whole matched string\n\n var rexp = new RegExp(pattern, 'g'); // This is technically not what we're supposed to do for a couple of reasons:\n // 1. We are assuming that there won't later be a $key match after we replace a variable.\n // 2. We are assuming that the variable is in a place where it can be escaped (eg: path or query string).\n\n result = result.replace(rexp, encodeURIComponent(toString(variables[key])));\n }\n\n return result;\n}\n\nfunction toString(a) {\n if (a === null || a === undefined) {\n return \"\".concat(a);\n }\n\n return String(a);\n}", - "\"use strict\";\n\nfunction _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); }\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.PostmessageTransport = void 0;\n\nvar _events = require(\"events\");\n\nvar _ = require(\"..\");\n\nfunction 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; }\n\nfunction _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; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _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); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _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); }; }\n\nfunction _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); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _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; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n/**\n * Transport for the Widget API over postMessage.\n */\nvar PostmessageTransport = /*#__PURE__*/function (_EventEmitter) {\n _inherits(PostmessageTransport, _EventEmitter);\n\n var _super = _createSuper(PostmessageTransport);\n\n function PostmessageTransport(sendDirection, initialWidgetId, transportWindow, inboundWindow) {\n var _this;\n\n _classCallCheck(this, PostmessageTransport);\n\n _this = _super.call(this);\n _this.sendDirection = sendDirection;\n _this.initialWidgetId = initialWidgetId;\n _this.transportWindow = transportWindow;\n _this.inboundWindow = inboundWindow;\n\n _defineProperty(_assertThisInitialized(_this), \"strictOriginCheck\", false);\n\n _defineProperty(_assertThisInitialized(_this), \"targetOrigin\", \"*\");\n\n _defineProperty(_assertThisInitialized(_this), \"timeoutSeconds\", 10);\n\n _defineProperty(_assertThisInitialized(_this), \"_ready\", false);\n\n _defineProperty(_assertThisInitialized(_this), \"_widgetId\", null);\n\n _defineProperty(_assertThisInitialized(_this), \"outboundRequests\", new Map());\n\n _defineProperty(_assertThisInitialized(_this), \"stopController\", new AbortController());\n\n _this._widgetId = initialWidgetId;\n return _this;\n }\n\n _createClass(PostmessageTransport, [{\n key: \"ready\",\n get: function get() {\n return this._ready;\n }\n }, {\n key: \"widgetId\",\n get: function get() {\n return this._widgetId || null;\n }\n }, {\n key: \"nextRequestId\",\n get: function get() {\n var idBase = \"widgetapi-\".concat(Date.now());\n var index = 0;\n var id = idBase;\n\n while (this.outboundRequests.has(id)) {\n id = \"\".concat(idBase, \"-\").concat(index++);\n } // reserve the ID\n\n\n this.outboundRequests.set(id, null);\n return id;\n }\n }, {\n key: \"sendInternal\",\n value: function sendInternal(message) {\n console.log(\"[PostmessageTransport] Sending object to \".concat(this.targetOrigin, \": \"), message);\n this.transportWindow.postMessage(message, this.targetOrigin);\n }\n }, {\n key: \"reply\",\n value: function reply(request, responseData) {\n return this.sendInternal(_objectSpread(_objectSpread({}, request), {}, {\n response: responseData\n }));\n }\n }, {\n key: \"send\",\n value: function send(action, data) {\n return this.sendComplete(action, data).then(function (r) {\n return r.response;\n });\n }\n }, {\n key: \"sendComplete\",\n value: function sendComplete(action, data) {\n var _this2 = this;\n\n if (!this.ready || !this.widgetId) {\n return Promise.reject(new Error(\"Not ready or unknown widget ID\"));\n }\n\n var request = {\n api: this.sendDirection,\n widgetId: this.widgetId,\n requestId: this.nextRequestId,\n action: action,\n data: data\n };\n\n if (action === _.WidgetApiToWidgetAction.UpdateVisibility) {\n request['visible'] = data['visible'];\n }\n\n return new Promise(function (prResolve, prReject) {\n var resolve = function resolve(response) {\n cleanUp();\n prResolve(response);\n };\n\n var reject = function reject(err) {\n cleanUp();\n prReject(err);\n };\n\n var timerId = setTimeout(function () {\n return reject(new Error(\"Request timed out\"));\n }, (_this2.timeoutSeconds || 1) * 1000);\n\n var onStop = function onStop() {\n return reject(new Error(\"Transport stopped\"));\n };\n\n _this2.stopController.signal.addEventListener(\"abort\", onStop);\n\n var cleanUp = function cleanUp() {\n _this2.outboundRequests[\"delete\"](request.requestId);\n\n clearTimeout(timerId);\n\n _this2.stopController.signal.removeEventListener(\"abort\", onStop);\n };\n\n _this2.outboundRequests.set(request.requestId, {\n request: request,\n resolve: resolve,\n reject: reject\n });\n\n _this2.sendInternal(request);\n });\n }\n }, {\n key: \"start\",\n value: function start() {\n var _this3 = this;\n\n this.inboundWindow.addEventListener(\"message\", function (ev) {\n _this3.handleMessage(ev);\n });\n this._ready = true;\n }\n }, {\n key: \"stop\",\n value: function stop() {\n this._ready = false;\n this.stopController.abort();\n }\n }, {\n key: \"handleMessage\",\n value: function handleMessage(ev) {\n if (this.stopController.signal.aborted) return;\n if (!ev.data) return; // invalid event\n\n if (this.strictOriginCheck && ev.origin !== window.origin) return; // bad origin\n // treat the message as a response first, then downgrade to a request\n\n var response = ev.data;\n if (!response.action || !response.requestId || !response.widgetId) return; // invalid request/response\n\n if (!response.response) {\n // it's a request\n var request = response;\n if (request.api !== (0, _.invertedDirection)(this.sendDirection)) return; // wrong direction\n\n this.handleRequest(request);\n } else {\n // it's a response\n if (response.api !== this.sendDirection) return; // wrong direction\n\n this.handleResponse(response);\n }\n }\n }, {\n key: \"handleRequest\",\n value: function handleRequest(request) {\n if (this.widgetId) {\n if (this.widgetId !== request.widgetId) return; // wrong widget\n } else {\n this._widgetId = request.widgetId;\n }\n\n this.emit(\"message\", new CustomEvent(\"message\", {\n detail: request\n }));\n }\n }, {\n key: \"handleResponse\",\n value: function handleResponse(response) {\n if (response.widgetId !== this.widgetId) return; // wrong widget\n\n var req = this.outboundRequests.get(response.requestId);\n if (!req) return; // response to an unknown request\n\n if ((0, _.isErrorResponse)(response.response)) {\n var _err = response.response;\n req.reject(new Error(_err.error.message));\n } else {\n req.resolve(response);\n }\n }\n }]);\n\n return PostmessageTransport;\n}(_events.EventEmitter);\n\nexports.PostmessageTransport = PostmessageTransport;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.SimpleObservable = void 0;\n\nfunction _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; } } }; }\n\nfunction _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); }\n\nfunction _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; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n/*\n * Copyright 2020 The Matrix.org Foundation C.I.C.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nvar SimpleObservable = /*#__PURE__*/function () {\n function SimpleObservable(initialFn) {\n _classCallCheck(this, SimpleObservable);\n\n _defineProperty(this, \"listeners\", []);\n\n if (initialFn) this.listeners.push(initialFn);\n }\n\n _createClass(SimpleObservable, [{\n key: \"onUpdate\",\n value: function onUpdate(fn) {\n this.listeners.push(fn);\n }\n }, {\n key: \"update\",\n value: function update(val) {\n var _iterator = _createForOfIteratorHelper(this.listeners),\n _step;\n\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var listener = _step.value;\n listener(val);\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n }\n }, {\n key: \"close\",\n value: function close() {\n this.listeners = []; // reset\n }\n }]);\n\n return SimpleObservable;\n}();\n\nexports.SimpleObservable = SimpleObservable;", - "'use strict'\nvar inherits = require('inherits')\nvar HashBase = require('hash-base')\nvar Buffer = require('safe-buffer').Buffer\n\nvar ARRAY16 = new Array(16)\n\nfunction MD5 () {\n HashBase.call(this, 64)\n\n // state\n this._a = 0x67452301\n this._b = 0xefcdab89\n this._c = 0x98badcfe\n this._d = 0x10325476\n}\n\ninherits(MD5, HashBase)\n\nMD5.prototype._update = function () {\n var M = ARRAY16\n for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4)\n\n var a = this._a\n var b = this._b\n var c = this._c\n var d = this._d\n\n a = fnF(a, b, c, d, M[0], 0xd76aa478, 7)\n d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12)\n c = fnF(c, d, a, b, M[2], 0x242070db, 17)\n b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22)\n a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7)\n d = fnF(d, a, b, c, M[5], 0x4787c62a, 12)\n c = fnF(c, d, a, b, M[6], 0xa8304613, 17)\n b = fnF(b, c, d, a, M[7], 0xfd469501, 22)\n a = fnF(a, b, c, d, M[8], 0x698098d8, 7)\n d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12)\n c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17)\n b = fnF(b, c, d, a, M[11], 0x895cd7be, 22)\n a = fnF(a, b, c, d, M[12], 0x6b901122, 7)\n d = fnF(d, a, b, c, M[13], 0xfd987193, 12)\n c = fnF(c, d, a, b, M[14], 0xa679438e, 17)\n b = fnF(b, c, d, a, M[15], 0x49b40821, 22)\n\n a = fnG(a, b, c, d, M[1], 0xf61e2562, 5)\n d = fnG(d, a, b, c, M[6], 0xc040b340, 9)\n c = fnG(c, d, a, b, M[11], 0x265e5a51, 14)\n b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20)\n a = fnG(a, b, c, d, M[5], 0xd62f105d, 5)\n d = fnG(d, a, b, c, M[10], 0x02441453, 9)\n c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14)\n b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20)\n a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5)\n d = fnG(d, a, b, c, M[14], 0xc33707d6, 9)\n c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14)\n b = fnG(b, c, d, a, M[8], 0x455a14ed, 20)\n a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5)\n d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9)\n c = fnG(c, d, a, b, M[7], 0x676f02d9, 14)\n b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20)\n\n a = fnH(a, b, c, d, M[5], 0xfffa3942, 4)\n d = fnH(d, a, b, c, M[8], 0x8771f681, 11)\n c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16)\n b = fnH(b, c, d, a, M[14], 0xfde5380c, 23)\n a = fnH(a, b, c, d, M[1], 0xa4beea44, 4)\n d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11)\n c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16)\n b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23)\n a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4)\n d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11)\n c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16)\n b = fnH(b, c, d, a, M[6], 0x04881d05, 23)\n a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4)\n d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11)\n c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16)\n b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23)\n\n a = fnI(a, b, c, d, M[0], 0xf4292244, 6)\n d = fnI(d, a, b, c, M[7], 0x432aff97, 10)\n c = fnI(c, d, a, b, M[14], 0xab9423a7, 15)\n b = fnI(b, c, d, a, M[5], 0xfc93a039, 21)\n a = fnI(a, b, c, d, M[12], 0x655b59c3, 6)\n d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10)\n c = fnI(c, d, a, b, M[10], 0xffeff47d, 15)\n b = fnI(b, c, d, a, M[1], 0x85845dd1, 21)\n a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6)\n d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10)\n c = fnI(c, d, a, b, M[6], 0xa3014314, 15)\n b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21)\n a = fnI(a, b, c, d, M[4], 0xf7537e82, 6)\n d = fnI(d, a, b, c, M[11], 0xbd3af235, 10)\n c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15)\n b = fnI(b, c, d, a, M[9], 0xeb86d391, 21)\n\n this._a = (this._a + a) | 0\n this._b = (this._b + b) | 0\n this._c = (this._c + c) | 0\n this._d = (this._d + d) | 0\n}\n\nMD5.prototype._digest = function () {\n // create padding and handle blocks\n this._block[this._blockOffset++] = 0x80\n if (this._blockOffset > 56) {\n this._block.fill(0, this._blockOffset, 64)\n this._update()\n this._blockOffset = 0\n }\n\n this._block.fill(0, this._blockOffset, 56)\n this._block.writeUInt32LE(this._length[0], 56)\n this._block.writeUInt32LE(this._length[1], 60)\n this._update()\n\n // produce result\n var buffer = Buffer.allocUnsafe(16)\n buffer.writeInt32LE(this._a, 0)\n buffer.writeInt32LE(this._b, 4)\n buffer.writeInt32LE(this._c, 8)\n buffer.writeInt32LE(this._d, 12)\n return buffer\n}\n\nfunction rotl (x, n) {\n return (x << n) | (x >>> (32 - n))\n}\n\nfunction fnF (a, b, c, d, m, k, s) {\n return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0\n}\n\nfunction fnG (a, b, c, d, m, k, s) {\n return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0\n}\n\nfunction fnH (a, b, c, d, m, k, s) {\n return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0\n}\n\nfunction fnI (a, b, c, d, m, k, s) {\n return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0\n}\n\nmodule.exports = MD5\n", - "var bn = require('bn.js');\nvar brorand = require('brorand');\n\nfunction MillerRabin(rand) {\n this.rand = rand || new brorand.Rand();\n}\nmodule.exports = MillerRabin;\n\nMillerRabin.create = function create(rand) {\n return new MillerRabin(rand);\n};\n\nMillerRabin.prototype._randbelow = function _randbelow(n) {\n var len = n.bitLength();\n var min_bytes = Math.ceil(len / 8);\n\n // Generage random bytes until a number less than n is found.\n // This ensures that 0..n-1 have an equal probability of being selected.\n do\n var a = new bn(this.rand.generate(min_bytes));\n while (a.cmp(n) >= 0);\n\n return a;\n};\n\nMillerRabin.prototype._randrange = function _randrange(start, stop) {\n // Generate a random number greater than or equal to start and less than stop.\n var size = stop.sub(start);\n return start.add(this._randbelow(size));\n};\n\nMillerRabin.prototype.test = function test(n, k, cb) {\n var len = n.bitLength();\n var red = bn.mont(n);\n var rone = new bn(1).toRed(red);\n\n if (!k)\n k = Math.max(1, (len / 48) | 0);\n\n // Find d and s, (n - 1) = (2 ^ s) * d;\n var n1 = n.subn(1);\n for (var s = 0; !n1.testn(s); s++) {}\n var d = n.shrn(s);\n\n var rn1 = n1.toRed(red);\n\n var prime = true;\n for (; k > 0; k--) {\n var a = this._randrange(new bn(2), n1);\n if (cb)\n cb(a);\n\n var x = a.toRed(red).redPow(d);\n if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)\n continue;\n\n for (var i = 1; i < s; i++) {\n x = x.redSqr();\n\n if (x.cmp(rone) === 0)\n return false;\n if (x.cmp(rn1) === 0)\n break;\n }\n\n if (i === s)\n return false;\n }\n\n return prime;\n};\n\nMillerRabin.prototype.getDivisor = function getDivisor(n, k) {\n var len = n.bitLength();\n var red = bn.mont(n);\n var rone = new bn(1).toRed(red);\n\n if (!k)\n k = Math.max(1, (len / 48) | 0);\n\n // Find d and s, (n - 1) = (2 ^ s) * d;\n var n1 = n.subn(1);\n for (var s = 0; !n1.testn(s); s++) {}\n var d = n.shrn(s);\n\n var rn1 = n1.toRed(red);\n\n for (; k > 0; k--) {\n var a = this._randrange(new bn(2), n1);\n\n var g = n.gcd(a);\n if (g.cmpn(1) !== 0)\n return g;\n\n var x = a.toRed(red).redPow(d);\n if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)\n continue;\n\n for (var i = 1; i < s; i++) {\n x = x.redSqr();\n\n if (x.cmp(rone) === 0)\n return x.fromRed().subn(1).gcd(n);\n if (x.cmp(rn1) === 0)\n break;\n }\n\n if (i === s) {\n x = x.redSqr();\n return x.fromRed().subn(1).gcd(n);\n }\n }\n\n return false;\n};\n", - "module.exports = assert;\n\nfunction assert(val, msg) {\n if (!val)\n throw new Error(msg || 'Assertion failed');\n}\n\nassert.equal = function assertEqual(l, r, msg) {\n if (l != r)\n throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));\n};\n", - "'use strict';\n\nvar utils = exports;\n\nfunction toArray(msg, enc) {\n if (Array.isArray(msg))\n return msg.slice();\n if (!msg)\n return [];\n var res = [];\n if (typeof msg !== 'string') {\n for (var i = 0; i < msg.length; i++)\n res[i] = msg[i] | 0;\n return res;\n }\n if (enc === 'hex') {\n msg = msg.replace(/[^a-z0-9]+/ig, '');\n if (msg.length % 2 !== 0)\n msg = '0' + msg;\n for (var i = 0; i < msg.length; i += 2)\n res.push(parseInt(msg[i] + msg[i + 1], 16));\n } else {\n for (var i = 0; i < msg.length; i++) {\n var c = msg.charCodeAt(i);\n var hi = c >> 8;\n var lo = c & 0xff;\n if (hi)\n res.push(hi, lo);\n else\n res.push(lo);\n }\n }\n return res;\n}\nutils.toArray = toArray;\n\nfunction zero2(word) {\n if (word.length === 1)\n return '0' + word;\n else\n return word;\n}\nutils.zero2 = zero2;\n\nfunction toHex(msg) {\n var res = '';\n for (var i = 0; i < msg.length; i++)\n res += zero2(msg[i].toString(16));\n return res;\n}\nutils.toHex = toHex;\n\nutils.encode = function encode(arr, enc) {\n if (enc === 'hex')\n return toHex(arr);\n else\n return arr;\n};\n", - "'use strict';\nconst retry = require('retry');\n\nconst networkErrorMsgs = [\n\t'Failed to fetch', // Chrome\n\t'NetworkError when attempting to fetch resource.', // Firefox\n\t'The Internet connection appears to be offline.', // Safari\n\t'Network request failed' // `cross-fetch`\n];\n\nclass AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\n\t\tif (message instanceof Error) {\n\t\t\tthis.originalError = message;\n\t\t\t({message} = message);\n\t\t} else {\n\t\t\tthis.originalError = new Error(message);\n\t\t\tthis.originalError.stack = this.stack;\n\t\t}\n\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\nconst decorateErrorWithCounts = (error, attemptNumber, options) => {\n\t// Minus 1 from attemptNumber because the first attempt does not count as a retry\n\tconst retriesLeft = options.retries - (attemptNumber - 1);\n\n\terror.attemptNumber = attemptNumber;\n\terror.retriesLeft = retriesLeft;\n\treturn error;\n};\n\nconst isNetworkError = errorMessage => networkErrorMsgs.includes(errorMessage);\n\nconst pRetry = (input, options) => new Promise((resolve, reject) => {\n\toptions = {\n\t\tonFailedAttempt: () => {},\n\t\tretries: 10,\n\t\t...options\n\t};\n\n\tconst operation = retry.operation(options);\n\n\toperation.attempt(async attemptNumber => {\n\t\ttry {\n\t\t\tresolve(await input(attemptNumber));\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof Error)) {\n\t\t\t\treject(new TypeError(`Non-error was thrown: \"${error}\". You should only throw errors.`));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (error instanceof AbortError) {\n\t\t\t\toperation.stop();\n\t\t\t\treject(error.originalError);\n\t\t\t} else if (error instanceof TypeError && !isNetworkError(error.message)) {\n\t\t\t\toperation.stop();\n\t\t\t\treject(error);\n\t\t\t} else {\n\t\t\t\tdecorateErrorWithCounts(error, attemptNumber, options);\n\n\t\t\t\ttry {\n\t\t\t\t\tawait options.onFailedAttempt(error);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!operation.retry(error)) {\n\t\t\t\t\treject(operation.mainError());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t});\n});\n\nmodule.exports = pRetry;\n// TODO: remove this in the next major version\nmodule.exports.default = pRetry;\n\nmodule.exports.AbortError = AbortError;\n", - "module.exports={\"2.16.840.1.101.3.4.1.1\": \"aes-128-ecb\",\n\"2.16.840.1.101.3.4.1.2\": \"aes-128-cbc\",\n\"2.16.840.1.101.3.4.1.3\": \"aes-128-ofb\",\n\"2.16.840.1.101.3.4.1.4\": \"aes-128-cfb\",\n\"2.16.840.1.101.3.4.1.21\": \"aes-192-ecb\",\n\"2.16.840.1.101.3.4.1.22\": \"aes-192-cbc\",\n\"2.16.840.1.101.3.4.1.23\": \"aes-192-ofb\",\n\"2.16.840.1.101.3.4.1.24\": \"aes-192-cfb\",\n\"2.16.840.1.101.3.4.1.41\": \"aes-256-ecb\",\n\"2.16.840.1.101.3.4.1.42\": \"aes-256-cbc\",\n\"2.16.840.1.101.3.4.1.43\": \"aes-256-ofb\",\n\"2.16.840.1.101.3.4.1.44\": \"aes-256-cfb\"\n}", - "// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js\n// Fedor, you are amazing.\n'use strict'\n\nvar asn1 = require('asn1.js')\n\nexports.certificate = require('./certificate')\n\nvar RSAPrivateKey = asn1.define('RSAPrivateKey', function () {\n this.seq().obj(\n this.key('version').int(),\n this.key('modulus').int(),\n this.key('publicExponent').int(),\n this.key('privateExponent').int(),\n this.key('prime1').int(),\n this.key('prime2').int(),\n this.key('exponent1').int(),\n this.key('exponent2').int(),\n this.key('coefficient').int()\n )\n})\nexports.RSAPrivateKey = RSAPrivateKey\n\nvar RSAPublicKey = asn1.define('RSAPublicKey', function () {\n this.seq().obj(\n this.key('modulus').int(),\n this.key('publicExponent').int()\n )\n})\nexports.RSAPublicKey = RSAPublicKey\n\nvar PublicKey = asn1.define('SubjectPublicKeyInfo', function () {\n this.seq().obj(\n this.key('algorithm').use(AlgorithmIdentifier),\n this.key('subjectPublicKey').bitstr()\n )\n})\nexports.PublicKey = PublicKey\n\nvar AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () {\n this.seq().obj(\n this.key('algorithm').objid(),\n this.key('none').null_().optional(),\n this.key('curve').objid().optional(),\n this.key('params').seq().obj(\n this.key('p').int(),\n this.key('q').int(),\n this.key('g').int()\n ).optional()\n )\n})\n\nvar PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () {\n this.seq().obj(\n this.key('version').int(),\n this.key('algorithm').use(AlgorithmIdentifier),\n this.key('subjectPrivateKey').octstr()\n )\n})\nexports.PrivateKey = PrivateKeyInfo\nvar EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () {\n this.seq().obj(\n this.key('algorithm').seq().obj(\n this.key('id').objid(),\n this.key('decrypt').seq().obj(\n this.key('kde').seq().obj(\n this.key('id').objid(),\n this.key('kdeparams').seq().obj(\n this.key('salt').octstr(),\n this.key('iters').int()\n )\n ),\n this.key('cipher').seq().obj(\n this.key('algo').objid(),\n this.key('iv').octstr()\n )\n )\n ),\n this.key('subjectPrivateKey').octstr()\n )\n})\n\nexports.EncryptedPrivateKey = EncryptedPrivateKeyInfo\n\nvar DSAPrivateKey = asn1.define('DSAPrivateKey', function () {\n this.seq().obj(\n this.key('version').int(),\n this.key('p').int(),\n this.key('q').int(),\n this.key('g').int(),\n this.key('pub_key').int(),\n this.key('priv_key').int()\n )\n})\nexports.DSAPrivateKey = DSAPrivateKey\n\nexports.DSAparam = asn1.define('DSAparam', function () {\n this.int()\n})\n\nvar ECPrivateKey = asn1.define('ECPrivateKey', function () {\n this.seq().obj(\n this.key('version').int(),\n this.key('privateKey').octstr(),\n this.key('parameters').optional().explicit(0).use(ECParameters),\n this.key('publicKey').optional().explicit(1).bitstr()\n )\n})\nexports.ECPrivateKey = ECPrivateKey\n\nvar ECParameters = asn1.define('ECParameters', function () {\n this.choice({\n namedCurve: this.objid()\n })\n})\n\nexports.signature = asn1.define('signature', function () {\n this.seq().obj(\n this.key('r').int(),\n this.key('s').int()\n )\n})\n", - "// from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js\n// thanks to @Rantanen\n\n'use strict'\n\nvar asn = require('asn1.js')\n\nvar Time = asn.define('Time', function () {\n this.choice({\n utcTime: this.utctime(),\n generalTime: this.gentime()\n })\n})\n\nvar AttributeTypeValue = asn.define('AttributeTypeValue', function () {\n this.seq().obj(\n this.key('type').objid(),\n this.key('value').any()\n )\n})\n\nvar AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () {\n this.seq().obj(\n this.key('algorithm').objid(),\n this.key('parameters').optional(),\n this.key('curve').objid().optional()\n )\n})\n\nvar SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () {\n this.seq().obj(\n this.key('algorithm').use(AlgorithmIdentifier),\n this.key('subjectPublicKey').bitstr()\n )\n})\n\nvar RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () {\n this.setof(AttributeTypeValue)\n})\n\nvar RDNSequence = asn.define('RDNSequence', function () {\n this.seqof(RelativeDistinguishedName)\n})\n\nvar Name = asn.define('Name', function () {\n this.choice({\n rdnSequence: this.use(RDNSequence)\n })\n})\n\nvar Validity = asn.define('Validity', function () {\n this.seq().obj(\n this.key('notBefore').use(Time),\n this.key('notAfter').use(Time)\n )\n})\n\nvar Extension = asn.define('Extension', function () {\n this.seq().obj(\n this.key('extnID').objid(),\n this.key('critical').bool().def(false),\n this.key('extnValue').octstr()\n )\n})\n\nvar TBSCertificate = asn.define('TBSCertificate', function () {\n this.seq().obj(\n this.key('version').explicit(0).int().optional(),\n this.key('serialNumber').int(),\n this.key('signature').use(AlgorithmIdentifier),\n this.key('issuer').use(Name),\n this.key('validity').use(Validity),\n this.key('subject').use(Name),\n this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo),\n this.key('issuerUniqueID').implicit(1).bitstr().optional(),\n this.key('subjectUniqueID').implicit(2).bitstr().optional(),\n this.key('extensions').explicit(3).seqof(Extension).optional()\n )\n})\n\nvar X509Certificate = asn.define('X509Certificate', function () {\n this.seq().obj(\n this.key('tbsCertificate').use(TBSCertificate),\n this.key('signatureAlgorithm').use(AlgorithmIdentifier),\n this.key('signatureValue').bitstr()\n )\n})\n\nmodule.exports = X509Certificate\n", - "// adapted from https://github.com/apatil/pemstrip\nvar findProc = /Proc-Type: 4,ENCRYPTED[\\n\\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\\n\\r]+([0-9A-z\\n\\r+/=]+)[\\n\\r]+/m\nvar startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m\nvar fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\\n\\r+/=]+)-----END \\1-----$/m\nvar evp = require('evp_bytestokey')\nvar ciphers = require('browserify-aes')\nvar Buffer = require('safe-buffer').Buffer\nmodule.exports = function (okey, password) {\n var key = okey.toString()\n var match = key.match(findProc)\n var decrypted\n if (!match) {\n var match2 = key.match(fullRegex)\n decrypted = Buffer.from(match2[2].replace(/[\\r\\n]/g, ''), 'base64')\n } else {\n var suite = 'aes' + match[1]\n var iv = Buffer.from(match[2], 'hex')\n var cipherText = Buffer.from(match[3].replace(/[\\r\\n]/g, ''), 'base64')\n var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key\n var out = []\n var cipher = ciphers.createDecipheriv(suite, cipherKey, iv)\n out.push(cipher.update(cipherText))\n out.push(cipher.final())\n decrypted = Buffer.concat(out)\n }\n var tag = key.match(startRegex)[1]\n return {\n tag: tag,\n data: decrypted\n }\n}\n", - "var asn1 = require('./asn1')\nvar aesid = require('./aesid.json')\nvar fixProc = require('./fixProc')\nvar ciphers = require('browserify-aes')\nvar compat = require('pbkdf2')\nvar Buffer = require('safe-buffer').Buffer\nmodule.exports = parseKeys\n\nfunction parseKeys (buffer) {\n var password\n if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) {\n password = buffer.passphrase\n buffer = buffer.key\n }\n if (typeof buffer === 'string') {\n buffer = Buffer.from(buffer)\n }\n\n var stripped = fixProc(buffer, password)\n\n var type = stripped.tag\n var data = stripped.data\n var subtype, ndata\n switch (type) {\n case 'CERTIFICATE':\n ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo\n // falls through\n case 'PUBLIC KEY':\n if (!ndata) {\n ndata = asn1.PublicKey.decode(data, 'der')\n }\n subtype = ndata.algorithm.algorithm.join('.')\n switch (subtype) {\n case '1.2.840.113549.1.1.1':\n return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der')\n case '1.2.840.10045.2.1':\n ndata.subjectPrivateKey = ndata.subjectPublicKey\n return {\n type: 'ec',\n data: ndata\n }\n case '1.2.840.10040.4.1':\n ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der')\n return {\n type: 'dsa',\n data: ndata.algorithm.params\n }\n default: throw new Error('unknown key id ' + subtype)\n }\n // throw new Error('unknown key type ' + type)\n case 'ENCRYPTED PRIVATE KEY':\n data = asn1.EncryptedPrivateKey.decode(data, 'der')\n data = decrypt(data, password)\n // falls through\n case 'PRIVATE KEY':\n ndata = asn1.PrivateKey.decode(data, 'der')\n subtype = ndata.algorithm.algorithm.join('.')\n switch (subtype) {\n case '1.2.840.113549.1.1.1':\n return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der')\n case '1.2.840.10045.2.1':\n return {\n curve: ndata.algorithm.curve,\n privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey\n }\n case '1.2.840.10040.4.1':\n ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der')\n return {\n type: 'dsa',\n params: ndata.algorithm.params\n }\n default: throw new Error('unknown key id ' + subtype)\n }\n // throw new Error('unknown key type ' + type)\n case 'RSA PUBLIC KEY':\n return asn1.RSAPublicKey.decode(data, 'der')\n case 'RSA PRIVATE KEY':\n return asn1.RSAPrivateKey.decode(data, 'der')\n case 'DSA PRIVATE KEY':\n return {\n type: 'dsa',\n params: asn1.DSAPrivateKey.decode(data, 'der')\n }\n case 'EC PRIVATE KEY':\n data = asn1.ECPrivateKey.decode(data, 'der')\n return {\n curve: data.parameters.value,\n privateKey: data.privateKey\n }\n default: throw new Error('unknown key type ' + type)\n }\n}\nparseKeys.signature = asn1.signature\nfunction decrypt (data, password) {\n var salt = data.algorithm.decrypt.kde.kdeparams.salt\n var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10)\n var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')]\n var iv = data.algorithm.decrypt.cipher.iv\n var cipherText = data.subjectPrivateKey\n var keylen = parseInt(algo.split('-')[1], 10) / 8\n var key = compat.pbkdf2Sync(password, salt, iters, keylen, 'sha1')\n var cipher = ciphers.createDecipheriv(algo, key, iv)\n var out = []\n out.push(cipher.update(cipherText))\n out.push(cipher.final())\n return Buffer.concat(out)\n}\n", - "exports.pbkdf2 = require('./lib/async')\nexports.pbkdf2Sync = require('./lib/sync')\n", - "var Buffer = require('safe-buffer').Buffer\n\nvar checkParameters = require('./precondition')\nvar defaultEncoding = require('./default-encoding')\nvar sync = require('./sync')\nvar toBuffer = require('./to-buffer')\n\nvar ZERO_BUF\nvar subtle = global.crypto && global.crypto.subtle\nvar toBrowser = {\n sha: 'SHA-1',\n 'sha-1': 'SHA-1',\n sha1: 'SHA-1',\n sha256: 'SHA-256',\n 'sha-256': 'SHA-256',\n sha384: 'SHA-384',\n 'sha-384': 'SHA-384',\n 'sha-512': 'SHA-512',\n sha512: 'SHA-512'\n}\nvar checks = []\nfunction checkNative (algo) {\n if (global.process && !global.process.browser) {\n return Promise.resolve(false)\n }\n if (!subtle || !subtle.importKey || !subtle.deriveBits) {\n return Promise.resolve(false)\n }\n if (checks[algo] !== undefined) {\n return checks[algo]\n }\n ZERO_BUF = ZERO_BUF || Buffer.alloc(8)\n var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo)\n .then(function () {\n return true\n }).catch(function () {\n return false\n })\n checks[algo] = prom\n return prom\n}\nvar nextTick\nfunction getNextTick () {\n if (nextTick) {\n return nextTick\n }\n if (global.process && global.process.nextTick) {\n nextTick = global.process.nextTick\n } else if (global.queueMicrotask) {\n nextTick = global.queueMicrotask\n } else if (global.setImmediate) {\n nextTick = global.setImmediate\n } else {\n nextTick = global.setTimeout\n }\n return nextTick\n}\nfunction browserPbkdf2 (password, salt, iterations, length, algo) {\n return subtle.importKey(\n 'raw', password, { name: 'PBKDF2' }, false, ['deriveBits']\n ).then(function (key) {\n return subtle.deriveBits({\n name: 'PBKDF2',\n salt: salt,\n iterations: iterations,\n hash: {\n name: algo\n }\n }, key, length << 3)\n }).then(function (res) {\n return Buffer.from(res)\n })\n}\n\nfunction resolvePromise (promise, callback) {\n promise.then(function (out) {\n getNextTick()(function () {\n callback(null, out)\n })\n }, function (e) {\n getNextTick()(function () {\n callback(e)\n })\n })\n}\nmodule.exports = function (password, salt, iterations, keylen, digest, callback) {\n if (typeof digest === 'function') {\n callback = digest\n digest = undefined\n }\n\n digest = digest || 'sha1'\n var algo = toBrowser[digest.toLowerCase()]\n\n if (!algo || typeof global.Promise !== 'function') {\n getNextTick()(function () {\n var out\n try {\n out = sync(password, salt, iterations, keylen, digest)\n } catch (e) {\n return callback(e)\n }\n callback(null, out)\n })\n return\n }\n\n checkParameters(iterations, keylen)\n password = toBuffer(password, defaultEncoding, 'Password')\n salt = toBuffer(salt, defaultEncoding, 'Salt')\n if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2')\n\n resolvePromise(checkNative(algo).then(function (resp) {\n if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo)\n\n return sync(password, salt, iterations, keylen, digest)\n }), callback)\n}\n", - "var defaultEncoding\n/* istanbul ignore next */\nif (global.process && global.process.browser) {\n defaultEncoding = 'utf-8'\n} else if (global.process && global.process.version) {\n var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10)\n\n defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary'\n} else {\n defaultEncoding = 'utf-8'\n}\nmodule.exports = defaultEncoding\n", - "var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs\n\nmodule.exports = function (iterations, keylen) {\n if (typeof iterations !== 'number') {\n throw new TypeError('Iterations not a number')\n }\n\n if (iterations < 0) {\n throw new TypeError('Bad iterations')\n }\n\n if (typeof keylen !== 'number') {\n throw new TypeError('Key length not a number')\n }\n\n if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */\n throw new TypeError('Bad key length')\n }\n}\n", - "var md5 = require('create-hash/md5')\nvar RIPEMD160 = require('ripemd160')\nvar sha = require('sha.js')\nvar Buffer = require('safe-buffer').Buffer\n\nvar checkParameters = require('./precondition')\nvar defaultEncoding = require('./default-encoding')\nvar toBuffer = require('./to-buffer')\n\nvar ZEROS = Buffer.alloc(128)\nvar sizes = {\n md5: 16,\n sha1: 20,\n sha224: 28,\n sha256: 32,\n sha384: 48,\n sha512: 64,\n rmd160: 20,\n ripemd160: 20\n}\n\nfunction Hmac (alg, key, saltLen) {\n var hash = getDigest(alg)\n var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64\n\n if (key.length > blocksize) {\n key = hash(key)\n } else if (key.length < blocksize) {\n key = Buffer.concat([key, ZEROS], blocksize)\n }\n\n var ipad = Buffer.allocUnsafe(blocksize + sizes[alg])\n var opad = Buffer.allocUnsafe(blocksize + sizes[alg])\n for (var i = 0; i < blocksize; i++) {\n ipad[i] = key[i] ^ 0x36\n opad[i] = key[i] ^ 0x5C\n }\n\n var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4)\n ipad.copy(ipad1, 0, 0, blocksize)\n this.ipad1 = ipad1\n this.ipad2 = ipad\n this.opad = opad\n this.alg = alg\n this.blocksize = blocksize\n this.hash = hash\n this.size = sizes[alg]\n}\n\nHmac.prototype.run = function (data, ipad) {\n data.copy(ipad, this.blocksize)\n var h = this.hash(ipad)\n h.copy(this.opad, this.blocksize)\n return this.hash(this.opad)\n}\n\nfunction getDigest (alg) {\n function shaFunc (data) {\n return sha(alg).update(data).digest()\n }\n function rmd160Func (data) {\n return new RIPEMD160().update(data).digest()\n }\n\n if (alg === 'rmd160' || alg === 'ripemd160') return rmd160Func\n if (alg === 'md5') return md5\n return shaFunc\n}\n\nfunction pbkdf2 (password, salt, iterations, keylen, digest) {\n checkParameters(iterations, keylen)\n password = toBuffer(password, defaultEncoding, 'Password')\n salt = toBuffer(salt, defaultEncoding, 'Salt')\n\n digest = digest || 'sha1'\n\n var hmac = new Hmac(digest, password, salt.length)\n\n var DK = Buffer.allocUnsafe(keylen)\n var block1 = Buffer.allocUnsafe(salt.length + 4)\n salt.copy(block1, 0, 0, salt.length)\n\n var destPos = 0\n var hLen = sizes[digest]\n var l = Math.ceil(keylen / hLen)\n\n for (var i = 1; i <= l; i++) {\n block1.writeUInt32BE(i, salt.length)\n\n var T = hmac.run(block1, hmac.ipad1)\n var U = T\n\n for (var j = 1; j < iterations; j++) {\n U = hmac.run(U, hmac.ipad2)\n for (var k = 0; k < hLen; k++) T[k] ^= U[k]\n }\n\n T.copy(DK, destPos)\n destPos += hLen\n }\n\n return DK\n}\n\nmodule.exports = pbkdf2\n", - "var Buffer = require('safe-buffer').Buffer\n\nmodule.exports = function (thing, encoding, name) {\n if (Buffer.isBuffer(thing)) {\n return thing\n } else if (typeof thing === 'string') {\n return Buffer.from(thing, encoding)\n } else if (ArrayBuffer.isView(thing)) {\n return Buffer.from(thing.buffer)\n } else {\n throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView')\n }\n}\n", - "// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n", - "exports.publicEncrypt = require('./publicEncrypt')\nexports.privateDecrypt = require('./privateDecrypt')\n\nexports.privateEncrypt = function privateEncrypt (key, buf) {\n return exports.publicEncrypt(key, buf, true)\n}\n\nexports.publicDecrypt = function publicDecrypt (key, buf) {\n return exports.privateDecrypt(key, buf, true)\n}\n", - "var createHash = require('create-hash')\nvar Buffer = require('safe-buffer').Buffer\n\nmodule.exports = function (seed, len) {\n var t = Buffer.alloc(0)\n var i = 0\n var c\n while (t.length < len) {\n c = i2ops(i++)\n t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()])\n }\n return t.slice(0, len)\n}\n\nfunction i2ops (c) {\n var out = Buffer.allocUnsafe(4)\n out.writeUInt32BE(c, 0)\n return out\n}\n", - "var parseKeys = require('parse-asn1')\nvar mgf = require('./mgf')\nvar xor = require('./xor')\nvar BN = require('bn.js')\nvar crt = require('browserify-rsa')\nvar createHash = require('create-hash')\nvar withPublic = require('./withPublic')\nvar Buffer = require('safe-buffer').Buffer\n\nmodule.exports = function privateDecrypt (privateKey, enc, reverse) {\n var padding\n if (privateKey.padding) {\n padding = privateKey.padding\n } else if (reverse) {\n padding = 1\n } else {\n padding = 4\n }\n\n var key = parseKeys(privateKey)\n var k = key.modulus.byteLength()\n if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0) {\n throw new Error('decryption error')\n }\n var msg\n if (reverse) {\n msg = withPublic(new BN(enc), key)\n } else {\n msg = crt(enc, key)\n }\n var zBuffer = Buffer.alloc(k - msg.length)\n msg = Buffer.concat([zBuffer, msg], k)\n if (padding === 4) {\n return oaep(key, msg)\n } else if (padding === 1) {\n return pkcs1(key, msg, reverse)\n } else if (padding === 3) {\n return msg\n } else {\n throw new Error('unknown padding')\n }\n}\n\nfunction oaep (key, msg) {\n var k = key.modulus.byteLength()\n var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()\n var hLen = iHash.length\n if (msg[0] !== 0) {\n throw new Error('decryption error')\n }\n var maskedSeed = msg.slice(1, hLen + 1)\n var maskedDb = msg.slice(hLen + 1)\n var seed = xor(maskedSeed, mgf(maskedDb, hLen))\n var db = xor(maskedDb, mgf(seed, k - hLen - 1))\n if (compare(iHash, db.slice(0, hLen))) {\n throw new Error('decryption error')\n }\n var i = hLen\n while (db[i] === 0) {\n i++\n }\n if (db[i++] !== 1) {\n throw new Error('decryption error')\n }\n return db.slice(i)\n}\n\nfunction pkcs1 (key, msg, reverse) {\n var p1 = msg.slice(0, 2)\n var i = 2\n var status = 0\n while (msg[i++] !== 0) {\n if (i >= msg.length) {\n status++\n break\n }\n }\n var ps = msg.slice(2, i - 1)\n\n if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)) {\n status++\n }\n if (ps.length < 8) {\n status++\n }\n if (status) {\n throw new Error('decryption error')\n }\n return msg.slice(i)\n}\nfunction compare (a, b) {\n a = Buffer.from(a)\n b = Buffer.from(b)\n var dif = 0\n var len = a.length\n if (a.length !== b.length) {\n dif++\n len = Math.min(a.length, b.length)\n }\n var i = -1\n while (++i < len) {\n dif += (a[i] ^ b[i])\n }\n return dif\n}\n", - "var parseKeys = require('parse-asn1')\nvar randomBytes = require('randombytes')\nvar createHash = require('create-hash')\nvar mgf = require('./mgf')\nvar xor = require('./xor')\nvar BN = require('bn.js')\nvar withPublic = require('./withPublic')\nvar crt = require('browserify-rsa')\nvar Buffer = require('safe-buffer').Buffer\n\nmodule.exports = function publicEncrypt (publicKey, msg, reverse) {\n var padding\n if (publicKey.padding) {\n padding = publicKey.padding\n } else if (reverse) {\n padding = 1\n } else {\n padding = 4\n }\n var key = parseKeys(publicKey)\n var paddedMsg\n if (padding === 4) {\n paddedMsg = oaep(key, msg)\n } else if (padding === 1) {\n paddedMsg = pkcs1(key, msg, reverse)\n } else if (padding === 3) {\n paddedMsg = new BN(msg)\n if (paddedMsg.cmp(key.modulus) >= 0) {\n throw new Error('data too long for modulus')\n }\n } else {\n throw new Error('unknown padding')\n }\n if (reverse) {\n return crt(paddedMsg, key)\n } else {\n return withPublic(paddedMsg, key)\n }\n}\n\nfunction oaep (key, msg) {\n var k = key.modulus.byteLength()\n var mLen = msg.length\n var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()\n var hLen = iHash.length\n var hLen2 = 2 * hLen\n if (mLen > k - hLen2 - 2) {\n throw new Error('message too long')\n }\n var ps = Buffer.alloc(k - mLen - hLen2 - 2)\n var dblen = k - hLen - 1\n var seed = randomBytes(hLen)\n var maskedDb = xor(Buffer.concat([iHash, ps, Buffer.alloc(1, 1), msg], dblen), mgf(seed, dblen))\n var maskedSeed = xor(seed, mgf(maskedDb, hLen))\n return new BN(Buffer.concat([Buffer.alloc(1), maskedSeed, maskedDb], k))\n}\nfunction pkcs1 (key, msg, reverse) {\n var mLen = msg.length\n var k = key.modulus.byteLength()\n if (mLen > k - 11) {\n throw new Error('message too long')\n }\n var ps\n if (reverse) {\n ps = Buffer.alloc(k - mLen - 3, 0xff)\n } else {\n ps = nonZero(k - mLen - 3)\n }\n return new BN(Buffer.concat([Buffer.from([0, reverse ? 1 : 2]), ps, Buffer.alloc(1), msg], k))\n}\nfunction nonZero (len) {\n var out = Buffer.allocUnsafe(len)\n var i = 0\n var cache = randomBytes(len * 2)\n var cur = 0\n var num\n while (i < len) {\n if (cur === cache.length) {\n cache = randomBytes(len * 2)\n cur = 0\n }\n num = cache[cur++]\n if (num) {\n out[i++] = num\n }\n }\n return out\n}\n", - "var BN = require('bn.js')\nvar Buffer = require('safe-buffer').Buffer\n\nfunction withPublic (paddedMsg, key) {\n return Buffer.from(paddedMsg\n .toRed(BN.mont(key.modulus))\n .redPow(new BN(key.publicExponent))\n .fromRed()\n .toArray())\n}\n\nmodule.exports = withPublic\n", - "module.exports = function xor (a, b) {\n var len = a.length\n var i = -1\n while (++i < len) {\n a[i] ^= b[i]\n }\n return a\n}\n", - "'use strict'\n\n// limit of Crypto.getRandomValues()\n// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues\nvar MAX_BYTES = 65536\n\n// Node supports requesting up to this number of bytes\n// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48\nvar MAX_UINT32 = 4294967295\n\nfunction oldBrowser () {\n throw new Error('Secure random number generation is not supported by this browser.\\nUse Chrome, Firefox or Internet Explorer 11')\n}\n\nvar Buffer = require('safe-buffer').Buffer\nvar crypto = global.crypto || global.msCrypto\n\nif (crypto && crypto.getRandomValues) {\n module.exports = randomBytes\n} else {\n module.exports = oldBrowser\n}\n\nfunction randomBytes (size, cb) {\n // phantomjs needs to throw\n if (size > MAX_UINT32) throw new RangeError('requested too many random bytes')\n\n var bytes = Buffer.allocUnsafe(size)\n\n if (size > 0) { // getRandomValues fails on IE if size == 0\n if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues\n // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues\n for (var generated = 0; generated < size; generated += MAX_BYTES) {\n // buffer.slice automatically checks if the end is past the end of\n // the buffer so we don't have to here\n crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES))\n }\n } else {\n crypto.getRandomValues(bytes)\n }\n }\n\n if (typeof cb === 'function') {\n return process.nextTick(function () {\n cb(null, bytes)\n })\n }\n\n return bytes\n}\n", - "'use strict'\n\nfunction oldBrowser () {\n throw new Error('secure random number generation not supported by this browser\\nuse chrome, FireFox or Internet Explorer 11')\n}\nvar safeBuffer = require('safe-buffer')\nvar randombytes = require('randombytes')\nvar Buffer = safeBuffer.Buffer\nvar kBufferMaxLength = safeBuffer.kMaxLength\nvar crypto = global.crypto || global.msCrypto\nvar kMaxUint32 = Math.pow(2, 32) - 1\nfunction assertOffset (offset, length) {\n if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare\n throw new TypeError('offset must be a number')\n }\n\n if (offset > kMaxUint32 || offset < 0) {\n throw new TypeError('offset must be a uint32')\n }\n\n if (offset > kBufferMaxLength || offset > length) {\n throw new RangeError('offset out of range')\n }\n}\n\nfunction assertSize (size, offset, length) {\n if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare\n throw new TypeError('size must be a number')\n }\n\n if (size > kMaxUint32 || size < 0) {\n throw new TypeError('size must be a uint32')\n }\n\n if (size + offset > length || size > kBufferMaxLength) {\n throw new RangeError('buffer too small')\n }\n}\nif ((crypto && crypto.getRandomValues) || !process.browser) {\n exports.randomFill = randomFill\n exports.randomFillSync = randomFillSync\n} else {\n exports.randomFill = oldBrowser\n exports.randomFillSync = oldBrowser\n}\nfunction randomFill (buf, offset, size, cb) {\n if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {\n throw new TypeError('\"buf\" argument must be a Buffer or Uint8Array')\n }\n\n if (typeof offset === 'function') {\n cb = offset\n offset = 0\n size = buf.length\n } else if (typeof size === 'function') {\n cb = size\n size = buf.length - offset\n } else if (typeof cb !== 'function') {\n throw new TypeError('\"cb\" argument must be a function')\n }\n assertOffset(offset, buf.length)\n assertSize(size, offset, buf.length)\n return actualFill(buf, offset, size, cb)\n}\n\nfunction actualFill (buf, offset, size, cb) {\n if (process.browser) {\n var ourBuf = buf.buffer\n var uint = new Uint8Array(ourBuf, offset, size)\n crypto.getRandomValues(uint)\n if (cb) {\n process.nextTick(function () {\n cb(null, buf)\n })\n return\n }\n return buf\n }\n if (cb) {\n randombytes(size, function (err, bytes) {\n if (err) {\n return cb(err)\n }\n bytes.copy(buf, offset)\n cb(null, buf)\n })\n return\n }\n var bytes = randombytes(size)\n bytes.copy(buf, offset)\n return buf\n}\nfunction randomFillSync (buf, offset, size) {\n if (typeof offset === 'undefined') {\n offset = 0\n }\n if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {\n throw new TypeError('\"buf\" argument must be a Buffer or Uint8Array')\n }\n\n assertOffset(offset, buf.length)\n\n if (size === undefined) size = buf.length - offset\n\n assertSize(size, offset, buf.length)\n\n return actualFill(buf, offset, size)\n}\n", - "module.exports = require('./lib/retry');", - "var RetryOperation = require('./retry_operation');\n\nexports.operation = function(options) {\n var timeouts = exports.timeouts(options);\n return new RetryOperation(timeouts, {\n forever: options && (options.forever || options.retries === Infinity),\n unref: options && options.unref,\n maxRetryTime: options && options.maxRetryTime\n });\n};\n\nexports.timeouts = function(options) {\n if (options instanceof Array) {\n return [].concat(options);\n }\n\n var opts = {\n retries: 10,\n factor: 2,\n minTimeout: 1 * 1000,\n maxTimeout: Infinity,\n randomize: false\n };\n for (var key in options) {\n opts[key] = options[key];\n }\n\n if (opts.minTimeout > opts.maxTimeout) {\n throw new Error('minTimeout is greater than maxTimeout');\n }\n\n var timeouts = [];\n for (var i = 0; i < opts.retries; i++) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n if (options && options.forever && !timeouts.length) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n // sort the array numerically ascending\n timeouts.sort(function(a,b) {\n return a - b;\n });\n\n return timeouts;\n};\n\nexports.createTimeout = function(attempt, opts) {\n var random = (opts.randomize)\n ? (Math.random() + 1)\n : 1;\n\n var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));\n timeout = Math.min(timeout, opts.maxTimeout);\n\n return timeout;\n};\n\nexports.wrap = function(obj, options, methods) {\n if (options instanceof Array) {\n methods = options;\n options = null;\n }\n\n if (!methods) {\n methods = [];\n for (var key in obj) {\n if (typeof obj[key] === 'function') {\n methods.push(key);\n }\n }\n }\n\n for (var i = 0; i < methods.length; i++) {\n var method = methods[i];\n var original = obj[method];\n\n obj[method] = function retryWrapper(original) {\n var op = exports.operation(options);\n var args = Array.prototype.slice.call(arguments, 1);\n var callback = args.pop();\n\n args.push(function(err) {\n if (op.retry(err)) {\n return;\n }\n if (err) {\n arguments[0] = op.mainError();\n }\n callback.apply(this, arguments);\n });\n\n op.attempt(function() {\n original.apply(obj, args);\n });\n }.bind(obj, original);\n obj[method].options = options;\n }\n};\n", - "function RetryOperation(timeouts, options) {\n // Compatibility for the old (timeouts, retryForever) signature\n if (typeof options === 'boolean') {\n options = { forever: options };\n }\n\n this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));\n this._timeouts = timeouts;\n this._options = options || {};\n this._maxRetryTime = options && options.maxRetryTime || Infinity;\n this._fn = null;\n this._errors = [];\n this._attempts = 1;\n this._operationTimeout = null;\n this._operationTimeoutCb = null;\n this._timeout = null;\n this._operationStart = null;\n this._timer = null;\n\n if (this._options.forever) {\n this._cachedTimeouts = this._timeouts.slice(0);\n }\n}\nmodule.exports = RetryOperation;\n\nRetryOperation.prototype.reset = function() {\n this._attempts = 1;\n this._timeouts = this._originalTimeouts.slice(0);\n}\n\nRetryOperation.prototype.stop = function() {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n if (this._timer) {\n clearTimeout(this._timer);\n }\n\n this._timeouts = [];\n this._cachedTimeouts = null;\n};\n\nRetryOperation.prototype.retry = function(err) {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n\n if (!err) {\n return false;\n }\n var currentTime = new Date().getTime();\n if (err && currentTime - this._operationStart >= this._maxRetryTime) {\n this._errors.push(err);\n this._errors.unshift(new Error('RetryOperation timeout occurred'));\n return false;\n }\n\n this._errors.push(err);\n\n var timeout = this._timeouts.shift();\n if (timeout === undefined) {\n if (this._cachedTimeouts) {\n // retry forever, only keep last error\n this._errors.splice(0, this._errors.length - 1);\n timeout = this._cachedTimeouts.slice(-1);\n } else {\n return false;\n }\n }\n\n var self = this;\n this._timer = setTimeout(function() {\n self._attempts++;\n\n if (self._operationTimeoutCb) {\n self._timeout = setTimeout(function() {\n self._operationTimeoutCb(self._attempts);\n }, self._operationTimeout);\n\n if (self._options.unref) {\n self._timeout.unref();\n }\n }\n\n self._fn(self._attempts);\n }, timeout);\n\n if (this._options.unref) {\n this._timer.unref();\n }\n\n return true;\n};\n\nRetryOperation.prototype.attempt = function(fn, timeoutOps) {\n this._fn = fn;\n\n if (timeoutOps) {\n if (timeoutOps.timeout) {\n this._operationTimeout = timeoutOps.timeout;\n }\n if (timeoutOps.cb) {\n this._operationTimeoutCb = timeoutOps.cb;\n }\n }\n\n var self = this;\n if (this._operationTimeoutCb) {\n this._timeout = setTimeout(function() {\n self._operationTimeoutCb();\n }, self._operationTimeout);\n }\n\n this._operationStart = new Date().getTime();\n\n this._fn(this._attempts);\n};\n\nRetryOperation.prototype.try = function(fn) {\n console.log('Using RetryOperation.try() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = function(fn) {\n console.log('Using RetryOperation.start() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = RetryOperation.prototype.try;\n\nRetryOperation.prototype.errors = function() {\n return this._errors;\n};\n\nRetryOperation.prototype.attempts = function() {\n return this._attempts;\n};\n\nRetryOperation.prototype.mainError = function() {\n if (this._errors.length === 0) {\n return null;\n }\n\n var counts = {};\n var mainError = null;\n var mainErrorCount = 0;\n\n for (var i = 0; i < this._errors.length; i++) {\n var error = this._errors[i];\n var message = error.message;\n var count = (counts[message] || 0) + 1;\n\n counts[message] = count;\n\n if (count >= mainErrorCount) {\n mainError = error;\n mainErrorCount = count;\n }\n }\n\n return mainError;\n};\n", - "'use strict'\nvar Buffer = require('buffer').Buffer\nvar inherits = require('inherits')\nvar HashBase = require('hash-base')\n\nvar ARRAY16 = new Array(16)\n\nvar zl = [\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,\n 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,\n 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13\n]\n\nvar zr = [\n 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,\n 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,\n 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,\n 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,\n 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11\n]\n\nvar sl = [\n 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,\n 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,\n 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,\n 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,\n 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6\n]\n\nvar sr = [\n 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,\n 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,\n 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,\n 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,\n 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11\n]\n\nvar hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]\nvar hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]\n\nfunction RIPEMD160 () {\n HashBase.call(this, 64)\n\n // state\n this._a = 0x67452301\n this._b = 0xefcdab89\n this._c = 0x98badcfe\n this._d = 0x10325476\n this._e = 0xc3d2e1f0\n}\n\ninherits(RIPEMD160, HashBase)\n\nRIPEMD160.prototype._update = function () {\n var words = ARRAY16\n for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4)\n\n var al = this._a | 0\n var bl = this._b | 0\n var cl = this._c | 0\n var dl = this._d | 0\n var el = this._e | 0\n\n var ar = this._a | 0\n var br = this._b | 0\n var cr = this._c | 0\n var dr = this._d | 0\n var er = this._e | 0\n\n // computation\n for (var i = 0; i < 80; i += 1) {\n var tl\n var tr\n if (i < 16) {\n tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i])\n tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i])\n } else if (i < 32) {\n tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i])\n tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i])\n } else if (i < 48) {\n tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i])\n tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i])\n } else if (i < 64) {\n tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i])\n tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i])\n } else { // if (i<80) {\n tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i])\n tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i])\n }\n\n al = el\n el = dl\n dl = rotl(cl, 10)\n cl = bl\n bl = tl\n\n ar = er\n er = dr\n dr = rotl(cr, 10)\n cr = br\n br = tr\n }\n\n // update state\n var t = (this._b + cl + dr) | 0\n this._b = (this._c + dl + er) | 0\n this._c = (this._d + el + ar) | 0\n this._d = (this._e + al + br) | 0\n this._e = (this._a + bl + cr) | 0\n this._a = t\n}\n\nRIPEMD160.prototype._digest = function () {\n // create padding and handle blocks\n this._block[this._blockOffset++] = 0x80\n if (this._blockOffset > 56) {\n this._block.fill(0, this._blockOffset, 64)\n this._update()\n this._blockOffset = 0\n }\n\n this._block.fill(0, this._blockOffset, 56)\n this._block.writeUInt32LE(this._length[0], 56)\n this._block.writeUInt32LE(this._length[1], 60)\n this._update()\n\n // produce result\n var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20)\n buffer.writeInt32LE(this._a, 0)\n buffer.writeInt32LE(this._b, 4)\n buffer.writeInt32LE(this._c, 8)\n buffer.writeInt32LE(this._d, 12)\n buffer.writeInt32LE(this._e, 16)\n return buffer\n}\n\nfunction rotl (x, n) {\n return (x << n) | (x >>> (32 - n))\n}\n\nfunction fn1 (a, b, c, d, e, m, k, s) {\n return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0\n}\n\nfunction fn2 (a, b, c, d, e, m, k, s) {\n return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0\n}\n\nfunction fn3 (a, b, c, d, e, m, k, s) {\n return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0\n}\n\nfunction fn4 (a, b, c, d, e, m, k, s) {\n return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0\n}\n\nfunction fn5 (a, b, c, d, e, m, k, s) {\n return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0\n}\n\nmodule.exports = RIPEMD160\n", - "/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n", - "/* eslint-disable node/no-deprecated-api */\n\n'use strict'\n\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\nvar safer = {}\n\nvar key\n\nfor (key in buffer) {\n if (!buffer.hasOwnProperty(key)) continue\n if (key === 'SlowBuffer' || key === 'Buffer') continue\n safer[key] = buffer[key]\n}\n\nvar Safer = safer.Buffer = {}\nfor (key in Buffer) {\n if (!Buffer.hasOwnProperty(key)) continue\n if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue\n Safer[key] = Buffer[key]\n}\n\nsafer.Buffer.prototype = Buffer.prototype\n\nif (!Safer.from || Safer.from === Uint8Array.from) {\n Safer.from = function (value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('The \"value\" argument must not be of type number. Received type ' + typeof value)\n }\n if (value && typeof value.length === 'undefined') {\n throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value)\n }\n return Buffer(value, encodingOrOffset, length)\n }\n}\n\nif (!Safer.alloc) {\n Safer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('The \"size\" argument must be of type number. Received type ' + typeof size)\n }\n if (size < 0 || size >= 2 * (1 << 30)) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n var buf = Buffer(size)\n if (!fill || fill.length === 0) {\n buf.fill(0)\n } else if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n return buf\n }\n}\n\nif (!safer.kStringMaxLength) {\n try {\n safer.kStringMaxLength = process.binding('buffer').kStringMaxLength\n } catch (e) {\n // we can't determine kStringMaxLength in environments where process.binding\n // is unsupported, so let's not set it\n }\n}\n\nif (!safer.constants) {\n safer.constants = {\n MAX_LENGTH: safer.kMaxLength\n }\n if (safer.kStringMaxLength) {\n safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength\n }\n}\n\nmodule.exports = safer\n", - "var grammar = module.exports = {\n v: [{\n name: 'version',\n reg: /^(\\d*)$/\n }],\n o: [{\n // o=- 20518 0 IN IP4 203.0.113.1\n // NB: sessionId will be a String in most cases because it is huge\n name: 'origin',\n reg: /^(\\S*) (\\d*) (\\d*) (\\S*) IP(\\d) (\\S*)/,\n names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],\n format: '%s %s %d %s IP%d %s'\n }],\n // default parsing of these only (though some of these feel outdated)\n s: [{ name: 'name' }],\n i: [{ name: 'description' }],\n u: [{ name: 'uri' }],\n e: [{ name: 'email' }],\n p: [{ name: 'phone' }],\n z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly...\n r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly\n // k: [{}], // outdated thing ignored\n t: [{\n // t=0 0\n name: 'timing',\n reg: /^(\\d*) (\\d*)/,\n names: ['start', 'stop'],\n format: '%d %d'\n }],\n c: [{\n // c=IN IP4 10.47.197.26\n name: 'connection',\n reg: /^IN IP(\\d) (\\S*)/,\n names: ['version', 'ip'],\n format: 'IN IP%d %s'\n }],\n b: [{\n // b=AS:4000\n push: 'bandwidth',\n reg: /^(TIAS|AS|CT|RR|RS):(\\d*)/,\n names: ['type', 'limit'],\n format: '%s:%s'\n }],\n m: [{\n // m=video 51744 RTP/AVP 126 97 98 34 31\n // NB: special - pushes to session\n // TODO: rtp/fmtp should be filtered by the payloads found here?\n reg: /^(\\w*) (\\d*) ([\\w/]*)(?: (.*))?/,\n names: ['type', 'port', 'protocol', 'payloads'],\n format: '%s %d %s %s'\n }],\n a: [\n {\n // a=rtpmap:110 opus/48000/2\n push: 'rtp',\n reg: /^rtpmap:(\\d*) ([\\w\\-.]*)(?:\\s*\\/(\\d*)(?:\\s*\\/(\\S*))?)?/,\n names: ['payload', 'codec', 'rate', 'encoding'],\n format: function (o) {\n return (o.encoding)\n ? 'rtpmap:%d %s/%s/%s'\n : o.rate\n ? 'rtpmap:%d %s/%s'\n : 'rtpmap:%d %s';\n }\n },\n {\n // a=fmtp:108 profile-level-id=24;object=23;bitrate=64000\n // a=fmtp:111 minptime=10; useinbandfec=1\n push: 'fmtp',\n reg: /^fmtp:(\\d*) ([\\S| ]*)/,\n names: ['payload', 'config'],\n format: 'fmtp:%d %s'\n },\n {\n // a=control:streamid=0\n name: 'control',\n reg: /^control:(.*)/,\n format: 'control:%s'\n },\n {\n // a=rtcp:65179 IN IP4 193.84.77.194\n name: 'rtcp',\n reg: /^rtcp:(\\d*)(?: (\\S*) IP(\\d) (\\S*))?/,\n names: ['port', 'netType', 'ipVer', 'address'],\n format: function (o) {\n return (o.address != null)\n ? 'rtcp:%d %s IP%d %s'\n : 'rtcp:%d';\n }\n },\n {\n // a=rtcp-fb:98 trr-int 100\n push: 'rtcpFbTrrInt',\n reg: /^rtcp-fb:(\\*|\\d*) trr-int (\\d*)/,\n names: ['payload', 'value'],\n format: 'rtcp-fb:%s trr-int %d'\n },\n {\n // a=rtcp-fb:98 nack rpsi\n push: 'rtcpFb',\n reg: /^rtcp-fb:(\\*|\\d*) ([\\w-_]*)(?: ([\\w-_]*))?/,\n names: ['payload', 'type', 'subtype'],\n format: function (o) {\n return (o.subtype != null)\n ? 'rtcp-fb:%s %s %s'\n : 'rtcp-fb:%s %s';\n }\n },\n {\n // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset\n // a=extmap:1/recvonly URI-gps-string\n // a=extmap:3 urn:ietf:params:rtp-hdrext:encrypt urn:ietf:params:rtp-hdrext:smpte-tc 25@600/24\n push: 'ext',\n reg: /^extmap:(\\d+)(?:\\/(\\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\\S*)(?: (\\S*))?/,\n names: ['value', 'direction', 'encrypt-uri', 'uri', 'config'],\n format: function (o) {\n return (\n 'extmap:%d' +\n (o.direction ? '/%s' : '%v') +\n (o['encrypt-uri'] ? ' %s' : '%v') +\n ' %s' +\n (o.config ? ' %s' : '')\n );\n }\n },\n {\n // a=extmap-allow-mixed\n name: 'extmapAllowMixed',\n reg: /^(extmap-allow-mixed)/\n },\n {\n // a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32\n push: 'crypto',\n reg: /^crypto:(\\d*) ([\\w_]*) (\\S*)(?: (\\S*))?/,\n names: ['id', 'suite', 'config', 'sessionConfig'],\n format: function (o) {\n return (o.sessionConfig != null)\n ? 'crypto:%d %s %s %s'\n : 'crypto:%d %s %s';\n }\n },\n {\n // a=setup:actpass\n name: 'setup',\n reg: /^setup:(\\w*)/,\n format: 'setup:%s'\n },\n {\n // a=connection:new\n name: 'connectionType',\n reg: /^connection:(new|existing)/,\n format: 'connection:%s'\n },\n {\n // a=mid:1\n name: 'mid',\n reg: /^mid:([^\\s]*)/,\n format: 'mid:%s'\n },\n {\n // a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a\n name: 'msid',\n reg: /^msid:(.*)/,\n format: 'msid:%s'\n },\n {\n // a=ptime:20\n name: 'ptime',\n reg: /^ptime:(\\d*(?:\\.\\d*)*)/,\n format: 'ptime:%d'\n },\n {\n // a=maxptime:60\n name: 'maxptime',\n reg: /^maxptime:(\\d*(?:\\.\\d*)*)/,\n format: 'maxptime:%d'\n },\n {\n // a=sendrecv\n name: 'direction',\n reg: /^(sendrecv|recvonly|sendonly|inactive)/\n },\n {\n // a=ice-lite\n name: 'icelite',\n reg: /^(ice-lite)/\n },\n {\n // a=ice-ufrag:F7gI\n name: 'iceUfrag',\n reg: /^ice-ufrag:(\\S*)/,\n format: 'ice-ufrag:%s'\n },\n {\n // a=ice-pwd:x9cml/YzichV2+XlhiMu8g\n name: 'icePwd',\n reg: /^ice-pwd:(\\S*)/,\n format: 'ice-pwd:%s'\n },\n {\n // a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33\n name: 'fingerprint',\n reg: /^fingerprint:(\\S*) (\\S*)/,\n names: ['type', 'hash'],\n format: 'fingerprint:%s %s'\n },\n {\n // a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host\n // a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0 network-id 3 network-cost 10\n // a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0 network-id 3 network-cost 10\n // a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0 network-id 3 network-cost 10\n // a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0 network-id 3 network-cost 10\n push:'candidates',\n reg: /^candidate:(\\S*) (\\d*) (\\S*) (\\d*) (\\S*) (\\d*) typ (\\S*)(?: raddr (\\S*) rport (\\d*))?(?: tcptype (\\S*))?(?: generation (\\d*))?(?: network-id (\\d*))?(?: network-cost (\\d*))?/,\n names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation', 'network-id', 'network-cost'],\n format: function (o) {\n var str = 'candidate:%s %d %s %d %s %d typ %s';\n\n str += (o.raddr != null) ? ' raddr %s rport %d' : '%v%v';\n\n // NB: candidate has three optional chunks, so %void middles one if it's missing\n str += (o.tcptype != null) ? ' tcptype %s' : '%v';\n\n if (o.generation != null) {\n str += ' generation %d';\n }\n\n str += (o['network-id'] != null) ? ' network-id %d' : '%v';\n str += (o['network-cost'] != null) ? ' network-cost %d' : '%v';\n return str;\n }\n },\n {\n // a=end-of-candidates (keep after the candidates line for readability)\n name: 'endOfCandidates',\n reg: /^(end-of-candidates)/\n },\n {\n // a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...\n name: 'remoteCandidates',\n reg: /^remote-candidates:(.*)/,\n format: 'remote-candidates:%s'\n },\n {\n // a=ice-options:google-ice\n name: 'iceOptions',\n reg: /^ice-options:(\\S*)/,\n format: 'ice-options:%s'\n },\n {\n // a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1\n push: 'ssrcs',\n reg: /^ssrc:(\\d*) ([\\w_-]*)(?::(.*))?/,\n names: ['id', 'attribute', 'value'],\n format: function (o) {\n var str = 'ssrc:%d';\n if (o.attribute != null) {\n str += ' %s';\n if (o.value != null) {\n str += ':%s';\n }\n }\n return str;\n }\n },\n {\n // a=ssrc-group:FEC 1 2\n // a=ssrc-group:FEC-FR 3004364195 1080772241\n push: 'ssrcGroups',\n // token-char = %x21 / %x23-27 / %x2A-2B / %x2D-2E / %x30-39 / %x41-5A / %x5E-7E\n reg: /^ssrc-group:([\\x21\\x23\\x24\\x25\\x26\\x27\\x2A\\x2B\\x2D\\x2E\\w]*) (.*)/,\n names: ['semantics', 'ssrcs'],\n format: 'ssrc-group:%s %s'\n },\n {\n // a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV\n name: 'msidSemantic',\n reg: /^msid-semantic:\\s?(\\w*) (\\S*)/,\n names: ['semantic', 'token'],\n format: 'msid-semantic: %s %s' // space after ':' is not accidental\n },\n {\n // a=group:BUNDLE audio video\n push: 'groups',\n reg: /^group:(\\w*) (.*)/,\n names: ['type', 'mids'],\n format: 'group:%s %s'\n },\n {\n // a=rtcp-mux\n name: 'rtcpMux',\n reg: /^(rtcp-mux)/\n },\n {\n // a=rtcp-rsize\n name: 'rtcpRsize',\n reg: /^(rtcp-rsize)/\n },\n {\n // a=sctpmap:5000 webrtc-datachannel 1024\n name: 'sctpmap',\n reg: /^sctpmap:([\\w_/]*) (\\S*)(?: (\\S*))?/,\n names: ['sctpmapNumber', 'app', 'maxMessageSize'],\n format: function (o) {\n return (o.maxMessageSize != null)\n ? 'sctpmap:%s %s %s'\n : 'sctpmap:%s %s';\n }\n },\n {\n // a=x-google-flag:conference\n name: 'xGoogleFlag',\n reg: /^x-google-flag:([^\\s]*)/,\n format: 'x-google-flag:%s'\n },\n {\n // a=rid:1 send max-width=1280;max-height=720;max-fps=30;depend=0\n push: 'rids',\n reg: /^rid:([\\d\\w]+) (\\w+)(?: ([\\S| ]*))?/,\n names: ['id', 'direction', 'params'],\n format: function (o) {\n return (o.params) ? 'rid:%s %s %s' : 'rid:%s %s';\n }\n },\n {\n // a=imageattr:97 send [x=800,y=640,sar=1.1,q=0.6] [x=480,y=320] recv [x=330,y=250]\n // a=imageattr:* send [x=800,y=640] recv *\n // a=imageattr:100 recv [x=320,y=240]\n push: 'imageattrs',\n reg: new RegExp(\n // a=imageattr:97\n '^imageattr:(\\\\d+|\\\\*)' +\n // send [x=800,y=640,sar=1.1,q=0.6] [x=480,y=320]\n '[\\\\s\\\\t]+(send|recv)[\\\\s\\\\t]+(\\\\*|\\\\[\\\\S+\\\\](?:[\\\\s\\\\t]+\\\\[\\\\S+\\\\])*)' +\n // recv [x=330,y=250]\n '(?:[\\\\s\\\\t]+(recv|send)[\\\\s\\\\t]+(\\\\*|\\\\[\\\\S+\\\\](?:[\\\\s\\\\t]+\\\\[\\\\S+\\\\])*))?'\n ),\n names: ['pt', 'dir1', 'attrs1', 'dir2', 'attrs2'],\n format: function (o) {\n return 'imageattr:%s %s %s' + (o.dir2 ? ' %s %s' : '');\n }\n },\n {\n // a=simulcast:send 1,2,3;~4,~5 recv 6;~7,~8\n // a=simulcast:recv 1;4,5 send 6;7\n name: 'simulcast',\n reg: new RegExp(\n // a=simulcast:\n '^simulcast:' +\n // send 1,2,3;~4,~5\n '(send|recv) ([a-zA-Z0-9\\\\-_~;,]+)' +\n // space + recv 6;~7,~8\n '(?:\\\\s?(send|recv) ([a-zA-Z0-9\\\\-_~;,]+))?' +\n // end\n '$'\n ),\n names: ['dir1', 'list1', 'dir2', 'list2'],\n format: function (o) {\n return 'simulcast:%s %s' + (o.dir2 ? ' %s %s' : '');\n }\n },\n {\n // old simulcast draft 03 (implemented by Firefox)\n // https://tools.ietf.org/html/draft-ietf-mmusic-sdp-simulcast-03\n // a=simulcast: recv pt=97;98 send pt=97\n // a=simulcast: send rid=5;6;7 paused=6,7\n name: 'simulcast_03',\n reg: /^simulcast:[\\s\\t]+([\\S+\\s\\t]+)$/,\n names: ['value'],\n format: 'simulcast: %s'\n },\n {\n // a=framerate:25\n // a=framerate:29.97\n name: 'framerate',\n reg: /^framerate:(\\d+(?:$|\\.\\d+))/,\n format: 'framerate:%s'\n },\n {\n // RFC4570\n // a=source-filter: incl IN IP4 239.5.2.31 10.1.15.5\n name: 'sourceFilter',\n reg: /^source-filter: *(excl|incl) (\\S*) (IP4|IP6|\\*) (\\S*) (.*)/,\n names: ['filterMode', 'netType', 'addressTypes', 'destAddress', 'srcList'],\n format: 'source-filter: %s %s %s %s %s'\n },\n {\n // a=bundle-only\n name: 'bundleOnly',\n reg: /^(bundle-only)/\n },\n {\n // a=label:1\n name: 'label',\n reg: /^label:(.+)/,\n format: 'label:%s'\n },\n {\n // RFC version 26 for SCTP over DTLS\n // https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-26#section-5\n name: 'sctpPort',\n reg: /^sctp-port:(\\d+)$/,\n format: 'sctp-port:%s'\n },\n {\n // RFC version 26 for SCTP over DTLS\n // https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-26#section-6\n name: 'maxMessageSize',\n reg: /^max-message-size:(\\d+)$/,\n format: 'max-message-size:%s'\n },\n {\n // RFC7273\n // a=ts-refclk:ptp=IEEE1588-2008:39-A7-94-FF-FE-07-CB-D0:37\n push:'tsRefClocks',\n reg: /^ts-refclk:([^\\s=]*)(?:=(\\S*))?/,\n names: ['clksrc', 'clksrcExt'],\n format: function (o) {\n return 'ts-refclk:%s' + (o.clksrcExt != null ? '=%s' : '');\n }\n },\n {\n // RFC7273\n // a=mediaclk:direct=963214424\n name:'mediaClk',\n reg: /^mediaclk:(?:id=(\\S*))? *([^\\s=]*)(?:=(\\S*))?(?: *rate=(\\d+)\\/(\\d+))?/,\n names: ['id', 'mediaClockName', 'mediaClockValue', 'rateNumerator', 'rateDenominator'],\n format: function (o) {\n var str = 'mediaclk:';\n str += (o.id != null ? 'id=%s %s' : '%v%s');\n str += (o.mediaClockValue != null ? '=%s' : '');\n str += (o.rateNumerator != null ? ' rate=%s' : '');\n str += (o.rateDenominator != null ? '/%s' : '');\n return str;\n }\n },\n {\n // a=keywds:keywords\n name: 'keywords',\n reg: /^keywds:(.+)$/,\n format: 'keywds:%s'\n },\n {\n // a=content:main\n name: 'content',\n reg: /^content:(.+)/,\n format: 'content:%s'\n },\n // BFCP https://tools.ietf.org/html/rfc4583\n {\n // a=floorctrl:c-s\n name: 'bfcpFloorCtrl',\n reg: /^floorctrl:(c-only|s-only|c-s)/,\n format: 'floorctrl:%s'\n },\n {\n // a=confid:1\n name: 'bfcpConfId',\n reg: /^confid:(\\d+)/,\n format: 'confid:%s'\n },\n {\n // a=userid:1\n name: 'bfcpUserId',\n reg: /^userid:(\\d+)/,\n format: 'userid:%s'\n },\n {\n // a=floorid:1\n name: 'bfcpFloorId',\n reg: /^floorid:(.+) (?:m-stream|mstrm):(.+)/,\n names: ['id', 'mStream'],\n format: 'floorid:%s mstrm:%s'\n },\n {\n // any a= that we don't understand is kept verbatim on media.invalid\n push: 'invalid',\n names: ['value']\n }\n ]\n};\n\n// set sensible defaults to avoid polluting the grammar with boring details\nObject.keys(grammar).forEach(function (key) {\n var objs = grammar[key];\n objs.forEach(function (obj) {\n if (!obj.reg) {\n obj.reg = /(.*)/;\n }\n if (!obj.format) {\n obj.format = '%s';\n }\n });\n});\n", - "var parser = require('./parser');\nvar writer = require('./writer');\n\nexports.write = writer;\nexports.parse = parser.parse;\nexports.parseParams = parser.parseParams;\nexports.parseFmtpConfig = parser.parseFmtpConfig; // Alias of parseParams().\nexports.parsePayloads = parser.parsePayloads;\nexports.parseRemoteCandidates = parser.parseRemoteCandidates;\nexports.parseImageAttributes = parser.parseImageAttributes;\nexports.parseSimulcastStreamList = parser.parseSimulcastStreamList;\n", - "var toIntIfInt = function (v) {\n return String(Number(v)) === v ? Number(v) : v;\n};\n\nvar attachProperties = function (match, location, names, rawName) {\n if (rawName && !names) {\n location[rawName] = toIntIfInt(match[1]);\n }\n else {\n for (var i = 0; i < names.length; i += 1) {\n if (match[i+1] != null) {\n location[names[i]] = toIntIfInt(match[i+1]);\n }\n }\n }\n};\n\nvar parseReg = function (obj, location, content) {\n var needsBlank = obj.name && obj.names;\n if (obj.push && !location[obj.push]) {\n location[obj.push] = [];\n }\n else if (needsBlank && !location[obj.name]) {\n location[obj.name] = {};\n }\n var keyLocation = obj.push ?\n {} : // blank object that will be pushed\n needsBlank ? location[obj.name] : location; // otherwise, named location or root\n\n attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);\n\n if (obj.push) {\n location[obj.push].push(keyLocation);\n }\n};\n\nvar grammar = require('./grammar');\nvar validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);\n\nexports.parse = function (sdp) {\n var session = {}\n , media = []\n , location = session; // points at where properties go under (one of the above)\n\n // parse lines we understand\n sdp.split(/(\\r\\n|\\r|\\n)/).filter(validLine).forEach(function (l) {\n var type = l[0];\n var content = l.slice(2);\n if (type === 'm') {\n media.push({rtp: [], fmtp: []});\n location = media[media.length-1]; // point at latest media line\n }\n\n for (var j = 0; j < (grammar[type] || []).length; j += 1) {\n var obj = grammar[type][j];\n if (obj.reg.test(content)) {\n return parseReg(obj, location, content);\n }\n }\n });\n\n session.media = media; // link it up\n return session;\n};\n\nvar paramReducer = function (acc, expr) {\n var s = expr.split(/=(.+)/, 2);\n if (s.length === 2) {\n acc[s[0]] = toIntIfInt(s[1]);\n } else if (s.length === 1 && expr.length > 1) {\n acc[s[0]] = undefined;\n }\n return acc;\n};\n\nexports.parseParams = function (str) {\n return str.split(/;\\s?/).reduce(paramReducer, {});\n};\n\n// For backward compatibility - alias will be removed in 3.0.0\nexports.parseFmtpConfig = exports.parseParams;\n\nexports.parsePayloads = function (str) {\n return str.toString().split(' ').map(Number);\n};\n\nexports.parseRemoteCandidates = function (str) {\n var candidates = [];\n var parts = str.split(' ').map(toIntIfInt);\n for (var i = 0; i < parts.length; i += 3) {\n candidates.push({\n component: parts[i],\n ip: parts[i + 1],\n port: parts[i + 2]\n });\n }\n return candidates;\n};\n\nexports.parseImageAttributes = function (str) {\n return str.split(' ').map(function (item) {\n return item.substring(1, item.length-1).split(',').reduce(paramReducer, {});\n });\n};\n\nexports.parseSimulcastStreamList = function (str) {\n return str.split(';').map(function (stream) {\n return stream.split(',').map(function (format) {\n var scid, paused = false;\n\n if (format[0] !== '~') {\n scid = toIntIfInt(format);\n } else {\n scid = toIntIfInt(format.substring(1, format.length));\n paused = true;\n }\n\n return {\n scid: scid,\n paused: paused\n };\n });\n });\n};\n", - "var grammar = require('./grammar');\n\n// customized util.format - discards excess arguments and can void middle ones\nvar formatRegExp = /%[sdv%]/g;\nvar format = function (formatStr) {\n var i = 1;\n var args = arguments;\n var len = args.length;\n return formatStr.replace(formatRegExp, function (x) {\n if (i >= len) {\n return x; // missing argument\n }\n var arg = args[i];\n i += 1;\n switch (x) {\n case '%%':\n return '%';\n case '%s':\n return String(arg);\n case '%d':\n return Number(arg);\n case '%v':\n return '';\n }\n });\n // NB: we discard excess arguments - they are typically undefined from makeLine\n};\n\nvar makeLine = function (type, obj, location) {\n var str = obj.format instanceof Function ?\n (obj.format(obj.push ? location : location[obj.name])) :\n obj.format;\n\n var args = [type + '=' + str];\n if (obj.names) {\n for (var i = 0; i < obj.names.length; i += 1) {\n var n = obj.names[i];\n if (obj.name) {\n args.push(location[obj.name][n]);\n }\n else { // for mLine and push attributes\n args.push(location[obj.names[i]]);\n }\n }\n }\n else {\n args.push(location[obj.name]);\n }\n return format.apply(null, args);\n};\n\n// RFC specified order\n// TODO: extend this with all the rest\nvar defaultOuterOrder = [\n 'v', 'o', 's', 'i',\n 'u', 'e', 'p', 'c',\n 'b', 't', 'r', 'z', 'a'\n];\nvar defaultInnerOrder = ['i', 'c', 'b', 'a'];\n\n\nmodule.exports = function (session, opts) {\n opts = opts || {};\n // ensure certain properties exist\n if (session.version == null) {\n session.version = 0; // 'v=0' must be there (only defined version atm)\n }\n if (session.name == null) {\n session.name = ' '; // 's= ' must be there if no meaningful name set\n }\n session.media.forEach(function (mLine) {\n if (mLine.payloads == null) {\n mLine.payloads = '';\n }\n });\n\n var outerOrder = opts.outerOrder || defaultOuterOrder;\n var innerOrder = opts.innerOrder || defaultInnerOrder;\n var sdp = [];\n\n // loop through outerOrder for matching properties on session\n outerOrder.forEach(function (type) {\n grammar[type].forEach(function (obj) {\n if (obj.name in session && session[obj.name] != null) {\n sdp.push(makeLine(type, obj, session));\n }\n else if (obj.push in session && session[obj.push] != null) {\n session[obj.push].forEach(function (el) {\n sdp.push(makeLine(type, obj, el));\n });\n }\n });\n });\n\n // then for each media line, follow the innerOrder\n session.media.forEach(function (mLine) {\n sdp.push(makeLine('m', grammar.m[0], mLine));\n\n innerOrder.forEach(function (type) {\n grammar[type].forEach(function (obj) {\n if (obj.name in mLine && mLine[obj.name] != null) {\n sdp.push(makeLine(type, obj, mLine));\n }\n else if (obj.push in mLine && mLine[obj.push] != null) {\n mLine[obj.push].forEach(function (el) {\n sdp.push(makeLine(type, obj, el));\n });\n }\n });\n });\n });\n\n return sdp.join('\\r\\n') + '\\r\\n';\n};\n", - "var Buffer = require('safe-buffer').Buffer\n\n// prototype class for hash functions\nfunction Hash (blockSize, finalSize) {\n this._block = Buffer.alloc(blockSize)\n this._finalSize = finalSize\n this._blockSize = blockSize\n this._len = 0\n}\n\nHash.prototype.update = function (data, enc) {\n if (typeof data === 'string') {\n enc = enc || 'utf8'\n data = Buffer.from(data, enc)\n }\n\n var block = this._block\n var blockSize = this._blockSize\n var length = data.length\n var accum = this._len\n\n for (var offset = 0; offset < length;) {\n var assigned = accum % blockSize\n var remainder = Math.min(length - offset, blockSize - assigned)\n\n for (var i = 0; i < remainder; i++) {\n block[assigned + i] = data[offset + i]\n }\n\n accum += remainder\n offset += remainder\n\n if ((accum % blockSize) === 0) {\n this._update(block)\n }\n }\n\n this._len += length\n return this\n}\n\nHash.prototype.digest = function (enc) {\n var rem = this._len % this._blockSize\n\n this._block[rem] = 0x80\n\n // zero (rem + 1) trailing bits, where (rem + 1) is the smallest\n // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize\n this._block.fill(0, rem + 1)\n\n if (rem >= this._finalSize) {\n this._update(this._block)\n this._block.fill(0)\n }\n\n var bits = this._len * 8\n\n // uint32\n if (bits <= 0xffffffff) {\n this._block.writeUInt32BE(bits, this._blockSize - 4)\n\n // uint64\n } else {\n var lowBits = (bits & 0xffffffff) >>> 0\n var highBits = (bits - lowBits) / 0x100000000\n\n this._block.writeUInt32BE(highBits, this._blockSize - 8)\n this._block.writeUInt32BE(lowBits, this._blockSize - 4)\n }\n\n this._update(this._block)\n var hash = this._hash()\n\n return enc ? hash.toString(enc) : hash\n}\n\nHash.prototype._update = function () {\n throw new Error('_update must be implemented by subclass')\n}\n\nmodule.exports = Hash\n", - "var exports = module.exports = function SHA (algorithm) {\n algorithm = algorithm.toLowerCase()\n\n var Algorithm = exports[algorithm]\n if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')\n\n return new Algorithm()\n}\n\nexports.sha = require('./sha')\nexports.sha1 = require('./sha1')\nexports.sha224 = require('./sha224')\nexports.sha256 = require('./sha256')\nexports.sha384 = require('./sha384')\nexports.sha512 = require('./sha512')\n", - "/*\n * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined\n * in FIPS PUB 180-1\n * This source code is derived from sha1.js of the same repository.\n * The difference between SHA-0 and SHA-1 is just a bitwise rotate left\n * operation was added.\n */\n\nvar inherits = require('inherits')\nvar Hash = require('./hash')\nvar Buffer = require('safe-buffer').Buffer\n\nvar K = [\n 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0\n]\n\nvar W = new Array(80)\n\nfunction Sha () {\n this.init()\n this._w = W\n\n Hash.call(this, 64, 56)\n}\n\ninherits(Sha, Hash)\n\nSha.prototype.init = function () {\n this._a = 0x67452301\n this._b = 0xefcdab89\n this._c = 0x98badcfe\n this._d = 0x10325476\n this._e = 0xc3d2e1f0\n\n return this\n}\n\nfunction rotl5 (num) {\n return (num << 5) | (num >>> 27)\n}\n\nfunction rotl30 (num) {\n return (num << 30) | (num >>> 2)\n}\n\nfunction ft (s, b, c, d) {\n if (s === 0) return (b & c) | ((~b) & d)\n if (s === 2) return (b & c) | (b & d) | (c & d)\n return b ^ c ^ d\n}\n\nSha.prototype._update = function (M) {\n var W = this._w\n\n var a = this._a | 0\n var b = this._b | 0\n var c = this._c | 0\n var d = this._d | 0\n var e = this._e | 0\n\n for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)\n for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]\n\n for (var j = 0; j < 80; ++j) {\n var s = ~~(j / 20)\n var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0\n\n e = d\n d = c\n c = rotl30(b)\n b = a\n a = t\n }\n\n this._a = (a + this._a) | 0\n this._b = (b + this._b) | 0\n this._c = (c + this._c) | 0\n this._d = (d + this._d) | 0\n this._e = (e + this._e) | 0\n}\n\nSha.prototype._hash = function () {\n var H = Buffer.allocUnsafe(20)\n\n H.writeInt32BE(this._a | 0, 0)\n H.writeInt32BE(this._b | 0, 4)\n H.writeInt32BE(this._c | 0, 8)\n H.writeInt32BE(this._d | 0, 12)\n H.writeInt32BE(this._e | 0, 16)\n\n return H\n}\n\nmodule.exports = Sha\n", - "/*\n * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined\n * in FIPS PUB 180-1\n * Version 2.1a Copyright Paul Johnston 2000 - 2002.\n * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet\n * Distributed under the BSD License\n * See http://pajhome.org.uk/crypt/md5 for details.\n */\n\nvar inherits = require('inherits')\nvar Hash = require('./hash')\nvar Buffer = require('safe-buffer').Buffer\n\nvar K = [\n 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0\n]\n\nvar W = new Array(80)\n\nfunction Sha1 () {\n this.init()\n this._w = W\n\n Hash.call(this, 64, 56)\n}\n\ninherits(Sha1, Hash)\n\nSha1.prototype.init = function () {\n this._a = 0x67452301\n this._b = 0xefcdab89\n this._c = 0x98badcfe\n this._d = 0x10325476\n this._e = 0xc3d2e1f0\n\n return this\n}\n\nfunction rotl1 (num) {\n return (num << 1) | (num >>> 31)\n}\n\nfunction rotl5 (num) {\n return (num << 5) | (num >>> 27)\n}\n\nfunction rotl30 (num) {\n return (num << 30) | (num >>> 2)\n}\n\nfunction ft (s, b, c, d) {\n if (s === 0) return (b & c) | ((~b) & d)\n if (s === 2) return (b & c) | (b & d) | (c & d)\n return b ^ c ^ d\n}\n\nSha1.prototype._update = function (M) {\n var W = this._w\n\n var a = this._a | 0\n var b = this._b | 0\n var c = this._c | 0\n var d = this._d | 0\n var e = this._e | 0\n\n for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)\n for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])\n\n for (var j = 0; j < 80; ++j) {\n var s = ~~(j / 20)\n var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0\n\n e = d\n d = c\n c = rotl30(b)\n b = a\n a = t\n }\n\n this._a = (a + this._a) | 0\n this._b = (b + this._b) | 0\n this._c = (c + this._c) | 0\n this._d = (d + this._d) | 0\n this._e = (e + this._e) | 0\n}\n\nSha1.prototype._hash = function () {\n var H = Buffer.allocUnsafe(20)\n\n H.writeInt32BE(this._a | 0, 0)\n H.writeInt32BE(this._b | 0, 4)\n H.writeInt32BE(this._c | 0, 8)\n H.writeInt32BE(this._d | 0, 12)\n H.writeInt32BE(this._e | 0, 16)\n\n return H\n}\n\nmodule.exports = Sha1\n", - "/**\n * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined\n * in FIPS 180-2\n * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.\n * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet\n *\n */\n\nvar inherits = require('inherits')\nvar Sha256 = require('./sha256')\nvar Hash = require('./hash')\nvar Buffer = require('safe-buffer').Buffer\n\nvar W = new Array(64)\n\nfunction Sha224 () {\n this.init()\n\n this._w = W // new Array(64)\n\n Hash.call(this, 64, 56)\n}\n\ninherits(Sha224, Sha256)\n\nSha224.prototype.init = function () {\n this._a = 0xc1059ed8\n this._b = 0x367cd507\n this._c = 0x3070dd17\n this._d = 0xf70e5939\n this._e = 0xffc00b31\n this._f = 0x68581511\n this._g = 0x64f98fa7\n this._h = 0xbefa4fa4\n\n return this\n}\n\nSha224.prototype._hash = function () {\n var H = Buffer.allocUnsafe(28)\n\n H.writeInt32BE(this._a, 0)\n H.writeInt32BE(this._b, 4)\n H.writeInt32BE(this._c, 8)\n H.writeInt32BE(this._d, 12)\n H.writeInt32BE(this._e, 16)\n H.writeInt32BE(this._f, 20)\n H.writeInt32BE(this._g, 24)\n\n return H\n}\n\nmodule.exports = Sha224\n", - "/**\n * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined\n * in FIPS 180-2\n * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.\n * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet\n *\n */\n\nvar inherits = require('inherits')\nvar Hash = require('./hash')\nvar Buffer = require('safe-buffer').Buffer\n\nvar K = [\n 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,\n 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,\n 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,\n 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,\n 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,\n 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,\n 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,\n 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,\n 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,\n 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,\n 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,\n 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,\n 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,\n 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,\n 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,\n 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2\n]\n\nvar W = new Array(64)\n\nfunction Sha256 () {\n this.init()\n\n this._w = W // new Array(64)\n\n Hash.call(this, 64, 56)\n}\n\ninherits(Sha256, Hash)\n\nSha256.prototype.init = function () {\n this._a = 0x6a09e667\n this._b = 0xbb67ae85\n this._c = 0x3c6ef372\n this._d = 0xa54ff53a\n this._e = 0x510e527f\n this._f = 0x9b05688c\n this._g = 0x1f83d9ab\n this._h = 0x5be0cd19\n\n return this\n}\n\nfunction ch (x, y, z) {\n return z ^ (x & (y ^ z))\n}\n\nfunction maj (x, y, z) {\n return (x & y) | (z & (x | y))\n}\n\nfunction sigma0 (x) {\n return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)\n}\n\nfunction sigma1 (x) {\n return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)\n}\n\nfunction gamma0 (x) {\n return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)\n}\n\nfunction gamma1 (x) {\n return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)\n}\n\nSha256.prototype._update = function (M) {\n var W = this._w\n\n var a = this._a | 0\n var b = this._b | 0\n var c = this._c | 0\n var d = this._d | 0\n var e = this._e | 0\n var f = this._f | 0\n var g = this._g | 0\n var h = this._h | 0\n\n for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)\n for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0\n\n for (var j = 0; j < 64; ++j) {\n var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0\n var T2 = (sigma0(a) + maj(a, b, c)) | 0\n\n h = g\n g = f\n f = e\n e = (d + T1) | 0\n d = c\n c = b\n b = a\n a = (T1 + T2) | 0\n }\n\n this._a = (a + this._a) | 0\n this._b = (b + this._b) | 0\n this._c = (c + this._c) | 0\n this._d = (d + this._d) | 0\n this._e = (e + this._e) | 0\n this._f = (f + this._f) | 0\n this._g = (g + this._g) | 0\n this._h = (h + this._h) | 0\n}\n\nSha256.prototype._hash = function () {\n var H = Buffer.allocUnsafe(32)\n\n H.writeInt32BE(this._a, 0)\n H.writeInt32BE(this._b, 4)\n H.writeInt32BE(this._c, 8)\n H.writeInt32BE(this._d, 12)\n H.writeInt32BE(this._e, 16)\n H.writeInt32BE(this._f, 20)\n H.writeInt32BE(this._g, 24)\n H.writeInt32BE(this._h, 28)\n\n return H\n}\n\nmodule.exports = Sha256\n", - "var inherits = require('inherits')\nvar SHA512 = require('./sha512')\nvar Hash = require('./hash')\nvar Buffer = require('safe-buffer').Buffer\n\nvar W = new Array(160)\n\nfunction Sha384 () {\n this.init()\n this._w = W\n\n Hash.call(this, 128, 112)\n}\n\ninherits(Sha384, SHA512)\n\nSha384.prototype.init = function () {\n this._ah = 0xcbbb9d5d\n this._bh = 0x629a292a\n this._ch = 0x9159015a\n this._dh = 0x152fecd8\n this._eh = 0x67332667\n this._fh = 0x8eb44a87\n this._gh = 0xdb0c2e0d\n this._hh = 0x47b5481d\n\n this._al = 0xc1059ed8\n this._bl = 0x367cd507\n this._cl = 0x3070dd17\n this._dl = 0xf70e5939\n this._el = 0xffc00b31\n this._fl = 0x68581511\n this._gl = 0x64f98fa7\n this._hl = 0xbefa4fa4\n\n return this\n}\n\nSha384.prototype._hash = function () {\n var H = Buffer.allocUnsafe(48)\n\n function writeInt64BE (h, l, offset) {\n H.writeInt32BE(h, offset)\n H.writeInt32BE(l, offset + 4)\n }\n\n writeInt64BE(this._ah, this._al, 0)\n writeInt64BE(this._bh, this._bl, 8)\n writeInt64BE(this._ch, this._cl, 16)\n writeInt64BE(this._dh, this._dl, 24)\n writeInt64BE(this._eh, this._el, 32)\n writeInt64BE(this._fh, this._fl, 40)\n\n return H\n}\n\nmodule.exports = Sha384\n", - "var inherits = require('inherits')\nvar Hash = require('./hash')\nvar Buffer = require('safe-buffer').Buffer\n\nvar K = [\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n]\n\nvar W = new Array(160)\n\nfunction Sha512 () {\n this.init()\n this._w = W\n\n Hash.call(this, 128, 112)\n}\n\ninherits(Sha512, Hash)\n\nSha512.prototype.init = function () {\n this._ah = 0x6a09e667\n this._bh = 0xbb67ae85\n this._ch = 0x3c6ef372\n this._dh = 0xa54ff53a\n this._eh = 0x510e527f\n this._fh = 0x9b05688c\n this._gh = 0x1f83d9ab\n this._hh = 0x5be0cd19\n\n this._al = 0xf3bcc908\n this._bl = 0x84caa73b\n this._cl = 0xfe94f82b\n this._dl = 0x5f1d36f1\n this._el = 0xade682d1\n this._fl = 0x2b3e6c1f\n this._gl = 0xfb41bd6b\n this._hl = 0x137e2179\n\n return this\n}\n\nfunction Ch (x, y, z) {\n return z ^ (x & (y ^ z))\n}\n\nfunction maj (x, y, z) {\n return (x & y) | (z & (x | y))\n}\n\nfunction sigma0 (x, xl) {\n return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)\n}\n\nfunction sigma1 (x, xl) {\n return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)\n}\n\nfunction Gamma0 (x, xl) {\n return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)\n}\n\nfunction Gamma0l (x, xl) {\n return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)\n}\n\nfunction Gamma1 (x, xl) {\n return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)\n}\n\nfunction Gamma1l (x, xl) {\n return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)\n}\n\nfunction getCarry (a, b) {\n return (a >>> 0) < (b >>> 0) ? 1 : 0\n}\n\nSha512.prototype._update = function (M) {\n var W = this._w\n\n var ah = this._ah | 0\n var bh = this._bh | 0\n var ch = this._ch | 0\n var dh = this._dh | 0\n var eh = this._eh | 0\n var fh = this._fh | 0\n var gh = this._gh | 0\n var hh = this._hh | 0\n\n var al = this._al | 0\n var bl = this._bl | 0\n var cl = this._cl | 0\n var dl = this._dl | 0\n var el = this._el | 0\n var fl = this._fl | 0\n var gl = this._gl | 0\n var hl = this._hl | 0\n\n for (var i = 0; i < 32; i += 2) {\n W[i] = M.readInt32BE(i * 4)\n W[i + 1] = M.readInt32BE(i * 4 + 4)\n }\n for (; i < 160; i += 2) {\n var xh = W[i - 15 * 2]\n var xl = W[i - 15 * 2 + 1]\n var gamma0 = Gamma0(xh, xl)\n var gamma0l = Gamma0l(xl, xh)\n\n xh = W[i - 2 * 2]\n xl = W[i - 2 * 2 + 1]\n var gamma1 = Gamma1(xh, xl)\n var gamma1l = Gamma1l(xl, xh)\n\n // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]\n var Wi7h = W[i - 7 * 2]\n var Wi7l = W[i - 7 * 2 + 1]\n\n var Wi16h = W[i - 16 * 2]\n var Wi16l = W[i - 16 * 2 + 1]\n\n var Wil = (gamma0l + Wi7l) | 0\n var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0\n Wil = (Wil + gamma1l) | 0\n Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0\n Wil = (Wil + Wi16l) | 0\n Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0\n\n W[i] = Wih\n W[i + 1] = Wil\n }\n\n for (var j = 0; j < 160; j += 2) {\n Wih = W[j]\n Wil = W[j + 1]\n\n var majh = maj(ah, bh, ch)\n var majl = maj(al, bl, cl)\n\n var sigma0h = sigma0(ah, al)\n var sigma0l = sigma0(al, ah)\n var sigma1h = sigma1(eh, el)\n var sigma1l = sigma1(el, eh)\n\n // t1 = h + sigma1 + ch + K[j] + W[j]\n var Kih = K[j]\n var Kil = K[j + 1]\n\n var chh = Ch(eh, fh, gh)\n var chl = Ch(el, fl, gl)\n\n var t1l = (hl + sigma1l) | 0\n var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0\n t1l = (t1l + chl) | 0\n t1h = (t1h + chh + getCarry(t1l, chl)) | 0\n t1l = (t1l + Kil) | 0\n t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0\n t1l = (t1l + Wil) | 0\n t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0\n\n // t2 = sigma0 + maj\n var t2l = (sigma0l + majl) | 0\n var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0\n\n hh = gh\n hl = gl\n gh = fh\n gl = fl\n fh = eh\n fl = el\n el = (dl + t1l) | 0\n eh = (dh + t1h + getCarry(el, dl)) | 0\n dh = ch\n dl = cl\n ch = bh\n cl = bl\n bh = ah\n bl = al\n al = (t1l + t2l) | 0\n ah = (t1h + t2h + getCarry(al, t1l)) | 0\n }\n\n this._al = (this._al + al) | 0\n this._bl = (this._bl + bl) | 0\n this._cl = (this._cl + cl) | 0\n this._dl = (this._dl + dl) | 0\n this._el = (this._el + el) | 0\n this._fl = (this._fl + fl) | 0\n this._gl = (this._gl + gl) | 0\n this._hl = (this._hl + hl) | 0\n\n this._ah = (this._ah + ah + getCarry(this._al, al)) | 0\n this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0\n this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0\n this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0\n this._eh = (this._eh + eh + getCarry(this._el, el)) | 0\n this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0\n this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0\n this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0\n}\n\nSha512.prototype._hash = function () {\n var H = Buffer.allocUnsafe(64)\n\n function writeInt64BE (h, l, offset) {\n H.writeInt32BE(h, offset)\n H.writeInt32BE(l, offset + 4)\n }\n\n writeInt64BE(this._ah, this._al, 0)\n writeInt64BE(this._bh, this._bl, 8)\n writeInt64BE(this._ch, this._cl, 16)\n writeInt64BE(this._dh, this._dl, 24)\n writeInt64BE(this._eh, this._el, 32)\n writeInt64BE(this._fh, this._fl, 40)\n writeInt64BE(this._gh, this._gl, 48)\n writeInt64BE(this._hh, this._hl, 56)\n\n return H\n}\n\nmodule.exports = Sha512\n", - "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nmodule.exports = Stream;\n\nvar EE = require('events').EventEmitter;\nvar inherits = require('inherits');\n\ninherits(Stream, EE);\nStream.Readable = require('readable-stream/lib/_stream_readable.js');\nStream.Writable = require('readable-stream/lib/_stream_writable.js');\nStream.Duplex = require('readable-stream/lib/_stream_duplex.js');\nStream.Transform = require('readable-stream/lib/_stream_transform.js');\nStream.PassThrough = require('readable-stream/lib/_stream_passthrough.js');\nStream.finished = require('readable-stream/lib/internal/streams/end-of-stream.js')\nStream.pipeline = require('readable-stream/lib/internal/streams/pipeline.js')\n\n// Backwards-compat with node 0.4.x\nStream.Stream = Stream;\n\n\n\n// old-style streams. Note that the pipe method (the only relevant\n// part of this class) is overridden in the Readable class.\n\nfunction Stream() {\n EE.call(this);\n}\n\nStream.prototype.pipe = function(dest, options) {\n var source = this;\n\n function ondata(chunk) {\n if (dest.writable) {\n if (false === dest.write(chunk) && source.pause) {\n source.pause();\n }\n }\n }\n\n source.on('data', ondata);\n\n function ondrain() {\n if (source.readable && source.resume) {\n source.resume();\n }\n }\n\n dest.on('drain', ondrain);\n\n // If the 'end' option is not supplied, dest.end() will be called when\n // source gets the 'end' or 'close' events. Only dest.end() once.\n if (!dest._isStdio && (!options || options.end !== false)) {\n source.on('end', onend);\n source.on('close', onclose);\n }\n\n var didOnEnd = false;\n function onend() {\n if (didOnEnd) return;\n didOnEnd = true;\n\n dest.end();\n }\n\n\n function onclose() {\n if (didOnEnd) return;\n didOnEnd = true;\n\n if (typeof dest.destroy === 'function') dest.destroy();\n }\n\n // don't leave dangling pipes when there are errors.\n function onerror(er) {\n cleanup();\n if (EE.listenerCount(this, 'error') === 0) {\n throw er; // Unhandled stream error in pipe.\n }\n }\n\n source.on('error', onerror);\n dest.on('error', onerror);\n\n // remove all the event listeners that were added.\n function cleanup() {\n source.removeListener('data', ondata);\n dest.removeListener('drain', ondrain);\n\n source.removeListener('end', onend);\n source.removeListener('close', onclose);\n\n source.removeListener('error', onerror);\n dest.removeListener('error', onerror);\n\n source.removeListener('end', cleanup);\n source.removeListener('close', cleanup);\n\n dest.removeListener('close', cleanup);\n }\n\n source.on('end', cleanup);\n source.on('close', cleanup);\n\n dest.on('close', cleanup);\n\n dest.emit('pipe', source);\n\n // Allow for unix-like usage: A.pipe(B).pipe(C)\n return dest;\n};\n", - "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n'use strict';\n/**/\n\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n\n for (var key in obj) {\n keys.push(key);\n }\n\n return keys;\n};\n/**/\n\n\nmodule.exports = Duplex;\n\nvar Readable = require('./_stream_readable');\n\nvar Writable = require('./_stream_writable');\n\nrequire('inherits')(Duplex, Readable);\n\n{\n // Allow the keys array to be GC'ed.\n var keys = objectKeys(Writable.prototype);\n\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n Readable.call(this, options);\n Writable.call(this, options);\n this.allowHalfOpen = true;\n\n if (options) {\n if (options.readable === false) this.readable = false;\n if (options.writable === false) this.writable = false;\n\n if (options.allowHalfOpen === false) {\n this.allowHalfOpen = false;\n this.once('end', onend);\n }\n }\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n}); // the no-half-open enforcer\n\nfunction onend() {\n // If the writable side ended, then we're ok.\n if (this._writableState.ended) return; // no more data can be written.\n // But allow more writes to happen in this tick.\n\n process.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});", - "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n'use strict';\n\nmodule.exports = Readable;\n/**/\n\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n/**/\n\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function EElistenerCount(emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\n\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n/**/\n\n\nvar debugUtil = require('util');\n\nvar debug;\n\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function debug() {};\n}\n/**/\n\n\nvar BufferList = require('./internal/streams/buffer_list');\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.\n\n\nvar StringDecoder;\nvar createReadableStreamAsyncIterator;\nvar from;\n\nrequire('inherits')(Readable, Stream);\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n\n this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n\n this.sync = true; // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n this.paused = true; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')\n\n this.autoDestroy = !!options.autoDestroy; // has it been destroyed\n\n this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s\n\n this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled\n\n this.readingMore = false;\n this.decoder = null;\n this.encoding = null;\n\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside\n // the ReadableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n this._readableState = new ReadableState(options, this, isDuplex); // legacy\n\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n }\n});\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\n\nReadable.prototype._destroy = function (err, cb) {\n cb(err);\n}; // Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\n\n\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n}; // Unshift should *always* be something directly out of read()\n\n\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n debug('readableAddChunk', chunk);\n var state = stream._readableState;\n\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n\n if (er) {\n errorOrDestroy(stream, er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());\n } else if (state.destroyed) {\n return false;\n } else {\n state.reading = false;\n\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n maybeReadMore(stream, state);\n }\n } // We can push more data if we are below the highWaterMark.\n // Also, if we have no data yet, we can stand some more bytes.\n // This is to work around cases where hwm=0, such as the repl.\n\n\n return !state.ended && (state.length < state.highWaterMark || state.length === 0);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n state.awaitDrain = 0;\n stream.emit('data', chunk);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n if (state.needReadable) emitReadable(stream);\n }\n\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);\n }\n\n return er;\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n}; // backwards compatibility.\n\n\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n var decoder = new StringDecoder(enc);\n this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8\n\n this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:\n\n var p = this._readableState.buffer.head;\n var content = '';\n\n while (p !== null) {\n content += decoder.write(p.data);\n p = p.next;\n }\n\n this._readableState.buffer.clear();\n\n if (content !== '') this._readableState.buffer.push(content);\n this._readableState.length = content.length;\n return this;\n}; // Don't raise the hwm > 1GB\n\n\nvar MAX_HWM = 0x40000000;\n\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n\n return n;\n} // This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\n\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n } // If we're asking for more than the current hwm, then raise the hwm.\n\n\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n; // Don't have enough\n\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n\n return state.length;\n} // you can override either this method, or the async _read(n) below.\n\n\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n\n if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.\n\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n } // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n // if we need a readable event, then we need to do some reading.\n\n\n var doRead = state.needReadable;\n debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some\n\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n } // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n\n\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true; // if the length is currently zero, then we *need* a readable event.\n\n if (state.length === 0) state.needReadable = true; // call internal read method\n\n this._read(state.highWaterMark);\n\n state.sync = false; // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = state.length <= state.highWaterMark;\n n = 0;\n } else {\n state.length -= n;\n state.awaitDrain = 0;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.\n\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n debug('onEofChunk');\n if (state.ended) return;\n\n if (state.decoder) {\n var chunk = state.decoder.end();\n\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n\n state.ended = true;\n\n if (state.sync) {\n // if we are sync, wait until next tick to emit the data.\n // Otherwise we risk emitting data in the flow()\n // the readable code triggers during a read() call\n emitReadable(stream);\n } else {\n // emit 'readable' now to make sure it gets picked up.\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n state.emittedReadable = true;\n emitReadable_(stream);\n }\n }\n} // Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\n\n\nfunction emitReadable(stream) {\n var state = stream._readableState;\n debug('emitReadable', state.needReadable, state.emittedReadable);\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n process.nextTick(emitReadable_, stream);\n }\n}\n\nfunction emitReadable_(stream) {\n var state = stream._readableState;\n debug('emitReadable_', state.destroyed, state.length, state.ended);\n\n if (!state.destroyed && (state.length || state.ended)) {\n stream.emit('readable');\n state.emittedReadable = false;\n } // The stream needs another readable event if\n // 1. It is not flowing, as the flow mechanism will take\n // care of it.\n // 2. It is not ended.\n // 3. It is below the highWaterMark, so we can schedule\n // another readable later.\n\n\n state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;\n flow(stream);\n} // at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\n\n\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n process.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n // Attempt to read more data if we should.\n //\n // The conditions for reading more data are (one of):\n // - Not enough data buffered (state.length < state.highWaterMark). The loop\n // is responsible for filling the buffer with enough data if such data\n // is available. If highWaterMark is 0 and we are not in the flowing mode\n // we should _not_ attempt to buffer any extra data. We'll get more data\n // when the stream consumer calls read() instead.\n // - No data in the buffer, and the stream is in flowing mode. In this mode\n // the loop below is responsible for ensuring read() is called. Failing to\n // call read here would abort the flow and there's no other mechanism for\n // continuing the flow if the stream consumer has just subscribed to the\n // 'data' event.\n //\n // In addition to the above conditions to keep reading data, the following\n // conditions prevent the data from being read:\n // - The stream has ended (state.ended).\n // - There is already a pending 'read' operation (state.reading). This is a\n // case where the the stream has called the implementation defined _read()\n // method, but they are processing the call asynchronously and have _not_\n // called push() with new data. In this case we skip performing more\n // read()s. The execution ends in this method again after the _read() ends\n // up calling push() with more data.\n while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {\n var len = state.length;\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length) // didn't get any data, stop spinning.\n break;\n }\n\n state.readingMore = false;\n} // abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\n\n\nReadable.prototype._read = function (n) {\n errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n\n default:\n state.pipes.push(dest);\n break;\n }\n\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);\n dest.on('unpipe', onunpipe);\n\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n } // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n\n\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n var cleanedUp = false;\n\n function cleanup() {\n debug('cleanup'); // cleanup event handlers once the pipe is broken\n\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n cleanedUp = true; // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n src.on('data', ondata);\n\n function ondata(chunk) {\n debug('ondata');\n var ret = dest.write(chunk);\n debug('dest.write', ret);\n\n if (ret === false) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n }\n\n src.pause();\n }\n } // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n\n\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);\n } // Make sure our error handler is attached before userland ones.\n\n\n prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.\n\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n\n dest.once('close', onclose);\n\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n } // tell the dest that it's being piped to\n\n\n dest.emit('pipe', src); // start the flow if it hasn't been started already.\n\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function pipeOnDrainFunctionResult() {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = {\n hasUnpiped: false\n }; // if we're not piping anywhere, then do nothing.\n\n if (state.pipesCount === 0) return this; // just one destination. most common case.\n\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n if (!dest) dest = state.pipes; // got a match.\n\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n } // slow case. multiple pipe destinations.\n\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, {\n hasUnpiped: false\n });\n }\n\n return this;\n } // try to find the right one.\n\n\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n dest.emit('unpipe', this, unpipeInfo);\n return this;\n}; // set up data events if they are asked for\n// Ensure readable listeners eventually get something\n\n\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n var state = this._readableState;\n\n if (ev === 'data') {\n // update readableListening so that resume() may be a no-op\n // a few lines down. This is needed to support once('readable').\n state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused\n\n if (state.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.flowing = false;\n state.emittedReadable = false;\n debug('on readable', state.length, state.reading);\n\n if (state.length) {\n emitReadable(this);\n } else if (!state.reading) {\n process.nextTick(nReadingNextTick, this);\n }\n }\n }\n\n return res;\n};\n\nReadable.prototype.addListener = Readable.prototype.on;\n\nReadable.prototype.removeListener = function (ev, fn) {\n var res = Stream.prototype.removeListener.call(this, ev, fn);\n\n if (ev === 'readable') {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nReadable.prototype.removeAllListeners = function (ev) {\n var res = Stream.prototype.removeAllListeners.apply(this, arguments);\n\n if (ev === 'readable' || ev === undefined) {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nfunction updateReadableListening(self) {\n var state = self._readableState;\n state.readableListening = self.listenerCount('readable') > 0;\n\n if (state.resumeScheduled && !state.paused) {\n // flowing needs to be set to true now, otherwise\n // the upcoming resume will not flow.\n state.flowing = true; // crude way to check if we should resume\n } else if (self.listenerCount('data') > 0) {\n self.resume();\n }\n}\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n} // pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\n\n\nReadable.prototype.resume = function () {\n var state = this._readableState;\n\n if (!state.flowing) {\n debug('resume'); // we flow only if there is no one listening\n // for readable, but we still have to call\n // resume()\n\n state.flowing = !state.readableListening;\n resume(this, state);\n }\n\n state.paused = false;\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n process.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n debug('resume', state.reading);\n\n if (!state.reading) {\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n\n if (this._readableState.flowing !== false) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n\n this._readableState.paused = true;\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n\n while (state.flowing && stream.read() !== null) {\n ;\n }\n} // wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\n\n\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n stream.on('end', function () {\n debug('wrapped end');\n\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode\n\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n\n if (!ret) {\n paused = true;\n stream.pause();\n }\n }); // proxy all the other methods.\n // important when wrapping filters and duplexes.\n\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function methodWrap(method) {\n return function methodWrapReturnFunction() {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n } // proxy certain important events.\n\n\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n } // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n\n\n this._read = function (n) {\n debug('wrapped _read', n);\n\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nif (typeof Symbol === 'function') {\n Readable.prototype[Symbol.asyncIterator] = function () {\n if (createReadableStreamAsyncIterator === undefined) {\n createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');\n }\n\n return createReadableStreamAsyncIterator(this);\n };\n}\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.highWaterMark;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState && this._readableState.buffer;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableFlowing', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.flowing;\n },\n set: function set(state) {\n if (this._readableState) {\n this._readableState.flowing = state;\n }\n }\n}); // exposed for testing purposes only.\n\nReadable._fromList = fromList;\nObject.defineProperty(Readable.prototype, 'readableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.length;\n }\n}); // Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = state.buffer.consume(n, state.decoder);\n }\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n debug('endReadable', state.endEmitted);\n\n if (!state.endEmitted) {\n state.ended = true;\n process.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.\n\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the writable side is ready for autoDestroy as well\n var wState = stream._writableState;\n\n if (!wState || wState.autoDestroy && wState.finished) {\n stream.destroy();\n }\n }\n }\n}\n\nif (typeof Symbol === 'function') {\n Readable.from = function (iterable, opts) {\n if (from === undefined) {\n from = require('./internal/streams/from');\n }\n\n return from(Readable, iterable, opts);\n };\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n\n return -1;\n}", - "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n'use strict';\n\nmodule.exports = Writable;\n/* */\n\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n} // It seems a linked list but it is not\n// there will be only 2 of these for each stream\n\n\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\n\n\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n/**/\n\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/**/\n\n/**/\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,\n ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,\n ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,\n ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\n\nrequire('inherits')(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream,\n // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n\n this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called\n\n this.finalCalled = false; // drain event flag.\n\n this.needDrain = false; // at the start of calling end()\n\n this.ending = false; // when end() has been called, and returned\n\n this.ended = false; // when 'finish' is emitted\n\n this.finished = false; // has it been destroyed\n\n this.destroyed = false; // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n\n this.length = 0; // a flag to see when we're in the middle of a write.\n\n this.writing = false; // when true all writes will be buffered until .uncork() call\n\n this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n\n this.sync = true; // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n\n this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)\n\n this.onwrite = function (er) {\n onwrite(stream, er);\n }; // the callback that the user supplies to write(chunk,encoding,cb)\n\n\n this.writecb = null; // the amount that is being written when _write is called.\n\n this.writelen = 0;\n this.bufferedRequest = null;\n this.lastBufferedRequest = null; // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n\n this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n\n this.prefinished = false; // True if the error was already emitted and should not be thrown again\n\n this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')\n\n this.autoDestroy = !!options.autoDestroy; // count buffered requests\n\n this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n\n while (current) {\n out.push(current);\n current = current.next;\n }\n\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function writableStateBufferGetter() {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})(); // Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\n\n\nvar realHasInstance;\n\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function value(object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function realHasInstance(object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the WritableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);\n this._writableState = new WritableState(options, this, isDuplex); // legacy.\n\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n if (typeof options.writev === 'function') this._writev = options.writev;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n} // Otherwise people can pipe Writable streams, which is just wrong.\n\n\nWritable.prototype.pipe = function () {\n errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb\n\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n} // Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\n\n\nfunction validChunk(stream, state, chunk, cb) {\n var er;\n\n if (chunk === null) {\n er = new ERR_STREAM_NULL_VALUES();\n } else if (typeof chunk !== 'string' && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);\n }\n\n if (er) {\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n return false;\n }\n\n return true;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n if (typeof cb !== 'function') cb = nop;\n if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n return ret;\n};\n\nWritable.prototype.cork = function () {\n this._writableState.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n}); // if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\n\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n\n var len = state.objectMode ? 1 : chunk.length;\n state.length += len;\n var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.\n\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n process.nextTick(cb, er); // this can emit finish, and it will always happen\n // after error\n\n process.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er); // this can emit finish, but finish must\n // always follow error\n\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();\n onwriteStateUpdate(state);\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state) || stream.destroyed;\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n process.nextTick(afterWrite, stream, state, finished, cb);\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n} // Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\n\n\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n} // if there's something in the buffer waiting, then process it\n\n\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n var count = 0;\n var allBuffers = true;\n\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n\n buffer.allBuffers = allBuffers;\n doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n\n state.pendingcb++;\n state.lastBufferedRequest = null;\n\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks\n\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n } // ignore unnecessary end() calls.\n\n\n if (!state.ending) endWritable(this, state, cb);\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n});\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\n\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n\n if (err) {\n errorOrDestroy(stream, err);\n }\n\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\n\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function' && !state.destroyed) {\n state.pendingcb++;\n state.finalCalled = true;\n process.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n\n if (need) {\n prefinish(stream, state);\n\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the readable side is ready for autoDestroy as well\n var rState = stream._readableState;\n\n if (!rState || rState.autoDestroy && rState.endEmitted) {\n stream.destroy();\n }\n }\n }\n }\n\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n\n if (cb) {\n if (state.finished) process.nextTick(cb);else stream.once('finish', cb);\n }\n\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n } // reuse the free corkReq.\n\n\n state.corkedRequestsFree.next = corkReq;\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._writableState === undefined) {\n return false;\n }\n\n return this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._writableState.destroyed = value;\n }\n});\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\n\nWritable.prototype._destroy = function (err, cb) {\n cb(err);\n};", - "'use strict';\n\nvar _Object$setPrototypeO;\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar finished = require('./end-of-stream');\n\nvar kLastResolve = Symbol('lastResolve');\nvar kLastReject = Symbol('lastReject');\nvar kError = Symbol('error');\nvar kEnded = Symbol('ended');\nvar kLastPromise = Symbol('lastPromise');\nvar kHandlePromise = Symbol('handlePromise');\nvar kStream = Symbol('stream');\n\nfunction createIterResult(value, done) {\n return {\n value: value,\n done: done\n };\n}\n\nfunction readAndResolve(iter) {\n var resolve = iter[kLastResolve];\n\n if (resolve !== null) {\n var data = iter[kStream].read(); // we defer if data is null\n // we can be expecting either 'end' or\n // 'error'\n\n if (data !== null) {\n iter[kLastPromise] = null;\n iter[kLastResolve] = null;\n iter[kLastReject] = null;\n resolve(createIterResult(data, false));\n }\n }\n}\n\nfunction onReadable(iter) {\n // we wait for the next tick, because it might\n // emit an error with process.nextTick\n process.nextTick(readAndResolve, iter);\n}\n\nfunction wrapForNext(lastPromise, iter) {\n return function (resolve, reject) {\n lastPromise.then(function () {\n if (iter[kEnded]) {\n resolve(createIterResult(undefined, true));\n return;\n }\n\n iter[kHandlePromise](resolve, reject);\n }, reject);\n };\n}\n\nvar AsyncIteratorPrototype = Object.getPrototypeOf(function () {});\nvar ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {\n get stream() {\n return this[kStream];\n },\n\n next: function next() {\n var _this = this;\n\n // if we have detected an error in the meanwhile\n // reject straight away\n var error = this[kError];\n\n if (error !== null) {\n return Promise.reject(error);\n }\n\n if (this[kEnded]) {\n return Promise.resolve(createIterResult(undefined, true));\n }\n\n if (this[kStream].destroyed) {\n // We need to defer via nextTick because if .destroy(err) is\n // called, the error will be emitted via nextTick, and\n // we cannot guarantee that there is no error lingering around\n // waiting to be emitted.\n return new Promise(function (resolve, reject) {\n process.nextTick(function () {\n if (_this[kError]) {\n reject(_this[kError]);\n } else {\n resolve(createIterResult(undefined, true));\n }\n });\n });\n } // if we have multiple next() calls\n // we will wait for the previous Promise to finish\n // this logic is optimized to support for await loops,\n // where next() is only called once at a time\n\n\n var lastPromise = this[kLastPromise];\n var promise;\n\n if (lastPromise) {\n promise = new Promise(wrapForNext(lastPromise, this));\n } else {\n // fast path needed to support multiple this.push()\n // without triggering the next() queue\n var data = this[kStream].read();\n\n if (data !== null) {\n return Promise.resolve(createIterResult(data, false));\n }\n\n promise = new Promise(this[kHandlePromise]);\n }\n\n this[kLastPromise] = promise;\n return promise;\n }\n}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {\n return this;\n}), _defineProperty(_Object$setPrototypeO, \"return\", function _return() {\n var _this2 = this;\n\n // destroy(err, cb) is a private API\n // we can guarantee we have that here, because we control the\n // Readable class this is attached to\n return new Promise(function (resolve, reject) {\n _this2[kStream].destroy(null, function (err) {\n if (err) {\n reject(err);\n return;\n }\n\n resolve(createIterResult(undefined, true));\n });\n });\n}), _Object$setPrototypeO), AsyncIteratorPrototype);\n\nvar createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {\n var _Object$create;\n\n var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {\n value: stream,\n writable: true\n }), _defineProperty(_Object$create, kLastResolve, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kLastReject, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kError, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kEnded, {\n value: stream._readableState.endEmitted,\n writable: true\n }), _defineProperty(_Object$create, kHandlePromise, {\n value: function value(resolve, reject) {\n var data = iterator[kStream].read();\n\n if (data) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(data, false));\n } else {\n iterator[kLastResolve] = resolve;\n iterator[kLastReject] = reject;\n }\n },\n writable: true\n }), _Object$create));\n iterator[kLastPromise] = null;\n finished(stream, function (err) {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise\n // returned by next() and store the error\n\n if (reject !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n reject(err);\n }\n\n iterator[kError] = err;\n return;\n }\n\n var resolve = iterator[kLastResolve];\n\n if (resolve !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(undefined, true));\n }\n\n iterator[kEnded] = true;\n });\n stream.on('readable', onReadable.bind(null, iterator));\n return iterator;\n};\n\nmodule.exports = createReadableStreamAsyncIterator;", - "'use strict'; // undocumented cb() API, needed for core, not for public API\n\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n process.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n process.nextTick(emitErrorNT, this, err);\n }\n }\n\n return this;\n } // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n } // if this is a duplex stream mark the writable part as destroyed as well\n\n\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n } else if (cb) {\n process.nextTick(emitCloseNT, _this);\n cb(err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n });\n\n return this;\n}\n\nfunction emitErrorAndCloseNT(self, err) {\n emitErrorNT(self, err);\n emitCloseNT(self);\n}\n\nfunction emitCloseNT(self) {\n if (self._writableState && !self._writableState.emitClose) return;\n if (self._readableState && !self._readableState.emitClose) return;\n self.emit('close');\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nfunction errorOrDestroy(stream, err) {\n // We have tests that rely on errors being emitted\n // in the same tick, so changing this is semver major.\n // For now when you opt-in to autoDestroy we allow\n // the error to be emitted nextTick. In a future\n // semver major update we should change the default to this.\n var rState = stream._readableState;\n var wState = stream._writableState;\n if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy,\n errorOrDestroy: errorOrDestroy\n};", - "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}", - "var nextTick = require('process/browser.js').nextTick;\nvar apply = Function.prototype.apply;\nvar slice = Array.prototype.slice;\nvar immediateIds = {};\nvar nextImmediateId = 0;\n\n// DOM APIs, for completeness\n\nexports.setTimeout = function() {\n return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);\n};\nexports.setInterval = function() {\n return new Timeout(apply.call(setInterval, window, arguments), clearInterval);\n};\nexports.clearTimeout =\nexports.clearInterval = function(timeout) { timeout.close(); };\n\nfunction Timeout(id, clearFn) {\n this._id = id;\n this._clearFn = clearFn;\n}\nTimeout.prototype.unref = Timeout.prototype.ref = function() {};\nTimeout.prototype.close = function() {\n this._clearFn.call(window, this._id);\n};\n\n// Does not start the time, just sets up the members needed.\nexports.enroll = function(item, msecs) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = msecs;\n};\n\nexports.unenroll = function(item) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = -1;\n};\n\nexports._unrefActive = exports.active = function(item) {\n clearTimeout(item._idleTimeoutId);\n\n var msecs = item._idleTimeout;\n if (msecs >= 0) {\n item._idleTimeoutId = setTimeout(function onTimeout() {\n if (item._onTimeout)\n item._onTimeout();\n }, msecs);\n }\n};\n\n// That's not how node.js implements it but the exposed api is the same.\nexports.setImmediate = typeof setImmediate === \"function\" ? setImmediate : function(fn) {\n var id = nextImmediateId++;\n var args = arguments.length < 2 ? false : slice.call(arguments, 1);\n\n immediateIds[id] = true;\n\n nextTick(function onNextTick() {\n if (immediateIds[id]) {\n // fn.call() is faster so we optimize for the common use-case\n // @see http://jsperf.com/call-apply-segu\n if (args) {\n fn.apply(null, args);\n } else {\n fn.call(null);\n }\n // Prevent ids from leaking\n exports.clearImmediate(id);\n }\n });\n\n return id;\n};\n\nexports.clearImmediate = typeof clearImmediate === \"function\" ? clearImmediate : function(id) {\n delete immediateIds[id];\n};", - "module.exports={\n \"0\": \"O\",\n \"1\": \"l\",\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 \"𑌀\": \"̊\",\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 \"̶\": \"̵\",\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 \"𑓁\": \"ঃ\",\n \"់\": \"่\",\n \"່\": \"่\",\n \"້\": \"้\",\n \"໊\": \"๊\",\n \"໋\": \"๋\",\n \"꙯\": \"⃩\",\n \"\\u2028\": \" \",\n \"\\u2029\": \" \",\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 \"։\": \":\",\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 \"‧\": \"·\",\n \"∙\": \"·\",\n \"⋅\": \"·\",\n \"ꞏ\": \"·\",\n \"ᐧ\": \"·\",\n \"⋯\": \"···\",\n \"ⵈ\": \"···\",\n \"ᑄ\": \"·<\",\n \"⋗\": \"·>\",\n \"ᐷ\": \"·>\",\n \"ᑀ\": \"·>\",\n \"ᔯ\": \"·4\",\n \"ᑾ\": \"·b\",\n \"ᒀ\": \"·ḃ\",\n \"ᑺ\": \"·d\",\n \"ᒘ\": \"·J\",\n \"ᒶ\": \"·L\",\n \"ᑶ\": \"·P\",\n \"ᑗ\": \"·U\",\n \"ᐺ\": \"·V\",\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 \"ᓺ\": \"·ᓰ\",\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 \"՚\": \"'\",\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 \"Ɓ\": \"'B\",\n \"Ɗ\": \"'D\",\n \"ʼn\": \"'n\",\n \"Ƥ\": \"'P\",\n \"Ƭ\": \"'T\",\n \"Ƴ\": \"'Y\",\n \"[\": \"(\",\n \"❨\": \"(\",\n \"❲\": \"(\",\n \"〔\": \"(\",\n \"﴾\": \"(\",\n \"⸨\": \"((\",\n \"㈠\": \"(ー)\",\n \"⑵\": \"(2)\",\n \"⒇\": \"(2O)\",\n \"⑶\": \"(3)\",\n \"⑷\": \"(4)\",\n \"⑸\": \"(5)\",\n \"⑹\": \"(6)\",\n \"⑺\": \"(7)\",\n \"⑻\": \"(8)\",\n \"⑼\": \"(9)\",\n \"⒜\": \"(a)\",\n \"🄐\": \"(A)\",\n \"⒝\": \"(b)\",\n \"🄑\": \"(B)\",\n \"⒞\": \"(c)\",\n \"🄒\": \"(C)\",\n \"⒟\": \"(d)\",\n \"🄓\": \"(D)\",\n \"⒠\": \"(e)\",\n \"🄔\": \"(E)\",\n \"⒡\": \"(f)\",\n \"🄕\": \"(F)\",\n \"⒢\": \"(g)\",\n \"🄖\": \"(G)\",\n \"⒣\": \"(h)\",\n \"🄗\": \"(H)\",\n \"⒤\": \"(i)\",\n \"⒥\": \"(j)\",\n \"🄙\": \"(J)\",\n \"⒦\": \"(k)\",\n \"🄚\": \"(K)\",\n \"⑴\": \"(l)\",\n \"🄘\": \"(l)\",\n \"⒧\": \"(l)\",\n \"🄛\": \"(L)\",\n \"⑿\": \"(l2)\",\n \"⒀\": \"(l3)\",\n \"⒁\": \"(l4)\",\n \"⒂\": \"(l5)\",\n \"⒃\": \"(l6)\",\n \"⒄\": \"(l7)\",\n \"⒅\": \"(l8)\",\n \"⒆\": \"(l9)\",\n \"⑾\": \"(ll)\",\n \"⑽\": \"(lO)\",\n \"🄜\": \"(M)\",\n \"⒩\": \"(n)\",\n \"🄝\": \"(N)\",\n \"⒪\": \"(o)\",\n \"🄞\": \"(O)\",\n \"⒫\": \"(p)\",\n \"🄟\": \"(P)\",\n \"⒬\": \"(q)\",\n \"🄠\": \"(Q)\",\n \"⒭\": \"(r)\",\n \"🄡\": \"(R)\",\n \"⒨\": \"(rn)\",\n \"⒮\": \"(s)\",\n \"🄢\": \"(S)\",\n \"🄪\": \"(S)\",\n \"⒯\": \"(t)\",\n \"🄣\": \"(T)\",\n \"⒰\": \"(u)\",\n \"🄤\": \"(U)\",\n \"⒱\": \"(v)\",\n \"🄥\": \"(V)\",\n \"⒲\": \"(w)\",\n \"🄦\": \"(W)\",\n \"⒳\": \"(x)\",\n \"🄧\": \"(X)\",\n \"⒴\": \"(y)\",\n \"🄨\": \"(Y)\",\n \"⒵\": \"(z)\",\n \"🄩\": \"(Z)\",\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 \"㈣\": \"(四)\",\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 \"∗\": \"*\",\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 \"﹊\": \"ˉ\",\n \"﹋\": \"ˉ\",\n \"﹌\": \"ˉ\",\n \"¯\": \"ˉ\",\n \" ̄\": \"ˉ\",\n \"▔\": \"ˉ\",\n \"ъ\": \"ˉb\",\n \"ꙑ\": \"ˉbi\",\n \"͵\": \"ˏ\",\n \"˻\": \"˪\",\n \"꜖\": \"˪\",\n \"꜔\": \"˫\",\n \"。\": \"˳\",\n \"⸰\": \"°\",\n \"˚\": \"°\",\n \"∘\": \"°\",\n \"○\": \"°\",\n \"◦\": \"°\",\n \"⍜\": \"°̲\",\n \"⍤\": \"°̈\",\n \"℃\": \"°C\",\n \"℉\": \"°F\",\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 \"˂\": \"<\",\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 \"🝞\": \"≏\",\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 \"🜊\": \"☩\",\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 \"𝟐\": \"2\",\n \"𝟚\": \"2\",\n \"𝟤\": \"2\",\n \"𝟮\": \"2\",\n \"𝟸\": \"2\",\n \"🯲\": \"2\",\n \"Ꝛ\": \"2\",\n \"Ƨ\": \"2\",\n \"Ϩ\": \"2\",\n \"Ꙅ\": \"2\",\n \"ᒿ\": \"2\",\n \"ꛯ\": \"2\",\n \"ꧏ\": \"٢\",\n \"۲\": \"٢\",\n \"૨\": \"२\",\n \"𑓒\": \"২\",\n \"೨\": \"౨\",\n \"②\": \"➁\",\n \"ƻ\": \"2̵\",\n \"🄃\": \"2,\",\n \"⒉\": \"2.\",\n \"㏵\": \"22日\",\n \"㍮\": \"22点\",\n \"㏶\": \"23日\",\n \"㍯\": \"23点\",\n \"㏷\": \"24日\",\n \"㍰\": \"24点\",\n \"㏸\": \"25日\",\n \"㏹\": \"26日\",\n \"㏺\": \"27日\",\n \"㏻\": \"28日\",\n \"㏼\": \"29日\",\n \"㏴\": \"2l日\",\n \"㍭\": \"2l点\",\n \"⒛\": \"2O.\",\n \"㏳\": \"2O日\",\n \"㍬\": \"2O点\",\n \"෩\": \"෨ා\",\n \"෯\": \"෨ී\",\n \"㏡\": \"2日\",\n \"㋁\": \"2月\",\n \"㍚\": \"2点\",\n \"𝈆\": \"3\",\n \"𝟑\": \"3\",\n \"𝟛\": \"3\",\n \"𝟥\": \"3\",\n \"𝟯\": \"3\",\n \"𝟹\": \"3\",\n \"🯳\": \"3\",\n \"Ɜ\": \"3\",\n \"Ȝ\": \"3\",\n \"Ʒ\": \"3\",\n \"Ꝫ\": \"3\",\n \"Ⳍ\": \"3\",\n \"З\": \"3\",\n \"Ӡ\": \"3\",\n \"𖼻\": \"3\",\n \"𑣊\": \"3\",\n \"۳\": \"٣\",\n \"𞣉\": \"٣\",\n \"૩\": \"३\",\n \"③\": \"➂\",\n \"Ҙ\": \"3̦\",\n \"🄄\": \"3,\",\n \"⒊\": \"3.\",\n \"㏾\": \"3l日\",\n \"㏽\": \"3O日\",\n \"㏢\": \"3日\",\n \"㋂\": \"3月\",\n \"㍛\": \"3点\",\n \"𝟒\": \"4\",\n \"𝟜\": \"4\",\n \"𝟦\": \"4\",\n \"𝟰\": \"4\",\n \"𝟺\": \"4\",\n \"🯴\": \"4\",\n \"Ꮞ\": \"4\",\n \"𑢯\": \"4\",\n \"۴\": \"٤\",\n \"૪\": \"४\",\n \"④\": \"➃\",\n \"🄅\": \"4,\",\n \"⒋\": \"4.\",\n \"ᔰ\": \"4·\",\n \"㏣\": \"4日\",\n \"㋃\": \"4月\",\n \"㍜\": \"4点\",\n \"𝟓\": \"5\",\n \"𝟝\": \"5\",\n \"𝟧\": \"5\",\n \"𝟱\": \"5\",\n \"𝟻\": \"5\",\n \"🯵\": \"5\",\n \"Ƽ\": \"5\",\n \"𑢻\": \"5\",\n \"⑤\": \"➄\",\n \"🄆\": \"5,\",\n \"⒌\": \"5.\",\n \"㏤\": \"5日\",\n \"㋄\": \"5月\",\n \"㍝\": \"5点\",\n \"𝟔\": \"6\",\n \"𝟞\": \"6\",\n \"𝟨\": \"6\",\n \"𝟲\": \"6\",\n \"𝟼\": \"6\",\n \"🯶\": \"6\",\n \"Ⳓ\": \"6\",\n \"б\": \"6\",\n \"Ꮾ\": \"6\",\n \"𑣕\": \"6\",\n \"۶\": \"٦\",\n \"𑓖\": \"৬\",\n \"⑥\": \"➅\",\n \"🄇\": \"6,\",\n \"⒍\": \"6.\",\n \"㏥\": \"6日\",\n \"㋅\": \"6月\",\n \"㍞\": \"6点\",\n \"𝈒\": \"7\",\n \"𝟕\": \"7\",\n \"𝟟\": \"7\",\n \"𝟩\": \"7\",\n \"𝟳\": \"7\",\n \"𝟽\": \"7\",\n \"🯷\": \"7\",\n \"𐓒\": \"7\",\n \"𑣆\": \"7\",\n \"⑦\": \"➆\",\n \"🄈\": \"7,\",\n \"⒎\": \"7.\",\n \"㏦\": \"7日\",\n \"㋆\": \"7月\",\n \"㍟\": \"7点\",\n \"ଃ\": \"8\",\n \"৪\": \"8\",\n \"੪\": \"8\",\n \"𞣋\": \"8\",\n \"𝟖\": \"8\",\n \"𝟠\": \"8\",\n \"𝟪\": \"8\",\n \"𝟴\": \"8\",\n \"𝟾\": \"8\",\n \"🯸\": \"8\",\n \"ȣ\": \"8\",\n \"Ȣ\": \"8\",\n \"𐌚\": \"8\",\n \"૮\": \"८\",\n \"⑧\": \"➇\",\n \"🄉\": \"8,\",\n \"⒏\": \"8.\",\n \"㏧\": \"8日\",\n \"㋇\": \"8月\",\n \"㍠\": \"8点\",\n \"੧\": \"9\",\n \"୨\": \"9\",\n \"৭\": \"9\",\n \"൭\": \"9\",\n \"𝟗\": \"9\",\n \"𝟡\": \"9\",\n \"𝟫\": \"9\",\n \"𝟵\": \"9\",\n \"𝟿\": \"9\",\n \"🯹\": \"9\",\n \"Ꝯ\": \"9\",\n \"Ⳋ\": \"9\",\n \"𑣌\": \"9\",\n \"𑢬\": \"9\",\n \"𑣖\": \"9\",\n \"१\": \"٩\",\n \"𑣤\": \"٩\",\n \"۹\": \"٩\",\n \"೯\": \"౯\",\n \"⑨\": \"➈\",\n \"🄊\": \"9,\",\n \"⒐\": \"9.\",\n \"㏨\": \"9日\",\n \"㋈\": \"9月\",\n \"㍡\": \"9点\",\n \"⍺\": \"a\",\n \"a\": \"a\",\n \"𝐚\": \"a\",\n \"𝑎\": \"a\",\n \"𝒂\": \"a\",\n \"𝒶\": \"a\",\n \"𝓪\": \"a\",\n \"𝔞\": \"a\",\n \"𝕒\": \"a\",\n \"𝖆\": \"a\",\n \"𝖺\": \"a\",\n \"𝗮\": \"a\",\n \"𝘢\": \"a\",\n \"𝙖\": \"a\",\n \"𝚊\": \"a\",\n \"ɑ\": \"a\",\n \"α\": \"a\",\n \"𝛂\": \"a\",\n \"𝛼\": \"a\",\n \"𝜶\": \"a\",\n \"𝝰\": \"a\",\n \"𝞪\": \"a\",\n \"а\": \"a\",\n \"ⷶ\": \"ͣ\",\n \"A\": \"A\",\n \"𝐀\": \"A\",\n \"𝐴\": \"A\",\n \"𝑨\": \"A\",\n \"𝒜\": \"A\",\n \"𝓐\": \"A\",\n \"𝔄\": \"A\",\n \"𝔸\": \"A\",\n \"𝕬\": \"A\",\n \"𝖠\": \"A\",\n \"𝗔\": \"A\",\n \"𝘈\": \"A\",\n \"𝘼\": \"A\",\n \"𝙰\": \"A\",\n \"Α\": \"A\",\n \"𝚨\": \"A\",\n \"𝛢\": \"A\",\n \"𝜜\": \"A\",\n \"𝝖\": \"A\",\n \"𝞐\": \"A\",\n \"А\": \"A\",\n \"Ꭺ\": \"A\",\n \"ᗅ\": \"A\",\n \"ꓮ\": \"A\",\n \"𖽀\": \"A\",\n \"𐊠\": \"A\",\n \"⍶\": \"a̲\",\n \"ǎ\": \"ă\",\n \"Ǎ\": \"Ă\",\n \"ȧ\": \"å\",\n \"Ȧ\": \"Å\",\n \"ẚ\": \"ả\",\n \"℀\": \"a/c\",\n \"℁\": \"a/s\",\n \"ꜳ\": \"aa\",\n \"Ꜳ\": \"AA\",\n \"æ\": \"ae\",\n \"ӕ\": \"ae\",\n \"Æ\": \"AE\",\n \"Ӕ\": \"AE\",\n \"ꜵ\": \"ao\",\n \"Ꜵ\": \"AO\",\n \"🜇\": \"AR\",\n \"ꜷ\": \"au\",\n \"Ꜷ\": \"AU\",\n \"ꜹ\": \"av\",\n \"ꜻ\": \"av\",\n \"Ꜹ\": \"AV\",\n \"Ꜻ\": \"AV\",\n \"ꜽ\": \"ay\",\n \"Ꜽ\": \"AY\",\n \"ꭺ\": \"ᴀ\",\n \"∀\": \"Ɐ\",\n \"𝈗\": \"Ɐ\",\n \"ᗄ\": \"Ɐ\",\n \"ꓯ\": \"Ɐ\",\n \"𐐟\": \"Ɒ\",\n \"𝐛\": \"b\",\n \"𝑏\": \"b\",\n \"𝒃\": \"b\",\n \"𝒷\": \"b\",\n \"𝓫\": \"b\",\n \"𝔟\": \"b\",\n \"𝕓\": \"b\",\n \"𝖇\": \"b\",\n \"𝖻\": \"b\",\n \"𝗯\": \"b\",\n \"𝘣\": \"b\",\n \"𝙗\": \"b\",\n \"𝚋\": \"b\",\n \"Ƅ\": \"b\",\n \"Ь\": \"b\",\n \"Ꮟ\": \"b\",\n \"ᑲ\": \"b\",\n \"ᖯ\": \"b\",\n \"B\": \"B\",\n \"ℬ\": \"B\",\n \"𝐁\": \"B\",\n \"𝐵\": \"B\",\n \"𝑩\": \"B\",\n \"𝓑\": \"B\",\n \"𝔅\": \"B\",\n \"𝔹\": \"B\",\n \"𝕭\": \"B\",\n \"𝖡\": \"B\",\n \"𝗕\": \"B\",\n \"𝘉\": \"B\",\n \"𝘽\": \"B\",\n \"𝙱\": \"B\",\n \"Ꞵ\": \"B\",\n \"Β\": \"B\",\n \"𝚩\": \"B\",\n \"𝛣\": \"B\",\n \"𝜝\": \"B\",\n \"𝝗\": \"B\",\n \"𝞑\": \"B\",\n \"В\": \"B\",\n \"Ᏼ\": \"B\",\n \"ᗷ\": \"B\",\n \"ꓐ\": \"B\",\n \"𐊂\": \"B\",\n \"𐊡\": \"B\",\n \"𐌁\": \"B\",\n \"ɓ\": \"b̔\",\n \"ᑳ\": \"ḃ\",\n \"ƃ\": \"b̄\",\n \"Ƃ\": \"b̄\",\n \"Б\": \"b̄\",\n \"ƀ\": \"b̵\",\n \"ҍ\": \"b̵\",\n \"Ҍ\": \"b̵\",\n \"ѣ\": \"b̵\",\n \"Ѣ\": \"b̵\",\n \"ᑿ\": \"b·\",\n \"ᒁ\": \"ḃ·\",\n \"ᒈ\": \"b'\",\n \"Ы\": \"bl\",\n \"в\": \"ʙ\",\n \"ᏼ\": \"ʙ\",\n \"c\": \"c\",\n \"ⅽ\": \"c\",\n \"𝐜\": \"c\",\n \"𝑐\": \"c\",\n \"𝒄\": \"c\",\n \"𝒸\": \"c\",\n \"𝓬\": \"c\",\n \"𝔠\": \"c\",\n \"𝕔\": \"c\",\n \"𝖈\": \"c\",\n \"𝖼\": \"c\",\n \"𝗰\": \"c\",\n \"𝘤\": \"c\",\n \"𝙘\": \"c\",\n \"𝚌\": \"c\",\n \"ᴄ\": \"c\",\n \"ϲ\": \"c\",\n \"ⲥ\": \"c\",\n \"с\": \"c\",\n \"ꮯ\": \"c\",\n \"𐐽\": \"c\",\n \"ⷭ\": \"ͨ\",\n \"🝌\": \"C\",\n \"𑣲\": \"C\",\n \"𑣩\": \"C\",\n \"C\": \"C\",\n \"Ⅽ\": \"C\",\n \"ℂ\": \"C\",\n \"ℭ\": \"C\",\n \"𝐂\": \"C\",\n \"𝐶\": \"C\",\n \"𝑪\": \"C\",\n \"𝒞\": \"C\",\n \"𝓒\": \"C\",\n \"𝕮\": \"C\",\n \"𝖢\": \"C\",\n \"𝗖\": \"C\",\n \"𝘊\": \"C\",\n \"𝘾\": \"C\",\n \"𝙲\": \"C\",\n \"Ϲ\": \"C\",\n \"Ⲥ\": \"C\",\n \"С\": \"C\",\n \"Ꮯ\": \"C\",\n \"ꓚ\": \"C\",\n \"𐊢\": \"C\",\n \"𐌂\": \"C\",\n \"𐐕\": \"C\",\n \"𐔜\": \"C\",\n \"¢\": \"c̸\",\n \"ȼ\": \"c̸\",\n \"₡\": \"C⃫\",\n \"🅮\": \"C⃠\",\n \"ç\": \"c̦\",\n \"ҫ\": \"c̦\",\n \"Ç\": \"C̦\",\n \"Ҫ\": \"C̦\",\n \"Ƈ\": \"C'\",\n \"℅\": \"c/o\",\n \"℆\": \"c/u\",\n \"🅭\": \"㏄\\t⃝\",\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 \"ⅾ\": \"d\",\n \"ⅆ\": \"d\",\n \"𝐝\": \"d\",\n \"𝑑\": \"d\",\n \"𝒅\": \"d\",\n \"𝒹\": \"d\",\n \"𝓭\": \"d\",\n \"𝔡\": \"d\",\n \"𝕕\": \"d\",\n \"𝖉\": \"d\",\n \"𝖽\": \"d\",\n \"𝗱\": \"d\",\n \"𝘥\": \"d\",\n \"𝙙\": \"d\",\n \"𝚍\": \"d\",\n \"ԁ\": \"d\",\n \"Ꮷ\": \"d\",\n \"ᑯ\": \"d\",\n \"ꓒ\": \"d\",\n \"Ⅾ\": \"D\",\n \"ⅅ\": \"D\",\n \"𝐃\": \"D\",\n \"𝐷\": \"D\",\n \"𝑫\": \"D\",\n \"𝒟\": \"D\",\n \"𝓓\": \"D\",\n \"𝔇\": \"D\",\n \"𝔻\": \"D\",\n \"𝕯\": \"D\",\n \"𝖣\": \"D\",\n \"𝗗\": \"D\",\n \"𝘋\": \"D\",\n \"𝘿\": \"D\",\n \"𝙳\": \"D\",\n \"Ꭰ\": \"D\",\n \"ᗞ\": \"D\",\n \"ᗪ\": \"D\",\n \"ꓓ\": \"D\",\n \"ɗ\": \"d̔\",\n \"ɖ\": \"d̨\",\n \"ƌ\": \"d̄\",\n \"đ\": \"d̵\",\n \"Đ\": \"D̵\",\n \"Ð\": \"D̵\",\n \"Ɖ\": \"D̵\",\n \"₫\": \"ḏ̵\",\n \"ꝺ\": \"Ꝺ\",\n \"ᑻ\": \"d·\",\n \"ᒇ\": \"d'\",\n \"ʤ\": \"dȝ\",\n \"dz\": \"dz\",\n \"ʣ\": \"dz\",\n \"Dz\": \"Dz\",\n \"DZ\": \"DZ\",\n \"dž\": \"dž\",\n \"Dž\": \"Dž\",\n \"DŽ\": \"DŽ\",\n \"ʥ\": \"dʑ\",\n \"ꭰ\": \"ᴅ\",\n \"⸹\": \"ẟ\",\n \"δ\": \"ẟ\",\n \"𝛅\": \"ẟ\",\n \"𝛿\": \"ẟ\",\n \"𝜹\": \"ẟ\",\n \"𝝳\": \"ẟ\",\n \"𝞭\": \"ẟ\",\n \"ծ\": \"ẟ\",\n \"ᕷ\": \"ẟ\",\n \"℮\": \"e\",\n \"e\": \"e\",\n \"ℯ\": \"e\",\n \"ⅇ\": \"e\",\n \"𝐞\": \"e\",\n \"𝑒\": \"e\",\n \"𝒆\": \"e\",\n \"𝓮\": \"e\",\n \"𝔢\": \"e\",\n \"𝕖\": \"e\",\n \"𝖊\": \"e\",\n \"𝖾\": \"e\",\n \"𝗲\": \"e\",\n \"𝘦\": \"e\",\n \"𝙚\": \"e\",\n \"𝚎\": \"e\",\n \"ꬲ\": \"e\",\n \"е\": \"e\",\n \"ҽ\": \"e\",\n \"ⷷ\": \"ͤ\",\n \"⋿\": \"E\",\n \"E\": \"E\",\n \"ℰ\": \"E\",\n \"𝐄\": \"E\",\n \"𝐸\": \"E\",\n \"𝑬\": \"E\",\n \"𝓔\": \"E\",\n \"𝔈\": \"E\",\n \"𝔼\": \"E\",\n \"𝕰\": \"E\",\n \"𝖤\": \"E\",\n \"𝗘\": \"E\",\n \"𝘌\": \"E\",\n \"𝙀\": \"E\",\n \"𝙴\": \"E\",\n \"Ε\": \"E\",\n \"𝚬\": \"E\",\n \"𝛦\": \"E\",\n \"𝜠\": \"E\",\n \"𝝚\": \"E\",\n \"𝞔\": \"E\",\n \"Е\": \"E\",\n \"ⴹ\": \"E\",\n \"Ꭼ\": \"E\",\n \"ꓰ\": \"E\",\n \"𑢦\": \"E\",\n \"𑢮\": \"E\",\n \"𐊆\": \"E\",\n \"ě\": \"ĕ\",\n \"Ě\": \"Ĕ\",\n \"ɇ\": \"e̸\",\n \"Ɇ\": \"E̸\",\n \"ҿ\": \"ę\",\n \"ꭼ\": \"ᴇ\",\n \"ə\": \"ǝ\",\n \"ә\": \"ǝ\",\n \"∃\": \"Ǝ\",\n \"ⴺ\": \"Ǝ\",\n \"ꓱ\": \"Ǝ\",\n \"ɚ\": \"ǝ˞\",\n \"ᴔ\": \"ǝo\",\n \"ꭁ\": \"ǝo̸\",\n \"ꭂ\": \"ǝo̵\",\n \"Ә\": \"Ə\",\n \"𝈡\": \"Ɛ\",\n \"ℇ\": \"Ɛ\",\n \"Ԑ\": \"Ɛ\",\n \"Ꮛ\": \"Ɛ\",\n \"𖼭\": \"Ɛ\",\n \"𐐁\": \"Ɛ\",\n \"ᶟ\": \"ᵋ\",\n \"ᴈ\": \"ɜ\",\n \"з\": \"ɜ\",\n \"ҙ\": \"ɜ̦\",\n \"𐑂\": \"ɞ\",\n \"ꞝ\": \"ʚ\",\n \"𐐪\": \"ʚ\",\n \"𝐟\": \"f\",\n \"𝑓\": \"f\",\n \"𝒇\": \"f\",\n \"𝒻\": \"f\",\n \"𝓯\": \"f\",\n \"𝔣\": \"f\",\n \"𝕗\": \"f\",\n \"𝖋\": \"f\",\n \"𝖿\": \"f\",\n \"𝗳\": \"f\",\n \"𝘧\": \"f\",\n \"𝙛\": \"f\",\n \"𝚏\": \"f\",\n \"ꬵ\": \"f\",\n \"ꞙ\": \"f\",\n \"ſ\": \"f\",\n \"ẝ\": \"f\",\n \"ք\": \"f\",\n \"𝈓\": \"F\",\n \"ℱ\": \"F\",\n \"𝐅\": \"F\",\n \"𝐹\": \"F\",\n \"𝑭\": \"F\",\n \"𝓕\": \"F\",\n \"𝔉\": \"F\",\n \"𝔽\": \"F\",\n \"𝕱\": \"F\",\n \"𝖥\": \"F\",\n \"𝗙\": \"F\",\n \"𝘍\": \"F\",\n \"𝙁\": \"F\",\n \"𝙵\": \"F\",\n \"Ꞙ\": \"F\",\n \"Ϝ\": \"F\",\n \"𝟊\": \"F\",\n \"ᖴ\": \"F\",\n \"ꓝ\": \"F\",\n \"𑣂\": \"F\",\n \"𑢢\": \"F\",\n \"𐊇\": \"F\",\n \"𐊥\": \"F\",\n \"𐔥\": \"F\",\n \"ƒ\": \"f̦\",\n \"Ƒ\": \"F̦\",\n \"ᵮ\": \"f̴\",\n \"℻\": \"FAX\",\n \"ff\": \"ff\",\n \"ffi\": \"ffi\",\n \"ffl\": \"ffl\",\n \"fi\": \"fi\",\n \"fl\": \"fl\",\n \"ʩ\": \"fŋ\",\n \"ᖵ\": \"Ⅎ\",\n \"ꓞ\": \"Ⅎ\",\n \"𝈰\": \"ꟻ\",\n \"ᖷ\": \"ꟻ\",\n \"g\": \"g\",\n \"ℊ\": \"g\",\n \"𝐠\": \"g\",\n \"𝑔\": \"g\",\n \"𝒈\": \"g\",\n \"𝓰\": \"g\",\n \"𝔤\": \"g\",\n \"𝕘\": \"g\",\n \"𝖌\": \"g\",\n \"𝗀\": \"g\",\n \"𝗴\": \"g\",\n \"𝘨\": \"g\",\n \"𝙜\": \"g\",\n \"𝚐\": \"g\",\n \"ɡ\": \"g\",\n \"ᶃ\": \"g\",\n \"ƍ\": \"g\",\n \"ց\": \"g\",\n \"𝐆\": \"G\",\n \"𝐺\": \"G\",\n \"𝑮\": \"G\",\n \"𝒢\": \"G\",\n \"𝓖\": \"G\",\n \"𝔊\": \"G\",\n \"𝔾\": \"G\",\n \"𝕲\": \"G\",\n \"𝖦\": \"G\",\n \"𝗚\": \"G\",\n \"𝘎\": \"G\",\n \"𝙂\": \"G\",\n \"𝙶\": \"G\",\n \"Ԍ\": \"G\",\n \"Ꮐ\": \"G\",\n \"Ᏻ\": \"G\",\n \"ꓖ\": \"G\",\n \"ᶢ\": \"ᵍ\",\n \"ɠ\": \"g̔\",\n \"ǧ\": \"ğ\",\n \"Ǧ\": \"Ğ\",\n \"ǵ\": \"ģ\",\n \"ǥ\": \"g̵\",\n \"Ǥ\": \"G̵\",\n \"Ɠ\": \"G'\",\n \"ԍ\": \"ɢ\",\n \"ꮐ\": \"ɢ\",\n \"ᏻ\": \"ɢ\",\n \"h\": \"h\",\n \"ℎ\": \"h\",\n \"𝐡\": \"h\",\n \"𝒉\": \"h\",\n \"𝒽\": \"h\",\n \"𝓱\": \"h\",\n \"𝔥\": \"h\",\n \"𝕙\": \"h\",\n \"𝖍\": \"h\",\n \"𝗁\": \"h\",\n \"𝗵\": \"h\",\n \"𝘩\": \"h\",\n \"𝙝\": \"h\",\n \"𝚑\": \"h\",\n \"һ\": \"h\",\n \"հ\": \"h\",\n \"Ꮒ\": \"h\",\n \"H\": \"H\",\n \"ℋ\": \"H\",\n \"ℌ\": \"H\",\n \"ℍ\": \"H\",\n \"𝐇\": \"H\",\n \"𝐻\": \"H\",\n \"𝑯\": \"H\",\n \"𝓗\": \"H\",\n \"𝕳\": \"H\",\n \"𝖧\": \"H\",\n \"𝗛\": \"H\",\n \"𝘏\": \"H\",\n \"𝙃\": \"H\",\n \"𝙷\": \"H\",\n \"Η\": \"H\",\n \"𝚮\": \"H\",\n \"𝛨\": \"H\",\n \"𝜢\": \"H\",\n \"𝝜\": \"H\",\n \"𝞖\": \"H\",\n \"Ⲏ\": \"H\",\n \"Н\": \"H\",\n \"Ꮋ\": \"H\",\n \"ᕼ\": \"H\",\n \"ꓧ\": \"H\",\n \"𐋏\": \"H\",\n \"ᵸ\": \"ᴴ\",\n \"ɦ\": \"h̔\",\n \"ꚕ\": \"h̔\",\n \"Ᏺ\": \"h̔\",\n \"Ⱨ\": \"H̩\",\n \"Ң\": \"H̩\",\n \"ħ\": \"h̵\",\n \"ℏ\": \"h̵\",\n \"ћ\": \"h̵\",\n \"Ħ\": \"H̵\",\n \"Ӊ\": \"H̦\",\n \"Ӈ\": \"H̦\",\n \"н\": \"ʜ\",\n \"ꮋ\": \"ʜ\",\n \"ң\": \"ʜ̩\",\n \"ӊ\": \"ʜ̦\",\n \"ӈ\": \"ʜ̦\",\n \"Ԋ\": \"Ƕ\",\n \"ꮀ\": \"ⱶ\",\n \"Ͱ\": \"Ⱶ\",\n \"Ꭸ\": \"Ⱶ\",\n \"Ꮀ\": \"Ⱶ\",\n \"ꚱ\": \"Ⱶ\",\n \"ꞕ\": \"ꜧ\",\n \"˛\": \"i\",\n \"⍳\": \"i\",\n \"i\": \"i\",\n \"ⅰ\": \"i\",\n \"ℹ\": \"i\",\n \"ⅈ\": \"i\",\n \"𝐢\": \"i\",\n \"𝑖\": \"i\",\n \"𝒊\": \"i\",\n \"𝒾\": \"i\",\n \"𝓲\": \"i\",\n \"𝔦\": \"i\",\n \"𝕚\": \"i\",\n \"𝖎\": \"i\",\n \"𝗂\": \"i\",\n \"𝗶\": \"i\",\n \"𝘪\": \"i\",\n \"𝙞\": \"i\",\n \"𝚒\": \"i\",\n \"ı\": \"i\",\n \"𝚤\": \"i\",\n \"ɪ\": \"i\",\n \"ɩ\": \"i\",\n \"ι\": \"i\",\n \"ι\": \"i\",\n \"ͺ\": \"i\",\n \"𝛊\": \"i\",\n \"𝜄\": \"i\",\n \"𝜾\": \"i\",\n \"𝝸\": \"i\",\n \"𝞲\": \"i\",\n \"і\": \"i\",\n \"ꙇ\": \"i\",\n \"ӏ\": \"i\",\n \"ꭵ\": \"i\",\n \"Ꭵ\": \"i\",\n \"𑣃\": \"i\",\n \"ⓛ\": \"Ⓘ\",\n \"⍸\": \"i̲\",\n \"ǐ\": \"ĭ\",\n \"Ǐ\": \"Ĭ\",\n \"ɨ\": \"i̵\",\n \"ᵻ\": \"i̵\",\n \"ᵼ\": \"i̵\",\n \"ⅱ\": \"ii\",\n \"ⅲ\": \"iii\",\n \"ij\": \"ij\",\n \"ⅳ\": \"iv\",\n \"ⅸ\": \"ix\",\n \"j\": \"j\",\n \"ⅉ\": \"j\",\n \"𝐣\": \"j\",\n \"𝑗\": \"j\",\n \"𝒋\": \"j\",\n \"𝒿\": \"j\",\n \"𝓳\": \"j\",\n \"𝔧\": \"j\",\n \"𝕛\": \"j\",\n \"𝖏\": \"j\",\n \"𝗃\": \"j\",\n \"𝗷\": \"j\",\n \"𝘫\": \"j\",\n \"𝙟\": \"j\",\n \"𝚓\": \"j\",\n \"ϳ\": \"j\",\n \"ј\": \"j\",\n \"J\": \"J\",\n \"𝐉\": \"J\",\n \"𝐽\": \"J\",\n \"𝑱\": \"J\",\n \"𝒥\": \"J\",\n \"𝓙\": \"J\",\n \"𝔍\": \"J\",\n \"𝕁\": \"J\",\n \"𝕵\": \"J\",\n \"𝖩\": \"J\",\n \"𝗝\": \"J\",\n \"𝘑\": \"J\",\n \"𝙅\": \"J\",\n \"𝙹\": \"J\",\n \"Ʝ\": \"J\",\n \"Ϳ\": \"J\",\n \"Ј\": \"J\",\n \"Ꭻ\": \"J\",\n \"ᒍ\": \"J\",\n \"ꓙ\": \"J\",\n \"ɉ\": \"j̵\",\n \"Ɉ\": \"J̵\",\n \"ᒙ\": \"J·\",\n \"𝚥\": \"ȷ\",\n \"յ\": \"ȷ\",\n \"ꭻ\": \"ᴊ\",\n \"𝐤\": \"k\",\n \"𝑘\": \"k\",\n \"𝒌\": \"k\",\n \"𝓀\": \"k\",\n \"𝓴\": \"k\",\n \"𝔨\": \"k\",\n \"𝕜\": \"k\",\n \"𝖐\": \"k\",\n \"𝗄\": \"k\",\n \"𝗸\": \"k\",\n \"𝘬\": \"k\",\n \"𝙠\": \"k\",\n \"𝚔\": \"k\",\n \"K\": \"K\",\n \"K\": \"K\",\n \"𝐊\": \"K\",\n \"𝐾\": \"K\",\n \"𝑲\": \"K\",\n \"𝒦\": \"K\",\n \"𝓚\": \"K\",\n \"𝔎\": \"K\",\n \"𝕂\": \"K\",\n \"𝕶\": \"K\",\n \"𝖪\": \"K\",\n \"𝗞\": \"K\",\n \"𝘒\": \"K\",\n \"𝙆\": \"K\",\n \"𝙺\": \"K\",\n \"Κ\": \"K\",\n \"𝚱\": \"K\",\n \"𝛫\": \"K\",\n \"𝜥\": \"K\",\n \"𝝟\": \"K\",\n \"𝞙\": \"K\",\n \"Ⲕ\": \"K\",\n \"К\": \"K\",\n \"Ꮶ\": \"K\",\n \"ᛕ\": \"K\",\n \"ꓗ\": \"K\",\n \"𐔘\": \"K\",\n \"ƙ\": \"k̔\",\n \"Ⱪ\": \"K̩\",\n \"Қ\": \"K̩\",\n \"₭\": \"K̵\",\n \"Ꝁ\": \"K̵\",\n \"Ҟ\": \"K̵\",\n \"Ƙ\": \"K'\",\n \"׀\": \"l\",\n \"|\": \"l\",\n \"∣\": \"l\",\n \"⏽\": \"l\",\n \"│\": \"l\",\n \"١\": \"l\",\n \"۱\": \"l\",\n \"𐌠\": \"l\",\n \"𞣇\": \"l\",\n \"𝟏\": \"l\",\n \"𝟙\": \"l\",\n \"𝟣\": \"l\",\n \"𝟭\": \"l\",\n \"𝟷\": \"l\",\n \"🯱\": \"l\",\n \"I\": \"l\",\n \"I\": \"l\",\n \"Ⅰ\": \"l\",\n \"ℐ\": \"l\",\n \"ℑ\": \"l\",\n \"𝐈\": \"l\",\n \"𝐼\": \"l\",\n \"𝑰\": \"l\",\n \"𝓘\": \"l\",\n \"𝕀\": \"l\",\n \"𝕴\": \"l\",\n \"𝖨\": \"l\",\n \"𝗜\": \"l\",\n \"𝘐\": \"l\",\n \"𝙄\": \"l\",\n \"𝙸\": \"l\",\n \"Ɩ\": \"l\",\n \"l\": \"l\",\n \"ⅼ\": \"l\",\n \"ℓ\": \"l\",\n \"𝐥\": \"l\",\n \"𝑙\": \"l\",\n \"𝒍\": \"l\",\n \"𝓁\": \"l\",\n \"𝓵\": \"l\",\n \"𝔩\": \"l\",\n \"𝕝\": \"l\",\n \"𝖑\": \"l\",\n \"𝗅\": \"l\",\n \"𝗹\": \"l\",\n \"𝘭\": \"l\",\n \"𝙡\": \"l\",\n \"𝚕\": \"l\",\n \"ǀ\": \"l\",\n \"Ι\": \"l\",\n \"𝚰\": \"l\",\n \"𝛪\": \"l\",\n \"𝜤\": \"l\",\n \"𝝞\": \"l\",\n \"𝞘\": \"l\",\n \"Ⲓ\": \"l\",\n \"І\": \"l\",\n \"Ӏ\": \"l\",\n \"ו\": \"l\",\n \"ן\": \"l\",\n \"ا\": \"l\",\n \"𞸀\": \"l\",\n \"𞺀\": \"l\",\n \"ﺎ\": \"l\",\n \"ﺍ\": \"l\",\n \"ߊ\": \"l\",\n \"ⵏ\": \"l\",\n \"ᛁ\": \"l\",\n \"ꓲ\": \"l\",\n \"𖼨\": \"l\",\n \"𐊊\": \"l\",\n \"𐌉\": \"l\",\n \"𝈪\": \"L\",\n \"Ⅼ\": \"L\",\n \"ℒ\": \"L\",\n \"𝐋\": \"L\",\n \"𝐿\": \"L\",\n \"𝑳\": \"L\",\n \"𝓛\": \"L\",\n \"𝔏\": \"L\",\n \"𝕃\": \"L\",\n \"𝕷\": \"L\",\n \"𝖫\": \"L\",\n \"𝗟\": \"L\",\n \"𝘓\": \"L\",\n \"𝙇\": \"L\",\n \"𝙻\": \"L\",\n \"Ⳑ\": \"L\",\n \"Ꮮ\": \"L\",\n \"ᒪ\": \"L\",\n \"ꓡ\": \"L\",\n \"𖼖\": \"L\",\n \"𑢣\": \"L\",\n \"𑢲\": \"L\",\n \"𐐛\": \"L\",\n \"𐔦\": \"L\",\n \"ﴼ\": \"l̋\",\n \"ﴽ\": \"l̋\",\n \"ł\": \"l̸\",\n \"Ł\": \"L̸\",\n \"ɭ\": \"l̨\",\n \"Ɨ\": \"l̵\",\n \"ƚ\": \"l̵\",\n \"ɫ\": \"l̴\",\n \"إ\": \"lٕ\",\n \"ﺈ\": \"lٕ\",\n \"ﺇ\": \"lٕ\",\n \"ٳ\": \"lٕ\",\n \"ŀ\": \"l·\",\n \"Ŀ\": \"l·\",\n \"ᒷ\": \"l·\",\n \"🄂\": \"l,\",\n \"⒈\": \"l.\",\n \"ױ\": \"l'\",\n \"⒓\": \"l2.\",\n \"㏫\": \"l2日\",\n \"㋋\": \"l2月\",\n \"㍤\": \"l2点\",\n \"⒔\": \"l3.\",\n \"㏬\": \"l3日\",\n \"㍥\": \"l3点\",\n \"⒕\": \"l4.\",\n \"㏭\": \"l4日\",\n \"㍦\": \"l4点\",\n \"⒖\": \"l5.\",\n \"㏮\": \"l5日\",\n \"㍧\": \"l5点\",\n \"⒗\": \"l6.\",\n \"㏯\": \"l6日\",\n \"㍨\": \"l6点\",\n \"⒘\": \"l7.\",\n \"㏰\": \"l7日\",\n \"㍩\": \"l7点\",\n \"⒙\": \"l8.\",\n \"㏱\": \"l8日\",\n \"㍪\": \"l8点\",\n \"⒚\": \"l9.\",\n \"㏲\": \"l9日\",\n \"㍫\": \"l9点\",\n \"lj\": \"lj\",\n \"IJ\": \"lJ\",\n \"Lj\": \"Lj\",\n \"LJ\": \"LJ\",\n \"‖\": \"ll\",\n \"∥\": \"ll\",\n \"Ⅱ\": \"ll\",\n \"ǁ\": \"ll\",\n \"װ\": \"ll\",\n \"𐆙\": \"l̵l̵\",\n \"⒒\": \"ll.\",\n \"Ⅲ\": \"lll\",\n \"𐆘\": \"l̵l̵S̵\",\n \"㏪\": \"ll日\",\n \"㋊\": \"ll月\",\n \"㍣\": \"ll点\",\n \"Ю\": \"lO\",\n \"⒑\": \"lO.\",\n \"㏩\": \"lO日\",\n \"㋉\": \"lO月\",\n \"㍢\": \"lO点\",\n \"ʪ\": \"ls\",\n \"₶\": \"lt\",\n \"Ⅳ\": \"lV\",\n \"Ⅸ\": \"lX\",\n \"ɮ\": \"lȝ\",\n \"ʫ\": \"lz\",\n \"أ\": \"lٴ\",\n \"ﺄ\": \"lٴ\",\n \"ﺃ\": \"lٴ\",\n \"ٲ\": \"lٴ\",\n \"ٵ\": \"lٴ\",\n \"ﷳ\": \"lكبر\",\n \"ﷲ\": \"lللّٰo\",\n \"㏠\": \"l日\",\n \"㋀\": \"l月\",\n \"㍙\": \"l点\",\n \"ⳑ\": \"ʟ\",\n \"ꮮ\": \"ʟ\",\n \"𐑃\": \"ʟ\",\n \"M\": \"M\",\n \"Ⅿ\": \"M\",\n \"ℳ\": \"M\",\n \"𝐌\": \"M\",\n \"𝑀\": \"M\",\n \"𝑴\": \"M\",\n \"𝓜\": \"M\",\n \"𝔐\": \"M\",\n \"𝕄\": \"M\",\n \"𝕸\": \"M\",\n \"𝖬\": \"M\",\n \"𝗠\": \"M\",\n \"𝘔\": \"M\",\n \"𝙈\": \"M\",\n \"𝙼\": \"M\",\n \"Μ\": \"M\",\n \"𝚳\": \"M\",\n \"𝛭\": \"M\",\n \"𝜧\": \"M\",\n \"𝝡\": \"M\",\n \"𝞛\": \"M\",\n \"Ϻ\": \"M\",\n \"Ⲙ\": \"M\",\n \"М\": \"M\",\n \"Ꮇ\": \"M\",\n \"ᗰ\": \"M\",\n \"ᛖ\": \"M\",\n \"ꓟ\": \"M\",\n \"𐊰\": \"M\",\n \"𐌑\": \"M\",\n \"Ӎ\": \"M̦\",\n \"🝫\": \"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\",\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̴\",\n \"nj\": \"nj\",\n \"Nj\": \"Nj\",\n \"NJ\": \"NJ\",\n \"№\": \"No\",\n \"ͷ\": \"ᴎ\",\n \"и\": \"ᴎ\",\n \"𐑍\": \"ᴎ\",\n \"ņ\": \"ɲ\",\n \"ం\": \"o\",\n \"ಂ\": \"o\",\n \"ം\": \"o\",\n \"ං\": \"o\",\n \"०\": \"o\",\n \"੦\": \"o\",\n \"૦\": \"o\",\n \"௦\": \"o\",\n \"౦\": \"o\",\n \"೦\": \"o\",\n \"൦\": \"o\",\n \"๐\": \"o\",\n \"໐\": \"o\",\n \"၀\": \"o\",\n \"٥\": \"o\",\n \"۵\": \"o\",\n \"o\": \"o\",\n \"ℴ\": \"o\",\n \"𝐨\": \"o\",\n \"𝑜\": \"o\",\n \"𝒐\": \"o\",\n \"𝓸\": \"o\",\n \"𝔬\": \"o\",\n \"𝕠\": \"o\",\n \"𝖔\": \"o\",\n \"𝗈\": \"o\",\n \"𝗼\": \"o\",\n \"𝘰\": \"o\",\n \"𝙤\": \"o\",\n \"𝚘\": \"o\",\n \"ᴏ\": \"o\",\n \"ᴑ\": \"o\",\n \"ꬽ\": \"o\",\n \"ο\": \"o\",\n \"𝛐\": \"o\",\n \"𝜊\": \"o\",\n \"𝝄\": \"o\",\n \"𝝾\": \"o\",\n \"𝞸\": \"o\",\n \"σ\": \"o\",\n \"𝛔\": \"o\",\n \"𝜎\": \"o\",\n \"𝝈\": \"o\",\n \"𝞂\": \"o\",\n \"𝞼\": \"o\",\n \"ⲟ\": \"o\",\n \"о\": \"o\",\n \"ჿ\": \"o\",\n \"օ\": \"o\",\n \"ס\": \"o\",\n \"ه\": \"o\",\n \"𞸤\": \"o\",\n \"𞹤\": \"o\",\n \"𞺄\": \"o\",\n \"ﻫ\": \"o\",\n \"ﻬ\": \"o\",\n \"ﻪ\": \"o\",\n \"ﻩ\": \"o\",\n \"ھ\": \"o\",\n \"ﮬ\": \"o\",\n \"ﮭ\": \"o\",\n \"ﮫ\": \"o\",\n \"ﮪ\": \"o\",\n \"ہ\": \"o\",\n \"ﮨ\": \"o\",\n \"ﮩ\": \"o\",\n \"ﮧ\": \"o\",\n \"ﮦ\": \"o\",\n \"ە\": \"o\",\n \"ഠ\": \"o\",\n \"ဝ\": \"o\",\n \"𐓪\": \"o\",\n \"𑣈\": \"o\",\n \"𑣗\": \"o\",\n \"𐐬\": \"o\",\n \"߀\": \"O\",\n \"০\": \"O\",\n \"୦\": \"O\",\n \"〇\": \"O\",\n \"𑓐\": \"O\",\n \"𑣠\": \"O\",\n \"𝟎\": \"O\",\n \"𝟘\": \"O\",\n \"𝟢\": \"O\",\n \"𝟬\": \"O\",\n \"𝟶\": \"O\",\n \"🯰\": \"O\",\n \"O\": \"O\",\n \"𝐎\": \"O\",\n \"𝑂\": \"O\",\n \"𝑶\": \"O\",\n \"𝒪\": \"O\",\n \"𝓞\": \"O\",\n \"𝔒\": \"O\",\n \"𝕆\": \"O\",\n \"𝕺\": \"O\",\n \"𝖮\": \"O\",\n \"𝗢\": \"O\",\n \"𝘖\": \"O\",\n \"𝙊\": \"O\",\n \"𝙾\": \"O\",\n \"Ο\": \"O\",\n \"𝚶\": \"O\",\n \"𝛰\": \"O\",\n \"𝜪\": \"O\",\n \"𝝤\": \"O\",\n \"𝞞\": \"O\",\n \"Ⲟ\": \"O\",\n \"О\": \"O\",\n \"Օ\": \"O\",\n \"ⵔ\": \"O\",\n \"ዐ\": \"O\",\n \"ଠ\": \"O\",\n \"𐓂\": \"O\",\n \"ꓳ\": \"O\",\n \"𑢵\": \"O\",\n \"𐊒\": \"O\",\n \"𐊫\": \"O\",\n \"𐐄\": \"O\",\n \"𐔖\": \"O\",\n \"⁰\": \"º\",\n \"ᵒ\": \"º\",\n \"ǒ\": \"ŏ\",\n \"Ǒ\": \"Ŏ\",\n \"ۿ\": \"ô\",\n \"Ő\": \"Ö\",\n \"ø\": \"o̸\",\n \"ꬾ\": \"o̸\",\n \"Ø\": \"O̸\",\n \"ⵁ\": \"O̸\",\n \"Ǿ\": \"Ó̸\",\n \"ɵ\": \"o̵\",\n \"ꝋ\": \"o̵\",\n \"ө\": \"o̵\",\n \"ѳ\": \"o̵\",\n \"ꮎ\": \"o̵\",\n \"ꮻ\": \"o̵\",\n \"⊖\": \"O̵\",\n \"⊝\": \"O̵\",\n \"⍬\": \"O̵\",\n \"𝈚\": \"O̵\",\n \"🜔\": \"O̵\",\n \"Ɵ\": \"O̵\",\n \"Ꝋ\": \"O̵\",\n \"θ\": \"O̵\",\n \"ϑ\": \"O̵\",\n \"𝛉\": \"O̵\",\n \"𝛝\": \"O̵\",\n \"𝜃\": \"O̵\",\n \"𝜗\": \"O̵\",\n \"𝜽\": \"O̵\",\n \"𝝑\": \"O̵\",\n \"𝝷\": \"O̵\",\n \"𝞋\": \"O̵\",\n \"𝞱\": \"O̵\",\n \"𝟅\": \"O̵\",\n \"Θ\": \"O̵\",\n \"ϴ\": \"O̵\",\n \"𝚯\": \"O̵\",\n \"𝚹\": \"O̵\",\n \"𝛩\": \"O̵\",\n \"𝛳\": \"O̵\",\n \"𝜣\": \"O̵\",\n \"𝜭\": \"O̵\",\n \"𝝝\": \"O̵\",\n \"𝝧\": \"O̵\",\n \"𝞗\": \"O̵\",\n \"𝞡\": \"O̵\",\n \"Ө\": \"O̵\",\n \"Ѳ\": \"O̵\",\n \"ⴱ\": \"O̵\",\n \"Ꮎ\": \"O̵\",\n \"Ꮻ\": \"O̵\",\n \"ꭴ\": \"ơ\",\n \"ﳙ\": \"oٰ\",\n \"🄁\": \"O,\",\n \"🄀\": \"O.\",\n \"ơ\": \"o'\",\n \"Ơ\": \"O'\",\n \"Ꭴ\": \"O'\",\n \"%\": \"º/₀\",\n \"٪\": \"º/₀\",\n \"⁒\": \"º/₀\",\n \"‰\": \"º/₀₀\",\n \"؉\": \"º/₀₀\",\n \"‱\": \"º/₀₀₀\",\n \"؊\": \"º/₀₀₀\",\n \"œ\": \"oe\",\n \"Œ\": \"OE\",\n \"ɶ\": \"oᴇ\",\n \"∞\": \"oo\",\n \"ꝏ\": \"oo\",\n \"ꚙ\": \"oo\",\n \"Ꝏ\": \"OO\",\n \"Ꚙ\": \"OO\",\n \"ﳗ\": \"oج\",\n \"ﱑ\": \"oج\",\n \"ﳘ\": \"oم\",\n \"ﱒ\": \"oم\",\n \"ﶓ\": \"oمج\",\n \"ﶔ\": \"oمم\",\n \"ﱓ\": \"oى\",\n \"ﱔ\": \"oى\",\n \"ൟ\": \"oരo\",\n \"တ\": \"oာ\",\n \"㍘\": \"O点\",\n \"ↄ\": \"ɔ\",\n \"ᴐ\": \"ɔ\",\n \"ͻ\": \"ɔ\",\n \"𐑋\": \"ɔ\",\n \"Ↄ\": \"Ɔ\",\n \"Ͻ\": \"Ɔ\",\n \"ꓛ\": \"Ɔ\",\n \"𐐣\": \"Ɔ\",\n \"ꬿ\": \"ɔ̸\",\n \"ꭢ\": \"ɔe\",\n \"𐐿\": \"ɷ\",\n \"⍴\": \"p\",\n \"p\": \"p\",\n \"𝐩\": \"p\",\n \"𝑝\": \"p\",\n \"𝒑\": \"p\",\n \"𝓅\": \"p\",\n \"𝓹\": \"p\",\n \"𝔭\": \"p\",\n \"𝕡\": \"p\",\n \"𝖕\": \"p\",\n \"𝗉\": \"p\",\n \"𝗽\": \"p\",\n \"𝘱\": \"p\",\n \"𝙥\": \"p\",\n \"𝚙\": \"p\",\n \"ρ\": \"p\",\n \"ϱ\": \"p\",\n \"𝛒\": \"p\",\n \"𝛠\": \"p\",\n \"𝜌\": \"p\",\n \"𝜚\": \"p\",\n \"𝝆\": \"p\",\n \"𝝔\": \"p\",\n \"𝞀\": \"p\",\n \"𝞎\": \"p\",\n \"𝞺\": \"p\",\n \"𝟈\": \"p\",\n \"ⲣ\": \"p\",\n \"р\": \"p\",\n \"P\": \"P\",\n \"ℙ\": \"P\",\n \"𝐏\": \"P\",\n \"𝑃\": \"P\",\n \"𝑷\": \"P\",\n \"𝒫\": \"P\",\n \"𝓟\": \"P\",\n \"𝔓\": \"P\",\n \"𝕻\": \"P\",\n \"𝖯\": \"P\",\n \"𝗣\": \"P\",\n \"𝘗\": \"P\",\n \"𝙋\": \"P\",\n \"𝙿\": \"P\",\n \"Ρ\": \"P\",\n \"𝚸\": \"P\",\n \"𝛲\": \"P\",\n \"𝜬\": \"P\",\n \"𝝦\": \"P\",\n \"𝞠\": \"P\",\n \"Ⲣ\": \"P\",\n \"Р\": \"P\",\n \"Ꮲ\": \"P\",\n \"ᑭ\": \"P\",\n \"ꓑ\": \"P\",\n \"𐊕\": \"P\",\n \"ƥ\": \"p̔\",\n \"ᵽ\": \"p̵\",\n \"ᑷ\": \"p·\",\n \"ᒆ\": \"P'\",\n \"ᴩ\": \"ᴘ\",\n \"ꮲ\": \"ᴘ\",\n \"φ\": \"ɸ\",\n \"ϕ\": \"ɸ\",\n \"𝛗\": \"ɸ\",\n \"𝛟\": \"ɸ\",\n \"𝜑\": \"ɸ\",\n \"𝜙\": \"ɸ\",\n \"𝝋\": \"ɸ\",\n \"𝝓\": \"ɸ\",\n \"𝞅\": \"ɸ\",\n \"𝞍\": \"ɸ\",\n \"𝞿\": \"ɸ\",\n \"𝟇\": \"ɸ\",\n \"ⲫ\": \"ɸ\",\n \"ф\": \"ɸ\",\n \"𝐪\": \"q\",\n \"𝑞\": \"q\",\n \"𝒒\": \"q\",\n \"𝓆\": \"q\",\n \"𝓺\": \"q\",\n \"𝔮\": \"q\",\n \"𝕢\": \"q\",\n \"𝖖\": \"q\",\n \"𝗊\": \"q\",\n \"𝗾\": \"q\",\n \"𝘲\": \"q\",\n \"𝙦\": \"q\",\n \"𝚚\": \"q\",\n \"ԛ\": \"q\",\n \"գ\": \"q\",\n \"զ\": \"q\",\n \"ℚ\": \"Q\",\n \"𝐐\": \"Q\",\n \"𝑄\": \"Q\",\n \"𝑸\": \"Q\",\n \"𝒬\": \"Q\",\n \"𝓠\": \"Q\",\n \"𝔔\": \"Q\",\n \"𝕼\": \"Q\",\n \"𝖰\": \"Q\",\n \"𝗤\": \"Q\",\n \"𝘘\": \"Q\",\n \"𝙌\": \"Q\",\n \"𝚀\": \"Q\",\n \"ⵕ\": \"Q\",\n \"ʠ\": \"q̔\",\n \"🜀\": \"QE\",\n \"ᶐ\": \"ɋ\",\n \"ᴋ\": \"ĸ\",\n \"κ\": \"ĸ\",\n \"ϰ\": \"ĸ\",\n \"𝛋\": \"ĸ\",\n \"𝛞\": \"ĸ\",\n \"𝜅\": \"ĸ\",\n \"𝜘\": \"ĸ\",\n \"𝜿\": \"ĸ\",\n \"𝝒\": \"ĸ\",\n \"𝝹\": \"ĸ\",\n \"𝞌\": \"ĸ\",\n \"𝞳\": \"ĸ\",\n \"𝟆\": \"ĸ\",\n \"ⲕ\": \"ĸ\",\n \"к\": \"ĸ\",\n \"ꮶ\": \"ĸ\",\n \"қ\": \"ĸ̩\",\n \"ҟ\": \"ĸ̵\",\n \"𝐫\": \"r\",\n \"𝑟\": \"r\",\n \"𝒓\": \"r\",\n \"𝓇\": \"r\",\n \"𝓻\": \"r\",\n \"𝔯\": \"r\",\n \"𝕣\": \"r\",\n \"𝖗\": \"r\",\n \"𝗋\": \"r\",\n \"𝗿\": \"r\",\n \"𝘳\": \"r\",\n \"𝙧\": \"r\",\n \"𝚛\": \"r\",\n \"ꭇ\": \"r\",\n \"ꭈ\": \"r\",\n \"ᴦ\": \"r\",\n \"ⲅ\": \"r\",\n \"г\": \"r\",\n \"ꮁ\": \"r\",\n \"𝈖\": \"R\",\n \"ℛ\": \"R\",\n \"ℜ\": \"R\",\n \"ℝ\": \"R\",\n \"𝐑\": \"R\",\n \"𝑅\": \"R\",\n \"𝑹\": \"R\",\n \"𝓡\": \"R\",\n \"𝕽\": \"R\",\n \"𝖱\": \"R\",\n \"𝗥\": \"R\",\n \"𝘙\": \"R\",\n \"𝙍\": \"R\",\n \"𝚁\": \"R\",\n \"Ʀ\": \"R\",\n \"Ꭱ\": \"R\",\n \"Ꮢ\": \"R\",\n \"𐒴\": \"R\",\n \"ᖇ\": \"R\",\n \"ꓣ\": \"R\",\n \"𖼵\": \"R\",\n \"ɽ\": \"r̨\",\n \"ɼ\": \"r̩\",\n \"ɍ\": \"r̵\",\n \"ғ\": \"r̵\",\n \"ᵲ\": \"r̴\",\n \"ґ\": \"r'\",\n \"𑣣\": \"rn\",\n \"m\": \"rn\",\n \"ⅿ\": \"rn\",\n \"𝐦\": \"rn\",\n \"𝑚\": \"rn\",\n \"𝒎\": \"rn\",\n \"𝓂\": \"rn\",\n \"𝓶\": \"rn\",\n \"𝔪\": \"rn\",\n \"𝕞\": \"rn\",\n \"𝖒\": \"rn\",\n \"𝗆\": \"rn\",\n \"𝗺\": \"rn\",\n \"𝘮\": \"rn\",\n \"𝙢\": \"rn\",\n \"𝚖\": \"rn\",\n \"𑜀\": \"rn\",\n \"₥\": \"rn̸\",\n \"ɱ\": \"rn̦\",\n \"ᵯ\": \"rn̴\",\n \"₨\": \"Rs\",\n \"ꭱ\": \"ʀ\",\n \"ꮢ\": \"ʀ\",\n \"я\": \"ᴙ\",\n \"ᵳ\": \"ɾ̴\",\n \"℩\": \"ɿ\",\n \"s\": \"s\",\n \"𝐬\": \"s\",\n \"𝑠\": \"s\",\n \"𝒔\": \"s\",\n \"𝓈\": \"s\",\n \"𝓼\": \"s\",\n \"𝔰\": \"s\",\n \"𝕤\": \"s\",\n \"𝖘\": \"s\",\n \"𝗌\": \"s\",\n \"𝘀\": \"s\",\n \"𝘴\": \"s\",\n \"𝙨\": \"s\",\n \"𝚜\": \"s\",\n \"ꜱ\": \"s\",\n \"ƽ\": \"s\",\n \"ѕ\": \"s\",\n \"ꮪ\": \"s\",\n \"𑣁\": \"s\",\n \"𐑈\": \"s\",\n \"S\": \"S\",\n \"𝐒\": \"S\",\n \"𝑆\": \"S\",\n \"𝑺\": \"S\",\n \"𝒮\": \"S\",\n \"𝓢\": \"S\",\n \"𝔖\": \"S\",\n \"𝕊\": \"S\",\n \"𝕾\": \"S\",\n \"𝖲\": \"S\",\n \"𝗦\": \"S\",\n \"𝘚\": \"S\",\n \"𝙎\": \"S\",\n \"𝚂\": \"S\",\n \"Ѕ\": \"S\",\n \"Տ\": \"S\",\n \"Ꮥ\": \"S\",\n \"Ꮪ\": \"S\",\n \"ꓢ\": \"S\",\n \"𖼺\": \"S\",\n \"𐊖\": \"S\",\n \"𐐠\": \"S\",\n \"ʂ\": \"s̨\",\n \"ᵴ\": \"s̴\",\n \"ꞵ\": \"ß\",\n \"β\": \"ß\",\n \"ϐ\": \"ß\",\n \"𝛃\": \"ß\",\n \"𝛽\": \"ß\",\n \"𝜷\": \"ß\",\n \"𝝱\": \"ß\",\n \"𝞫\": \"ß\",\n \"Ᏸ\": \"ß\",\n \"🝜\": \"sss\",\n \"st\": \"st\",\n \"∫\": \"ʃ\",\n \"ꭍ\": \"ʃ\",\n \"∑\": \"Ʃ\",\n \"⅀\": \"Ʃ\",\n \"Σ\": \"Ʃ\",\n \"𝚺\": \"Ʃ\",\n \"𝛴\": \"Ʃ\",\n \"𝜮\": \"Ʃ\",\n \"𝝨\": \"Ʃ\",\n \"𝞢\": \"Ʃ\",\n \"ⵉ\": \"Ʃ\",\n \"∬\": \"ʃʃ\",\n \"∭\": \"ʃʃʃ\",\n \"⨌\": \"ʃʃʃʃ\",\n \"𝐭\": \"t\",\n \"𝑡\": \"t\",\n \"𝒕\": \"t\",\n \"𝓉\": \"t\",\n \"𝓽\": \"t\",\n \"𝔱\": \"t\",\n \"𝕥\": \"t\",\n \"𝖙\": \"t\",\n \"𝗍\": \"t\",\n \"𝘁\": \"t\",\n \"𝘵\": \"t\",\n \"𝙩\": \"t\",\n \"𝚝\": \"t\",\n \"⊤\": \"T\",\n \"⟙\": \"T\",\n \"🝨\": \"T\",\n \"T\": \"T\",\n \"𝐓\": \"T\",\n \"𝑇\": \"T\",\n \"𝑻\": \"T\",\n \"𝒯\": \"T\",\n \"𝓣\": \"T\",\n \"𝔗\": \"T\",\n \"𝕋\": \"T\",\n \"𝕿\": \"T\",\n \"𝖳\": \"T\",\n \"𝗧\": \"T\",\n \"𝘛\": \"T\",\n \"𝙏\": \"T\",\n \"𝚃\": \"T\",\n \"Τ\": \"T\",\n \"𝚻\": \"T\",\n \"𝛵\": \"T\",\n \"𝜯\": \"T\",\n \"𝝩\": \"T\",\n \"𝞣\": \"T\",\n \"Ⲧ\": \"T\",\n \"Т\": \"T\",\n \"Ꭲ\": \"T\",\n \"ꓔ\": \"T\",\n \"𖼊\": \"T\",\n \"𑢼\": \"T\",\n \"𐊗\": \"T\",\n \"𐊱\": \"T\",\n \"𐌕\": \"T\",\n \"ƭ\": \"t̔\",\n \"⍡\": \"T̈\",\n \"Ⱦ\": \"T̸\",\n \"Ț\": \"Ţ\",\n \"Ʈ\": \"T̨\",\n \"Ҭ\": \"T̩\",\n \"₮\": \"T⃫\",\n \"ŧ\": \"t̵\",\n \"Ŧ\": \"T̵\",\n \"ᵵ\": \"t̴\",\n \"Ⴀ\": \"Ꞇ\",\n \"Ꜩ\": \"T3\",\n \"ʨ\": \"tɕ\",\n \"℡\": \"TEL\",\n \"ꝷ\": \"tf\",\n \"ʦ\": \"ts\",\n \"ʧ\": \"tʃ\",\n \"ꜩ\": \"tȝ\",\n \"τ\": \"ᴛ\",\n \"𝛕\": \"ᴛ\",\n \"𝜏\": \"ᴛ\",\n \"𝝉\": \"ᴛ\",\n \"𝞃\": \"ᴛ\",\n \"𝞽\": \"ᴛ\",\n \"т\": \"ᴛ\",\n \"ꭲ\": \"ᴛ\",\n \"ҭ\": \"ᴛ̩\",\n \"ţ\": \"ƫ\",\n \"ț\": \"ƫ\",\n \"Ꮏ\": \"ƫ\",\n \"𝐮\": \"u\",\n \"𝑢\": \"u\",\n \"𝒖\": \"u\",\n \"𝓊\": \"u\",\n \"𝓾\": \"u\",\n \"𝔲\": \"u\",\n \"𝕦\": \"u\",\n \"𝖚\": \"u\",\n \"𝗎\": \"u\",\n \"𝘂\": \"u\",\n \"𝘶\": \"u\",\n \"𝙪\": \"u\",\n \"𝚞\": \"u\",\n \"ꞟ\": \"u\",\n \"ᴜ\": \"u\",\n \"ꭎ\": \"u\",\n \"ꭒ\": \"u\",\n \"ʋ\": \"u\",\n \"υ\": \"u\",\n \"𝛖\": \"u\",\n \"𝜐\": \"u\",\n \"𝝊\": \"u\",\n \"𝞄\": \"u\",\n \"𝞾\": \"u\",\n \"ս\": \"u\",\n \"𐓶\": \"u\",\n \"𑣘\": \"u\",\n \"∪\": \"U\",\n \"⋃\": \"U\",\n \"𝐔\": \"U\",\n \"𝑈\": \"U\",\n \"𝑼\": \"U\",\n \"𝒰\": \"U\",\n \"𝓤\": \"U\",\n \"𝔘\": \"U\",\n \"𝕌\": \"U\",\n \"𝖀\": \"U\",\n \"𝖴\": \"U\",\n \"𝗨\": \"U\",\n \"𝘜\": \"U\",\n \"𝙐\": \"U\",\n \"𝚄\": \"U\",\n \"Ս\": \"U\",\n \"ሀ\": \"U\",\n \"𐓎\": \"U\",\n \"ᑌ\": \"U\",\n \"ꓴ\": \"U\",\n \"𖽂\": \"U\",\n \"𑢸\": \"U\",\n \"ǔ\": \"ŭ\",\n \"Ǔ\": \"Ŭ\",\n \"ᵾ\": \"u̵\",\n \"ꮜ\": \"u̵\",\n \"Ʉ\": \"U̵\",\n \"Ꮜ\": \"U̵\",\n \"ᑘ\": \"U·\",\n \"ᑧ\": \"U'\",\n \"ᵫ\": \"ue\",\n \"ꭣ\": \"uo\",\n \"ṃ\": \"ꭑ\",\n \"պ\": \"ɰ\",\n \"ሣ\": \"ɰ\",\n \"℧\": \"Ʊ\",\n \"ᘮ\": \"Ʊ\",\n \"ᘴ\": \"Ʊ\",\n \"ᵿ\": \"ʊ̵\",\n \"∨\": \"v\",\n \"⋁\": \"v\",\n \"v\": \"v\",\n \"ⅴ\": \"v\",\n \"𝐯\": \"v\",\n \"𝑣\": \"v\",\n \"𝒗\": \"v\",\n \"𝓋\": \"v\",\n \"𝓿\": \"v\",\n \"𝔳\": \"v\",\n \"𝕧\": \"v\",\n \"𝖛\": \"v\",\n \"𝗏\": \"v\",\n \"𝘃\": \"v\",\n \"𝘷\": \"v\",\n \"𝙫\": \"v\",\n \"𝚟\": \"v\",\n \"ᴠ\": \"v\",\n \"ν\": \"v\",\n \"𝛎\": \"v\",\n \"𝜈\": \"v\",\n \"𝝂\": \"v\",\n \"𝝼\": \"v\",\n \"𝞶\": \"v\",\n \"ѵ\": \"v\",\n \"ט\": \"v\",\n \"𑜆\": \"v\",\n \"ꮩ\": \"v\",\n \"𑣀\": \"v\",\n \"𝈍\": \"V\",\n \"٧\": \"V\",\n \"۷\": \"V\",\n \"Ⅴ\": \"V\",\n \"𝐕\": \"V\",\n \"𝑉\": \"V\",\n \"𝑽\": \"V\",\n \"𝒱\": \"V\",\n \"𝓥\": \"V\",\n \"𝔙\": \"V\",\n \"𝕍\": \"V\",\n \"𝖁\": \"V\",\n \"𝖵\": \"V\",\n \"𝗩\": \"V\",\n \"𝘝\": \"V\",\n \"𝙑\": \"V\",\n \"𝚅\": \"V\",\n \"Ѵ\": \"V\",\n \"ⴸ\": \"V\",\n \"Ꮩ\": \"V\",\n \"ᐯ\": \"V\",\n \"ꛟ\": \"V\",\n \"ꓦ\": \"V\",\n \"𖼈\": \"V\",\n \"𑢠\": \"V\",\n \"𐔝\": \"V\",\n \"𐆗\": \"V̵\",\n \"ᐻ\": \"V·\",\n \"🝬\": \"VB\",\n \"ⅵ\": \"vi\",\n \"ⅶ\": \"vii\",\n \"ⅷ\": \"viii\",\n \"Ⅵ\": \"Vl\",\n \"Ⅶ\": \"Vll\",\n \"Ⅷ\": \"Vlll\",\n \"🜈\": \"Vᷤ\",\n \"ᴧ\": \"ʌ\",\n \"𐓘\": \"ʌ\",\n \"٨\": \"Ʌ\",\n \"۸\": \"Ʌ\",\n \"Λ\": \"Ʌ\",\n \"𝚲\": \"Ʌ\",\n \"𝛬\": \"Ʌ\",\n \"𝜦\": \"Ʌ\",\n \"𝝠\": \"Ʌ\",\n \"𝞚\": \"Ʌ\",\n \"Л\": \"Ʌ\",\n \"ⴷ\": \"Ʌ\",\n \"𐒰\": \"Ʌ\",\n \"ᐱ\": \"Ʌ\",\n \"ꛎ\": \"Ʌ\",\n \"ꓥ\": \"Ʌ\",\n \"𖼽\": \"Ʌ\",\n \"𐊍\": \"Ʌ\",\n \"Ӆ\": \"Ʌ̦\",\n \"ᐽ\": \"Ʌ·\",\n \"ɯ\": \"w\",\n \"𝐰\": \"w\",\n \"𝑤\": \"w\",\n \"𝒘\": \"w\",\n \"𝓌\": \"w\",\n \"𝔀\": \"w\",\n \"𝔴\": \"w\",\n \"𝕨\": \"w\",\n \"𝖜\": \"w\",\n \"𝗐\": \"w\",\n \"𝘄\": \"w\",\n \"𝘸\": \"w\",\n \"𝙬\": \"w\",\n \"𝚠\": \"w\",\n \"ᴡ\": \"w\",\n \"ѡ\": \"w\",\n \"ԝ\": \"w\",\n \"ա\": \"w\",\n \"𑜊\": \"w\",\n \"𑜎\": \"w\",\n \"𑜏\": \"w\",\n \"ꮃ\": \"w\",\n \"𑣯\": \"W\",\n \"𑣦\": \"W\",\n \"𝐖\": \"W\",\n \"𝑊\": \"W\",\n \"𝑾\": \"W\",\n \"𝒲\": \"W\",\n \"𝓦\": \"W\",\n \"𝔚\": \"W\",\n \"𝕎\": \"W\",\n \"𝖂\": \"W\",\n \"𝖶\": \"W\",\n \"𝗪\": \"W\",\n \"𝘞\": \"W\",\n \"𝙒\": \"W\",\n \"𝚆\": \"W\",\n \"Ԝ\": \"W\",\n \"Ꮃ\": \"W\",\n \"Ꮤ\": \"W\",\n \"ꓪ\": \"W\",\n \"ѽ\": \"w҆҇\",\n \"𑓅\": \"ẇ\",\n \"₩\": \"W̵\",\n \"ꝡ\": \"w̦\",\n \"ᴍ\": \"ʍ\",\n \"м\": \"ʍ\",\n \"ꮇ\": \"ʍ\",\n \"ӎ\": \"ʍ̦\",\n \"᙮\": \"x\",\n \"×\": \"x\",\n \"⤫\": \"x\",\n \"⤬\": \"x\",\n \"⨯\": \"x\",\n \"x\": \"x\",\n \"ⅹ\": \"x\",\n \"𝐱\": \"x\",\n \"𝑥\": \"x\",\n \"𝒙\": \"x\",\n \"𝓍\": \"x\",\n \"𝔁\": \"x\",\n \"𝔵\": \"x\",\n \"𝕩\": \"x\",\n \"𝖝\": \"x\",\n \"𝗑\": \"x\",\n \"𝘅\": \"x\",\n \"𝘹\": \"x\",\n \"𝙭\": \"x\",\n \"𝚡\": \"x\",\n \"х\": \"x\",\n \"ᕁ\": \"x\",\n \"ᕽ\": \"x\",\n \"ⷯ\": \"ͯ\",\n \"᙭\": \"X\",\n \"╳\": \"X\",\n \"𐌢\": \"X\",\n \"𑣬\": \"X\",\n \"X\": \"X\",\n \"Ⅹ\": \"X\",\n \"𝐗\": \"X\",\n \"𝑋\": \"X\",\n \"𝑿\": \"X\",\n \"𝒳\": \"X\",\n \"𝓧\": \"X\",\n \"𝔛\": \"X\",\n \"𝕏\": \"X\",\n \"𝖃\": \"X\",\n \"𝖷\": \"X\",\n \"𝗫\": \"X\",\n \"𝘟\": \"X\",\n \"𝙓\": \"X\",\n \"𝚇\": \"X\",\n \"Ꭓ\": \"X\",\n \"Χ\": \"X\",\n \"𝚾\": \"X\",\n \"𝛸\": \"X\",\n \"𝜲\": \"X\",\n \"𝝬\": \"X\",\n \"𝞦\": \"X\",\n \"Ⲭ\": \"X\",\n \"Х\": \"X\",\n \"ⵝ\": \"X\",\n \"ᚷ\": \"X\",\n \"ꓫ\": \"X\",\n \"𐊐\": \"X\",\n \"𐊴\": \"X\",\n \"𐌗\": \"X\",\n \"𐔧\": \"X\",\n \"⨰\": \"ẋ\",\n \"Ҳ\": \"X̩\",\n \"𐆖\": \"X̵\",\n \"ⅺ\": \"xi\",\n \"ⅻ\": \"xii\",\n \"Ⅺ\": \"Xl\",\n \"Ⅻ\": \"Xll\",\n \"ɣ\": \"y\",\n \"ᶌ\": \"y\",\n \"y\": \"y\",\n \"𝐲\": \"y\",\n \"𝑦\": \"y\",\n \"𝒚\": \"y\",\n \"𝓎\": \"y\",\n \"𝔂\": \"y\",\n \"𝔶\": \"y\",\n \"𝕪\": \"y\",\n \"𝖞\": \"y\",\n \"𝗒\": \"y\",\n \"𝘆\": \"y\",\n \"𝘺\": \"y\",\n \"𝙮\": \"y\",\n \"𝚢\": \"y\",\n \"ʏ\": \"y\",\n \"ỿ\": \"y\",\n \"ꭚ\": \"y\",\n \"γ\": \"y\",\n \"ℽ\": \"y\",\n \"𝛄\": \"y\",\n \"𝛾\": \"y\",\n \"𝜸\": \"y\",\n \"𝝲\": \"y\",\n \"𝞬\": \"y\",\n \"у\": \"y\",\n \"ү\": \"y\",\n \"ყ\": \"y\",\n \"𑣜\": \"y\",\n \"Y\": \"Y\",\n \"𝐘\": \"Y\",\n \"𝑌\": \"Y\",\n \"𝒀\": \"Y\",\n \"𝒴\": \"Y\",\n \"𝓨\": \"Y\",\n \"𝔜\": \"Y\",\n \"𝕐\": \"Y\",\n \"𝖄\": \"Y\",\n \"𝖸\": \"Y\",\n \"𝗬\": \"Y\",\n \"𝘠\": \"Y\",\n \"𝙔\": \"Y\",\n \"𝚈\": \"Y\",\n \"Υ\": \"Y\",\n \"ϒ\": \"Y\",\n \"𝚼\": \"Y\",\n \"𝛶\": \"Y\",\n \"𝜰\": \"Y\",\n \"𝝪\": \"Y\",\n \"𝞤\": \"Y\",\n \"Ⲩ\": \"Y\",\n \"У\": \"Y\",\n \"Ү\": \"Y\",\n \"Ꭹ\": \"Y\",\n \"Ꮍ\": \"Y\",\n \"ꓬ\": \"Y\",\n \"𖽃\": \"Y\",\n \"𑢤\": \"Y\",\n \"𐊲\": \"Y\",\n \"ƴ\": \"y̔\",\n \"ɏ\": \"y̵\",\n \"ұ\": \"y̵\",\n \"¥\": \"Y̵\",\n \"Ɏ\": \"Y̵\",\n \"Ұ\": \"Y̵\",\n \"ʒ\": \"ȝ\",\n \"ꝫ\": \"ȝ\",\n \"ⳍ\": \"ȝ\",\n \"ӡ\": \"ȝ\",\n \"ჳ\": \"ȝ\",\n \"𝐳\": \"z\",\n \"𝑧\": \"z\",\n \"𝒛\": \"z\",\n \"𝓏\": \"z\",\n \"𝔃\": \"z\",\n \"𝔷\": \"z\",\n \"𝕫\": \"z\",\n \"𝖟\": \"z\",\n \"𝗓\": \"z\",\n \"𝘇\": \"z\",\n \"𝘻\": \"z\",\n \"𝙯\": \"z\",\n \"𝚣\": \"z\",\n \"ᴢ\": \"z\",\n \"ꮓ\": \"z\",\n \"𑣄\": \"z\",\n \"𐋵\": \"Z\",\n \"𑣥\": \"Z\",\n \"Z\": \"Z\",\n \"ℤ\": \"Z\",\n \"ℨ\": \"Z\",\n \"𝐙\": \"Z\",\n \"𝑍\": \"Z\",\n \"𝒁\": \"Z\",\n \"𝒵\": \"Z\",\n \"𝓩\": \"Z\",\n \"𝖅\": \"Z\",\n \"𝖹\": \"Z\",\n \"𝗭\": \"Z\",\n \"𝘡\": \"Z\",\n \"𝙕\": \"Z\",\n \"𝚉\": \"Z\",\n \"Ζ\": \"Z\",\n \"𝚭\": \"Z\",\n \"𝛧\": \"Z\",\n \"𝜡\": \"Z\",\n \"𝝛\": \"Z\",\n \"𝞕\": \"Z\",\n \"Ꮓ\": \"Z\",\n \"ꓜ\": \"Z\",\n \"𑢩\": \"Z\",\n \"ʐ\": \"z̨\",\n \"ƶ\": \"z̵\",\n \"Ƶ\": \"Z̵\",\n \"ȥ\": \"z̦\",\n \"Ȥ\": \"Z̦\",\n \"ᵶ\": \"z̴\",\n \"ƿ\": \"þ\",\n \"ϸ\": \"þ\",\n \"Ϸ\": \"Þ\",\n \"𐓄\": \"Þ\",\n \"⁹\": \"ꝰ\",\n \"ᴤ\": \"ƨ\",\n \"ϩ\": \"ƨ\",\n \"ꙅ\": \"ƨ\",\n \"ь\": \"ƅ\",\n \"ꮟ\": \"ƅ\",\n \"ы\": \"ƅi\",\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 \"𝝀\": \"λ\",\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 \"𝝇\": \"ς\",\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 \"𝛺\": \"Ω\",\n \"𝜴\": \"Ω\",\n \"𝝮\": \"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"վն\",\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 \"ﲠ\": \"بo\",\n \"ﳢ\": \"بo\",\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 \"ﺕ\": \"ت\",\n \"ﲥ\": \"تo\",\n \"ﳤ\": \"تo\",\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 \"ﲧ\": \"جح\",\n \"ﰕ\": \"جح\",\n \"ﶦ\": \"جحى\",\n \"ﶾ\": \"جحى\",\n \"ﷻ\": \"جل جلlلo\",\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 \"ﴀ\": \"حى\",\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 \"ڑ\": \"رؕ\",\n \"ﮍ\": \"رؕ\",\n \"ﮌ\": \"رؕ\",\n \"ژ\": \"رۛ\",\n \"ﮋ\": \"رۛ\",\n \"ﮊ\": \"رۛ\",\n \"ڒ\": \"ر̆\",\n \"ࢹ\": \"ر̆̇\",\n \"ۯ\": \"ر̂\",\n \"ݬ\": \"رٔ\",\n \"ﱜ\": \"رٰ\",\n \"ﷶ\": \"رسول\",\n \"﷼\": \"رىlل\",\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 \"ﴱ\": \"سo\",\n \"ﳨ\": \"سo\",\n \"ﴲ\": \"سۛo\",\n \"ﳪ\": \"سۛo\",\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 \"ﵬ\": \"سۛمم\",\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 \"ﷺ\": \"صلى lللo علىo وسلم\",\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 \"ﴺ\": \"طم\",\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 \"ﷷ\": \"علىo\",\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 \"ﳁ\": \"فم\",\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 \"𞹪\": \"ك\",\n \"ﻛ\": \"ك\",\n \"ﻜ\": \"ك\",\n \"ﻚ\": \"ك\",\n \"ﻙ\": \"ك\",\n \"ک\": \"ك\",\n \"ﮐ\": \"ك\",\n \"ﮑ\": \"ك\",\n \"ﮏ\": \"ك\",\n \"ﮎ\": \"ك\",\n \"ڪ\": \"ك\",\n \"ڭ\": \"كۛ\",\n \"ﯕ\": \"كۛ\",\n \"ﯖ\": \"كۛ\",\n \"ﯔ\": \"كۛ\",\n \"ﯓ\": \"كۛ\",\n \"ݣ\": \"كۛ\",\n \"ﲀ\": \"كl\",\n \"ﰷ\": \"كl\",\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 \"ﻼ\": \"لl\",\n \"ﻻ\": \"لl\",\n \"ﻺ\": \"لlٕ\",\n \"ﻹ\": \"لlٕ\",\n \"ﻸ\": \"لlٴ\",\n \"ﻷ\": \"لlٴ\",\n \"ﳍ\": \"لo\",\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 \"ﲈ\": \"مl\",\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 \"ﳖ\": \"نo\",\n \"ﳯ\": \"نo\",\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 \"ﯜ\": \"وٰ\",\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 \"ﮣ\": \"ىؕ\",\n \"ﮡ\": \"ىؕ\",\n \"ﮠ\": \"ىؕ\",\n \"پ\": \"ىۛ\",\n \"ﭘ\": \"ىۛ\",\n \"ﭙ\": \"ىۛ\",\n \"ﭗ\": \"ىۛ\",\n \"ﭖ\":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": \"ىٴو\",\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 \"ﮰ\": \"ۓ\",\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 \"𑒝\": \"ল\",\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 \"ை\": \"ன\",\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 \"൮\": \"വ്ര\",\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 \"ༀ\": \"ཨོཾ\",\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 \"⫗\": \"ᑐᑕ\",\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 \"ᔎ\": \"ᔋb\",\n \"ᔍ\": \"ᔋᑕ\",\n \"ᔏ\": \"ᔋᒐ\",\n \"ᔘ\": \"ᔐ·\",\n \"ᔚ\": \"ᔑ·\",\n \"ᔜ\": \"ᔒ·\",\n \"ᔞ\": \"ᔓ·\",\n \"ᔠ\": \"ᔔ·\",\n \"ᔢ\": \"ᔕ·\",\n \"ᔤ\": \"ᔖ·\",\n \"ᔲ\": \"ᔨ·\",\n \"ᔴ\": \"ᔩ·\",\n \"ᔶ\": \"ᔪ·\",\n \"ᔸ\": \"ᔫ·\",\n \"ᔺ\": \"ᔭ·\",\n \"ᔼ\": \"ᔮ·\",\n \"ᘢ\": \"ᕃ\",\n \"ᣠ\": \"ᕃ·\",\n \"ᘣ\": \"ᕆ\",\n \"ᘤ\": \"ᕊ\",\n \"ᕏ\": \"ᕌ·\",\n \"ᖃ\": \"ᕐb\",\n \"ᖄ\": \"ᕐḃ\",\n \"ᖁ\": \"ᕐd\",\n \"ᕿ\": \"ᕐP\",\n \"ᙯ\": \"ᕐᑫ\",\n \"ᕾ\": \"ᕐᑬ\",\n \"ᖀ\": \"ᕐᑮ\",\n \"ᖂ\": \"ᕐᑰ\",\n \"ᖅ\": \"ᕐᒃ\",\n \"ᕜ\": \"ᕚ·\",\n \"ᣣ\": \"ᕞ·\",\n \"ᣤ\": \"ᕦ·\",\n \"ᕩ\": \"ᕧ·\",\n \"ᣥ\": \"ᕫ·\",\n \"ᣨ\": \"ᖆ·\",\n \"ᖑ\": \"ᖕJ\",\n \"ᙰ\": \"ᖕᒉ\",\n \"ᖎ\": \"ᖕᒊ\",\n \"ᖏ\": \"ᖕᒋ\",\n \"ᖐ\": \"ᖕᒌ\",\n \"ᖒ\": \"ᖕᒎ\",\n \"ᖓ\": \"ᖕᒐ\",\n \"ᖔ\": \"ᖕᒑ\",\n \"ᙳ\": \"ᖖJ\",\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 \"𐓐\": \"ᛦ\",\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 \"ퟍ\": \"ᄃᄃ\",\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 \"ᇔ\": \"ᄅᄇᄒ\",\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 \"ㅂ\": \"ᄇ\",\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 \"ᄯ\": \"ᄉᄃ\",\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 \"ꥷ\": \"ᄋᄒ\",\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 \"ퟶ\": \"ᅌᄒ\",\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 \"ᆄ\": \"ᅭᅣ\",\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 \"꒨\": \"ꄲ\",\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 \"〹\": \"卄\",\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 \"⺅\": \"亻\",\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 \"⼍\": \"冖\",\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 \"匆\": \"匆\",\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 \"咢\": \"咢\",\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 \"壮\": \"壮\",\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 \"尢\": \"尢\",\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 \"㡼\": \"㡼\",\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 \"惇\": \"惇\",\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 \"捨\": \"捨\",\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 \"暑\": \"暑\",\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 \"梎\": \"梎\",\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 \"⺢\": \"氺\",\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 \"濾\": \"濾\",\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 \"𤜵\": \"𤜵\",\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 \"瘐\": \"瘐\",\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 \"碌\": \"碌\",\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 \"竮\": \"竮\",\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 \"缾\": \"缾\",\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 \"𦞵\": \"𦞵\",\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 \"著\": \"著\",\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 \"蠁\": \"蠁\",\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 \"謁\": \"謁\",\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 \"輻\": \"輻\",\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 \"鐕\": \"鐕\",\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 \"⾰\": \"革\",\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 \"⾼\": \"高\",\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 \"鼅\": \"鼅\",\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}", - "'use strict';\n\n\nvar data = require('./data.json');\n\nfunction escapeRegexp(str) {\n return str.replace(/([.?*+^$[\\]\\\\(){}|-])/g, '\\\\$1');\n}\n\nvar REPLACE_RE = RegExp(Object.keys(data).map(escapeRegexp).join('|'), 'g');\n\nfunction replace_fn(match) {\n return data[match];\n}\n\nfunction unhomoglyph(str) {\n return str.replace(REPLACE_RE, replace_fn);\n}\n\nmodule.exports = unhomoglyph;\n", - "\n/**\n * Module exports.\n */\n\nmodule.exports = deprecate;\n\n/**\n * Mark that a method should not be used.\n * Returns a modified function which warns once by default.\n *\n * If `localStorage.noDeprecation = true` is set, then it is a no-op.\n *\n * If `localStorage.throwDeprecation = true` is set, then deprecated functions\n * will throw an Error when invoked.\n *\n * If `localStorage.traceDeprecation = true` is set, then deprecated functions\n * will invoke `console.trace()` instead of `console.error()`.\n *\n * @param {Function} fn - the function to deprecate\n * @param {String} msg - the string to print to the console when `fn` is invoked\n * @returns {Function} a new \"deprecated\" version of `fn`\n * @api public\n */\n\nfunction deprecate (fn, msg) {\n if (config('noDeprecation')) {\n return fn;\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (config('throwDeprecation')) {\n throw new Error(msg);\n } else if (config('traceDeprecation')) {\n console.trace(msg);\n } else {\n console.warn(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n}\n\n/**\n * Checks `localStorage` for boolean values for the given `name`.\n *\n * @param {String} name\n * @returns {Boolean}\n * @api private\n */\n\nfunction config (name) {\n // accessing global.localStorage can trigger a DOMException in sandboxed iframes\n try {\n if (!global.localStorage) return false;\n } catch (_) {\n return false;\n }\n var val = global.localStorage[name];\n if (null == val) return false;\n return String(val).toLowerCase() === 'true';\n}\n", - "module.exports = function isBuffer(arg) {\n return arg && typeof arg === 'object'\n && typeof arg.copy === 'function'\n && typeof arg.fill === 'function'\n && typeof arg.readUInt8 === 'function';\n}", - "// Currently in sync with Node.js lib/internal/util/types.js\n// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9\n\n'use strict';\n\nvar isArgumentsObject = require('is-arguments');\nvar isGeneratorFunction = require('is-generator-function');\nvar whichTypedArray = require('which-typed-array');\nvar isTypedArray = require('is-typed-array');\n\nfunction uncurryThis(f) {\n return f.call.bind(f);\n}\n\nvar BigIntSupported = typeof BigInt !== 'undefined';\nvar SymbolSupported = typeof Symbol !== 'undefined';\n\nvar ObjectToString = uncurryThis(Object.prototype.toString);\n\nvar numberValue = uncurryThis(Number.prototype.valueOf);\nvar stringValue = uncurryThis(String.prototype.valueOf);\nvar booleanValue = uncurryThis(Boolean.prototype.valueOf);\n\nif (BigIntSupported) {\n var bigIntValue = uncurryThis(BigInt.prototype.valueOf);\n}\n\nif (SymbolSupported) {\n var symbolValue = uncurryThis(Symbol.prototype.valueOf);\n}\n\nfunction checkBoxedPrimitive(value, prototypeValueOf) {\n if (typeof value !== 'object') {\n return false;\n }\n try {\n prototypeValueOf(value);\n return true;\n } catch(e) {\n return false;\n }\n}\n\nexports.isArgumentsObject = isArgumentsObject;\nexports.isGeneratorFunction = isGeneratorFunction;\nexports.isTypedArray = isTypedArray;\n\n// Taken from here and modified for better browser support\n// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js\nfunction isPromise(input) {\n\treturn (\n\t\t(\n\t\t\ttypeof Promise !== 'undefined' &&\n\t\t\tinput instanceof Promise\n\t\t) ||\n\t\t(\n\t\t\tinput !== null &&\n\t\t\ttypeof input === 'object' &&\n\t\t\ttypeof input.then === 'function' &&\n\t\t\ttypeof input.catch === 'function'\n\t\t)\n\t);\n}\nexports.isPromise = isPromise;\n\nfunction isArrayBufferView(value) {\n if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {\n return ArrayBuffer.isView(value);\n }\n\n return (\n isTypedArray(value) ||\n isDataView(value)\n );\n}\nexports.isArrayBufferView = isArrayBufferView;\n\n\nfunction isUint8Array(value) {\n return whichTypedArray(value) === 'Uint8Array';\n}\nexports.isUint8Array = isUint8Array;\n\nfunction isUint8ClampedArray(value) {\n return whichTypedArray(value) === 'Uint8ClampedArray';\n}\nexports.isUint8ClampedArray = isUint8ClampedArray;\n\nfunction isUint16Array(value) {\n return whichTypedArray(value) === 'Uint16Array';\n}\nexports.isUint16Array = isUint16Array;\n\nfunction isUint32Array(value) {\n return whichTypedArray(value) === 'Uint32Array';\n}\nexports.isUint32Array = isUint32Array;\n\nfunction isInt8Array(value) {\n return whichTypedArray(value) === 'Int8Array';\n}\nexports.isInt8Array = isInt8Array;\n\nfunction isInt16Array(value) {\n return whichTypedArray(value) === 'Int16Array';\n}\nexports.isInt16Array = isInt16Array;\n\nfunction isInt32Array(value) {\n return whichTypedArray(value) === 'Int32Array';\n}\nexports.isInt32Array = isInt32Array;\n\nfunction isFloat32Array(value) {\n return whichTypedArray(value) === 'Float32Array';\n}\nexports.isFloat32Array = isFloat32Array;\n\nfunction isFloat64Array(value) {\n return whichTypedArray(value) === 'Float64Array';\n}\nexports.isFloat64Array = isFloat64Array;\n\nfunction isBigInt64Array(value) {\n return whichTypedArray(value) === 'BigInt64Array';\n}\nexports.isBigInt64Array = isBigInt64Array;\n\nfunction isBigUint64Array(value) {\n return whichTypedArray(value) === 'BigUint64Array';\n}\nexports.isBigUint64Array = isBigUint64Array;\n\nfunction isMapToString(value) {\n return ObjectToString(value) === '[object Map]';\n}\nisMapToString.working = (\n typeof Map !== 'undefined' &&\n isMapToString(new Map())\n);\n\nfunction isMap(value) {\n if (typeof Map === 'undefined') {\n return false;\n }\n\n return isMapToString.working\n ? isMapToString(value)\n : value instanceof Map;\n}\nexports.isMap = isMap;\n\nfunction isSetToString(value) {\n return ObjectToString(value) === '[object Set]';\n}\nisSetToString.working = (\n typeof Set !== 'undefined' &&\n isSetToString(new Set())\n);\nfunction isSet(value) {\n if (typeof Set === 'undefined') {\n return false;\n }\n\n return isSetToString.working\n ? isSetToString(value)\n : value instanceof Set;\n}\nexports.isSet = isSet;\n\nfunction isWeakMapToString(value) {\n return ObjectToString(value) === '[object WeakMap]';\n}\nisWeakMapToString.working = (\n typeof WeakMap !== 'undefined' &&\n isWeakMapToString(new WeakMap())\n);\nfunction isWeakMap(value) {\n if (typeof WeakMap === 'undefined') {\n return false;\n }\n\n return isWeakMapToString.working\n ? isWeakMapToString(value)\n : value instanceof WeakMap;\n}\nexports.isWeakMap = isWeakMap;\n\nfunction isWeakSetToString(value) {\n return ObjectToString(value) === '[object WeakSet]';\n}\nisWeakSetToString.working = (\n typeof WeakSet !== 'undefined' &&\n isWeakSetToString(new WeakSet())\n);\nfunction isWeakSet(value) {\n return isWeakSetToString(value);\n}\nexports.isWeakSet = isWeakSet;\n\nfunction isArrayBufferToString(value) {\n return ObjectToString(value) === '[object ArrayBuffer]';\n}\nisArrayBufferToString.working = (\n typeof ArrayBuffer !== 'undefined' &&\n isArrayBufferToString(new ArrayBuffer())\n);\nfunction isArrayBuffer(value) {\n if (typeof ArrayBuffer === 'undefined') {\n return false;\n }\n\n return isArrayBufferToString.working\n ? isArrayBufferToString(value)\n : value instanceof ArrayBuffer;\n}\nexports.isArrayBuffer = isArrayBuffer;\n\nfunction isDataViewToString(value) {\n return ObjectToString(value) === '[object DataView]';\n}\nisDataViewToString.working = (\n typeof ArrayBuffer !== 'undefined' &&\n typeof DataView !== 'undefined' &&\n isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1))\n);\nfunction isDataView(value) {\n if (typeof DataView === 'undefined') {\n return false;\n }\n\n return isDataViewToString.working\n ? isDataViewToString(value)\n : value instanceof DataView;\n}\nexports.isDataView = isDataView;\n\n// Store a copy of SharedArrayBuffer in case it's deleted elsewhere\nvar SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined;\nfunction isSharedArrayBufferToString(value) {\n return ObjectToString(value) === '[object SharedArrayBuffer]';\n}\nfunction isSharedArrayBuffer(value) {\n if (typeof SharedArrayBufferCopy === 'undefined') {\n return false;\n }\n\n if (typeof isSharedArrayBufferToString.working === 'undefined') {\n isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy());\n }\n\n return isSharedArrayBufferToString.working\n ? isSharedArrayBufferToString(value)\n : value instanceof SharedArrayBufferCopy;\n}\nexports.isSharedArrayBuffer = isSharedArrayBuffer;\n\nfunction isAsyncFunction(value) {\n return ObjectToString(value) === '[object AsyncFunction]';\n}\nexports.isAsyncFunction = isAsyncFunction;\n\nfunction isMapIterator(value) {\n return ObjectToString(value) === '[object Map Iterator]';\n}\nexports.isMapIterator = isMapIterator;\n\nfunction isSetIterator(value) {\n return ObjectToString(value) === '[object Set Iterator]';\n}\nexports.isSetIterator = isSetIterator;\n\nfunction isGeneratorObject(value) {\n return ObjectToString(value) === '[object Generator]';\n}\nexports.isGeneratorObject = isGeneratorObject;\n\nfunction isWebAssemblyCompiledModule(value) {\n return ObjectToString(value) === '[object WebAssembly.Module]';\n}\nexports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule;\n\nfunction isNumberObject(value) {\n return checkBoxedPrimitive(value, numberValue);\n}\nexports.isNumberObject = isNumberObject;\n\nfunction isStringObject(value) {\n return checkBoxedPrimitive(value, stringValue);\n}\nexports.isStringObject = isStringObject;\n\nfunction isBooleanObject(value) {\n return checkBoxedPrimitive(value, booleanValue);\n}\nexports.isBooleanObject = isBooleanObject;\n\nfunction isBigIntObject(value) {\n return BigIntSupported && checkBoxedPrimitive(value, bigIntValue);\n}\nexports.isBigIntObject = isBigIntObject;\n\nfunction isSymbolObject(value) {\n return SymbolSupported && checkBoxedPrimitive(value, symbolValue);\n}\nexports.isSymbolObject = isSymbolObject;\n\nfunction isBoxedPrimitive(value) {\n return (\n isNumberObject(value) ||\n isStringObject(value) ||\n isBooleanObject(value) ||\n isBigIntObject(value) ||\n isSymbolObject(value)\n );\n}\nexports.isBoxedPrimitive = isBoxedPrimitive;\n\nfunction isAnyArrayBuffer(value) {\n return typeof Uint8Array !== 'undefined' && (\n isArrayBuffer(value) ||\n isSharedArrayBuffer(value)\n );\n}\nexports.isAnyArrayBuffer = isAnyArrayBuffer;\n\n['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) {\n Object.defineProperty(exports, method, {\n enumerable: false,\n value: function() {\n throw new Error(method + ' is not supported in userland');\n }\n });\n});\n", - "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||\n function getOwnPropertyDescriptors(obj) {\n var keys = Object.keys(obj);\n var descriptors = {};\n for (var i = 0; i < keys.length; i++) {\n descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);\n }\n return descriptors;\n };\n\nvar formatRegExp = /%[sdj%]/g;\nexports.format = function(f) {\n if (!isString(f)) {\n var objects = [];\n for (var i = 0; i < arguments.length; i++) {\n objects.push(inspect(arguments[i]));\n }\n return objects.join(' ');\n }\n\n var i = 1;\n var args = arguments;\n var len = args.length;\n var str = String(f).replace(formatRegExp, function(x) {\n if (x === '%%') return '%';\n if (i >= len) return x;\n switch (x) {\n case '%s': return String(args[i++]);\n case '%d': return Number(args[i++]);\n case '%j':\n try {\n return JSON.stringify(args[i++]);\n } catch (_) {\n return '[Circular]';\n }\n default:\n return x;\n }\n });\n for (var x = args[i]; i < len; x = args[++i]) {\n if (isNull(x) || !isObject(x)) {\n str += ' ' + x;\n } else {\n str += ' ' + inspect(x);\n }\n }\n return str;\n};\n\n\n// Mark that a method should not be used.\n// Returns a modified function which warns once by default.\n// If --no-deprecation is set, then it is a no-op.\nexports.deprecate = function(fn, msg) {\n if (typeof process !== 'undefined' && process.noDeprecation === true) {\n return fn;\n }\n\n // Allow for deprecating things in the process of starting up.\n if (typeof process === 'undefined') {\n return function() {\n return exports.deprecate(fn, msg).apply(this, arguments);\n };\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (process.throwDeprecation) {\n throw new Error(msg);\n } else if (process.traceDeprecation) {\n console.trace(msg);\n } else {\n console.error(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n};\n\n\nvar debugs = {};\nvar debugEnvRegex = /^$/;\n\nif (process.env.NODE_DEBUG) {\n var debugEnv = process.env.NODE_DEBUG;\n debugEnv = debugEnv.replace(/[|\\\\{}()[\\]^$+?.]/g, '\\\\$&')\n .replace(/\\*/g, '.*')\n .replace(/,/g, '$|^')\n .toUpperCase();\n debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i');\n}\nexports.debuglog = function(set) {\n set = set.toUpperCase();\n if (!debugs[set]) {\n if (debugEnvRegex.test(set)) {\n var pid = process.pid;\n debugs[set] = function() {\n var msg = exports.format.apply(exports, arguments);\n console.error('%s %d: %s', set, pid, msg);\n };\n } else {\n debugs[set] = function() {};\n }\n }\n return debugs[set];\n};\n\n\n/**\n * Echos the value of a value. Trys to print the value out\n * in the best way possible given the different types.\n *\n * @param {Object} obj The object to print out.\n * @param {Object} opts Optional options object that alters the output.\n */\n/* legacy: obj, showHidden, depth, colors*/\nfunction inspect(obj, opts) {\n // default options\n var ctx = {\n seen: [],\n stylize: stylizeNoColor\n };\n // legacy...\n if (arguments.length >= 3) ctx.depth = arguments[2];\n if (arguments.length >= 4) ctx.colors = arguments[3];\n if (isBoolean(opts)) {\n // legacy...\n ctx.showHidden = opts;\n } else if (opts) {\n // got an \"options\" object\n exports._extend(ctx, opts);\n }\n // set default options\n if (isUndefined(ctx.showHidden)) ctx.showHidden = false;\n if (isUndefined(ctx.depth)) ctx.depth = 2;\n if (isUndefined(ctx.colors)) ctx.colors = false;\n if (isUndefined(ctx.customInspect)) ctx.customInspect = true;\n if (ctx.colors) ctx.stylize = stylizeWithColor;\n return formatValue(ctx, obj, ctx.depth);\n}\nexports.inspect = inspect;\n\n\n// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics\ninspect.colors = {\n 'bold' : [1, 22],\n 'italic' : [3, 23],\n 'underline' : [4, 24],\n 'inverse' : [7, 27],\n 'white' : [37, 39],\n 'grey' : [90, 39],\n 'black' : [30, 39],\n 'blue' : [34, 39],\n 'cyan' : [36, 39],\n 'green' : [32, 39],\n 'magenta' : [35, 39],\n 'red' : [31, 39],\n 'yellow' : [33, 39]\n};\n\n// Don't use 'blue' not visible on cmd.exe\ninspect.styles = {\n 'special': 'cyan',\n 'number': 'yellow',\n 'boolean': 'yellow',\n 'undefined': 'grey',\n 'null': 'bold',\n 'string': 'green',\n 'date': 'magenta',\n // \"name\": intentionally not styling\n 'regexp': 'red'\n};\n\n\nfunction stylizeWithColor(str, styleType) {\n var style = inspect.styles[styleType];\n\n if (style) {\n return '\\u001b[' + inspect.colors[style][0] + 'm' + str +\n '\\u001b[' + inspect.colors[style][1] + 'm';\n } else {\n return str;\n }\n}\n\n\nfunction stylizeNoColor(str, styleType) {\n return str;\n}\n\n\nfunction arrayToHash(array) {\n var hash = {};\n\n array.forEach(function(val, idx) {\n hash[val] = true;\n });\n\n return hash;\n}\n\n\nfunction formatValue(ctx, value, recurseTimes) {\n // Provide a hook for user-specified inspect functions.\n // Check that value is an object with an inspect function on it\n if (ctx.customInspect &&\n value &&\n isFunction(value.inspect) &&\n // Filter out the util module, it's inspect function is special\n value.inspect !== exports.inspect &&\n // Also filter out any prototype objects using the circular check.\n !(value.constructor && value.constructor.prototype === value)) {\n var ret = value.inspect(recurseTimes, ctx);\n if (!isString(ret)) {\n ret = formatValue(ctx, ret, recurseTimes);\n }\n return ret;\n }\n\n // Primitive types cannot have properties\n var primitive = formatPrimitive(ctx, value);\n if (primitive) {\n return primitive;\n }\n\n // Look up the keys of the object.\n var keys = Object.keys(value);\n var visibleKeys = arrayToHash(keys);\n\n if (ctx.showHidden) {\n keys = Object.getOwnPropertyNames(value);\n }\n\n // IE doesn't make error fields non-enumerable\n // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx\n if (isError(value)\n && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {\n return formatError(value);\n }\n\n // Some type of object without properties can be shortcutted.\n if (keys.length === 0) {\n if (isFunction(value)) {\n var name = value.name ? ': ' + value.name : '';\n return ctx.stylize('[Function' + name + ']', 'special');\n }\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n }\n if (isDate(value)) {\n return ctx.stylize(Date.prototype.toString.call(value), 'date');\n }\n if (isError(value)) {\n return formatError(value);\n }\n }\n\n var base = '', array = false, braces = ['{', '}'];\n\n // Make Array say that they are Array\n if (isArray(value)) {\n array = true;\n braces = ['[', ']'];\n }\n\n // Make functions say that they are functions\n if (isFunction(value)) {\n var n = value.name ? ': ' + value.name : '';\n base = ' [Function' + n + ']';\n }\n\n // Make RegExps say that they are RegExps\n if (isRegExp(value)) {\n base = ' ' + RegExp.prototype.toString.call(value);\n }\n\n // Make dates with properties first say the date\n if (isDate(value)) {\n base = ' ' + Date.prototype.toUTCString.call(value);\n }\n\n // Make error with message first say the error\n if (isError(value)) {\n base = ' ' + formatError(value);\n }\n\n if (keys.length === 0 && (!array || value.length == 0)) {\n return braces[0] + base + braces[1];\n }\n\n if (recurseTimes < 0) {\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n } else {\n return ctx.stylize('[Object]', 'special');\n }\n }\n\n ctx.seen.push(value);\n\n var output;\n if (array) {\n output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);\n } else {\n output = keys.map(function(key) {\n return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);\n });\n }\n\n ctx.seen.pop();\n\n return reduceToSingleString(output, base, braces);\n}\n\n\nfunction formatPrimitive(ctx, value) {\n if (isUndefined(value))\n return ctx.stylize('undefined', 'undefined');\n if (isString(value)) {\n var simple = '\\'' + JSON.stringify(value).replace(/^\"|\"$/g, '')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"') + '\\'';\n return ctx.stylize(simple, 'string');\n }\n if (isNumber(value))\n return ctx.stylize('' + value, 'number');\n if (isBoolean(value))\n return ctx.stylize('' + value, 'boolean');\n // For some reason typeof null is \"object\", so special case here.\n if (isNull(value))\n return ctx.stylize('null', 'null');\n}\n\n\nfunction formatError(value) {\n return '[' + Error.prototype.toString.call(value) + ']';\n}\n\n\nfunction formatArray(ctx, value, recurseTimes, visibleKeys, keys) {\n var output = [];\n for (var i = 0, l = value.length; i < l; ++i) {\n if (hasOwnProperty(value, String(i))) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n String(i), true));\n } else {\n output.push('');\n }\n }\n keys.forEach(function(key) {\n if (!key.match(/^\\d+$/)) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n key, true));\n }\n });\n return output;\n}\n\n\nfunction formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {\n var name, str, desc;\n desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };\n if (desc.get) {\n if (desc.set) {\n str = ctx.stylize('[Getter/Setter]', 'special');\n } else {\n str = ctx.stylize('[Getter]', 'special');\n }\n } else {\n if (desc.set) {\n str = ctx.stylize('[Setter]', 'special');\n }\n }\n if (!hasOwnProperty(visibleKeys, key)) {\n name = '[' + key + ']';\n }\n if (!str) {\n if (ctx.seen.indexOf(desc.value) < 0) {\n if (isNull(recurseTimes)) {\n str = formatValue(ctx, desc.value, null);\n } else {\n str = formatValue(ctx, desc.value, recurseTimes - 1);\n }\n if (str.indexOf('\\n') > -1) {\n if (array) {\n str = str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n').slice(2);\n } else {\n str = '\\n' + str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n');\n }\n }\n } else {\n str = ctx.stylize('[Circular]', 'special');\n }\n }\n if (isUndefined(name)) {\n if (array && key.match(/^\\d+$/)) {\n return str;\n }\n name = JSON.stringify('' + key);\n if (name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/)) {\n name = name.slice(1, -1);\n name = ctx.stylize(name, 'name');\n } else {\n name = name.replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"')\n .replace(/(^\"|\"$)/g, \"'\");\n name = ctx.stylize(name, 'string');\n }\n }\n\n return name + ': ' + str;\n}\n\n\nfunction reduceToSingleString(output, base, braces) {\n var numLinesEst = 0;\n var length = output.reduce(function(prev, cur) {\n numLinesEst++;\n if (cur.indexOf('\\n') >= 0) numLinesEst++;\n return prev + cur.replace(/\\u001b\\[\\d\\d?m/g, '').length + 1;\n }, 0);\n\n if (length > 60) {\n return braces[0] +\n (base === '' ? '' : base + '\\n ') +\n ' ' +\n output.join(',\\n ') +\n ' ' +\n braces[1];\n }\n\n return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];\n}\n\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\nexports.types = require('./support/types');\n\nfunction isArray(ar) {\n return Array.isArray(ar);\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return isObject(re) && objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\nexports.types.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return isObject(d) && objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\nexports.types.isDate = isDate;\n\nfunction isError(e) {\n return isObject(e) &&\n (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\nexports.types.isNativeError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = require('./support/isBuffer');\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n\n\nfunction pad(n) {\n return n < 10 ? '0' + n.toString(10) : n.toString(10);\n}\n\n\nvar months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',\n 'Oct', 'Nov', 'Dec'];\n\n// 26 Feb 16:19:34\nfunction timestamp() {\n var d = new Date();\n var time = [pad(d.getHours()),\n pad(d.getMinutes()),\n pad(d.getSeconds())].join(':');\n return [d.getDate(), months[d.getMonth()], time].join(' ');\n}\n\n\n// log is just a thin wrapper to console.log that prepends a timestamp\nexports.log = function() {\n console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));\n};\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * The Function.prototype.inherits from lang.js rewritten as a standalone\n * function (not on Function.prototype). NOTE: If this file is to be loaded\n * during bootstrapping this function needs to be rewritten using some native\n * functions as prototype setup using normal JavaScript does not work as\n * expected during bootstrapping (see mirror.js in r114903).\n *\n * @param {function} ctor Constructor function which needs to inherit the\n * prototype.\n * @param {function} superCtor Constructor function to inherit prototype from.\n */\nexports.inherits = require('inherits');\n\nexports._extend = function(origin, add) {\n // Don't do anything if add isn't an object\n if (!add || !isObject(add)) return origin;\n\n var keys = Object.keys(add);\n var i = keys.length;\n while (i--) {\n origin[keys[i]] = add[keys[i]];\n }\n return origin;\n};\n\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nvar kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;\n\nexports.promisify = function promisify(original) {\n if (typeof original !== 'function')\n throw new TypeError('The \"original\" argument must be of type Function');\n\n if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {\n var fn = original[kCustomPromisifiedSymbol];\n if (typeof fn !== 'function') {\n throw new TypeError('The \"util.promisify.custom\" argument must be of type Function');\n }\n Object.defineProperty(fn, kCustomPromisifiedSymbol, {\n value: fn, enumerable: false, writable: false, configurable: true\n });\n return fn;\n }\n\n function fn() {\n var promiseResolve, promiseReject;\n var promise = new Promise(function (resolve, reject) {\n promiseResolve = resolve;\n promiseReject = reject;\n });\n\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n args.push(function (err, value) {\n if (err) {\n promiseReject(err);\n } else {\n promiseResolve(value);\n }\n });\n\n try {\n original.apply(this, args);\n } catch (err) {\n promiseReject(err);\n }\n\n return promise;\n }\n\n Object.setPrototypeOf(fn, Object.getPrototypeOf(original));\n\n if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {\n value: fn, enumerable: false, writable: false, configurable: true\n });\n return Object.defineProperties(\n fn,\n getOwnPropertyDescriptors(original)\n );\n}\n\nexports.promisify.custom = kCustomPromisifiedSymbol\n\nfunction callbackifyOnRejected(reason, cb) {\n // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).\n // Because `null` is a special error value in callbacks which means \"no error\n // occurred\", we error-wrap so the callback consumer can distinguish between\n // \"the promise rejected with null\" or \"the promise fulfilled with undefined\".\n if (!reason) {\n var newReason = new Error('Promise was rejected with a falsy value');\n newReason.reason = reason;\n reason = newReason;\n }\n return cb(reason);\n}\n\nfunction callbackify(original) {\n if (typeof original !== 'function') {\n throw new TypeError('The \"original\" argument must be of type Function');\n }\n\n // We DO NOT return the promise as it gives the user a false sense that\n // the promise is actually somehow related to the callback's execution\n // and that the callback throwing will reject the promise.\n function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) },\n function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) });\n }\n\n Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));\n Object.defineProperties(callbackified,\n getOwnPropertyDescriptors(original));\n return callbackified;\n}\nexports.callbackify = callbackify;\n", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"NIL\", {\n enumerable: true,\n get: function () {\n return _nil.default;\n }\n});\nObject.defineProperty(exports, \"parse\", {\n enumerable: true,\n get: function () {\n return _parse.default;\n }\n});\nObject.defineProperty(exports, \"stringify\", {\n enumerable: true,\n get: function () {\n return _stringify.default;\n }\n});\nObject.defineProperty(exports, \"v1\", {\n enumerable: true,\n get: function () {\n return _v.default;\n }\n});\nObject.defineProperty(exports, \"v3\", {\n enumerable: true,\n get: function () {\n return _v2.default;\n }\n});\nObject.defineProperty(exports, \"v4\", {\n enumerable: true,\n get: function () {\n return _v3.default;\n }\n});\nObject.defineProperty(exports, \"v5\", {\n enumerable: true,\n get: function () {\n return _v4.default;\n }\n});\nObject.defineProperty(exports, \"validate\", {\n enumerable: true,\n get: function () {\n return _validate.default;\n }\n});\nObject.defineProperty(exports, \"version\", {\n enumerable: true,\n get: function () {\n return _version.default;\n }\n});\n\nvar _v = _interopRequireDefault(require(\"./v1.js\"));\n\nvar _v2 = _interopRequireDefault(require(\"./v3.js\"));\n\nvar _v3 = _interopRequireDefault(require(\"./v4.js\"));\n\nvar _v4 = _interopRequireDefault(require(\"./v5.js\"));\n\nvar _nil = _interopRequireDefault(require(\"./nil.js\"));\n\nvar _version = _interopRequireDefault(require(\"./version.js\"));\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\n\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\n/*\n * Browser-compatible JavaScript MD5\n *\n * Modification of JavaScript MD5\n * https://github.com/blueimp/JavaScript-MD5\n *\n * Copyright 2011, Sebastian Tschan\n * https://blueimp.net\n *\n * Licensed under the MIT license:\n * https://opensource.org/licenses/MIT\n *\n * Based on\n * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message\n * Digest Algorithm, as defined in RFC 1321.\n * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009\n * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet\n * Distributed under the BSD License\n * See http://pajhome.org.uk/crypt/md5 for more info.\n */\nfunction md5(bytes) {\n if (typeof bytes === 'string') {\n const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape\n\n bytes = new Uint8Array(msg.length);\n\n for (let i = 0; i < msg.length; ++i) {\n bytes[i] = msg.charCodeAt(i);\n }\n }\n\n return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));\n}\n/*\n * Convert an array of little-endian words to an array of bytes\n */\n\n\nfunction md5ToHexEncodedArray(input) {\n const output = [];\n const length32 = input.length * 32;\n const hexTab = '0123456789abcdef';\n\n for (let i = 0; i < length32; i += 8) {\n const x = input[i >> 5] >>> i % 32 & 0xff;\n const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);\n output.push(hex);\n }\n\n return output;\n}\n/**\n * Calculate output length with padding and bit length\n */\n\n\nfunction getOutputLength(inputLength8) {\n return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;\n}\n/*\n * Calculate the MD5 of an array of little-endian words, and a bit length.\n */\n\n\nfunction wordsToMd5(x, len) {\n /* append padding */\n x[len >> 5] |= 0x80 << len % 32;\n x[getOutputLength(len) - 1] = len;\n let a = 1732584193;\n let b = -271733879;\n let c = -1732584194;\n let d = 271733878;\n\n for (let i = 0; i < x.length; i += 16) {\n const olda = a;\n const oldb = b;\n const oldc = c;\n const oldd = d;\n a = md5ff(a, b, c, d, x[i], 7, -680876936);\n d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);\n c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);\n b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);\n a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);\n d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);\n c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);\n b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);\n a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);\n d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);\n c = md5ff(c, d, a, b, x[i + 10], 17, -42063);\n b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);\n a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);\n d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);\n c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);\n b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);\n a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);\n d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);\n c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);\n b = md5gg(b, c, d, a, x[i], 20, -373897302);\n a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);\n d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);\n c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);\n b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);\n a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);\n d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);\n c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);\n b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);\n a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);\n d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);\n c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);\n b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);\n a = md5hh(a, b, c, d, x[i + 5], 4, -378558);\n d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);\n c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);\n b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);\n a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);\n d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);\n c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);\n b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);\n a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);\n d = md5hh(d, a, b, c, x[i], 11, -358537222);\n c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);\n b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);\n a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);\n d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);\n c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);\n b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);\n a = md5ii(a, b, c, d, x[i], 6, -198630844);\n d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);\n c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);\n b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);\n a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);\n d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);\n c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);\n b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);\n a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);\n d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);\n c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);\n b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);\n a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);\n d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);\n c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);\n b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);\n a = safeAdd(a, olda);\n b = safeAdd(b, oldb);\n c = safeAdd(c, oldc);\n d = safeAdd(d, oldd);\n }\n\n return [a, b, c, d];\n}\n/*\n * Convert an array bytes to an array of little-endian words\n * Characters >255 have their high-byte silently ignored.\n */\n\n\nfunction bytesToWords(input) {\n if (input.length === 0) {\n return [];\n }\n\n const length8 = input.length * 8;\n const output = new Uint32Array(getOutputLength(length8));\n\n for (let i = 0; i < length8; i += 8) {\n output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;\n }\n\n return output;\n}\n/*\n * Add integers, wrapping at 2^32. This uses 16-bit operations internally\n * to work around bugs in some JS interpreters.\n */\n\n\nfunction safeAdd(x, y) {\n const lsw = (x & 0xffff) + (y & 0xffff);\n const msw = (x >> 16) + (y >> 16) + (lsw >> 16);\n return msw << 16 | lsw & 0xffff;\n}\n/*\n * Bitwise rotate a 32-bit number to the left.\n */\n\n\nfunction bitRotateLeft(num, cnt) {\n return num << cnt | num >>> 32 - cnt;\n}\n/*\n * These functions implement the four basic operations the algorithm uses.\n */\n\n\nfunction md5cmn(q, a, b, x, s, t) {\n return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);\n}\n\nfunction md5ff(a, b, c, d, x, s, t) {\n return md5cmn(b & c | ~b & d, a, b, x, s, t);\n}\n\nfunction md5gg(a, b, c, d, x, s, t) {\n return md5cmn(b & d | c & ~d, a, b, x, s, t);\n}\n\nfunction md5hh(a, b, c, d, x, s, t) {\n return md5cmn(b ^ c ^ d, a, b, x, s, t);\n}\n\nfunction md5ii(a, b, c, d, x, s, t) {\n return md5cmn(c ^ (b | ~d), a, b, x, s, t);\n}\n\nvar _default = md5;\nexports.default = _default;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nconst randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);\nvar _default = {\n randomUUID\n};\nexports.default = _default;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = '00000000-0000-0000-0000-000000000000';\nexports.default = _default;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction parse(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n let v;\n const arr = new Uint8Array(16); // Parse ########-....-....-....-............\n\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff; // Parse ........-####-....-....-............\n\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff; // Parse ........-....-####-....-............\n\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff; // Parse ........-....-....-####-............\n\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff; // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\n\nvar _default = parse;\nexports.default = _default;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;\nexports.default = _default;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = rng;\n// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nlet getRandomValues;\nconst rnds8 = new Uint8Array(16);\n\nfunction rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\n// Adapted from Chris Veness' SHA1 code at\n// http://www.movable-type.co.uk/scripts/sha1.html\nfunction f(s, x, y, z) {\n switch (s) {\n case 0:\n return x & y ^ ~x & z;\n\n case 1:\n return x ^ y ^ z;\n\n case 2:\n return x & y ^ x & z ^ y & z;\n\n case 3:\n return x ^ y ^ z;\n }\n}\n\nfunction ROTL(x, n) {\n return x << n | x >>> 32 - n;\n}\n\nfunction sha1(bytes) {\n const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];\n const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];\n\n if (typeof bytes === 'string') {\n const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape\n\n bytes = [];\n\n for (let i = 0; i < msg.length; ++i) {\n bytes.push(msg.charCodeAt(i));\n }\n } else if (!Array.isArray(bytes)) {\n // Convert Array-like to Array\n bytes = Array.prototype.slice.call(bytes);\n }\n\n bytes.push(0x80);\n const l = bytes.length / 4 + 2;\n const N = Math.ceil(l / 16);\n const M = new Array(N);\n\n for (let i = 0; i < N; ++i) {\n const arr = new Uint32Array(16);\n\n for (let j = 0; j < 16; ++j) {\n arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3];\n }\n\n M[i] = arr;\n }\n\n M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);\n M[N - 1][14] = Math.floor(M[N - 1][14]);\n M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;\n\n for (let i = 0; i < N; ++i) {\n const W = new Uint32Array(80);\n\n for (let t = 0; t < 16; ++t) {\n W[t] = M[i][t];\n }\n\n for (let t = 16; t < 80; ++t) {\n W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);\n }\n\n let a = H[0];\n let b = H[1];\n let c = H[2];\n let d = H[3];\n let e = H[4];\n\n for (let t = 0; t < 80; ++t) {\n const s = Math.floor(t / 20);\n const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0;\n e = d;\n d = c;\n c = ROTL(b, 30) >>> 0;\n b = a;\n a = T;\n }\n\n H[0] = H[0] + a >>> 0;\n H[1] = H[1] + b >>> 0;\n H[2] = H[2] + c >>> 0;\n H[3] = H[3] + d >>> 0;\n H[4] = H[4] + e >>> 0;\n }\n\n return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];\n}\n\nvar _default = sha1;\nexports.default = _default;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nexports.unsafeStringify = unsafeStringify;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\n\nfunction unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();\n}\n\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nvar _default = stringify;\nexports.default = _default;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\n\nvar _stringify = require(\"./stringify.js\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\nlet _nodeId;\n\nlet _clockseq; // Previous uuid creation time\n\n\nlet _lastMSecs = 0;\nlet _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details\n\nfunction v1(options, buf, offset) {\n let i = buf && offset || 0;\n const b = buf || new Array(16);\n options = options || {};\n let node = options.node || _nodeId;\n let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not\n // specified. We do this lazily to minimize issues related to insufficient\n // system entropy. See #189\n\n if (node == null || clockseq == null) {\n const seedBytes = options.random || (options.rng || _rng.default)();\n\n if (node == null) {\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];\n }\n\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n }\n } // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n\n\n let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n\n let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)\n\n const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression\n\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n\n\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n } // Per 4.2.1.2 Throw error if too many uuids are requested\n\n\n if (nsecs >= 10000) {\n throw new Error(\"uuid.v1(): Can't create more than 10M uuids/sec\");\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n\n msecs += 12219292800000; // `time_low`\n\n const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff; // `time_mid`\n\n const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff; // `time_high_and_version`\n\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n\n b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n\n b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`\n\n b[i++] = clockseq & 0xff; // `node`\n\n for (let n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n\n return buf || (0, _stringify.unsafeStringify)(b);\n}\n\nvar _default = v1;\nexports.default = _default;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\n\nvar _md = _interopRequireDefault(require(\"./md5.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconst v3 = (0, _v.default)('v3', 0x30, _md.default);\nvar _default = v3;\nexports.default = _default;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.URL = exports.DNS = void 0;\nexports.default = v35;\n\nvar _stringify = require(\"./stringify.js\");\n\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n const bytes = [];\n\n for (let i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n\n return bytes;\n}\n\nconst DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nexports.DNS = DNS;\nconst URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nexports.URL = URL;\n\nfunction v35(name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n var _namespace;\n\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n\n if (typeof namespace === 'string') {\n namespace = (0, _parse.default)(namespace);\n }\n\n if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n } // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n\n\n let bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n\n return buf;\n }\n\n return (0, _stringify.unsafeStringify)(bytes);\n } // Function#name is not settable on some platforms (#270)\n\n\n try {\n generateUUID.name = name; // eslint-disable-next-line no-empty\n } catch (err) {} // For CommonJS default export support\n\n\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _native = _interopRequireDefault(require(\"./native.js\"));\n\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\n\nvar _stringify = require(\"./stringify.js\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction v4(options, buf, offset) {\n if (_native.default.randomUUID && !buf && !options) {\n return _native.default.randomUUID();\n }\n\n options = options || {};\n\n const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return (0, _stringify.unsafeStringify)(rnds);\n}\n\nvar _default = v4;\nexports.default = _default;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\n\nvar _sha = _interopRequireDefault(require(\"./sha1.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconst v5 = (0, _v.default)('v5', 0x50, _sha.default);\nvar _default = v5;\nexports.default = _default;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _regex = _interopRequireDefault(require(\"./regex.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && _regex.default.test(uuid);\n}\n\nvar _default = validate;\nexports.default = _default;", - "\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction version(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n return parseInt(uuid.slice(14, 15), 16);\n}\n\nvar _default = version;\nexports.default = _default;", - "'use strict';\n\nvar forEach = require('for-each');\nvar availableTypedArrays = require('available-typed-arrays');\nvar callBound = require('call-bind/callBound');\nvar gOPD = require('gopd');\n\nvar $toString = callBound('Object.prototype.toString');\nvar hasToStringTag = require('has-tostringtag/shams')();\n\nvar g = typeof globalThis === 'undefined' ? global : globalThis;\nvar typedArrays = availableTypedArrays();\n\nvar $slice = callBound('String.prototype.slice');\nvar toStrTags = {};\nvar getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');\nif (hasToStringTag && gOPD && getPrototypeOf) {\n\tforEach(typedArrays, function (typedArray) {\n\t\tif (typeof g[typedArray] === 'function') {\n\t\t\tvar arr = new g[typedArray]();\n\t\t\tif (Symbol.toStringTag in arr) {\n\t\t\t\tvar proto = getPrototypeOf(arr);\n\t\t\t\tvar descriptor = gOPD(proto, Symbol.toStringTag);\n\t\t\t\tif (!descriptor) {\n\t\t\t\t\tvar superProto = getPrototypeOf(proto);\n\t\t\t\t\tdescriptor = gOPD(superProto, Symbol.toStringTag);\n\t\t\t\t}\n\t\t\t\ttoStrTags[typedArray] = descriptor.get;\n\t\t\t}\n\t\t}\n\t});\n}\n\nvar tryTypedArrays = function tryAllTypedArrays(value) {\n\tvar foundName = false;\n\tforEach(toStrTags, function (getter, typedArray) {\n\t\tif (!foundName) {\n\t\t\ttry {\n\t\t\t\tvar name = getter.call(value);\n\t\t\t\tif (name === typedArray) {\n\t\t\t\t\tfoundName = name;\n\t\t\t\t}\n\t\t\t} catch (e) {}\n\t\t}\n\t});\n\treturn foundName;\n};\n\nvar isTypedArray = require('is-typed-array');\n\nmodule.exports = function whichTypedArray(value) {\n\tif (!isTypedArray(value)) { return false; }\n\tif (!hasToStringTag || !(Symbol.toStringTag in value)) { return $slice($toString(value), 8, -1); }\n\treturn tryTypedArrays(value);\n};\n", - "/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// allow camelcase as these are things that go onto the wire\n/* eslint-disable camelcase */\n\nexport enum PushRuleActionName {\n DontNotify = \"dont_notify\",\n Notify = \"notify\",\n Coalesce = \"coalesce\",\n}\n\nexport enum TweakName {\n Highlight = \"highlight\",\n Sound = \"sound\",\n}\n\nexport type Tweak = {\n set_tweak: N;\n value?: V;\n};\n\nexport type TweakHighlight = Tweak;\nexport type TweakSound = Tweak;\n\nexport type Tweaks = TweakHighlight | TweakSound;\n\nexport enum ConditionOperator {\n ExactEquals = \"==\",\n LessThan = \"<\",\n GreaterThan = \">\",\n GreaterThanOrEqual = \">=\",\n LessThanOrEqual = \"<=\",\n}\n\nexport type PushRuleAction = Tweaks | PushRuleActionName;\n\nexport type MemberCountCondition =\n | `${Op}${N}`\n | (Op extends ConditionOperator.ExactEquals ? `${N}` : never);\n\nexport type AnyMemberCountCondition = MemberCountCondition;\n\nexport const DMMemberCountCondition: MemberCountCondition<2> = \"2\";\n\nexport function isDmMemberCountCondition(condition: AnyMemberCountCondition): boolean {\n return condition === \"==2\" || condition === \"2\";\n}\n\nexport enum ConditionKind {\n EventMatch = \"event_match\",\n EventPropertyIs = \"event_property_is\",\n EventPropertyContains = \"event_property_contains\",\n ContainsDisplayName = \"contains_display_name\",\n RoomMemberCount = \"room_member_count\",\n SenderNotificationPermission = \"sender_notification_permission\",\n CallStarted = \"call_started\",\n CallStartedPrefix = \"org.matrix.msc3914.call_started\",\n}\n\nexport interface IPushRuleCondition {\n [k: string]: any; // for custom conditions, there can be other fields here\n kind: N;\n}\n\nexport interface IEventMatchCondition extends IPushRuleCondition {\n key: string;\n pattern?: string;\n // Note that value property is an optimization for patterns which do not do\n // any globbing and when the key is not \"content.body\".\n value?: string;\n}\n\nexport interface IEventPropertyIsCondition extends IPushRuleCondition {\n key: string;\n value: string | boolean | null | number;\n}\n\nexport interface IEventPropertyContainsCondition extends IPushRuleCondition {\n key: string;\n value: string | boolean | null | number;\n}\n\nexport interface IContainsDisplayNameCondition extends IPushRuleCondition {\n // no additional fields\n}\n\nexport interface IRoomMemberCountCondition extends IPushRuleCondition {\n is: AnyMemberCountCondition;\n}\n\nexport interface ISenderNotificationPermissionCondition\n extends IPushRuleCondition {\n key: string;\n}\n\nexport interface ICallStartedCondition extends IPushRuleCondition {\n // no additional fields\n}\n\nexport interface ICallStartedPrefixCondition extends IPushRuleCondition {\n // no additional fields\n}\n\n// XXX: custom conditions are possible but always fail, and break the typescript discriminated union so ignore them here\n// IPushRuleCondition> unfortunately does not resolve this at the time of writing.\nexport type PushRuleCondition =\n | IEventMatchCondition\n | IEventPropertyIsCondition\n | IEventPropertyContainsCondition\n | IContainsDisplayNameCondition\n | IRoomMemberCountCondition\n | ISenderNotificationPermissionCondition\n | ICallStartedCondition\n | ICallStartedPrefixCondition;\n\nexport enum PushRuleKind {\n Override = \"override\",\n ContentSpecific = \"content\",\n RoomSpecific = \"room\",\n SenderSpecific = \"sender\",\n Underride = \"underride\",\n}\n\nexport enum RuleId {\n Master = \".m.rule.master\",\n IsUserMention = \".org.matrix.msc3952.is_user_mention\",\n IsRoomMention = \".org.matrix.msc3952.is_room_mention\",\n ContainsDisplayName = \".m.rule.contains_display_name\",\n ContainsUserName = \".m.rule.contains_user_name\",\n AtRoomNotification = \".m.rule.roomnotif\",\n DM = \".m.rule.room_one_to_one\",\n EncryptedDM = \".m.rule.encrypted_room_one_to_one\",\n Message = \".m.rule.message\",\n EncryptedMessage = \".m.rule.encrypted\",\n InviteToSelf = \".m.rule.invite_for_me\",\n MemberEvent = \".m.rule.member_event\",\n IncomingCall = \".m.rule.call\",\n SuppressNotices = \".m.rule.suppress_notices\",\n Tombstone = \".m.rule.tombstone\",\n PollStart = \".m.rule.poll_start\",\n PollStartUnstable = \".org.matrix.msc3930.rule.poll_start\",\n PollEnd = \".m.rule.poll_end\",\n PollEndUnstable = \".org.matrix.msc3930.rule.poll_end\",\n PollStartOneToOne = \".m.rule.poll_start_one_to_one\",\n PollStartOneToOneUnstable = \".org.matrix.msc3930.rule.poll_start_one_to_one\",\n PollEndOneToOne = \".m.rule.poll_end_one_to_one\",\n PollEndOneToOneUnstable = \".org.matrix.msc3930.rule.poll_end_one_to_one\",\n}\n\nexport type PushRuleSet = {\n [k in PushRuleKind]?: IPushRule[];\n};\n\nexport interface IPushRule {\n actions: PushRuleAction[];\n conditions?: PushRuleCondition[];\n default: boolean;\n enabled: boolean;\n pattern?: string;\n rule_id: RuleId | string;\n}\n\nexport interface IAnnotatedPushRule extends IPushRule {\n kind: PushRuleKind;\n}\n\nexport interface IPushRules {\n global: PushRuleSet;\n device?: PushRuleSet;\n}\n\nexport interface IPusher {\n \"app_display_name\": string;\n \"app_id\": string;\n \"data\": {\n format?: string;\n url?: string; // TODO: Required if kind==http\n brand?: string; // TODO: For email notifications only? Unspecced field\n };\n \"device_display_name\": string;\n \"kind\": \"http\" | string;\n \"lang\": string;\n \"profile_tag\"?: string;\n \"pushkey\": string;\n \"enabled\"?: boolean | null;\n \"org.matrix.msc3881.enabled\"?: boolean | null;\n \"device_id\"?: string | null;\n \"org.matrix.msc3881.device_id\"?: string | null;\n}\n\nexport interface IPusherRequest extends Omit {\n append?: boolean;\n}\n\n/* eslint-enable camelcase */\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { RelatesToRelationship, REFERENCE_RELATION } from \"./extensible_events\";\nimport { UnstableValue } from \"../NamespacedValue\";\nimport { MAssetEvent, MLocationEvent, MTimestampEvent } from \"./location\";\n\n/**\n * Beacon info and beacon event types as described in MSC3672\n * https://github.com/matrix-org/matrix-spec-proposals/pull/3672\n */\n\n/**\n * Beacon info events are state events.\n * We have two requirements for these events:\n * 1. they can only be written by their owner\n * 2. a user can have an arbitrary number of beacon_info events\n *\n * 1. is achieved by setting the state_key to the owners mxid.\n * Event keys in room state are a combination of `type` + `state_key`.\n * To achieve an arbitrary number of only owner-writable state events\n * we introduce a variable suffix to the event type\n *\n * @example\n * ```\n * {\n * \"type\": \"m.beacon_info.@matthew:matrix.org.1\",\n * \"state_key\": \"@matthew:matrix.org\",\n * \"content\": {\n * \"m.beacon_info\": {\n * \"description\": \"The Matthew Tracker\",\n * \"timeout\": 86400000,\n * },\n * // more content as described below\n * }\n * },\n * {\n * \"type\": \"m.beacon_info.@matthew:matrix.org.2\",\n * \"state_key\": \"@matthew:matrix.org\",\n * \"content\": {\n * \"m.beacon_info\": {\n * \"description\": \"Another different Matthew tracker\",\n * \"timeout\": 400000,\n * },\n * // more content as described below\n * }\n * }\n * ```\n */\n\n/**\n * Non-variable type for m.beacon_info event content\n */\nexport const M_BEACON_INFO = new UnstableValue(\"m.beacon_info\", \"org.matrix.msc3672.beacon_info\");\nexport const M_BEACON = new UnstableValue(\"m.beacon\", \"org.matrix.msc3672.beacon\");\n\nexport type MBeaconInfoContent = {\n description?: string;\n // how long from the last event until we consider the beacon inactive in milliseconds\n timeout: number;\n // true when this is a live location beacon\n // https://github.com/matrix-org/matrix-spec-proposals/pull/3672\n live?: boolean;\n};\n\n/**\n * m.beacon_info Event example from the spec\n * https://github.com/matrix-org/matrix-spec-proposals/pull/3672\n * @example\n * ```\n * {\n * \"type\": \"m.beacon_info\",\n * \"state_key\": \"@matthew:matrix.org\",\n * \"content\": {\n * \"m.beacon_info\": {\n * \"description\": \"The Matthew Tracker\", // same as an `m.location` description\n * \"timeout\": 86400000, // how long from the last event until we consider the beacon inactive in milliseconds\n * },\n * \"m.ts\": 1436829458432, // creation timestamp of the beacon on the client\n * \"m.asset\": {\n * \"type\": \"m.self\" // the type of asset being tracked as per MSC3488\n * }\n * }\n * }\n * ```\n */\n\n/**\n * m.beacon_info.* event content\n */\nexport type MBeaconInfoEventContent = MBeaconInfoContent &\n // creation timestamp of the beacon on the client\n MTimestampEvent &\n // the type of asset being tracked as per MSC3488\n MAssetEvent;\n\n/**\n * m.beacon event example\n * https://github.com/matrix-org/matrix-spec-proposals/pull/3672\n * @example\n * ```\n * {\n * \"type\": \"m.beacon\",\n * \"sender\": \"@matthew:matrix.org\",\n * \"content\": {\n * \"m.relates_to\": { // from MSC2674: https://github.com/matrix-org/matrix-doc/pull/2674\n * \"rel_type\": \"m.reference\", // from MSC3267: https://github.com/matrix-org/matrix-doc/pull/3267\n * \"event_id\": \"$beacon_info\"\n * },\n * \"m.location\": {\n * \"uri\": \"geo:51.5008,0.1247;u=35\",\n * \"description\": \"Arbitrary beacon information\"\n * },\n * \"m.ts\": 1636829458432,\n * }\n * }\n * ```\n */\n\n/**\n * Content of an m.beacon event\n */\nexport type MBeaconEventContent = MLocationEvent &\n // timestamp when location was taken\n MTimestampEvent &\n // relates to a beacon_info event\n RelatesToRelationship;\n", - "/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { UnstableValue } from \"../NamespacedValue\";\n\nexport enum EventType {\n // Room state events\n RoomCanonicalAlias = \"m.room.canonical_alias\",\n RoomCreate = \"m.room.create\",\n RoomJoinRules = \"m.room.join_rules\",\n RoomMember = \"m.room.member\",\n RoomThirdPartyInvite = \"m.room.third_party_invite\",\n RoomPowerLevels = \"m.room.power_levels\",\n RoomName = \"m.room.name\",\n RoomTopic = \"m.room.topic\",\n RoomAvatar = \"m.room.avatar\",\n RoomPinnedEvents = \"m.room.pinned_events\",\n RoomEncryption = \"m.room.encryption\",\n RoomHistoryVisibility = \"m.room.history_visibility\",\n RoomGuestAccess = \"m.room.guest_access\",\n RoomServerAcl = \"m.room.server_acl\",\n RoomTombstone = \"m.room.tombstone\",\n RoomPredecessor = \"org.matrix.msc3946.room_predecessor\",\n\n SpaceChild = \"m.space.child\",\n SpaceParent = \"m.space.parent\",\n\n // Room timeline events\n RoomRedaction = \"m.room.redaction\",\n RoomMessage = \"m.room.message\",\n RoomMessageEncrypted = \"m.room.encrypted\",\n Sticker = \"m.sticker\",\n CallInvite = \"m.call.invite\",\n CallCandidates = \"m.call.candidates\",\n CallAnswer = \"m.call.answer\",\n CallHangup = \"m.call.hangup\",\n CallReject = \"m.call.reject\",\n CallSelectAnswer = \"m.call.select_answer\",\n CallNegotiate = \"m.call.negotiate\",\n CallSDPStreamMetadataChanged = \"m.call.sdp_stream_metadata_changed\",\n CallSDPStreamMetadataChangedPrefix = \"org.matrix.call.sdp_stream_metadata_changed\",\n CallReplaces = \"m.call.replaces\",\n CallAssertedIdentity = \"m.call.asserted_identity\",\n CallAssertedIdentityPrefix = \"org.matrix.call.asserted_identity\",\n KeyVerificationRequest = \"m.key.verification.request\",\n KeyVerificationStart = \"m.key.verification.start\",\n KeyVerificationCancel = \"m.key.verification.cancel\",\n KeyVerificationMac = \"m.key.verification.mac\",\n KeyVerificationDone = \"m.key.verification.done\",\n KeyVerificationKey = \"m.key.verification.key\",\n KeyVerificationAccept = \"m.key.verification.accept\",\n // Not used directly - see READY_TYPE in VerificationRequest.\n KeyVerificationReady = \"m.key.verification.ready\",\n // use of this is discouraged https://matrix.org/docs/spec/client_server/r0.6.1#m-room-message-feedback\n RoomMessageFeedback = \"m.room.message.feedback\",\n Reaction = \"m.reaction\",\n PollStart = \"org.matrix.msc3381.poll.start\",\n\n // Room ephemeral events\n Typing = \"m.typing\",\n Receipt = \"m.receipt\",\n Presence = \"m.presence\",\n\n // Room account_data events\n FullyRead = \"m.fully_read\",\n Tag = \"m.tag\",\n SpaceOrder = \"org.matrix.msc3230.space_order\", // MSC3230\n\n // User account_data events\n PushRules = \"m.push_rules\",\n Direct = \"m.direct\",\n IgnoredUserList = \"m.ignored_user_list\",\n\n // to_device events\n RoomKey = \"m.room_key\",\n RoomKeyRequest = \"m.room_key_request\",\n ForwardedRoomKey = \"m.forwarded_room_key\",\n Dummy = \"m.dummy\",\n\n // Group call events\n GroupCallPrefix = \"org.matrix.msc3401.call\",\n GroupCallMemberPrefix = \"org.matrix.msc3401.call.member\",\n}\n\nexport enum RelationType {\n Annotation = \"m.annotation\",\n Replace = \"m.replace\",\n Reference = \"m.reference\",\n Thread = \"m.thread\",\n}\n\nexport enum MsgType {\n Text = \"m.text\",\n Emote = \"m.emote\",\n Notice = \"m.notice\",\n Image = \"m.image\",\n File = \"m.file\",\n Audio = \"m.audio\",\n Location = \"m.location\",\n Video = \"m.video\",\n KeyVerificationRequest = \"m.key.verification.request\",\n}\n\nexport const RoomCreateTypeField = \"type\";\n\nexport enum RoomType {\n Space = \"m.space\",\n UnstableCall = \"org.matrix.msc3417.call\",\n ElementVideo = \"io.element.video\",\n}\n\nexport const ToDeviceMessageId = \"org.matrix.msgid\";\n\n/**\n * Identifier for an [MSC3088](https://github.com/matrix-org/matrix-doc/pull/3088)\n * room purpose. Note that this reference is UNSTABLE and subject to breaking changes,\n * including its eventual removal.\n */\nexport const UNSTABLE_MSC3088_PURPOSE = new UnstableValue(\"m.room.purpose\", \"org.matrix.msc3088.purpose\");\n\n/**\n * Enabled flag for an [MSC3088](https://github.com/matrix-org/matrix-doc/pull/3088)\n * room purpose. Note that this reference is UNSTABLE and subject to breaking changes,\n * including its eventual removal.\n */\nexport const UNSTABLE_MSC3088_ENABLED = new UnstableValue(\"m.enabled\", \"org.matrix.msc3088.enabled\");\n\n/**\n * Subtype for an [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room.\n * Note that this reference is UNSTABLE and subject to breaking changes, including its\n * eventual removal.\n */\nexport const UNSTABLE_MSC3089_TREE_SUBTYPE = new UnstableValue(\"m.data_tree\", \"org.matrix.msc3089.data_tree\");\n\n/**\n * Leaf type for an event in a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room.\n * Note that this reference is UNSTABLE and subject to breaking changes, including its\n * eventual removal.\n */\nexport const UNSTABLE_MSC3089_LEAF = new UnstableValue(\"m.leaf\", \"org.matrix.msc3089.leaf\");\n\n/**\n * Branch (Leaf Reference) type for the index approach in a\n * [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) space-room. Note that this reference is\n * UNSTABLE and subject to breaking changes, including its eventual removal.\n */\nexport const UNSTABLE_MSC3089_BRANCH = new UnstableValue(\"m.branch\", \"org.matrix.msc3089.branch\");\n\n/**\n * Marker event type to point back at imported historical content in a room. See\n * [MSC2716](https://github.com/matrix-org/matrix-spec-proposals/pull/2716).\n * Note that this reference is UNSTABLE and subject to breaking changes,\n * including its eventual removal.\n */\nexport const UNSTABLE_MSC2716_MARKER = new UnstableValue(\"m.room.marker\", \"org.matrix.msc2716.marker\");\n\n/**\n * Name of the \"with_relations\" request property for relation based redactions.\n * {@link https://github.com/matrix-org/matrix-spec-proposals/pull/3912}\n */\nexport const MSC3912_RELATION_BASED_REDACTIONS_PROP = new UnstableValue(\n \"with_relations\",\n \"org.matrix.msc3912.with_relations\",\n);\n\n/**\n * Functional members type for declaring a purpose of room members (e.g. helpful bots).\n * Note that this reference is UNSTABLE and subject to breaking changes, including its\n * eventual removal.\n *\n * Schema (TypeScript):\n * ```\n * {\n * service_members?: string[]\n * }\n * ```\n *\n * @example\n * ```\n * {\n * \"service_members\": [\n * \"@helperbot:localhost\",\n * \"@reminderbot:alice.tdl\"\n * ]\n * }\n * ```\n */\nexport const UNSTABLE_ELEMENT_FUNCTIONAL_USERS = new UnstableValue(\n \"io.element.functional_members\",\n \"io.element.functional_members\",\n);\n\n/**\n * A type of message that affects visibility of a message,\n * as per https://github.com/matrix-org/matrix-doc/pull/3531\n *\n * @experimental\n */\nexport const EVENT_VISIBILITY_CHANGE_TYPE = new UnstableValue(\"m.visibility\", \"org.matrix.msc3531.visibility\");\n\n/**\n * https://github.com/matrix-org/matrix-doc/pull/3881\n *\n * @experimental\n */\nexport const PUSHER_ENABLED = new UnstableValue(\"enabled\", \"org.matrix.msc3881.enabled\");\n\n/**\n * https://github.com/matrix-org/matrix-doc/pull/3881\n *\n * @experimental\n */\nexport const PUSHER_DEVICE_ID = new UnstableValue(\"device_id\", \"org.matrix.msc3881.device_id\");\n\n/**\n * https://github.com/matrix-org/matrix-doc/pull/3890\n *\n * @experimental\n */\nexport const LOCAL_NOTIFICATION_SETTINGS_PREFIX = new UnstableValue(\n \"m.local_notification_settings\",\n \"org.matrix.msc3890.local_notification_settings\",\n);\n\nexport interface IEncryptedFile {\n url: string;\n mimetype?: string;\n key: {\n alg: string;\n key_ops: string[]; // eslint-disable-line camelcase\n kty: string;\n k: string;\n ext: boolean;\n };\n iv: string;\n hashes: { [alg: string]: string };\n v: string;\n}\n", - "/*\nCopyright 2021 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EitherAnd, NamespacedValue, Optional, UnstableValue } from \"matrix-events-sdk\";\n\nimport { isProvided } from \"../extensible_events_v1/utilities\";\n\n// Types and utilities for MSC1767: Extensible events (version 1) in Matrix\n\n/**\n * Represents the stable and unstable values of a given namespace.\n */\nexport type TSNamespace = N extends NamespacedValue\n ? TSNamespaceValue | TSNamespaceValue\n : never;\n\n/**\n * Represents a namespaced value, if the value is a string. Used to extract provided types\n * from a TSNamespace (in cases where only stable *or* unstable is provided).\n */\nexport type TSNamespaceValue = V extends string ? V : never;\n\n/**\n * Creates a type which is V when T is `never`, otherwise T.\n */\n// See https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887 for details on the array syntax.\nexport type DefaultNever = [T] extends [never] ? V : T;\n\n/**\n * The namespaced value for m.message\n */\nexport const M_MESSAGE = new UnstableValue(\"m.message\", \"org.matrix.msc1767.message\");\n\n/**\n * An m.message event rendering\n */\nexport interface IMessageRendering {\n body: string;\n mimetype?: string;\n}\n\n/**\n * The content for an m.message event\n */\nexport type ExtensibleMessageEventContent = EitherAnd<\n { [M_MESSAGE.name]: IMessageRendering[] },\n { [M_MESSAGE.altName]: IMessageRendering[] }\n>;\n\n/**\n * The namespaced value for m.text\n */\nexport const M_TEXT = new UnstableValue(\"m.text\", \"org.matrix.msc1767.text\");\n\n/**\n * The content for an m.text event\n */\nexport type TextEventContent = EitherAnd<{ [M_TEXT.name]: string }, { [M_TEXT.altName]: string }>;\n\n/**\n * The namespaced value for m.html\n */\nexport const M_HTML = new UnstableValue(\"m.html\", \"org.matrix.msc1767.html\");\n\n/**\n * The content for an m.html event\n */\nexport type HtmlEventContent = EitherAnd<{ [M_HTML.name]: string }, { [M_HTML.altName]: string }>;\n\n/**\n * The content for an m.message, m.text, or m.html event\n */\nexport type ExtensibleAnyMessageEventContent = ExtensibleMessageEventContent | TextEventContent | HtmlEventContent;\n\n/**\n * The namespaced value for an m.reference relation\n */\nexport const REFERENCE_RELATION = new NamespacedValue(\"m.reference\");\n\n/**\n * Represents any relation type\n */\nexport type AnyRelation = TSNamespace | string;\n\n/**\n * An m.relates_to relationship\n */\nexport type RelatesToRelationship = {\n \"m.relates_to\": {\n // See https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887 for array syntax\n rel_type: [R] extends [never] ? AnyRelation : TSNamespace;\n event_id: string;\n } & DefaultNever;\n};\n\n/**\n * Partial types for a Matrix Event.\n */\nexport interface IPartialEvent {\n type: string;\n content: TContent;\n}\n\n/**\n * Represents a potentially namespaced event type.\n */\nexport type ExtensibleEventType = NamespacedValue | string;\n\n/**\n * Determines if two event types are the same, including namespaces.\n * @param given - The given event type. This will be compared\n * against the expected type.\n * @param expected - The expected event type.\n * @returns True if the given type matches the expected type.\n */\nexport function isEventTypeSame(\n given: Optional,\n expected: Optional,\n): boolean {\n if (typeof given === \"string\") {\n if (typeof expected === \"string\") {\n return expected === given;\n } else {\n return (expected as NamespacedValue).matches(given as string);\n }\n } else {\n if (typeof expected === \"string\") {\n return (given as NamespacedValue).matches(expected as string);\n } else {\n const expectedNs = expected as NamespacedValue;\n const givenNs = given as NamespacedValue;\n return (\n expectedNs.matches(givenNs.name) ||\n (isProvided(givenNs.altName) && expectedNs.matches(givenNs.altName!))\n );\n }\n }\n}\n", - "/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// Types for MSC3488 - m.location: Extending events with location data\nimport { EitherAnd } from \"matrix-events-sdk\";\n\nimport { UnstableValue } from \"../NamespacedValue\";\nimport { M_TEXT } from \"./extensible_events\";\n\nexport enum LocationAssetType {\n Self = \"m.self\",\n Pin = \"m.pin\",\n}\n\nexport const M_ASSET = new UnstableValue(\"m.asset\", \"org.matrix.msc3488.asset\");\nexport type MAssetContent = { type: LocationAssetType };\n/**\n * The event definition for an m.asset event (in content)\n */\nexport type MAssetEvent = EitherAnd<{ [M_ASSET.name]: MAssetContent }, { [M_ASSET.altName]: MAssetContent }>;\n\nexport const M_TIMESTAMP = new UnstableValue(\"m.ts\", \"org.matrix.msc3488.ts\");\n/**\n * The event definition for an m.ts event (in content)\n */\nexport type MTimestampEvent = EitherAnd<{ [M_TIMESTAMP.name]: number }, { [M_TIMESTAMP.altName]: number }>;\n\nexport const M_LOCATION = new UnstableValue(\"m.location\", \"org.matrix.msc3488.location\");\n\nexport type MLocationContent = {\n uri: string;\n description?: string | null;\n};\n\nexport type MLocationEvent = EitherAnd<\n { [M_LOCATION.name]: MLocationContent },\n { [M_LOCATION.altName]: MLocationContent }\n>;\n\nexport type MTextEvent = EitherAnd<{ [M_TEXT.name]: string }, { [M_TEXT.altName]: string }>;\n\n/* From the spec at:\n * https://github.com/matrix-org/matrix-doc/blob/matthew/location/proposals/3488-location.md\n{\n \"type\": \"m.room.message\",\n \"content\": {\n \"body\": \"Matthew was at geo:51.5008,0.1247;u=35 as of Sat Nov 13 18:50:58 2021\",\n \"msgtype\": \"m.location\",\n \"geo_uri\": \"geo:51.5008,0.1247;u=35\",\n \"m.location\": {\n \"uri\": \"geo:51.5008,0.1247;u=35\",\n \"description\": \"Matthew's whereabouts\",\n },\n \"m.asset\": {\n \"type\": \"m.self\"\n },\n \"m.text\": \"Matthew was at geo:51.5008,0.1247;u=35 as of Sat Nov 13 18:50:58 2021\",\n \"m.ts\": 1636829458432,\n }\n}\n*/\ntype OptionalTimestampEvent = MTimestampEvent | undefined;\n/**\n * The content for an m.location event\n */\nexport type MLocationEventContent = MLocationEvent & MAssetEvent & MTextEvent & OptionalTimestampEvent;\n\nexport type LegacyLocationEventContent = {\n body: string;\n msgtype: string;\n geo_uri: string;\n};\n\n/**\n * Possible content for location events as sent over the wire\n */\nexport type LocationEventWireContent = Partial;\n\nexport type ILocationContent = MLocationEventContent & LegacyLocationEventContent;\n", - "/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport interface IImageInfo {\n size?: number;\n mimetype?: string;\n thumbnail_info?: {\n // eslint-disable-line camelcase\n w?: number;\n h?: number;\n size?: number;\n mimetype?: string;\n };\n w?: number;\n h?: number;\n}\n\nexport enum Visibility {\n Public = \"public\",\n Private = \"private\",\n}\n\nexport enum Preset {\n PrivateChat = \"private_chat\",\n TrustedPrivateChat = \"trusted_private_chat\",\n PublicChat = \"public_chat\",\n}\n\nexport type ResizeMethod = \"crop\" | \"scale\";\n\nexport type IdServerUnbindResult = \"no-support\" | \"success\";\n\n// Knock and private are reserved keywords which are not yet implemented.\nexport enum JoinRule {\n Public = \"public\",\n Invite = \"invite\",\n /**\n * @deprecated Reserved keyword. Should not be used. Not yet implemented.\n */\n Private = \"private\",\n Knock = \"knock\",\n Restricted = \"restricted\",\n}\n\nexport enum RestrictedAllowType {\n RoomMembership = \"m.room_membership\",\n}\n\nexport interface IJoinRuleEventContent {\n join_rule: JoinRule; // eslint-disable-line camelcase\n allow?: {\n type: RestrictedAllowType;\n room_id: string; // eslint-disable-line camelcase\n }[];\n}\n\nexport enum GuestAccess {\n CanJoin = \"can_join\",\n Forbidden = \"forbidden\",\n}\n\nexport enum HistoryVisibility {\n Invited = \"invited\",\n Joined = \"joined\",\n Shared = \"shared\",\n WorldReadable = \"world_readable\",\n}\n\nexport interface IUsageLimit {\n // \"hs_disabled\" is NOT a specced string, but is used in Synapse\n // This is tracked over at https://github.com/matrix-org/synapse/issues/9237\n // eslint-disable-next-line camelcase\n limit_type: \"monthly_active_user\" | \"hs_disabled\" | string;\n // eslint-disable-next-line camelcase\n admin_contact?: string;\n}\n", - "/*\nCopyright 2022 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EitherAnd, UnstableValue } from \"matrix-events-sdk\";\n\nimport {\n ExtensibleAnyMessageEventContent,\n REFERENCE_RELATION,\n RelatesToRelationship,\n TSNamespace,\n} from \"./extensible_events\";\n\n/**\n * Identifier for a disclosed poll.\n */\nexport const M_POLL_KIND_DISCLOSED = new UnstableValue(\"m.poll.disclosed\", \"org.matrix.msc3381.poll.disclosed\");\n\n/**\n * Identifier for an undisclosed poll.\n */\nexport const M_POLL_KIND_UNDISCLOSED = new UnstableValue(\"m.poll.undisclosed\", \"org.matrix.msc3381.poll.undisclosed\");\n\n/**\n * Any poll kind.\n */\nexport type PollKind = TSNamespace | TSNamespace | string;\n\n/**\n * Known poll kind namespaces.\n */\nexport type KnownPollKind = typeof M_POLL_KIND_DISCLOSED | typeof M_POLL_KIND_UNDISCLOSED;\n\n/**\n * The namespaced value for m.poll.start\n */\nexport const M_POLL_START = new UnstableValue(\"m.poll.start\", \"org.matrix.msc3381.poll.start\");\n\n/**\n * The m.poll.start type within event content\n */\nexport type PollStartSubtype = {\n question: ExtensibleAnyMessageEventContent;\n kind: PollKind;\n max_selections?: number; // default 1, always positive\n answers: PollAnswer[];\n};\n\n/**\n * A poll answer.\n */\nexport type PollAnswer = ExtensibleAnyMessageEventContent & { id: string };\n\n/**\n * The event definition for an m.poll.start event (in content)\n */\nexport type PollStartEvent = EitherAnd<\n { [M_POLL_START.name]: PollStartSubtype },\n { [M_POLL_START.altName]: PollStartSubtype }\n>;\n\n/**\n * The content for an m.poll.start event\n */\nexport type PollStartEventContent = PollStartEvent & ExtensibleAnyMessageEventContent;\n\n/**\n * The namespaced value for m.poll.response\n */\nexport const M_POLL_RESPONSE = new UnstableValue(\"m.poll.response\", \"org.matrix.msc3381.poll.response\");\n\n/**\n * The m.poll.response type within event content\n */\nexport type PollResponseSubtype = {\n answers: string[];\n};\n\n/**\n * The event definition for an m.poll.response event (in content)\n */\nexport type PollResponseEvent = EitherAnd<\n { [M_POLL_RESPONSE.name]: PollResponseSubtype },\n { [M_POLL_RESPONSE.altName]: PollResponseSubtype }\n>;\n\n/**\n * The content for an m.poll.response event\n */\nexport type PollResponseEventContent = PollResponseEvent & RelatesToRelationship;\n\n/**\n * The namespaced value for m.poll.end\n */\nexport const M_POLL_END = new UnstableValue(\"m.poll.end\", \"org.matrix.msc3381.poll.end\");\n\n/**\n * The event definition for an m.poll.end event (in content)\n */\nexport type PollEndEvent = EitherAnd<{ [M_POLL_END.name]: {} }, { [M_POLL_END.altName]: {} }>;\n\n/**\n * The content for an m.poll.end event\n */\nexport type PollEndEventContent = PollEndEvent &\n RelatesToRelationship &\n ExtensibleAnyMessageEventContent;\n", - "/*\nCopyright 2022 Šimon Brandner \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport enum ReceiptType {\n Read = \"m.read\",\n FullyRead = \"m.fully_read\",\n ReadPrivate = \"m.read.private\",\n}\n\nexport const MAIN_ROOM_TIMELINE = \"main\";\n\nexport interface Receipt {\n ts: number;\n thread_id?: string;\n}\n\nexport interface WrappedReceipt {\n eventId: string;\n data: Receipt;\n}\n\nexport interface CachedReceipt {\n type: ReceiptType;\n userId: string;\n data: Receipt;\n}\n\nexport type ReceiptCache = Map;\n\nexport interface ReceiptContent {\n [eventId: string]: {\n [key in ReceiptType | string]: {\n [userId: string]: Receipt;\n };\n };\n}\n\n// We will only hold a synthetic receipt if we do not have a real receipt or the synthetic is newer.\n// map: receipt type → user Id → receipt\nexport type Receipts = Map>;\n\nexport type CachedReceiptStructure = {\n eventId: string;\n receiptType: string | ReceiptType;\n userId: string;\n receipt: Receipt;\n synthetic: boolean;\n};\n", - "/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { IContent, IEvent } from \"../models/event\";\nimport { Preset, Visibility } from \"./partials\";\nimport { IEventWithRoomId, SearchKey } from \"./search\";\nimport { IRoomEventFilter } from \"../filter\";\nimport { Direction } from \"../models/event-timeline\";\nimport { PushRuleAction } from \"./PushRules\";\nimport { IRoomEvent } from \"../sync-accumulator\";\nimport { EventType, RelationType, RoomType } from \"./event\";\n\n// allow camelcase as these are things that go onto the wire\n/* eslint-disable camelcase */\n\nexport interface IJoinRoomOpts {\n /**\n * True to do a room initial sync on the resulting\n * room. If false, the returned Room object will have no current state.\n * Default: true.\n */\n syncRoom?: boolean;\n\n /**\n * If the caller has a keypair 3pid invite, the signing URL is passed in this parameter.\n */\n inviteSignUrl?: string;\n\n /**\n * The server names to try and join through in addition to those that are automatically chosen.\n */\n viaServers?: string[];\n}\n\nexport interface IRedactOpts {\n reason?: string;\n /**\n * Whether events related to the redacted event should be redacted.\n *\n * If specified, then any events which relate to the event being redacted with\n * any of the relationship types listed will also be redacted.\n *\n * Raises an Error if the server does not support it.\n * Check for server-side support before using this param with\n * client.canSupport.get(Feature.RelationBasedRedactions).\n * {@link https://github.com/matrix-org/matrix-spec-proposals/pull/3912}\n */\n with_relations?: Array;\n}\n\nexport interface ISendEventResponse {\n event_id: string;\n}\n\nexport interface IPresenceOpts {\n // One of \"online\", \"offline\" or \"unavailable\"\n presence: \"online\" | \"offline\" | \"unavailable\";\n // The status message to attach.\n status_msg?: string;\n}\n\nexport interface IPaginateOpts {\n // true to fill backwards, false to go forwards\n backwards?: boolean;\n // number of events to request\n limit?: number;\n}\n\nexport interface IGuestAccessOpts {\n /**\n * True to allow guests to join this room. This\n * implicitly gives guests write access. If false or not given, guests are\n * explicitly forbidden from joining the room.\n */\n allowJoin: boolean;\n /**\n * True to set history visibility to\n * be world_readable. This gives guests read access *from this point forward*.\n * If false or not given, history visibility is not modified.\n */\n allowRead: boolean;\n}\n\nexport interface ISearchOpts {\n keys?: SearchKey[];\n query: string;\n}\n\nexport interface IEventSearchOpts {\n // a JSON filter object to pass in the request\n filter?: IRoomEventFilter;\n // the term to search for\n term: string;\n}\n\nexport interface IInvite3PID {\n id_server: string;\n id_access_token?: string; // this gets injected by the js-sdk\n medium: string;\n address: string;\n}\n\nexport interface ICreateRoomStateEvent {\n type: string;\n state_key?: string; // defaults to an empty string\n content: IContent;\n}\n\nexport interface ICreateRoomOpts {\n // The alias localpart to assign to this room.\n room_alias_name?: string;\n // Either 'public' or 'private'.\n visibility?: Visibility;\n // The name to give this room.\n name?: string;\n // The topic to give this room.\n topic?: string;\n preset?: Preset;\n power_level_content_override?: {\n ban?: number;\n events?: Record;\n events_default?: number;\n invite?: number;\n kick?: number;\n notifications?: Record;\n redact?: number;\n state_default?: number;\n users?: Record;\n users_default?: number;\n };\n creation_content?: object;\n initial_state?: ICreateRoomStateEvent[];\n // A list of user IDs to invite to this room.\n invite?: string[];\n invite_3pid?: IInvite3PID[];\n is_direct?: boolean;\n room_version?: string;\n}\n\nexport interface IRoomDirectoryOptions {\n server?: string;\n limit?: number;\n since?: string;\n\n // Filter parameters\n filter?: {\n // String to search for\n generic_search_term?: string;\n room_types?: Array;\n };\n include_all_networks?: boolean;\n third_party_instance_id?: string;\n}\n\nexport interface IAddThreePidOnlyBody {\n auth?: {\n type: string;\n session?: string;\n };\n client_secret: string;\n sid: string;\n}\n\nexport interface IBindThreePidBody {\n client_secret: string;\n id_server: string;\n id_access_token: string;\n sid: string;\n}\n\nexport interface IRelationsRequestOpts {\n from?: string;\n to?: string;\n limit?: number;\n dir?: Direction;\n}\n\nexport interface IRelationsResponse {\n chunk: IEvent[];\n next_batch?: string;\n prev_batch?: string;\n}\n\nexport interface IContextResponse {\n end: string;\n start: string;\n state: IEventWithRoomId[];\n events_before: IEventWithRoomId[];\n events_after: IEventWithRoomId[];\n event: IEventWithRoomId;\n}\n\nexport interface IEventsResponse {\n chunk: IEventWithRoomId[];\n end: string;\n start: string;\n}\n\nexport interface INotification {\n actions: PushRuleAction[];\n event: IRoomEvent;\n profile_tag?: string;\n read: boolean;\n room_id: string;\n ts: number;\n}\n\nexport interface INotificationsResponse {\n next_token: string;\n notifications: INotification[];\n}\n\nexport interface IFilterResponse {\n filter_id: string;\n}\n\nexport interface ITagsResponse {\n tags: {\n [tagId: string]: {\n order: number;\n };\n };\n}\n\nexport interface IStatusResponse extends IPresenceOpts {\n currently_active?: boolean;\n last_active_ago?: number;\n}\n\n/* eslint-enable camelcase */\n", - "/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// Types relating to the /search API\n\nimport { IRoomEvent, IStateEvent } from \"../sync-accumulator\";\nimport { IRoomEventFilter } from \"../filter\";\nimport { SearchResult } from \"../models/search-result\";\n\n/* eslint-disable camelcase */\nexport interface IEventWithRoomId extends IRoomEvent {\n room_id: string;\n}\n\nexport interface IStateEventWithRoomId extends IStateEvent {\n room_id: string;\n}\n\nexport interface IMatrixProfile {\n avatar_url?: string;\n displayname?: string;\n}\n\nexport interface IResultContext {\n events_before: IEventWithRoomId[];\n events_after: IEventWithRoomId[];\n profile_info: Record;\n start?: string;\n end?: string;\n}\n\nexport interface ISearchResult {\n rank: number;\n result: IEventWithRoomId;\n context: IResultContext;\n}\n\nenum GroupKey {\n RoomId = \"room_id\",\n Sender = \"sender\",\n}\n\nexport interface IResultRoomEvents {\n count: number;\n highlights: string[];\n results: ISearchResult[];\n state?: { [roomId: string]: IStateEventWithRoomId[] };\n groups?: {\n [groupKey in GroupKey]: {\n [value: string]: {\n next_batch?: string;\n order: number;\n results: string[];\n };\n };\n };\n next_batch?: string;\n}\n\ninterface IResultCategories {\n room_events: IResultRoomEvents;\n}\n\nexport type SearchKey = \"content.body\" | \"content.name\" | \"content.topic\";\n\nexport enum SearchOrderBy {\n Recent = \"recent\",\n Rank = \"rank\",\n}\n\nexport interface ISearchRequestBody {\n search_categories: {\n room_events: {\n search_term: string;\n keys?: SearchKey[];\n filter?: IRoomEventFilter;\n order_by?: SearchOrderBy;\n event_context?: {\n before_limit?: number;\n after_limit?: number;\n include_profile?: boolean;\n };\n include_state?: boolean;\n groupings?: {\n group_by: {\n key: GroupKey;\n }[];\n };\n };\n };\n}\n\nexport interface ISearchResponse {\n search_categories: IResultCategories;\n}\n\nexport interface ISearchResults {\n _query?: ISearchRequestBody;\n results: SearchResult[];\n highlights: string[];\n count?: number;\n next_batch?: string;\n pendingRequest?: Promise;\n abortSignal?: AbortSignal;\n}\n/* eslint-enable camelcase */\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { ServerControlledNamespacedValue } from \"../NamespacedValue\";\n\n/**\n * https://github.com/matrix-org/matrix-doc/pull/3773\n *\n * @experimental\n */\nexport const UNREAD_THREAD_NOTIFICATIONS = new ServerControlledNamespacedValue(\n \"unread_thread_notifications\",\n \"org.matrix.msc3773.unread_thread_notifications\",\n);\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EitherAnd } from \"matrix-events-sdk\";\n\nimport { UnstableValue } from \"../NamespacedValue\";\nimport { IMessageRendering } from \"./extensible_events\";\n\n/**\n * Extensible topic event type based on MSC3765\n * https://github.com/matrix-org/matrix-spec-proposals/pull/3765\n *\n * @example\n * ```\n * {\n * \"type\": \"m.room.topic,\n * \"state_key\": \"\",\n * \"content\": {\n * \"topic\": \"All about **pizza**\",\n * \"m.topic\": [{\n * \"body\": \"All about **pizza**\",\n * \"mimetype\": \"text/plain\",\n * }, {\n * \"body\": \"All about pizza\",\n * \"mimetype\": \"text/html\",\n * }],\n * }\n * }\n * ```\n */\n\n/**\n * The event type for an m.topic event (in content)\n */\nexport const M_TOPIC = new UnstableValue(\"m.topic\", \"org.matrix.msc3765.topic\");\n\n/**\n * The event content for an m.topic event (in content)\n */\nexport type MTopicContent = IMessageRendering[];\n\n/**\n * The event definition for an m.topic event (in content)\n */\nexport type MTopicEvent = EitherAnd<{ [M_TOPIC.name]: MTopicContent }, { [M_TOPIC.altName]: MTopicContent }>;\n\n/**\n * The event content for an m.room.topic event\n */\nexport type MRoomTopicEventContent = { topic: string } & MTopicEvent;\n", - "/*\nCopyright 2021 - 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { Optional } from \"matrix-events-sdk/lib/types\";\n\n/**\n * Represents a simple Matrix namespaced value. This will assume that if a stable prefix\n * is provided that the stable prefix should be used when representing the identifier.\n */\nexport class NamespacedValue {\n // Stable is optional, but one of the two parameters is required, hence the weird-looking types.\n // Goal is to to have developers explicitly say there is no stable value (if applicable).\n public constructor(stable: S, unstable: U);\n public constructor(stable: S, unstable?: U);\n public constructor(stable: null | undefined, unstable: U);\n public constructor(public readonly stable?: S | null, public readonly unstable?: U) {\n if (!this.unstable && !this.stable) {\n throw new Error(\"One of stable or unstable values must be supplied\");\n }\n }\n\n public get name(): U | S {\n if (this.stable) {\n return this.stable;\n }\n return this.unstable!;\n }\n\n public get altName(): U | S | null | undefined {\n if (!this.stable) {\n return null;\n }\n return this.unstable;\n }\n\n public get names(): (U | S)[] {\n const names = [this.name];\n const altName = this.altName;\n if (altName) names.push(altName);\n return names;\n }\n\n public matches(val: string): boolean {\n return this.name === val || this.altName === val;\n }\n\n // this desperately wants https://github.com/microsoft/TypeScript/pull/26349 at the top level of the class\n // so we can instantiate `NamespacedValue` as a default type for that namespace.\n public findIn(obj: any): Optional {\n let val: T | undefined = undefined;\n if (this.name) {\n val = obj?.[this.name];\n }\n if (!val && this.altName) {\n val = obj?.[this.altName];\n }\n return val;\n }\n\n public includedIn(arr: any[]): boolean {\n let included = false;\n if (this.name) {\n included = arr.includes(this.name);\n }\n if (!included && this.altName) {\n included = arr.includes(this.altName);\n }\n return included;\n }\n}\n\nexport class ServerControlledNamespacedValue extends NamespacedValue {\n private preferUnstable = false;\n\n public setPreferUnstable(preferUnstable: boolean): void {\n this.preferUnstable = preferUnstable;\n }\n\n public get name(): U | S {\n if (this.stable && !this.preferUnstable) {\n return this.stable;\n }\n return this.unstable!;\n }\n}\n\n/**\n * Represents a namespaced value which prioritizes the unstable value over the stable\n * value.\n */\nexport class UnstableValue extends NamespacedValue {\n // Note: Constructor difference is that `unstable` is *required*.\n public constructor(stable: S, unstable: U) {\n super(stable, unstable);\n if (!this.unstable) {\n throw new Error(\"Unstable value must be supplied\");\n }\n }\n\n public get name(): U {\n return this.unstable!;\n }\n\n public get altName(): S {\n return this.stable!;\n }\n}\n", - "/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations Ltd\nCopyright 2017 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// eslint-disable-next-line no-restricted-imports\nimport { EventEmitter } from \"events\";\n\nimport { ListenerMap, TypedEventEmitter } from \"./models/typed-event-emitter\";\n\nexport class ReEmitter {\n public constructor(private readonly target: EventEmitter) {}\n\n // Map from emitter to event name to re-emitter\n private reEmitters = new Map void>>();\n\n public reEmit(source: EventEmitter, eventNames: string[]): void {\n let reEmittersByEvent = this.reEmitters.get(source);\n if (!reEmittersByEvent) {\n reEmittersByEvent = new Map();\n this.reEmitters.set(source, reEmittersByEvent);\n }\n\n for (const eventName of eventNames) {\n // We include the source as the last argument for event handlers which may need it,\n // such as read receipt listeners on the client class which won't have the context\n // of the room.\n const forSource = (...args: any[]): void => {\n // EventEmitter special cases 'error' to make the emit function throw if no\n // handler is attached, which sort of makes sense for making sure that something\n // handles an error, but for re-emitting, there could be a listener on the original\n // source object so the test doesn't really work. We *could* try to replicate the\n // same logic and throw if there is no listener on either the source or the target,\n // but this behaviour is fairly undesireable for us anyway: the main place we throw\n // 'error' events is for calls, where error events are usually emitted some time\n // later by a different part of the code where 'emit' throwing because the app hasn't\n // added an error handler isn't terribly helpful. (A better fix in retrospect may\n // have been to just avoid using the event name 'error', but backwards compat...)\n if (eventName === \"error\" && this.target.listenerCount(\"error\") === 0) return;\n this.target.emit(eventName, ...args, source);\n };\n source.on(eventName, forSource);\n reEmittersByEvent.set(eventName, forSource);\n }\n }\n\n public stopReEmitting(source: EventEmitter, eventNames: string[]): void {\n const reEmittersByEvent = this.reEmitters.get(source);\n if (!reEmittersByEvent) return; // We were never re-emitting these events in the first place\n\n for (const eventName of eventNames) {\n source.off(eventName, reEmittersByEvent.get(eventName)!);\n reEmittersByEvent.delete(eventName);\n }\n\n if (reEmittersByEvent.size === 0) this.reEmitters.delete(source);\n }\n}\n\nexport class TypedReEmitter> extends ReEmitter {\n public constructor(target: TypedEventEmitter) {\n super(target);\n }\n\n public reEmit(\n source: TypedEventEmitter,\n eventNames: T[],\n ): void {\n super.reEmit(source, eventNames);\n }\n\n public stopReEmitting(\n source: TypedEventEmitter,\n eventNames: T[],\n ): void {\n super.stopReEmitting(source, eventNames);\n }\n}\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { ToDeviceMessageId } from \"./@types/event\";\nimport { logger } from \"./logger\";\nimport { MatrixClient, ClientEvent } from \"./client\";\nimport { MatrixError } from \"./http-api\";\nimport { IndexedToDeviceBatch, ToDeviceBatch, ToDeviceBatchWithTxnId, ToDevicePayload } from \"./models/ToDeviceMessage\";\nimport { MatrixScheduler } from \"./scheduler\";\nimport { SyncState } from \"./sync\";\nimport { MapWithDefault } from \"./utils\";\n\nconst MAX_BATCH_SIZE = 20;\n\n/**\n * Maintains a queue of outgoing to-device messages, sending them\n * as soon as the homeserver is reachable.\n */\nexport class ToDeviceMessageQueue {\n private sending = false;\n private running = true;\n private retryTimeout: ReturnType | null = null;\n private retryAttempts = 0;\n\n public constructor(private client: MatrixClient) {}\n\n public start(): void {\n this.running = true;\n this.sendQueue();\n this.client.on(ClientEvent.Sync, this.onResumedSync);\n }\n\n public stop(): void {\n this.running = false;\n if (this.retryTimeout !== null) clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n this.client.removeListener(ClientEvent.Sync, this.onResumedSync);\n }\n\n public async queueBatch(batch: ToDeviceBatch): Promise {\n const batches: ToDeviceBatchWithTxnId[] = [];\n for (let i = 0; i < batch.batch.length; i += MAX_BATCH_SIZE) {\n const batchWithTxnId = {\n eventType: batch.eventType,\n batch: batch.batch.slice(i, i + MAX_BATCH_SIZE),\n txnId: this.client.makeTxnId(),\n };\n batches.push(batchWithTxnId);\n const msgmap = batchWithTxnId.batch.map(\n (msg) => `${msg.userId}/${msg.deviceId} (msgid ${msg.payload[ToDeviceMessageId]})`,\n );\n logger.info(\n `Enqueuing batch of to-device messages. type=${batch.eventType} txnid=${batchWithTxnId.txnId}`,\n msgmap,\n );\n }\n\n await this.client.store.saveToDeviceBatches(batches);\n this.sendQueue();\n }\n\n public sendQueue = async (): Promise => {\n if (this.retryTimeout !== null) clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n\n if (this.sending || !this.running) return;\n\n logger.debug(\"Attempting to send queued to-device messages\");\n\n this.sending = true;\n let headBatch: IndexedToDeviceBatch | null;\n try {\n while (this.running) {\n headBatch = await this.client.store.getOldestToDeviceBatch();\n if (headBatch === null) break;\n await this.sendBatch(headBatch);\n await this.client.store.removeToDeviceBatch(headBatch.id);\n this.retryAttempts = 0;\n }\n\n // Make sure we're still running after the async tasks: if not, stop.\n if (!this.running) return;\n\n logger.debug(\"All queued to-device messages sent\");\n } catch (e) {\n ++this.retryAttempts;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n // eslint-disable-next-line new-cap\n const retryDelay = MatrixScheduler.RETRY_BACKOFF_RATELIMIT(null, this.retryAttempts, e);\n if (retryDelay === -1) {\n // the scheduler function doesn't differentiate between fatal errors and just getting\n // bored and giving up for now\n if (Math.floor((e).httpStatus! / 100) === 4) {\n logger.error(\"Fatal error when sending to-device message - dropping to-device batch!\", e);\n await this.client.store.removeToDeviceBatch(headBatch!.id);\n } else {\n logger.info(\"Automatic retry limit reached for to-device messages.\");\n }\n return;\n }\n\n logger.info(`Failed to send batch of to-device messages. Will retry in ${retryDelay}ms`, e);\n this.retryTimeout = setTimeout(this.sendQueue, retryDelay);\n } finally {\n this.sending = false;\n }\n };\n\n /**\n * Attempts to send a batch of to-device messages.\n */\n private async sendBatch(batch: IndexedToDeviceBatch): Promise {\n const contentMap: MapWithDefault> = new MapWithDefault(() => new Map());\n for (const item of batch.batch) {\n contentMap.getOrCreate(item.userId).set(item.deviceId, item.payload);\n }\n\n logger.info(\n `Sending batch of ${batch.batch.length} to-device messages with ID ${batch.id} and txnId ${batch.txnId}`,\n );\n\n await this.client.sendToDevice(batch.eventType, contentMap, batch.txnId);\n }\n\n /**\n * Listen to sync state changes and automatically resend any pending events\n * once syncing is resumed\n */\n private onResumedSync = (state: SyncState | null, oldState: SyncState | null): void => {\n if (state === SyncState.Syncing && oldState !== SyncState.Syncing) {\n logger.info(`Resuming queue after resumed sync`);\n this.sendQueue();\n }\n };\n}\n", - "/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { IClientWellKnown, IWellKnownConfig } from \"./client\";\nimport { logger } from \"./logger\";\nimport { MatrixError, Method, timeoutSignal } from \"./http-api\";\n\n// Dev note: Auto discovery is part of the spec.\n// See: https://matrix.org/docs/spec/client_server/r0.4.0.html#server-discovery\n\nexport enum AutoDiscoveryAction {\n SUCCESS = \"SUCCESS\",\n IGNORE = \"IGNORE\",\n PROMPT = \"PROMPT\",\n FAIL_PROMPT = \"FAIL_PROMPT\",\n FAIL_ERROR = \"FAIL_ERROR\",\n}\n\nenum AutoDiscoveryError {\n Invalid = \"Invalid homeserver discovery response\",\n GenericFailure = \"Failed to get autodiscovery configuration from server\",\n InvalidHsBaseUrl = \"Invalid base_url for m.homeserver\",\n InvalidHomeserver = \"Homeserver URL does not appear to be a valid Matrix homeserver\",\n InvalidIsBaseUrl = \"Invalid base_url for m.identity_server\",\n InvalidIdentityServer = \"Identity server URL does not appear to be a valid identity server\",\n InvalidIs = \"Invalid identity server discovery response\",\n MissingWellknown = \"No .well-known JSON file found\",\n InvalidJson = \"Invalid JSON\",\n}\n\ninterface WellKnownConfig extends Omit {\n state: AutoDiscoveryAction;\n error?: IWellKnownConfig[\"error\"] | null;\n}\n\nexport interface ClientConfig extends Omit {\n \"m.homeserver\": WellKnownConfig;\n \"m.identity_server\": WellKnownConfig;\n}\n\n/**\n * Utilities for automatically discovery resources, such as homeservers\n * for users to log in to.\n */\nexport class AutoDiscovery {\n // Dev note: the constants defined here are related to but not\n // exactly the same as those in the spec. This is to hopefully\n // translate the meaning of the states in the spec, but also\n // support our own if needed.\n\n public static readonly ERROR_INVALID = AutoDiscoveryError.Invalid;\n\n public static readonly ERROR_GENERIC_FAILURE = AutoDiscoveryError.GenericFailure;\n\n public static readonly ERROR_INVALID_HS_BASE_URL = AutoDiscoveryError.InvalidHsBaseUrl;\n\n public static readonly ERROR_INVALID_HOMESERVER = AutoDiscoveryError.InvalidHomeserver;\n\n public static readonly ERROR_INVALID_IS_BASE_URL = AutoDiscoveryError.InvalidIsBaseUrl;\n\n public static readonly ERROR_INVALID_IDENTITY_SERVER = AutoDiscoveryError.InvalidIdentityServer;\n\n public static readonly ERROR_INVALID_IS = AutoDiscoveryError.InvalidIs;\n\n public static readonly ERROR_MISSING_WELLKNOWN = AutoDiscoveryError.MissingWellknown;\n\n public static readonly ERROR_INVALID_JSON = AutoDiscoveryError.InvalidJson;\n\n public static readonly ALL_ERRORS = Object.keys(AutoDiscoveryError);\n\n /**\n * The auto discovery failed. The client is expected to communicate\n * the error to the user and refuse logging in.\n */\n public static readonly FAIL_ERROR = AutoDiscoveryAction.FAIL_ERROR;\n\n /**\n * The auto discovery failed, however the client may still recover\n * from the problem. The client is recommended to that the same\n * action it would for PROMPT while also warning the user about\n * what went wrong. The client may also treat this the same as\n * a FAIL_ERROR state.\n */\n public static readonly FAIL_PROMPT = AutoDiscoveryAction.FAIL_PROMPT;\n\n /**\n * The auto discovery didn't fail but did not find anything of\n * interest. The client is expected to prompt the user for more\n * information, or fail if it prefers.\n */\n public static readonly PROMPT = AutoDiscoveryAction.PROMPT;\n\n /**\n * The auto discovery was successful.\n */\n public static readonly SUCCESS = AutoDiscoveryAction.SUCCESS;\n\n /**\n * Validates and verifies client configuration information for purposes\n * of logging in. Such information includes the homeserver URL\n * and identity server URL the client would want. Additional details\n * may also be included, and will be transparently brought into the\n * response object unaltered.\n * @param wellknown - The configuration object itself, as returned\n * by the .well-known auto-discovery endpoint.\n * @returns Promise which resolves to the verified\n * configuration, which may include error states. Rejects on unexpected\n * failure, not when verification fails.\n */\n public static async fromDiscoveryConfig(wellknown: IClientWellKnown): Promise {\n // Step 1 is to get the config, which is provided to us here.\n\n // We default to an error state to make the first few checks easier to\n // write. We'll update the properties of this object over the duration\n // of this function.\n const clientConfig: ClientConfig = {\n \"m.homeserver\": {\n state: AutoDiscovery.FAIL_ERROR,\n error: AutoDiscovery.ERROR_INVALID,\n base_url: null,\n },\n \"m.identity_server\": {\n // Technically, we don't have a problem with the identity server\n // config at this point.\n state: AutoDiscovery.PROMPT,\n error: null,\n base_url: null,\n },\n };\n\n if (!wellknown || !wellknown[\"m.homeserver\"]) {\n logger.error(\"No m.homeserver key in config\");\n\n clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID;\n\n return Promise.resolve(clientConfig);\n }\n\n if (!wellknown[\"m.homeserver\"][\"base_url\"]) {\n logger.error(\"No m.homeserver base_url in config\");\n\n clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;\n\n return Promise.resolve(clientConfig);\n }\n\n // Step 2: Make sure the homeserver URL is valid *looking*. We'll make\n // sure it points to a homeserver in Step 3.\n const hsUrl = this.sanitizeWellKnownUrl(wellknown[\"m.homeserver\"][\"base_url\"]);\n if (!hsUrl) {\n logger.error(\"Invalid base_url for m.homeserver\");\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HS_BASE_URL;\n return Promise.resolve(clientConfig);\n }\n\n // Step 3: Make sure the homeserver URL points to a homeserver.\n const hsVersions = await this.fetchWellKnownObject(`${hsUrl}/_matrix/client/versions`);\n if (!hsVersions || !hsVersions.raw?.[\"versions\"]) {\n logger.error(\"Invalid /versions response\");\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID_HOMESERVER;\n\n // Supply the base_url to the caller because they may be ignoring liveliness\n // errors, like this one.\n clientConfig[\"m.homeserver\"].base_url = hsUrl;\n\n return Promise.resolve(clientConfig);\n }\n\n // Step 4: Now that the homeserver looks valid, update our client config.\n clientConfig[\"m.homeserver\"] = {\n state: AutoDiscovery.SUCCESS,\n error: null,\n base_url: hsUrl,\n };\n\n // Step 5: Try to pull out the identity server configuration\n let isUrl: string | boolean = \"\";\n if (wellknown[\"m.identity_server\"]) {\n // We prepare a failing identity server response to save lines later\n // in this branch.\n const failingClientConfig: ClientConfig = {\n \"m.homeserver\": clientConfig[\"m.homeserver\"],\n \"m.identity_server\": {\n state: AutoDiscovery.FAIL_PROMPT,\n error: AutoDiscovery.ERROR_INVALID_IS,\n base_url: null,\n },\n };\n\n // Step 5a: Make sure the URL is valid *looking*. We'll make sure it\n // points to an identity server in Step 5b.\n isUrl = this.sanitizeWellKnownUrl(wellknown[\"m.identity_server\"][\"base_url\"]);\n if (!isUrl) {\n logger.error(\"Invalid base_url for m.identity_server\");\n failingClientConfig[\"m.identity_server\"].error = AutoDiscovery.ERROR_INVALID_IS_BASE_URL;\n return Promise.resolve(failingClientConfig);\n }\n\n // Step 5b: Verify there is an identity server listening on the provided\n // URL.\n const isResponse = await this.fetchWellKnownObject(`${isUrl}/_matrix/identity/v2`);\n if (!isResponse?.raw || isResponse.action !== AutoDiscoveryAction.SUCCESS) {\n logger.error(\"Invalid /v2 response\");\n failingClientConfig[\"m.identity_server\"].error = AutoDiscovery.ERROR_INVALID_IDENTITY_SERVER;\n\n // Supply the base_url to the caller because they may be ignoring\n // liveliness errors, like this one.\n failingClientConfig[\"m.identity_server\"].base_url = isUrl;\n\n return Promise.resolve(failingClientConfig);\n }\n }\n\n // Step 6: Now that the identity server is valid, or never existed,\n // populate the IS section.\n if (isUrl && isUrl.toString().length > 0) {\n clientConfig[\"m.identity_server\"] = {\n state: AutoDiscovery.SUCCESS,\n error: null,\n base_url: isUrl,\n };\n }\n\n // Step 7: Copy any other keys directly into the clientConfig. This is for\n // things like custom configuration of services.\n Object.keys(wellknown).forEach((k: keyof IClientWellKnown) => {\n if (k === \"m.homeserver\" || k === \"m.identity_server\") {\n // Only copy selected parts of the config to avoid overwriting\n // properties computed by the validation logic above.\n const notProps = [\"error\", \"state\", \"base_url\"];\n for (const prop of Object.keys(wellknown[k]!)) {\n if (notProps.includes(prop)) continue;\n type Prop = Exclude;\n // @ts-ignore - ts gets unhappy as we're mixing types here\n clientConfig[k][prop as Prop] = wellknown[k]![prop as Prop];\n }\n } else {\n // Just copy the whole thing over otherwise\n clientConfig[k] = wellknown[k];\n }\n });\n\n // Step 8: Give the config to the caller (finally)\n return Promise.resolve(clientConfig);\n }\n\n /**\n * Attempts to automatically discover client configuration information\n * prior to logging in. Such information includes the homeserver URL\n * and identity server URL the client would want. Additional details\n * may also be discovered, and will be transparently included in the\n * response object unaltered.\n * @param domain - The homeserver domain to perform discovery\n * on. For example, \"matrix.org\".\n * @returns Promise which resolves to the discovered\n * configuration, which may include error states. Rejects on unexpected\n * failure, not when discovery fails.\n */\n public static async findClientConfig(domain: string): Promise {\n if (!domain || typeof domain !== \"string\" || domain.length === 0) {\n throw new Error(\"'domain' must be a string of non-zero length\");\n }\n\n // We use a .well-known lookup for all cases. According to the spec, we\n // can do other discovery mechanisms if we want such as custom lookups\n // however we won't bother with that here (mostly because the spec only\n // supports .well-known right now).\n //\n // By using .well-known, we need to ensure we at least pull out a URL\n // for the homeserver. We don't really need an identity server configuration\n // but will return one anyways (with state PROMPT) to make development\n // easier for clients. If we can't get a homeserver URL, all bets are\n // off on the rest of the config and we'll assume it is invalid too.\n\n // We default to an error state to make the first few checks easier to\n // write. We'll update the properties of this object over the duration\n // of this function.\n const clientConfig: ClientConfig = {\n \"m.homeserver\": {\n state: AutoDiscovery.FAIL_ERROR,\n error: AutoDiscovery.ERROR_INVALID,\n base_url: null,\n },\n \"m.identity_server\": {\n // Technically, we don't have a problem with the identity server\n // config at this point.\n state: AutoDiscovery.PROMPT,\n error: null,\n base_url: null,\n },\n };\n\n // Step 1: Actually request the .well-known JSON file and make sure it\n // at least has a homeserver definition.\n const wellknown = await this.fetchWellKnownObject(`https://${domain}/.well-known/matrix/client`);\n if (!wellknown || wellknown.action !== AutoDiscoveryAction.SUCCESS) {\n logger.error(\"No response or error when parsing .well-known\");\n if (wellknown.reason) logger.error(wellknown.reason);\n if (wellknown.action === AutoDiscoveryAction.IGNORE) {\n clientConfig[\"m.homeserver\"] = {\n state: AutoDiscovery.PROMPT,\n error: null,\n base_url: null,\n };\n } else {\n // this can only ever be FAIL_PROMPT at this point.\n clientConfig[\"m.homeserver\"].state = AutoDiscovery.FAIL_PROMPT;\n clientConfig[\"m.homeserver\"].error = AutoDiscovery.ERROR_INVALID;\n }\n return Promise.resolve(clientConfig);\n }\n\n // Step 2: Validate and parse the config\n return AutoDiscovery.fromDiscoveryConfig(wellknown.raw!);\n }\n\n /**\n * Gets the raw discovery client configuration for the given domain name.\n * Should only be used if there's no validation to be done on the resulting\n * object, otherwise use findClientConfig().\n * @param domain - The domain to get the client config for.\n * @returns Promise which resolves to the domain's client config. Can\n * be an empty object.\n */\n public static async getRawClientConfig(domain?: string): Promise {\n if (!domain || typeof domain !== \"string\" || domain.length === 0) {\n throw new Error(\"'domain' must be a string of non-zero length\");\n }\n\n const response = await this.fetchWellKnownObject(`https://${domain}/.well-known/matrix/client`);\n if (!response) return {};\n return response.raw || {};\n }\n\n /**\n * Sanitizes a given URL to ensure it is either an HTTP or HTTP URL and\n * is suitable for the requirements laid out by .well-known auto discovery.\n * If valid, the URL will also be stripped of any trailing slashes.\n * @param url - The potentially invalid URL to sanitize.\n * @returns The sanitized URL or a falsey value if the URL is invalid.\n * @internal\n */\n private static sanitizeWellKnownUrl(url?: string | null): string | false {\n if (!url) return false;\n\n try {\n let parsed: URL | undefined;\n try {\n parsed = new URL(url);\n } catch (e) {\n logger.error(\"Could not parse url\", e);\n }\n\n if (!parsed?.hostname) return false;\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") return false;\n\n const port = parsed.port ? `:${parsed.port}` : \"\";\n const path = parsed.pathname ? parsed.pathname : \"\";\n let saferUrl = `${parsed.protocol}//${parsed.hostname}${port}${path}`;\n if (saferUrl.endsWith(\"/\")) {\n saferUrl = saferUrl.substring(0, saferUrl.length - 1);\n }\n return saferUrl;\n } catch (e) {\n logger.error(e);\n return false;\n }\n }\n\n private static fetch(resource: URL | string, options?: RequestInit): ReturnType {\n if (this.fetchFn) {\n return this.fetchFn(resource, options);\n }\n return global.fetch(resource, options);\n }\n\n private static fetchFn?: typeof global.fetch;\n\n public static setFetchFn(fetchFn: typeof global.fetch): void {\n AutoDiscovery.fetchFn = fetchFn;\n }\n\n /**\n * Fetches a JSON object from a given URL, as expected by all .well-known\n * related lookups. If the server gives a 404 then the `action` will be\n * IGNORE. If the server returns something that isn't JSON, the `action`\n * will be FAIL_PROMPT. For any other failure the `action` will be FAIL_PROMPT.\n *\n * The returned object will be a result of the call in object form with\n * the following properties:\n * raw: The JSON object returned by the server.\n * action: One of SUCCESS, IGNORE, or FAIL_PROMPT.\n * reason: Relatively human-readable description of what went wrong.\n * error: The actual Error, if one exists.\n * @param url - The URL to fetch a JSON object from.\n * @returns Promise which resolves to the returned state.\n * @internal\n */\n private static async fetchWellKnownObject(url: string): Promise {\n let response: Response;\n\n try {\n response = await AutoDiscovery.fetch(url, {\n method: Method.Get,\n signal: timeoutSignal(5000),\n });\n\n if (response.status === 404) {\n return {\n raw: {},\n action: AutoDiscoveryAction.IGNORE,\n reason: AutoDiscovery.ERROR_MISSING_WELLKNOWN,\n };\n }\n\n if (!response.ok) {\n return {\n raw: {},\n action: AutoDiscoveryAction.FAIL_PROMPT,\n reason: \"General failure\",\n };\n }\n } catch (err) {\n const error = err as AutoDiscoveryError | string | undefined;\n let reason = \"\";\n if (typeof error === \"object\") {\n reason = (error)?.message;\n }\n\n return {\n error,\n raw: {},\n action: AutoDiscoveryAction.FAIL_PROMPT,\n reason: reason || \"General failure\",\n };\n }\n\n try {\n return {\n raw: await response.json(),\n action: AutoDiscoveryAction.SUCCESS,\n };\n } catch (err) {\n const error = err as Error;\n return {\n error,\n raw: {},\n action: AutoDiscoveryAction.FAIL_PROMPT,\n reason:\n (error as MatrixError)?.name === \"SyntaxError\"\n ? AutoDiscovery.ERROR_INVALID_JSON\n : AutoDiscovery.ERROR_INVALID,\n };\n }\n }\n}\n", - "/*\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport * as matrixcs from \"./matrix\";\n\ntype BrowserMatrix = typeof matrixcs;\ndeclare global {\n /* eslint-disable no-var, camelcase */\n var __js_sdk_entrypoint: boolean;\n var matrixcs: BrowserMatrix;\n /* eslint-enable no-var */\n}\n\nif (global.__js_sdk_entrypoint) {\n throw new Error(\"Multiple matrix-js-sdk entrypoints detected!\");\n}\nglobal.__js_sdk_entrypoint = true;\n\n// just *accessing* indexedDB throws an exception in firefox with indexeddb disabled.\nlet indexedDB: IDBFactory | undefined;\ntry {\n indexedDB = global.indexedDB;\n} catch (e) {}\n\n// if our browser (appears to) support indexeddb, use an indexeddb crypto store.\nif (indexedDB) {\n matrixcs.setCryptoStoreFactory(() => new matrixcs.IndexedDBCryptoStore(indexedDB!, \"matrix-js-sdk:crypto\"));\n}\n\n// We export 3 things to make browserify happy as well as downstream projects.\n// It's awkward, but required.\nexport * from \"./matrix\";\nexport default matrixcs; // keep export for browserify package deps\nglobal.matrixcs = matrixcs;\n", - "/*\nCopyright 2015-2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixClient} for the public class.\n */\n\nimport { Optional } from \"matrix-events-sdk\";\n\nimport type { IDeviceKeys, IMegolmSessionData, IOneTimeKey } from \"./@types/crypto\";\nimport { ISyncStateData, SyncApi, SyncApiOptions, SyncState } from \"./sync\";\nimport {\n EventStatus,\n IContent,\n IDecryptOptions,\n IEvent,\n MatrixEvent,\n MatrixEventEvent,\n MatrixEventHandlerMap,\n} from \"./models/event\";\nimport { StubStore } from \"./store/stub\";\nimport { CallEvent, CallEventHandlerMap, createNewMatrixCall, MatrixCall, supportsMatrixCall } from \"./webrtc/call\";\nimport { Filter, IFilterDefinition, IRoomEventFilter } from \"./filter\";\nimport { CallEventHandlerEvent, CallEventHandler, CallEventHandlerEventHandlerMap } from \"./webrtc/callEventHandler\";\nimport { GroupCallEventHandlerEvent, GroupCallEventHandlerEventHandlerMap } from \"./webrtc/groupCallEventHandler\";\nimport * as utils from \"./utils\";\nimport { replaceParam, QueryDict, sleep, noUnsafeEventProps } from \"./utils\";\nimport { Direction, EventTimeline } from \"./models/event-timeline\";\nimport { IActionsObject, PushProcessor } from \"./pushprocessor\";\nimport { AutoDiscovery, AutoDiscoveryAction } from \"./autodiscovery\";\nimport * as olmlib from \"./crypto/olmlib\";\nimport { decodeBase64, encodeBase64 } from \"./crypto/olmlib\";\nimport { IExportedDevice as IExportedOlmDevice } from \"./crypto/OlmDevice\";\nimport { IOlmDevice } from \"./crypto/algorithms/megolm\";\nimport { TypedReEmitter } from \"./ReEmitter\";\nimport { IRoomEncryption, RoomList } from \"./crypto/RoomList\";\nimport { logger } from \"./logger\";\nimport { SERVICE_TYPES } from \"./service-types\";\nimport {\n HttpApiEvent,\n HttpApiEventHandlerMap,\n Upload,\n UploadOpts,\n MatrixError,\n MatrixHttpApi,\n Method,\n retryNetworkOperation,\n ClientPrefix,\n MediaPrefix,\n IdentityPrefix,\n IHttpOpts,\n FileType,\n UploadResponse,\n HTTPError,\n IRequestOpts,\n} from \"./http-api\";\nimport {\n Crypto,\n CryptoEvent,\n CryptoEventHandlerMap,\n fixBackupKey,\n ICryptoCallbacks,\n IBootstrapCrossSigningOpts,\n ICheckOwnCrossSigningTrustOpts,\n isCryptoAvailable,\n VerificationMethod,\n IRoomKeyRequestBody,\n} from \"./crypto\";\nimport { DeviceInfo } from \"./crypto/deviceinfo\";\nimport { decodeRecoveryKey } from \"./crypto/recoverykey\";\nimport { keyFromAuthData } from \"./crypto/key_passphrase\";\nimport { User, UserEvent, UserEventHandlerMap } from \"./models/user\";\nimport { getHttpUriForMxc } from \"./content-repo\";\nimport { SearchResult } from \"./models/search-result\";\nimport { DEHYDRATION_ALGORITHM, IDehydratedDevice, IDehydratedDeviceKeyInfo } from \"./crypto/dehydration\";\nimport {\n IKeyBackupInfo,\n IKeyBackupPrepareOpts,\n IKeyBackupRestoreOpts,\n IKeyBackupRestoreResult,\n IKeyBackupRoomSessions,\n IKeyBackupSession,\n} from \"./crypto/keybackup\";\nimport { IIdentityServerProvider } from \"./@types/IIdentityServerProvider\";\nimport { MatrixScheduler } from \"./scheduler\";\nimport { BeaconEvent, BeaconEventHandlerMap } from \"./models/beacon\";\nimport { IAuthData, IAuthDict } from \"./interactive-auth\";\nimport { IMinimalEvent, IRoomEvent, IStateEvent } from \"./sync-accumulator\";\nimport {\n CrossSigningKey,\n IAddSecretStorageKeyOpts,\n ICreateSecretStorageOpts,\n IEncryptedEventInfo,\n IImportRoomKeysOpts,\n IRecoveryKey,\n} from \"./crypto/api\";\nimport { EventTimelineSet } from \"./models/event-timeline-set\";\nimport { VerificationRequest } from \"./crypto/verification/request/VerificationRequest\";\nimport { VerificationBase as Verification } from \"./crypto/verification/Base\";\nimport * as ContentHelpers from \"./content-helpers\";\nimport { CrossSigningInfo, DeviceTrustLevel, ICacheCallbacks, UserTrustLevel } from \"./crypto/CrossSigning\";\nimport { Room, NotificationCountType, RoomEvent, RoomEventHandlerMap, RoomNameState } from \"./models/room\";\nimport { RoomMemberEvent, RoomMemberEventHandlerMap } from \"./models/room-member\";\nimport { RoomStateEvent, RoomStateEventHandlerMap } from \"./models/room-state\";\nimport {\n IAddThreePidOnlyBody,\n IBindThreePidBody,\n IContextResponse,\n ICreateRoomOpts,\n IEventSearchOpts,\n IGuestAccessOpts,\n IJoinRoomOpts,\n IPaginateOpts,\n IPresenceOpts,\n IRedactOpts,\n IRelationsRequestOpts,\n IRelationsResponse,\n IRoomDirectoryOptions,\n ISearchOpts,\n ISendEventResponse,\n INotificationsResponse,\n IFilterResponse,\n ITagsResponse,\n IStatusResponse,\n} from \"./@types/requests\";\nimport {\n EventType,\n LOCAL_NOTIFICATION_SETTINGS_PREFIX,\n MsgType,\n PUSHER_ENABLED,\n RelationType,\n RoomCreateTypeField,\n RoomType,\n UNSTABLE_MSC3088_ENABLED,\n UNSTABLE_MSC3088_PURPOSE,\n UNSTABLE_MSC3089_TREE_SUBTYPE,\n MSC3912_RELATION_BASED_REDACTIONS_PROP,\n} from \"./@types/event\";\nimport { IdServerUnbindResult, IImageInfo, Preset, Visibility } from \"./@types/partials\";\nimport { EventMapper, eventMapperFor, MapperOpts } from \"./event-mapper\";\nimport { randomString } from \"./randomstring\";\nimport { BackupManager, IKeyBackup, IKeyBackupCheck, IPreparedKeyBackupVersion, TrustInfo } from \"./crypto/backup\";\nimport { DEFAULT_TREE_POWER_LEVELS_TEMPLATE, MSC3089TreeSpace } from \"./models/MSC3089TreeSpace\";\nimport { ISignatures } from \"./@types/signed\";\nimport { IStore } from \"./store\";\nimport { ISecretRequest } from \"./crypto/SecretStorage\";\nimport {\n IEventWithRoomId,\n ISearchRequestBody,\n ISearchResponse,\n ISearchResults,\n IStateEventWithRoomId,\n SearchOrderBy,\n} from \"./@types/search\";\nimport { ISynapseAdminDeactivateResponse, ISynapseAdminWhoisResponse } from \"./@types/synapse\";\nimport { IHierarchyRoom } from \"./@types/spaces\";\nimport {\n IPusher,\n IPusherRequest,\n IPushRule,\n IPushRules,\n PushRuleAction,\n PushRuleActionName,\n PushRuleKind,\n RuleId,\n} from \"./@types/PushRules\";\nimport { IThreepid } from \"./@types/threepids\";\nimport { CryptoStore, OutgoingRoomKeyRequest } from \"./crypto/store/base\";\nimport { GroupCall, IGroupCallDataChannelOptions, GroupCallIntent, GroupCallType } from \"./webrtc/groupCall\";\nimport { MediaHandler } from \"./webrtc/mediaHandler\";\nimport { GroupCallEventHandler } from \"./webrtc/groupCallEventHandler\";\nimport { LoginTokenPostResponse, ILoginFlowsResponse, IRefreshTokenResponse, SSOAction } from \"./@types/auth\";\nimport { TypedEventEmitter } from \"./models/typed-event-emitter\";\nimport { MAIN_ROOM_TIMELINE, ReceiptType } from \"./@types/read_receipts\";\nimport { MSC3575SlidingSyncRequest, MSC3575SlidingSyncResponse, SlidingSync } from \"./sliding-sync\";\nimport { SlidingSyncSdk } from \"./sliding-sync-sdk\";\nimport {\n FeatureSupport,\n Thread,\n THREAD_RELATION_TYPE,\n determineFeatureSupport,\n ThreadFilterType,\n threadFilterTypeToFilter,\n} from \"./models/thread\";\nimport { MBeaconInfoEventContent, M_BEACON_INFO } from \"./@types/beacon\";\nimport { UnstableValue } from \"./NamespacedValue\";\nimport { ToDeviceMessageQueue } from \"./ToDeviceMessageQueue\";\nimport { ToDeviceBatch } from \"./models/ToDeviceMessage\";\nimport { IgnoredInvites } from \"./models/invites-ignorer\";\nimport { UIARequest, UIAResponse } from \"./@types/uia\";\nimport { LocalNotificationSettings } from \"./@types/local_notifications\";\nimport { buildFeatureSupportMap, Feature, ServerSupport } from \"./feature\";\nimport { CryptoBackend } from \"./common-crypto/CryptoBackend\";\nimport { RUST_SDK_STORE_PREFIX } from \"./rust-crypto/constants\";\nimport { CryptoApi } from \"./crypto-api\";\nimport { DeviceInfoMap } from \"./crypto/DeviceList\";\nimport { SecretStorageKeyDescription } from \"./secret-storage\";\n\nexport type Store = IStore;\n\nexport type ResetTimelineCallback = (roomId: string) => boolean;\n\nconst SCROLLBACK_DELAY_MS = 3000;\nexport const CRYPTO_ENABLED: boolean = isCryptoAvailable();\nconst CAPABILITIES_CACHE_MS = 21600000; // 6 hours - an arbitrary value\nconst TURN_CHECK_INTERVAL = 10 * 60 * 1000; // poll for turn credentials every 10 minutes\n\nexport const UNSTABLE_MSC3852_LAST_SEEN_UA = new UnstableValue(\n \"last_seen_user_agent\",\n \"org.matrix.msc3852.last_seen_user_agent\",\n);\n\ninterface IExportedDevice {\n olmDevice: IExportedOlmDevice;\n userId: string;\n deviceId: string;\n}\n\nexport interface IKeysUploadResponse {\n one_time_key_counts: {\n // eslint-disable-line camelcase\n [algorithm: string]: number;\n };\n}\n\nexport interface ICreateClientOpts {\n baseUrl: string;\n\n idBaseUrl?: string;\n\n /**\n * The data store used for sync data from the homeserver. If not specified,\n * this client will not store any HTTP responses. The `createClient` helper\n * will create a default store if needed.\n */\n store?: Store;\n\n /**\n * A store to be used for end-to-end crypto session data. If not specified,\n * end-to-end crypto will be disabled. The `createClient` helper will create\n * a default store if needed. Calls the factory supplied to\n * {@link setCryptoStoreFactory} if unspecified; or if no factory has been\n * specified, uses a default implementation (indexeddb in the browser,\n * in-memory otherwise).\n */\n cryptoStore?: CryptoStore;\n\n /**\n * The scheduler to use. If not\n * specified, this client will not retry requests on failure. This client\n * will supply its own processing function to\n * {@link MatrixScheduler#setProcessFunction}.\n */\n scheduler?: MatrixScheduler;\n\n /**\n * The function to invoke for HTTP requests.\n * Most supported environments have a global `fetch` registered to which this will fall back.\n */\n fetchFn?: typeof global.fetch;\n\n userId?: string;\n\n /**\n * A unique identifier for this device; used for tracking things like crypto\n * keys and access tokens. If not specified, end-to-end encryption will be\n * disabled.\n */\n deviceId?: string;\n\n accessToken?: string;\n\n /**\n * Identity server provider to retrieve the user's access token when accessing\n * the identity server. See also https://github.com/vector-im/element-web/issues/10615\n * which seeks to replace the previous approach of manual access tokens params\n * with this callback throughout the SDK.\n */\n identityServer?: IIdentityServerProvider;\n\n /**\n * The default maximum amount of\n * time to wait before timing out HTTP requests. If not specified, there is no timeout.\n */\n localTimeoutMs?: number;\n\n /**\n * Set to true to use\n * Authorization header instead of query param to send the access token to the server.\n *\n * Default false.\n */\n useAuthorizationHeader?: boolean;\n\n /**\n * Set to true to enable\n * improved timeline support, see {@link MatrixClient#getEventTimeline}.\n * It is disabled by default for compatibility with older clients - in particular to\n * maintain support for back-paginating the live timeline after a '/sync'\n * result with a gap.\n */\n timelineSupport?: boolean;\n\n /**\n * Extra query parameters to append\n * to all requests with this client. Useful for application services which require\n * `?user_id=`.\n */\n queryParams?: Record;\n\n /**\n * Device data exported with\n * \"exportDevice\" method that must be imported to recreate this device.\n * Should only be useful for devices with end-to-end crypto enabled.\n * If provided, deviceId and userId should **NOT** be provided at the top\n * level (they are present in the exported data).\n */\n deviceToImport?: IExportedDevice;\n\n /**\n * Key used to pickle olm objects or other sensitive data.\n */\n pickleKey?: string;\n\n verificationMethods?: Array;\n\n /**\n * Whether relaying calls through a TURN server should be forced. Default false.\n */\n forceTURN?: boolean;\n\n /**\n * Up to this many ICE candidates will be gathered when an incoming call arrives.\n * Gathering does not send data to the caller, but will communicate with the configured TURN\n * server. Default 0.\n */\n iceCandidatePoolSize?: number;\n\n /**\n * True to advertise support for call transfers to other parties on Matrix calls. Default false.\n */\n supportsCallTransfer?: boolean;\n\n /**\n * Whether to allow a fallback ICE server should be used for negotiating a\n * WebRTC connection if the homeserver doesn't provide any servers. Defaults to false.\n */\n fallbackICEServerAllowed?: boolean;\n\n /**\n * If true, to-device signalling for group calls will be encrypted\n * with Olm. Default: true.\n */\n useE2eForGroupCall?: boolean;\n\n cryptoCallbacks?: ICryptoCallbacks;\n\n /**\n * Method to generate room names for empty rooms and rooms names based on membership.\n * Defaults to a built-in English handler with basic pluralisation.\n */\n roomNameGenerator?: (roomId: string, state: RoomNameState) => string | null;\n\n /**\n * If true, participant can join group call without video and audio this has to be allowed. By default, a local\n * media stream is needed to establish a group call.\n * Default: false.\n */\n isVoipWithNoMediaAllowed?: boolean;\n}\n\nexport interface IMatrixClientCreateOpts extends ICreateClientOpts {\n /**\n * Whether to allow sending messages to encrypted rooms when encryption\n * is not available internally within this SDK. This is useful if you are using an external\n * E2E proxy, for example. Defaults to false.\n */\n usingExternalCrypto?: boolean;\n}\n\nexport enum PendingEventOrdering {\n Chronological = \"chronological\",\n Detached = \"detached\",\n}\n\nexport interface IStartClientOpts {\n /**\n * The event `limit=` to apply to initial sync. Default: 8.\n */\n initialSyncLimit?: number;\n\n /**\n * True to put `archived=true on the /initialSync` request. Default: false.\n */\n includeArchivedRooms?: boolean;\n\n /**\n * True to do /profile requests on every invite event if the displayname/avatar_url is not known for this user ID. Default: false.\n */\n resolveInvitesToProfiles?: boolean;\n\n /**\n * Controls where pending messages appear in a room's timeline. If \"chronological\", messages will\n * appear in the timeline when the call to `sendEvent` was made. If \"detached\",\n * pending messages will appear in a separate list, accessbile via {@link Room#getPendingEvents}.\n * Default: \"chronological\".\n */\n pendingEventOrdering?: PendingEventOrdering;\n\n /**\n * The number of milliseconds to wait on /sync. Default: 30000 (30 seconds).\n */\n pollTimeout?: number;\n\n /**\n * The filter to apply to /sync calls.\n */\n filter?: Filter;\n\n /**\n * True to perform syncing without automatically updating presence.\n */\n disablePresence?: boolean;\n\n /**\n * True to not load all membership events during initial sync but fetch them when needed by calling\n * `loadOutOfBandMembers` This will override the filter option at this moment.\n */\n lazyLoadMembers?: boolean;\n\n /**\n * The number of seconds between polls to /.well-known/matrix/client, undefined to disable.\n * This should be in the order of hours. Default: undefined.\n */\n clientWellKnownPollPeriod?: number;\n\n /**\n * @deprecated use `threadSupport` instead\n */\n experimentalThreadSupport?: boolean;\n\n /**\n * Will organises events in threaded conversations when\n * a thread relation is encountered\n */\n threadSupport?: boolean;\n\n /**\n * @experimental\n */\n slidingSync?: SlidingSync;\n\n /**\n * @experimental\n */\n intentionalMentions?: boolean;\n}\n\nexport interface IStoredClientOpts extends IStartClientOpts {}\n\nexport enum RoomVersionStability {\n Stable = \"stable\",\n Unstable = \"unstable\",\n}\n\nexport interface IRoomVersionsCapability {\n default: string;\n available: Record;\n}\n\nexport interface ICapability {\n enabled: boolean;\n}\n\nexport interface IChangePasswordCapability extends ICapability {}\n\nexport interface IThreadsCapability extends ICapability {}\n\ninterface ICapabilities {\n [key: string]: any;\n \"m.change_password\"?: IChangePasswordCapability;\n \"m.room_versions\"?: IRoomVersionsCapability;\n \"io.element.thread\"?: IThreadsCapability;\n}\n\n/* eslint-disable camelcase */\nexport interface ICrossSigningKey {\n keys: { [algorithm: string]: string };\n signatures?: ISignatures;\n usage: string[];\n user_id: string;\n}\n\nenum CrossSigningKeyType {\n MasterKey = \"master_key\",\n SelfSigningKey = \"self_signing_key\",\n UserSigningKey = \"user_signing_key\",\n}\n\nexport type CrossSigningKeys = Record;\n\nexport type SendToDeviceContentMap = Map>>;\n\nexport interface ISignedKey {\n keys: Record;\n signatures: ISignatures;\n user_id: string;\n algorithms: string[];\n device_id: string;\n}\n\nexport type KeySignatures = Record>;\nexport interface IUploadKeySignaturesResponse {\n failures: Record<\n string,\n Record<\n string,\n {\n errcode: string;\n error: string;\n }\n >\n >;\n}\n\nexport interface IPreviewUrlResponse {\n [key: string]: undefined | string | number;\n \"og:title\": string;\n \"og:type\": string;\n \"og:url\": string;\n \"og:image\"?: string;\n \"og:image:type\"?: string;\n \"og:image:height\"?: number;\n \"og:image:width\"?: number;\n \"og:description\"?: string;\n \"matrix:image:size\"?: number;\n}\n\nexport interface ITurnServerResponse {\n uris: string[];\n username: string;\n password: string;\n ttl: number;\n}\n\nexport interface ITurnServer {\n urls: string[];\n username: string;\n credential: string;\n}\n\nexport interface IServerVersions {\n versions: string[];\n unstable_features: Record;\n}\n\nexport const M_AUTHENTICATION = new UnstableValue(\"m.authentication\", \"org.matrix.msc2965.authentication\");\n\nexport interface IClientWellKnown {\n [key: string]: any;\n \"m.homeserver\"?: IWellKnownConfig;\n \"m.identity_server\"?: IWellKnownConfig;\n [M_AUTHENTICATION.name]?: IDelegatedAuthConfig; // MSC2965\n}\n\nexport interface IWellKnownConfig {\n raw?: IClientWellKnown;\n action?: AutoDiscoveryAction;\n reason?: string;\n error?: Error | string;\n // eslint-disable-next-line\n base_url?: string | null;\n // XXX: this is undocumented\n server_name?: string;\n}\n\nexport interface IDelegatedAuthConfig {\n // MSC2965\n /** The OIDC Provider/issuer the client should use */\n issuer: string;\n /** The optional URL of the web UI where the user can manage their account */\n account?: string;\n}\n\ninterface IKeyBackupPath {\n path: string;\n queryData?: {\n version: string;\n };\n}\n\ninterface IMediaConfig {\n [key: string]: any; // extensible\n \"m.upload.size\"?: number;\n}\n\ninterface IThirdPartySigned {\n sender: string;\n mxid: string;\n token: string;\n signatures: ISignatures;\n}\n\ninterface IJoinRequestBody {\n third_party_signed?: IThirdPartySigned;\n}\n\ninterface ITagMetadata {\n [key: string]: any;\n order: number;\n}\n\ninterface IMessagesResponse {\n start?: string;\n end?: string;\n chunk: IRoomEvent[];\n state?: IStateEvent[];\n}\n\ninterface IThreadedMessagesResponse {\n prev_batch: string;\n next_batch: string;\n chunk: IRoomEvent[];\n state: IStateEvent[];\n}\n\nexport interface IRequestTokenResponse {\n sid: string;\n submit_url?: string;\n}\n\nexport interface IRequestMsisdnTokenResponse extends IRequestTokenResponse {\n msisdn: string;\n success: boolean;\n intl_fmt: string;\n}\n\nexport interface IUploadKeysRequest {\n \"device_keys\"?: Required;\n \"one_time_keys\"?: Record;\n \"org.matrix.msc2732.fallback_keys\"?: Record;\n}\n\nexport interface IQueryKeysRequest {\n device_keys: { [userId: string]: string[] };\n timeout?: number;\n token?: string;\n}\n\nexport interface IClaimKeysRequest {\n one_time_keys: { [userId: string]: { [deviceId: string]: string } };\n timeout?: number;\n}\n\nexport interface IOpenIDToken {\n access_token: string;\n token_type: \"Bearer\" | string;\n matrix_server_name: string;\n expires_in: number;\n}\n\ninterface IRoomInitialSyncResponse {\n room_id: string;\n membership: \"invite\" | \"join\" | \"leave\" | \"ban\";\n messages?: {\n start?: string;\n end?: string;\n chunk: IEventWithRoomId[];\n };\n state?: IStateEventWithRoomId[];\n visibility: Visibility;\n account_data?: IMinimalEvent[];\n presence: Partial; // legacy and undocumented, api is deprecated so this won't get attention\n}\n\ninterface IJoinedRoomsResponse {\n joined_rooms: string[];\n}\n\ninterface IJoinedMembersResponse {\n joined: {\n [userId: string]: {\n display_name: string;\n avatar_url: string;\n };\n };\n}\n\nexport interface IRegisterRequestParams {\n auth?: IAuthData;\n username?: string;\n password?: string;\n refresh_token?: boolean;\n guest_access_token?: string;\n x_show_msisdn?: boolean;\n bind_msisdn?: boolean;\n bind_email?: boolean;\n inhibit_login?: boolean;\n initial_device_display_name?: string;\n}\n\nexport interface IPublicRoomsChunkRoom {\n room_id: string;\n name?: string;\n avatar_url?: string;\n topic?: string;\n canonical_alias?: string;\n aliases?: string[];\n world_readable: boolean;\n guest_can_join: boolean;\n num_joined_members: number;\n room_type?: RoomType | string; // Added by MSC3827\n}\n\ninterface IPublicRoomsResponse {\n chunk: IPublicRoomsChunkRoom[];\n next_batch?: string;\n prev_batch?: string;\n total_room_count_estimate?: number;\n}\n\ninterface IUserDirectoryResponse {\n results: {\n user_id: string;\n display_name?: string;\n avatar_url?: string;\n }[];\n limited: boolean;\n}\n\nexport interface IMyDevice {\n \"device_id\": string;\n \"display_name\"?: string;\n \"last_seen_ip\"?: string;\n \"last_seen_ts\"?: number;\n // UNSTABLE_MSC3852_LAST_SEEN_UA\n \"last_seen_user_agent\"?: string;\n \"org.matrix.msc3852.last_seen_user_agent\"?: string;\n}\n\nexport interface Keys {\n keys: { [keyId: string]: string };\n usage: string[];\n user_id: string;\n}\n\nexport interface SigningKeys extends Keys {\n signatures: ISignatures;\n}\n\nexport interface DeviceKeys {\n [deviceId: string]: IDeviceKeys & {\n unsigned?: {\n device_display_name: string;\n };\n };\n}\n\nexport interface IDownloadKeyResult {\n failures: { [serverName: string]: object };\n device_keys: { [userId: string]: DeviceKeys };\n // the following three fields were added in 1.1\n master_keys?: { [userId: string]: Keys };\n self_signing_keys?: { [userId: string]: SigningKeys };\n user_signing_keys?: { [userId: string]: SigningKeys };\n}\n\nexport interface IClaimOTKsResult {\n failures: { [serverName: string]: object };\n one_time_keys: {\n [userId: string]: {\n [deviceId: string]: {\n [keyId: string]: {\n key: string;\n signatures: ISignatures;\n };\n };\n };\n };\n}\n\nexport interface IFieldType {\n regexp: string;\n placeholder: string;\n}\n\nexport interface IInstance {\n desc: string;\n icon?: string;\n fields: object;\n network_id: string;\n // XXX: this is undocumented but we rely on it: https://github.com/matrix-org/matrix-doc/issues/3203\n instance_id: string;\n}\n\nexport interface IProtocol {\n user_fields: string[];\n location_fields: string[];\n icon: string;\n field_types: Record;\n instances: IInstance[];\n}\n\ninterface IThirdPartyLocation {\n alias: string;\n protocol: string;\n fields: object;\n}\n\ninterface IThirdPartyUser {\n userid: string;\n protocol: string;\n fields: object;\n}\n\ninterface IRoomSummary extends Omit {\n room_type?: RoomType;\n membership?: string;\n is_encrypted: boolean;\n}\n\ninterface IRoomKeysResponse {\n sessions: IKeyBackupRoomSessions;\n}\n\ninterface IRoomsKeysResponse {\n rooms: Record;\n}\n\ninterface IRoomHierarchy {\n rooms: IHierarchyRoom[];\n next_batch?: string;\n}\n\nexport interface TimestampToEventResponse {\n event_id: string;\n origin_server_ts: string;\n}\n\ninterface IWhoamiResponse {\n user_id: string;\n device_id?: string;\n}\n/* eslint-enable camelcase */\n\n// We're using this constant for methods overloading and inspect whether a variable\n// contains an eventId or not. This was required to ensure backwards compatibility\n// of methods for threads\n// Probably not the most graceful solution but does a good enough job for now\nconst EVENT_ID_PREFIX = \"$\";\n\nexport enum ClientEvent {\n Sync = \"sync\",\n Event = \"event\",\n ToDeviceEvent = \"toDeviceEvent\",\n AccountData = \"accountData\",\n Room = \"Room\",\n DeleteRoom = \"deleteRoom\",\n SyncUnexpectedError = \"sync.unexpectedError\",\n ClientWellKnown = \"WellKnown.client\",\n ReceivedVoipEvent = \"received_voip_event\",\n UndecryptableToDeviceEvent = \"toDeviceEvent.undecryptable\",\n TurnServers = \"turnServers\",\n TurnServersError = \"turnServers.error\",\n}\n\ntype RoomEvents =\n | RoomEvent.Name\n | RoomEvent.Redaction\n | RoomEvent.RedactionCancelled\n | RoomEvent.Receipt\n | RoomEvent.Tags\n | RoomEvent.LocalEchoUpdated\n | RoomEvent.HistoryImportedWithinTimeline\n | RoomEvent.AccountData\n | RoomEvent.MyMembership\n | RoomEvent.Timeline\n | RoomEvent.TimelineReset;\n\ntype RoomStateEvents =\n | RoomStateEvent.Events\n | RoomStateEvent.Members\n | RoomStateEvent.NewMember\n | RoomStateEvent.Update\n | RoomStateEvent.Marker;\n\ntype CryptoEvents =\n | CryptoEvent.KeySignatureUploadFailure\n | CryptoEvent.KeyBackupStatus\n | CryptoEvent.KeyBackupFailed\n | CryptoEvent.KeyBackupSessionsRemaining\n | CryptoEvent.RoomKeyRequest\n | CryptoEvent.RoomKeyRequestCancellation\n | CryptoEvent.VerificationRequest\n | CryptoEvent.DeviceVerificationChanged\n | CryptoEvent.UserTrustStatusChanged\n | CryptoEvent.KeysChanged\n | CryptoEvent.Warning\n | CryptoEvent.DevicesUpdated\n | CryptoEvent.WillUpdateDevices;\n\ntype MatrixEventEvents = MatrixEventEvent.Decrypted | MatrixEventEvent.Replaced | MatrixEventEvent.VisibilityChange;\n\ntype RoomMemberEvents =\n | RoomMemberEvent.Name\n | RoomMemberEvent.Typing\n | RoomMemberEvent.PowerLevel\n | RoomMemberEvent.Membership;\n\ntype UserEvents =\n | UserEvent.AvatarUrl\n | UserEvent.DisplayName\n | UserEvent.Presence\n | UserEvent.CurrentlyActive\n | UserEvent.LastPresenceTs;\n\nexport type EmittedEvents =\n | ClientEvent\n | RoomEvents\n | RoomStateEvents\n | CryptoEvents\n | MatrixEventEvents\n | RoomMemberEvents\n | UserEvents\n | CallEvent // re-emitted by call.ts using Object.values\n | CallEventHandlerEvent.Incoming\n | GroupCallEventHandlerEvent.Incoming\n | GroupCallEventHandlerEvent.Outgoing\n | GroupCallEventHandlerEvent.Ended\n | GroupCallEventHandlerEvent.Participants\n | HttpApiEvent.SessionLoggedOut\n | HttpApiEvent.NoConsent\n | BeaconEvent;\n\nexport type ClientEventHandlerMap = {\n /**\n * Fires whenever the SDK's syncing state is updated. The state can be one of:\n *
    \n *\n *
  • PREPARED: The client has synced with the server at least once and is\n * ready for methods to be called on it. This will be immediately followed by\n * a state of SYNCING. This is the equivalent of \"syncComplete\" in the\n * previous API.
  • \n *\n *
  • CATCHUP: The client has detected the connection to the server might be\n * available again and will now try to do a sync again. As this sync might take\n * a long time (depending how long ago was last synced, and general server\n * performance) the client is put in this mode so the UI can reflect trying\n * to catch up with the server after losing connection.
  • \n *\n *
  • SYNCING : The client is currently polling for new events from the server.\n * This will be called after processing latest events from a sync.
  • \n *\n *
  • ERROR : The client has had a problem syncing with the server. If this is\n * called before PREPARED then there was a problem performing the initial\n * sync. If this is called after PREPARED then there was a problem polling\n * the server for updates. This may be called multiple times even if the state is\n * already ERROR. This is the equivalent of \"syncError\" in the previous\n * API.
  • \n *\n *
  • RECONNECTING: The sync connection has dropped, but not (yet) in a way that\n * should be considered erroneous.\n *
  • \n *\n *
  • STOPPED: The client has stopped syncing with server due to stopClient\n * being called.\n *
  • \n *
\n * State transition diagram:\n * ```\n * +---->STOPPED\n * |\n * +----->PREPARED -------> SYNCING <--+\n * | ^ | ^ |\n * | CATCHUP ----------+ | | |\n * | ^ V | |\n * null ------+ | +------- RECONNECTING |\n * | V V |\n * +------->ERROR ---------------------+\n *\n * NB: 'null' will never be emitted by this event.\n *\n * ```\n * Transitions:\n *
    \n *\n *
  • `null -> PREPARED` : Occurs when the initial sync is completed\n * first time. This involves setting up filters and obtaining push rules.\n *\n *
  • `null -> ERROR` : Occurs when the initial sync failed first time.\n *\n *
  • `ERROR -> PREPARED` : Occurs when the initial sync succeeds\n * after previously failing.\n *\n *
  • `PREPARED -> SYNCING` : Occurs immediately after transitioning\n * to PREPARED. Starts listening for live updates rather than catching up.\n *\n *
  • `SYNCING -> RECONNECTING` : Occurs when the live update fails.\n *\n *
  • `RECONNECTING -> RECONNECTING` : Can occur if the update calls\n * continue to fail, but the keepalive calls (to /versions) succeed.\n *\n *
  • `RECONNECTING -> ERROR` : Occurs when the keepalive call also fails\n *\n *
  • `ERROR -> SYNCING` : Occurs when the client has performed a\n * live update after having previously failed.\n *\n *
  • `ERROR -> ERROR` : Occurs when the client has failed to keepalive\n * for a second time or more.
  • \n *\n *
  • `SYNCING -> SYNCING` : Occurs when the client has performed a live\n * update. This is called after processing.
  • \n *\n *
  • `* -> STOPPED` : Occurs once the client has stopped syncing or\n * trying to sync after stopClient has been called.
  • \n *
\n *\n * @param state - An enum representing the syncing state. One of \"PREPARED\",\n * \"SYNCING\", \"ERROR\", \"STOPPED\".\n *\n * @param prevState - An enum representing the previous syncing state.\n * One of \"PREPARED\", \"SYNCING\", \"ERROR\", \"STOPPED\" or null.\n *\n * @param data - Data about this transition.\n *\n * @example\n * ```\n * matrixClient.on(\"sync\", function(state, prevState, data) {\n * switch (state) {\n * case \"ERROR\":\n * // update UI to say \"Connection Lost\"\n * break;\n * case \"SYNCING\":\n * // update UI to remove any \"Connection Lost\" message\n * break;\n * case \"PREPARED\":\n * // the client instance is ready to be queried.\n * var rooms = matrixClient.getRooms();\n * break;\n * }\n * });\n * ```\n */\n [ClientEvent.Sync]: (state: SyncState, lastState: SyncState | null, data?: ISyncStateData) => void;\n /**\n * Fires whenever the SDK receives a new event.\n *

\n * This is only fired for live events received via /sync - it is not fired for\n * events received over context, search, or pagination APIs.\n *\n * @param event - The matrix event which caused this event to fire.\n * @example\n * ```\n * matrixClient.on(\"event\", function(event){\n * var sender = event.getSender();\n * });\n * ```\n */\n [ClientEvent.Event]: (event: MatrixEvent) => void;\n /**\n * Fires whenever the SDK receives a new to-device event.\n * @param event - The matrix event which caused this event to fire.\n * @example\n * ```\n * matrixClient.on(\"toDeviceEvent\", function(event){\n * var sender = event.getSender();\n * });\n * ```\n */\n [ClientEvent.ToDeviceEvent]: (event: MatrixEvent) => void;\n /**\n * Fires if a to-device event is received that cannot be decrypted.\n * Encrypted to-device events will (generally) use plain Olm encryption,\n * in which case decryption failures are fatal: the event will never be\n * decryptable, unlike Megolm encrypted events where the key may simply\n * arrive later.\n *\n * An undecryptable to-device event is therefore likley to indicate problems.\n *\n * @param event - The undecyptable to-device event\n */\n [ClientEvent.UndecryptableToDeviceEvent]: (event: MatrixEvent) => void;\n /**\n * Fires whenever new user-scoped account_data is added.\n * @param event - The event describing the account_data just added\n * @param event - The previous account data, if known.\n * @example\n * ```\n * matrixClient.on(\"accountData\", function(event, oldEvent){\n * myAccountData[event.type] = event.content;\n * });\n * ```\n */\n [ClientEvent.AccountData]: (event: MatrixEvent, lastEvent?: MatrixEvent) => void;\n /**\n * Fires whenever a new Room is added. This will fire when you are invited to a\n * room, as well as when you join a room. This event is experimental and\n * may change.\n * @param room - The newly created, fully populated room.\n * @example\n * ```\n * matrixClient.on(\"Room\", function(room){\n * var roomId = room.roomId;\n * });\n * ```\n */\n [ClientEvent.Room]: (room: Room) => void;\n /**\n * Fires whenever a Room is removed. This will fire when you forget a room.\n * This event is experimental and may change.\n * @param roomId - The deleted room ID.\n * @example\n * ```\n * matrixClient.on(\"deleteRoom\", function(roomId){\n * // update UI from getRooms()\n * });\n * ```\n */\n [ClientEvent.DeleteRoom]: (roomId: string) => void;\n [ClientEvent.SyncUnexpectedError]: (error: Error) => void;\n /**\n * Fires when the client .well-known info is fetched.\n *\n * @param data - The JSON object returned by the server\n */\n [ClientEvent.ClientWellKnown]: (data: IClientWellKnown) => void;\n [ClientEvent.ReceivedVoipEvent]: (event: MatrixEvent) => void;\n [ClientEvent.TurnServers]: (servers: ITurnServer[]) => void;\n [ClientEvent.TurnServersError]: (error: Error, fatal: boolean) => void;\n} & RoomEventHandlerMap &\n RoomStateEventHandlerMap &\n CryptoEventHandlerMap &\n MatrixEventHandlerMap &\n RoomMemberEventHandlerMap &\n UserEventHandlerMap &\n CallEventHandlerEventHandlerMap &\n GroupCallEventHandlerEventHandlerMap &\n CallEventHandlerMap &\n HttpApiEventHandlerMap &\n BeaconEventHandlerMap;\n\nconst SSO_ACTION_PARAM = new UnstableValue(\"action\", \"org.matrix.msc3824.action\");\n\n/**\n * Represents a Matrix Client. Only directly construct this if you want to use\n * custom modules. Normally, {@link createClient} should be used\n * as it specifies 'sensible' defaults for these modules.\n */\nexport class MatrixClient extends TypedEventEmitter {\n public static readonly RESTORE_BACKUP_ERROR_BAD_KEY = \"RESTORE_BACKUP_ERROR_BAD_KEY\";\n\n public reEmitter = new TypedReEmitter(this);\n public olmVersion: [number, number, number] | null = null; // populated after initCrypto\n public usingExternalCrypto = false;\n public store: Store;\n public deviceId: string | null;\n public credentials: { userId: string | null };\n public pickleKey?: string;\n public scheduler?: MatrixScheduler;\n public clientRunning = false;\n public timelineSupport = false;\n public urlPreviewCache: { [key: string]: Promise } = {};\n public identityServer?: IIdentityServerProvider;\n public http: MatrixHttpApi; // XXX: Intended private, used in code.\n\n /**\n * The libolm crypto implementation, if it is in use.\n *\n * @deprecated This should not be used. Instead, use the methods exposed directly on this class or\n * (where they are available) via {@link getCrypto}.\n */\n public crypto?: Crypto; // XXX: Intended private, used in code. Being replaced by cryptoBackend\n\n private cryptoBackend?: CryptoBackend; // one of crypto or rustCrypto\n public cryptoCallbacks: ICryptoCallbacks; // XXX: Intended private, used in code.\n public callEventHandler?: CallEventHandler; // XXX: Intended private, used in code.\n public groupCallEventHandler?: GroupCallEventHandler;\n public supportsCallTransfer = false; // XXX: Intended private, used in code.\n public forceTURN = false; // XXX: Intended private, used in code.\n public iceCandidatePoolSize = 0; // XXX: Intended private, used in code.\n public idBaseUrl?: string;\n public baseUrl: string;\n public readonly isVoipWithNoMediaAllowed;\n\n // Note: these are all `protected` to let downstream consumers make mistakes if they want to.\n // We don't technically support this usage, but have reasons to do this.\n\n protected canSupportVoip = false;\n protected peekSync: SyncApi | null = null;\n protected isGuestAccount = false;\n protected ongoingScrollbacks: { [roomId: string]: { promise?: Promise; errorTs?: number } } = {};\n protected notifTimelineSet: EventTimelineSet | null = null;\n protected cryptoStore?: CryptoStore;\n protected verificationMethods?: VerificationMethod[];\n protected fallbackICEServerAllowed = false;\n protected roomList: RoomList;\n protected syncApi?: SlidingSyncSdk | SyncApi;\n public roomNameGenerator?: ICreateClientOpts[\"roomNameGenerator\"];\n public pushRules?: IPushRules;\n protected syncLeftRoomsPromise?: Promise;\n protected syncedLeftRooms = false;\n protected clientOpts?: IStoredClientOpts;\n protected clientWellKnownIntervalID?: ReturnType;\n protected canResetTimelineCallback?: ResetTimelineCallback;\n\n public canSupport = new Map();\n\n // The pushprocessor caches useful things, so keep one and re-use it\n protected pushProcessor = new PushProcessor(this);\n\n // Promise to a response of the server's /versions response\n // TODO: This should expire: https://github.com/matrix-org/matrix-js-sdk/issues/1020\n protected serverVersionsPromise?: Promise;\n\n public cachedCapabilities?: {\n capabilities: ICapabilities;\n expiration: number;\n };\n protected clientWellKnown?: IClientWellKnown;\n protected clientWellKnownPromise?: Promise;\n protected turnServers: ITurnServer[] = [];\n protected turnServersExpiry = 0;\n protected checkTurnServersIntervalID?: ReturnType;\n protected exportedOlmDeviceToImport?: IExportedOlmDevice;\n protected txnCtr = 0;\n protected mediaHandler = new MediaHandler(this);\n protected sessionId: string;\n protected pendingEventEncryption = new Map>();\n\n private useE2eForGroupCall = true;\n private toDeviceMessageQueue: ToDeviceMessageQueue;\n\n // A manager for determining which invites should be ignored.\n public readonly ignoredInvites: IgnoredInvites;\n\n public constructor(opts: IMatrixClientCreateOpts) {\n super();\n\n opts.baseUrl = utils.ensureNoTrailingSlash(opts.baseUrl);\n opts.idBaseUrl = utils.ensureNoTrailingSlash(opts.idBaseUrl);\n\n this.baseUrl = opts.baseUrl;\n this.idBaseUrl = opts.idBaseUrl;\n this.identityServer = opts.identityServer;\n\n this.usingExternalCrypto = opts.usingExternalCrypto ?? false;\n this.store = opts.store || new StubStore();\n this.deviceId = opts.deviceId || null;\n this.sessionId = randomString(10);\n\n const userId = opts.userId || null;\n this.credentials = { userId };\n\n this.http = new MatrixHttpApi(this as ConstructorParameters[0], {\n fetchFn: opts.fetchFn,\n baseUrl: opts.baseUrl,\n idBaseUrl: opts.idBaseUrl,\n accessToken: opts.accessToken,\n prefix: ClientPrefix.R0,\n onlyData: true,\n extraParams: opts.queryParams,\n localTimeoutMs: opts.localTimeoutMs,\n useAuthorizationHeader: opts.useAuthorizationHeader,\n });\n\n if (opts.deviceToImport) {\n if (this.deviceId) {\n logger.warn(\n \"not importing device because device ID is provided to \" +\n \"constructor independently of exported data\",\n );\n } else if (this.credentials.userId) {\n logger.warn(\n \"not importing device because user ID is provided to \" +\n \"constructor independently of exported data\",\n );\n } else if (!opts.deviceToImport.deviceId) {\n logger.warn(\"not importing device because no device ID in exported data\");\n } else {\n this.deviceId = opts.deviceToImport.deviceId;\n this.credentials.userId = opts.deviceToImport.userId;\n // will be used during async initialization of the crypto\n this.exportedOlmDeviceToImport = opts.deviceToImport.olmDevice;\n }\n } else if (opts.pickleKey) {\n this.pickleKey = opts.pickleKey;\n }\n\n this.scheduler = opts.scheduler;\n if (this.scheduler) {\n this.scheduler.setProcessFunction(async (eventToSend: MatrixEvent) => {\n const room = this.getRoom(eventToSend.getRoomId());\n if (eventToSend.status !== EventStatus.SENDING) {\n this.updatePendingEventStatus(room, eventToSend, EventStatus.SENDING);\n }\n const res = await this.sendEventHttpRequest(eventToSend);\n if (room) {\n // ensure we update pending event before the next scheduler run so that any listeners to event id\n // updates on the synchronous event emitter get a chance to run first.\n room.updatePendingEvent(eventToSend, EventStatus.SENT, res.event_id);\n }\n return res;\n });\n }\n\n if (supportsMatrixCall()) {\n this.callEventHandler = new CallEventHandler(this);\n this.groupCallEventHandler = new GroupCallEventHandler(this);\n this.canSupportVoip = true;\n // Start listening for calls after the initial sync is done\n // We do not need to backfill the call event buffer\n // with encrypted events that might never get decrypted\n this.on(ClientEvent.Sync, this.startCallEventHandler);\n }\n\n this.on(ClientEvent.Sync, this.fixupRoomNotifications);\n\n this.timelineSupport = Boolean(opts.timelineSupport);\n\n this.cryptoStore = opts.cryptoStore;\n this.verificationMethods = opts.verificationMethods;\n this.cryptoCallbacks = opts.cryptoCallbacks || {};\n\n this.forceTURN = opts.forceTURN || false;\n this.iceCandidatePoolSize = opts.iceCandidatePoolSize === undefined ? 0 : opts.iceCandidatePoolSize;\n this.supportsCallTransfer = opts.supportsCallTransfer || false;\n this.fallbackICEServerAllowed = opts.fallbackICEServerAllowed || false;\n this.isVoipWithNoMediaAllowed = opts.isVoipWithNoMediaAllowed || false;\n\n if (opts.useE2eForGroupCall !== undefined) this.useE2eForGroupCall = opts.useE2eForGroupCall;\n\n // List of which rooms have encryption enabled: separate from crypto because\n // we still want to know which rooms are encrypted even if crypto is disabled:\n // we don't want to start sending unencrypted events to them.\n this.roomList = new RoomList(this.cryptoStore);\n this.roomNameGenerator = opts.roomNameGenerator;\n\n this.toDeviceMessageQueue = new ToDeviceMessageQueue(this);\n\n // The SDK doesn't really provide a clean way for events to recalculate the push\n // actions for themselves, so we have to kinda help them out when they are encrypted.\n // We do this so that push rules are correctly executed on events in their decrypted\n // state, such as highlights when the user's name is mentioned.\n this.on(MatrixEventEvent.Decrypted, (event) => {\n fixNotificationCountOnDecryption(this, event);\n });\n\n // Like above, we have to listen for read receipts from ourselves in order to\n // correctly handle notification counts on encrypted rooms.\n // This fixes https://github.com/vector-im/element-web/issues/9421\n this.on(RoomEvent.Receipt, (event, room) => {\n if (room && this.isRoomEncrypted(room.roomId)) {\n // Figure out if we've read something or if it's just informational\n const content = event.getContent();\n const isSelf =\n Object.keys(content).filter((eid) => {\n for (const [key, value] of Object.entries(content[eid])) {\n if (!utils.isSupportedReceiptType(key)) continue;\n if (!value) continue;\n\n if (Object.keys(value).includes(this.getUserId()!)) return true;\n }\n\n return false;\n }).length > 0;\n\n if (!isSelf) return;\n\n // Work backwards to determine how many events are unread. We also set\n // a limit for how back we'll look to avoid spinning CPU for too long.\n // If we hit the limit, we assume the count is unchanged.\n const maxHistory = 20;\n const events = room.getLiveTimeline().getEvents();\n\n let highlightCount = 0;\n\n for (let i = events.length - 1; i >= 0; i--) {\n if (i === events.length - maxHistory) return; // limit reached\n\n const event = events[i];\n\n if (room.hasUserReadEvent(this.getUserId()!, event.getId()!)) {\n // If the user has read the event, then the counting is done.\n break;\n }\n\n const pushActions = this.getPushActionsForEvent(event);\n highlightCount += pushActions?.tweaks?.highlight ? 1 : 0;\n }\n\n // Note: we don't need to handle 'total' notifications because the counts\n // will come from the server.\n room.setUnreadNotificationCount(NotificationCountType.Highlight, highlightCount);\n }\n });\n\n this.ignoredInvites = new IgnoredInvites(this);\n }\n\n /**\n * High level helper method to begin syncing and poll for new events. To listen for these\n * events, add a listener for {@link ClientEvent.Event}\n * via {@link MatrixClient#on}. Alternatively, listen for specific\n * state change events.\n * @param opts - Options to apply when syncing.\n */\n public async startClient(opts?: IStartClientOpts): Promise {\n if (this.clientRunning) {\n // client is already running.\n return;\n }\n this.clientRunning = true;\n // backwards compat for when 'opts' was 'historyLen'.\n if (typeof opts === \"number\") {\n opts = {\n initialSyncLimit: opts,\n };\n }\n\n // Create our own user object artificially (instead of waiting for sync)\n // so it's always available, even if the user is not in any rooms etc.\n const userId = this.getUserId();\n if (userId) {\n this.store.storeUser(new User(userId));\n }\n\n // periodically poll for turn servers if we support voip\n if (this.canSupportVoip) {\n this.checkTurnServersIntervalID = setInterval(() => {\n this.checkTurnServers();\n }, TURN_CHECK_INTERVAL);\n // noinspection ES6MissingAwait\n this.checkTurnServers();\n }\n\n if (this.syncApi) {\n // This shouldn't happen since we thought the client was not running\n logger.error(\"Still have sync object whilst not running: stopping old one\");\n this.syncApi.stop();\n }\n\n try {\n await this.getVersions();\n\n // This should be done with `canSupport`\n // TODO: https://github.com/vector-im/element-web/issues/23643\n const { threads, list, fwdPagination } = await this.doesServerSupportThread();\n Thread.setServerSideSupport(threads);\n Thread.setServerSideListSupport(list);\n Thread.setServerSideFwdPaginationSupport(fwdPagination);\n } catch (e) {\n logger.error(\"Can't fetch server versions, continuing to initialise sync, this will be retried later\", e);\n }\n\n this.clientOpts = opts ?? {};\n if (this.clientOpts.slidingSync) {\n this.syncApi = new SlidingSyncSdk(\n this.clientOpts.slidingSync,\n this,\n this.clientOpts,\n this.buildSyncApiOptions(),\n );\n } else {\n this.syncApi = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n }\n\n if (this.clientOpts.hasOwnProperty(\"experimentalThreadSupport\")) {\n logger.warn(\"`experimentalThreadSupport` has been deprecated, use `threadSupport` instead\");\n }\n\n // If `threadSupport` is omitted and the deprecated `experimentalThreadSupport` has been passed\n // We should fallback to that value for backwards compatibility purposes\n if (\n !this.clientOpts.hasOwnProperty(\"threadSupport\") &&\n this.clientOpts.hasOwnProperty(\"experimentalThreadSupport\")\n ) {\n this.clientOpts.threadSupport = this.clientOpts.experimentalThreadSupport;\n }\n\n this.syncApi.sync();\n\n if (this.clientOpts.clientWellKnownPollPeriod !== undefined) {\n this.clientWellKnownIntervalID = setInterval(() => {\n this.fetchClientWellKnown();\n }, 1000 * this.clientOpts.clientWellKnownPollPeriod);\n this.fetchClientWellKnown();\n }\n\n this.toDeviceMessageQueue.start();\n }\n\n /**\n * Construct a SyncApiOptions for this client, suitable for passing into the SyncApi constructor\n */\n protected buildSyncApiOptions(): SyncApiOptions {\n return {\n crypto: this.crypto,\n cryptoCallbacks: this.cryptoBackend,\n canResetEntireTimeline: (roomId: string): boolean => {\n if (!this.canResetTimelineCallback) {\n return false;\n }\n return this.canResetTimelineCallback(roomId);\n },\n };\n }\n\n /**\n * High level helper method to stop the client from polling and allow a\n * clean shutdown.\n */\n public stopClient(): void {\n this.cryptoBackend?.stop(); // crypto might have been initialised even if the client wasn't fully started\n\n if (!this.clientRunning) return; // already stopped\n\n logger.log(\"stopping MatrixClient\");\n\n this.clientRunning = false;\n\n this.syncApi?.stop();\n this.syncApi = undefined;\n\n this.peekSync?.stopPeeking();\n\n this.callEventHandler?.stop();\n this.groupCallEventHandler?.stop();\n this.callEventHandler = undefined;\n this.groupCallEventHandler = undefined;\n\n global.clearInterval(this.checkTurnServersIntervalID);\n this.checkTurnServersIntervalID = undefined;\n\n if (this.clientWellKnownIntervalID !== undefined) {\n global.clearInterval(this.clientWellKnownIntervalID);\n }\n\n this.toDeviceMessageQueue.stop();\n }\n\n /**\n * Try to rehydrate a device if available. The client must have been\n * initialized with a `cryptoCallback.getDehydrationKey` option, and this\n * function must be called before initCrypto and startClient are called.\n *\n * @returns Promise which resolves to undefined if a device could not be dehydrated, or\n * to the new device ID if the dehydration was successful.\n * @returns Rejects: with an error response.\n */\n public async rehydrateDevice(): Promise {\n if (this.crypto) {\n throw new Error(\"Cannot rehydrate device after crypto is initialized\");\n }\n\n if (!this.cryptoCallbacks.getDehydrationKey) {\n return;\n }\n\n const getDeviceResult = await this.getDehydratedDevice();\n if (!getDeviceResult) {\n return;\n }\n\n if (!getDeviceResult.device_data || !getDeviceResult.device_id) {\n logger.info(\"no dehydrated device found\");\n return;\n }\n\n const account = new global.Olm.Account();\n try {\n const deviceData = getDeviceResult.device_data;\n if (deviceData.algorithm !== DEHYDRATION_ALGORITHM) {\n logger.warn(\"Wrong algorithm for dehydrated device\");\n return;\n }\n logger.log(\"unpickling dehydrated device\");\n const key = await this.cryptoCallbacks.getDehydrationKey(deviceData, (k) => {\n // copy the key so that it doesn't get clobbered\n account.unpickle(new Uint8Array(k), deviceData.account);\n });\n account.unpickle(key, deviceData.account);\n logger.log(\"unpickled device\");\n\n const rehydrateResult = await this.http.authedRequest<{ success: boolean }>(\n Method.Post,\n \"/dehydrated_device/claim\",\n undefined,\n {\n device_id: getDeviceResult.device_id,\n },\n {\n prefix: \"/_matrix/client/unstable/org.matrix.msc2697.v2\",\n },\n );\n\n if (rehydrateResult.success) {\n this.deviceId = getDeviceResult.device_id;\n logger.info(\"using dehydrated device\");\n const pickleKey = this.pickleKey || \"DEFAULT_KEY\";\n this.exportedOlmDeviceToImport = {\n pickledAccount: account.pickle(pickleKey),\n sessions: [],\n pickleKey: pickleKey,\n };\n account.free();\n return this.deviceId;\n } else {\n account.free();\n logger.info(\"not using dehydrated device\");\n return;\n }\n } catch (e) {\n account.free();\n logger.warn(\"could not unpickle\", e);\n }\n }\n\n /**\n * Get the current dehydrated device, if any\n * @returns A promise of an object containing the dehydrated device\n */\n public async getDehydratedDevice(): Promise {\n try {\n return await this.http.authedRequest(\n Method.Get,\n \"/dehydrated_device\",\n undefined,\n undefined,\n {\n prefix: \"/_matrix/client/unstable/org.matrix.msc2697.v2\",\n },\n );\n } catch (e) {\n logger.info(\"could not get dehydrated device\", e);\n return;\n }\n }\n\n /**\n * Set the dehydration key. This will also periodically dehydrate devices to\n * the server.\n *\n * @param key - the dehydration key\n * @param keyInfo - Information about the key. Primarily for\n * information about how to generate the key from a passphrase.\n * @param deviceDisplayName - The device display name for the\n * dehydrated device.\n * @returns A promise that resolves when the dehydrated device is stored.\n */\n public async setDehydrationKey(\n key: Uint8Array,\n keyInfo: IDehydratedDeviceKeyInfo,\n deviceDisplayName?: string,\n ): Promise {\n if (!this.crypto) {\n logger.warn(\"not dehydrating device if crypto is not enabled\");\n return;\n }\n return this.crypto.dehydrationManager.setKeyAndQueueDehydration(key, keyInfo, deviceDisplayName);\n }\n\n /**\n * Creates a new dehydrated device (without queuing periodic dehydration)\n * @param key - the dehydration key\n * @param keyInfo - Information about the key. Primarily for\n * information about how to generate the key from a passphrase.\n * @param deviceDisplayName - The device display name for the\n * dehydrated device.\n * @returns the device id of the newly created dehydrated device\n */\n public async createDehydratedDevice(\n key: Uint8Array,\n keyInfo: IDehydratedDeviceKeyInfo,\n deviceDisplayName?: string,\n ): Promise {\n if (!this.crypto) {\n logger.warn(\"not dehydrating device if crypto is not enabled\");\n return;\n }\n await this.crypto.dehydrationManager.setKey(key, keyInfo, deviceDisplayName);\n return this.crypto.dehydrationManager.dehydrateDevice();\n }\n\n public async exportDevice(): Promise {\n if (!this.crypto) {\n logger.warn(\"not exporting device if crypto is not enabled\");\n return;\n }\n return {\n userId: this.credentials.userId!,\n deviceId: this.deviceId!,\n // XXX: Private member access.\n olmDevice: await this.crypto.olmDevice.export(),\n };\n }\n\n /**\n * Clear any data out of the persistent stores used by the client.\n *\n * @returns Promise which resolves when the stores have been cleared.\n */\n public clearStores(): Promise {\n if (this.clientRunning) {\n throw new Error(\"Cannot clear stores while client is running\");\n }\n\n const promises: Promise[] = [];\n\n promises.push(this.store.deleteAllData());\n if (this.cryptoStore) {\n promises.push(this.cryptoStore.deleteAllData());\n }\n\n // delete the stores used by the rust matrix-sdk-crypto, in case they were used\n const deleteRustSdkStore = async (): Promise => {\n let indexedDB: IDBFactory;\n try {\n indexedDB = global.indexedDB;\n } catch (e) {\n // No indexeddb support\n return;\n }\n for (const dbname of [\n `${RUST_SDK_STORE_PREFIX}::matrix-sdk-crypto`,\n `${RUST_SDK_STORE_PREFIX}::matrix-sdk-crypto-meta`,\n ]) {\n const prom = new Promise((resolve, reject) => {\n logger.info(`Removing IndexedDB instance ${dbname}`);\n const req = indexedDB.deleteDatabase(dbname);\n req.onsuccess = (_): void => {\n logger.info(`Removed IndexedDB instance ${dbname}`);\n resolve(0);\n };\n req.onerror = (e): void => {\n // In private browsing, Firefox has a global.indexedDB, but attempts to delete an indexeddb\n // (even a non-existent one) fail with \"DOMException: A mutation operation was attempted on a\n // database that did not allow mutations.\"\n //\n // it seems like the only thing we can really do is ignore the error.\n logger.warn(`Failed to remove IndexedDB instance ${dbname}:`, e);\n resolve(0);\n };\n req.onblocked = (e): void => {\n logger.info(`cannot yet remove IndexedDB instance ${dbname}`);\n };\n });\n await prom;\n }\n };\n promises.push(deleteRustSdkStore());\n\n return Promise.all(promises).then(); // .then to fix types\n }\n\n /**\n * Get the user-id of the logged-in user\n *\n * @returns MXID for the logged-in user, or null if not logged in\n */\n public getUserId(): string | null {\n if (this.credentials && this.credentials.userId) {\n return this.credentials.userId;\n }\n return null;\n }\n\n /**\n * Get the user-id of the logged-in user\n *\n * @returns MXID for the logged-in user\n * @throws Error if not logged in\n */\n public getSafeUserId(): string {\n const userId = this.getUserId();\n if (!userId) {\n throw new Error(\"Expected logged in user but found none.\");\n }\n return userId;\n }\n\n /**\n * Get the domain for this client's MXID\n * @returns Domain of this MXID\n */\n public getDomain(): string | null {\n if (this.credentials && this.credentials.userId) {\n return this.credentials.userId.replace(/^.*?:/, \"\");\n }\n return null;\n }\n\n /**\n * Get the local part of the current user ID e.g. \"foo\" in \"\\@foo:bar\".\n * @returns The user ID localpart or null.\n */\n public getUserIdLocalpart(): string | null {\n if (this.credentials && this.credentials.userId) {\n return this.credentials.userId.split(\":\")[0].substring(1);\n }\n return null;\n }\n\n /**\n * Get the device ID of this client\n * @returns device ID\n */\n public getDeviceId(): string | null {\n return this.deviceId;\n }\n\n /**\n * Get the session ID of this client\n * @returns session ID\n */\n public getSessionId(): string {\n return this.sessionId;\n }\n\n /**\n * Check if the runtime environment supports VoIP calling.\n * @returns True if VoIP is supported.\n */\n public supportsVoip(): boolean {\n return this.canSupportVoip;\n }\n\n /**\n * @returns\n */\n public getMediaHandler(): MediaHandler {\n return this.mediaHandler;\n }\n\n /**\n * Set whether VoIP calls are forced to use only TURN\n * candidates. This is the same as the forceTURN option\n * when creating the client.\n * @param force - True to force use of TURN servers\n */\n public setForceTURN(force: boolean): void {\n this.forceTURN = force;\n }\n\n /**\n * Set whether to advertise transfer support to other parties on Matrix calls.\n * @param support - True to advertise the 'm.call.transferee' capability\n */\n public setSupportsCallTransfer(support: boolean): void {\n this.supportsCallTransfer = support;\n }\n\n /**\n * Returns true if to-device signalling for group calls will be encrypted with Olm.\n * If false, it will be sent unencrypted.\n * @returns boolean Whether group call signalling will be encrypted\n */\n public getUseE2eForGroupCall(): boolean {\n return this.useE2eForGroupCall;\n }\n\n /**\n * Creates a new call.\n * The place*Call methods on the returned call can be used to actually place a call\n *\n * @param roomId - The room the call is to be placed in.\n * @returns the call or null if the browser doesn't support calling.\n */\n public createCall(roomId: string): MatrixCall | null {\n return createNewMatrixCall(this, roomId);\n }\n\n /**\n * Creates a new group call and sends the associated state event\n * to alert other members that the room now has a group call.\n *\n * @param roomId - The room the call is to be placed in.\n */\n public async createGroupCall(\n roomId: string,\n type: GroupCallType,\n isPtt: boolean,\n intent: GroupCallIntent,\n dataChannelsEnabled?: boolean,\n dataChannelOptions?: IGroupCallDataChannelOptions,\n ): Promise {\n if (this.getGroupCallForRoom(roomId)) {\n throw new Error(`${roomId} already has an existing group call`);\n }\n\n const room = this.getRoom(roomId);\n\n if (!room) {\n throw new Error(`Cannot find room ${roomId}`);\n }\n\n // Because without Media section a WebRTC connection is not possible, so need a RTCDataChannel to set up a\n // no media WebRTC connection anyway.\n return new GroupCall(\n this,\n room,\n type,\n isPtt,\n intent,\n undefined,\n dataChannelsEnabled || this.isVoipWithNoMediaAllowed,\n dataChannelOptions,\n this.isVoipWithNoMediaAllowed,\n ).create();\n }\n\n /**\n * Wait until an initial state for the given room has been processed by the\n * client and the client is aware of any ongoing group calls. Awaiting on\n * the promise returned by this method before calling getGroupCallForRoom()\n * avoids races where getGroupCallForRoom is called before the state for that\n * room has been processed. It does not, however, fix other races, eg. two\n * clients both creating a group call at the same time.\n * @param roomId - The room ID to wait for\n * @returns A promise that resolves once existing group calls in the room\n * have been processed.\n */\n public waitUntilRoomReadyForGroupCalls(roomId: string): Promise {\n return this.groupCallEventHandler!.waitUntilRoomReadyForGroupCalls(roomId);\n }\n\n /**\n * Get an existing group call for the provided room.\n * @returns The group call or null if it doesn't already exist.\n */\n public getGroupCallForRoom(roomId: string): GroupCall | null {\n return this.groupCallEventHandler!.groupCalls.get(roomId) || null;\n }\n\n /**\n * Get the current sync state.\n * @returns the sync state, which may be null.\n * @see MatrixClient#event:\"sync\"\n */\n public getSyncState(): SyncState | null {\n return this.syncApi?.getSyncState() ?? null;\n }\n\n /**\n * Returns the additional data object associated with\n * the current sync state, or null if there is no\n * such data.\n * Sync errors, if available, are put in the 'error' key of\n * this object.\n */\n public getSyncStateData(): ISyncStateData | null {\n if (!this.syncApi) {\n return null;\n }\n return this.syncApi.getSyncStateData();\n }\n\n /**\n * Whether the initial sync has completed.\n * @returns True if at least one sync has happened.\n */\n public isInitialSyncComplete(): boolean {\n const state = this.getSyncState();\n if (!state) {\n return false;\n }\n return state === SyncState.Prepared || state === SyncState.Syncing;\n }\n\n /**\n * Return whether the client is configured for a guest account.\n * @returns True if this is a guest access_token (or no token is supplied).\n */\n public isGuest(): boolean {\n return this.isGuestAccount;\n }\n\n /**\n * Set whether this client is a guest account. This method is experimental\n * and may change without warning.\n * @param guest - True if this is a guest account.\n */\n public setGuest(guest: boolean): void {\n // EXPERIMENTAL:\n // If the token is a macaroon, it should be encoded in it that it is a 'guest'\n // access token, which means that the SDK can determine this entirely without\n // the dev manually flipping this flag.\n this.isGuestAccount = guest;\n }\n\n /**\n * Return the provided scheduler, if any.\n * @returns The scheduler or undefined\n */\n public getScheduler(): MatrixScheduler | undefined {\n return this.scheduler;\n }\n\n /**\n * Retry a backed off syncing request immediately. This should only be used when\n * the user explicitly attempts to retry their lost connection.\n * Will also retry any outbound to-device messages currently in the queue to be sent\n * (retries of regular outgoing events are handled separately, per-event).\n * @returns True if this resulted in a request being retried.\n */\n public retryImmediately(): boolean {\n // don't await for this promise: we just want to kick it off\n this.toDeviceMessageQueue.sendQueue();\n return this.syncApi?.retryImmediately() ?? false;\n }\n\n /**\n * Return the global notification EventTimelineSet, if any\n *\n * @returns the globl notification EventTimelineSet\n */\n public getNotifTimelineSet(): EventTimelineSet | null {\n return this.notifTimelineSet;\n }\n\n /**\n * Set the global notification EventTimelineSet\n *\n */\n public setNotifTimelineSet(set: EventTimelineSet): void {\n this.notifTimelineSet = set;\n }\n\n /**\n * Gets the capabilities of the homeserver. Always returns an object of\n * capability keys and their options, which may be empty.\n * @param fresh - True to ignore any cached values.\n * @returns Promise which resolves to the capabilities of the homeserver\n * @returns Rejects: with an error response.\n */\n public getCapabilities(fresh = false): Promise {\n const now = new Date().getTime();\n\n if (this.cachedCapabilities && !fresh) {\n if (now < this.cachedCapabilities.expiration) {\n logger.log(\"Returning cached capabilities\");\n return Promise.resolve(this.cachedCapabilities.capabilities);\n }\n }\n\n type Response = {\n capabilities?: ICapabilities;\n };\n return this.http\n .authedRequest(Method.Get, \"/capabilities\")\n .catch((e: Error): Response => {\n // We swallow errors because we need a default object anyhow\n logger.error(e);\n return {};\n })\n .then((r = {}) => {\n const capabilities = r[\"capabilities\"] || {};\n\n // If the capabilities missed the cache, cache it for a shorter amount\n // of time to try and refresh them later.\n const cacheMs = Object.keys(capabilities).length ? CAPABILITIES_CACHE_MS : 60000 + Math.random() * 5000;\n\n this.cachedCapabilities = {\n capabilities,\n expiration: now + cacheMs,\n };\n\n logger.log(\"Caching capabilities: \", capabilities);\n return capabilities;\n });\n }\n\n /**\n * Initialise support for end-to-end encryption in this client, using libolm.\n *\n * You should call this method after creating the matrixclient, but *before*\n * calling `startClient`, if you want to support end-to-end encryption.\n *\n * It will return a Promise which will resolve when the crypto layer has been\n * successfully initialised.\n */\n public async initCrypto(): Promise {\n if (!isCryptoAvailable()) {\n throw new Error(\n `End-to-end encryption not supported in this js-sdk build: did ` +\n `you remember to load the olm library?`,\n );\n }\n\n if (this.cryptoBackend) {\n logger.warn(\"Attempt to re-initialise e2e encryption on MatrixClient\");\n return;\n }\n\n if (!this.cryptoStore) {\n // the cryptostore is provided by sdk.createClient, so this shouldn't happen\n throw new Error(`Cannot enable encryption: no cryptoStore provided`);\n }\n\n logger.log(\"Crypto: Starting up crypto store...\");\n await this.cryptoStore.startup();\n\n // initialise the list of encrypted rooms (whether or not crypto is enabled)\n logger.log(\"Crypto: initialising roomlist...\");\n await this.roomList.init();\n\n const userId = this.getUserId();\n if (userId === null) {\n throw new Error(\n `Cannot enable encryption on MatrixClient with unknown userId: ` +\n `ensure userId is passed in createClient().`,\n );\n }\n if (this.deviceId === null) {\n throw new Error(\n `Cannot enable encryption on MatrixClient with unknown deviceId: ` +\n `ensure deviceId is passed in createClient().`,\n );\n }\n\n const crypto = new Crypto(\n this,\n userId,\n this.deviceId,\n this.store,\n this.cryptoStore,\n this.roomList,\n this.verificationMethods!,\n );\n\n this.reEmitter.reEmit(crypto, [\n CryptoEvent.KeyBackupFailed,\n CryptoEvent.KeyBackupSessionsRemaining,\n CryptoEvent.RoomKeyRequest,\n CryptoEvent.RoomKeyRequestCancellation,\n CryptoEvent.Warning,\n CryptoEvent.DevicesUpdated,\n CryptoEvent.WillUpdateDevices,\n CryptoEvent.DeviceVerificationChanged,\n CryptoEvent.UserTrustStatusChanged,\n CryptoEvent.KeysChanged,\n ]);\n\n logger.log(\"Crypto: initialising crypto object...\");\n await crypto.init({\n exportedOlmDevice: this.exportedOlmDeviceToImport,\n pickleKey: this.pickleKey,\n });\n delete this.exportedOlmDeviceToImport;\n\n this.olmVersion = Crypto.getOlmVersion();\n\n // if crypto initialisation was successful, tell it to attach its event handlers.\n crypto.registerEventHandlers(this as Parameters[0]);\n this.cryptoBackend = this.crypto = crypto;\n\n // upload our keys in the background\n this.crypto.uploadDeviceKeys().catch((e) => {\n // TODO: throwing away this error is a really bad idea.\n logger.error(\"Error uploading device keys\", e);\n });\n }\n\n /**\n * Initialise support for end-to-end encryption in this client, using the rust matrix-sdk-crypto.\n *\n * An alternative to {@link initCrypto}.\n *\n * *WARNING*: this API is very experimental, should not be used in production, and may change without notice!\n * Eventually it will be deprecated and `initCrypto` will do the same thing.\n *\n * @experimental\n *\n * @returns a Promise which will resolve when the crypto layer has been\n * successfully initialised.\n */\n public async initRustCrypto(): Promise {\n if (this.cryptoBackend) {\n logger.warn(\"Attempt to re-initialise e2e encryption on MatrixClient\");\n return;\n }\n\n const userId = this.getUserId();\n if (userId === null) {\n throw new Error(\n `Cannot enable encryption on MatrixClient with unknown userId: ` +\n `ensure userId is passed in createClient().`,\n );\n }\n const deviceId = this.getDeviceId();\n if (deviceId === null) {\n throw new Error(\n `Cannot enable encryption on MatrixClient with unknown deviceId: ` +\n `ensure deviceId is passed in createClient().`,\n );\n }\n\n // importing rust-crypto will download the webassembly, so we delay it until we know it will be\n // needed.\n const RustCrypto = await import(\"./rust-crypto\");\n const rustCrypto = await RustCrypto.initRustCrypto(this.http, userId, deviceId);\n this.cryptoBackend = rustCrypto;\n\n // attach the event listeners needed by RustCrypto\n this.on(RoomMemberEvent.Membership, rustCrypto.onRoomMembership.bind(rustCrypto));\n }\n\n /**\n * Access the crypto API for this client.\n *\n * If end-to-end encryption has been enabled for this client (via {@link initCrypto} or {@link initRustCrypto}),\n * returns an object giving access to the crypto API. Otherwise, returns `undefined`.\n */\n public getCrypto(): CryptoApi | undefined {\n return this.cryptoBackend;\n }\n\n /**\n * Is end-to-end crypto enabled for this client.\n * @returns True if end-to-end is enabled.\n * @deprecated prefer {@link getCrypto}\n */\n public isCryptoEnabled(): boolean {\n return !!this.cryptoBackend;\n }\n\n /**\n * Get the Ed25519 key for this device\n *\n * @returns base64-encoded ed25519 key. Null if crypto is\n * disabled.\n */\n public getDeviceEd25519Key(): string | null {\n return this.crypto?.getDeviceEd25519Key() ?? null;\n }\n\n /**\n * Get the Curve25519 key for this device\n *\n * @returns base64-encoded curve25519 key. Null if crypto is\n * disabled.\n */\n public getDeviceCurve25519Key(): string | null {\n return this.crypto?.getDeviceCurve25519Key() ?? null;\n }\n\n /**\n * @deprecated Does nothing.\n */\n public async uploadKeys(): Promise {\n logger.warn(\"MatrixClient.uploadKeys is deprecated\");\n }\n\n /**\n * Download the keys for a list of users and stores the keys in the session\n * store.\n * @param userIds - The users to fetch.\n * @param forceDownload - Always download the keys even if cached.\n *\n * @returns A promise which resolves to a map userId-\\>deviceId-\\>{@link DeviceInfo}\n */\n public downloadKeys(userIds: string[], forceDownload?: boolean): Promise {\n if (!this.crypto) {\n return Promise.reject(new Error(\"End-to-end encryption disabled\"));\n }\n return this.crypto.downloadKeys(userIds, forceDownload);\n }\n\n /**\n * Get the stored device keys for a user id\n *\n * @param userId - the user to list keys for.\n *\n * @returns list of devices\n */\n public getStoredDevicesForUser(userId: string): DeviceInfo[] {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getStoredDevicesForUser(userId) || [];\n }\n\n /**\n * Get the stored device key for a user id and device id\n *\n * @param userId - the user to list keys for.\n * @param deviceId - unique identifier for the device\n *\n * @returns device or null\n */\n public getStoredDevice(userId: string, deviceId: string): DeviceInfo | null {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getStoredDevice(userId, deviceId) || null;\n }\n\n /**\n * Mark the given device as verified\n *\n * @param userId - owner of the device\n * @param deviceId - unique identifier for the device or user's\n * cross-signing public key ID.\n *\n * @param verified - whether to mark the device as verified. defaults\n * to 'true'.\n *\n * @returns\n *\n * @remarks\n * Fires {@link CryptoEvent#DeviceVerificationChanged}\n */\n public setDeviceVerified(userId: string, deviceId: string, verified = true): Promise {\n const prom = this.setDeviceVerification(userId, deviceId, verified, null, null);\n\n // if one of the user's own devices is being marked as verified / unverified,\n // check the key backup status, since whether or not we use this depends on\n // whether it has a signature from a verified device\n if (userId == this.credentials.userId) {\n this.checkKeyBackup();\n }\n return prom;\n }\n\n /**\n * Mark the given device as blocked/unblocked\n *\n * @param userId - owner of the device\n * @param deviceId - unique identifier for the device or user's\n * cross-signing public key ID.\n *\n * @param blocked - whether to mark the device as blocked. defaults\n * to 'true'.\n *\n * @returns\n *\n * @remarks\n * Fires {@link CryptoEvent.DeviceVerificationChanged}\n */\n public setDeviceBlocked(userId: string, deviceId: string, blocked = true): Promise {\n return this.setDeviceVerification(userId, deviceId, null, blocked, null);\n }\n\n /**\n * Mark the given device as known/unknown\n *\n * @param userId - owner of the device\n * @param deviceId - unique identifier for the device or user's\n * cross-signing public key ID.\n *\n * @param known - whether to mark the device as known. defaults\n * to 'true'.\n *\n * @returns\n *\n * @remarks\n * Fires {@link CryptoEvent#DeviceVerificationChanged}\n */\n public setDeviceKnown(userId: string, deviceId: string, known = true): Promise {\n return this.setDeviceVerification(userId, deviceId, null, null, known);\n }\n\n private async setDeviceVerification(\n userId: string,\n deviceId: string,\n verified?: boolean | null,\n blocked?: boolean | null,\n known?: boolean | null,\n ): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n await this.crypto.setDeviceVerification(userId, deviceId, verified, blocked, known);\n }\n\n /**\n * Request a key verification from another user, using a DM.\n *\n * @param userId - the user to request verification with\n * @param roomId - the room to use for verification\n *\n * @returns resolves to a VerificationRequest\n * when the request has been sent to the other party.\n */\n public requestVerificationDM(userId: string, roomId: string): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.requestVerificationDM(userId, roomId);\n }\n\n /**\n * Finds a DM verification request that is already in progress for the given room id\n *\n * @param roomId - the room to use for verification\n *\n * @returns the VerificationRequest that is in progress, if any\n */\n public findVerificationRequestDMInProgress(roomId: string): VerificationRequest | undefined {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.findVerificationRequestDMInProgress(roomId);\n }\n\n /**\n * Returns all to-device verification requests that are already in progress for the given user id\n *\n * @param userId - the ID of the user to query\n *\n * @returns the VerificationRequests that are in progress\n */\n public getVerificationRequestsToDeviceInProgress(userId: string): VerificationRequest[] {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getVerificationRequestsToDeviceInProgress(userId);\n }\n\n /**\n * Request a key verification from another user.\n *\n * @param userId - the user to request verification with\n * @param devices - array of device IDs to send requests to. Defaults to\n * all devices owned by the user\n *\n * @returns resolves to a VerificationRequest\n * when the request has been sent to the other party.\n */\n public requestVerification(userId: string, devices?: string[]): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.requestVerification(userId, devices);\n }\n\n /**\n * Begin a key verification.\n *\n * @param method - the verification method to use\n * @param userId - the user to verify keys with\n * @param deviceId - the device to verify\n *\n * @returns a verification object\n * @deprecated Use `requestVerification` instead.\n */\n public beginKeyVerification(method: string, userId: string, deviceId: string): Verification {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.beginKeyVerification(method, userId, deviceId);\n }\n\n public checkSecretStorageKey(key: Uint8Array, info: SecretStorageKeyDescription): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.checkSecretStorageKey(key, info);\n }\n\n /**\n * Set the global override for whether the client should ever send encrypted\n * messages to unverified devices. This provides the default for rooms which\n * do not specify a value.\n *\n * @param value - whether to blacklist all unverified devices by default\n *\n * @deprecated Prefer direct access to {@link CryptoApi.globalBlacklistUnverifiedDevices}:\n *\n * ```javascript\n * client.getCrypto().globalBlacklistUnverifiedDevices = value;\n * ```\n */\n public setGlobalBlacklistUnverifiedDevices(value: boolean): boolean {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n this.cryptoBackend.globalBlacklistUnverifiedDevices = value;\n return value;\n }\n\n /**\n * @returns whether to blacklist all unverified devices by default\n *\n * @deprecated Prefer direct access to {@link CryptoApi.globalBlacklistUnverifiedDevices}:\n *\n * ```javascript\n * value = client.getCrypto().globalBlacklistUnverifiedDevices;\n * ```\n */\n public getGlobalBlacklistUnverifiedDevices(): boolean {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.globalBlacklistUnverifiedDevices;\n }\n\n /**\n * Set whether sendMessage in a room with unknown and unverified devices\n * should throw an error and not send them message. This has 'Global' for\n * symmetry with setGlobalBlacklistUnverifiedDevices but there is currently\n * no room-level equivalent for this setting.\n *\n * This API is currently UNSTABLE and may change or be removed without notice.\n *\n * @param value - whether error on unknown devices\n *\n * @deprecated Prefer direct access to {@link CryptoApi.globalBlacklistUnverifiedDevices}:\n *\n * ```ts\n * client.getCrypto().globalBlacklistUnverifiedDevices = value;\n * ```\n */\n public setGlobalErrorOnUnknownDevices(value: boolean): void {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n this.cryptoBackend.globalErrorOnUnknownDevices = value;\n }\n\n /**\n * @returns whether to error on unknown devices\n *\n * This API is currently UNSTABLE and may change or be removed without notice.\n */\n public getGlobalErrorOnUnknownDevices(): boolean {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.globalErrorOnUnknownDevices;\n }\n\n /**\n * Get the user's cross-signing key ID.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param type - The type of key to get the ID of. One of\n * \"master\", \"self_signing\", or \"user_signing\". Defaults to \"master\".\n *\n * @returns the key ID\n */\n public getCrossSigningId(type: CrossSigningKey | string = CrossSigningKey.Master): string | null {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getCrossSigningId(type);\n }\n\n /**\n * Get the cross signing information for a given user.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param userId - the user ID to get the cross-signing info for.\n *\n * @returns the cross signing information for the user.\n */\n public getStoredCrossSigningForUser(userId: string): CrossSigningInfo | null {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getStoredCrossSigningForUser(userId);\n }\n\n /**\n * Check whether a given user is trusted.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param userId - The ID of the user to check.\n */\n public checkUserTrust(userId: string): UserTrustLevel {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.checkUserTrust(userId);\n }\n\n /**\n * Check whether a given device is trusted.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param userId - The ID of the user whose devices is to be checked.\n * @param deviceId - The ID of the device to check\n */\n public checkDeviceTrust(userId: string, deviceId: string): DeviceTrustLevel {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.checkDeviceTrust(userId, deviceId);\n }\n\n /**\n * Check whether one of our own devices is cross-signed by our\n * user's stored keys, regardless of whether we trust those keys yet.\n *\n * @param deviceId - The ID of the device to check\n *\n * @returns true if the device is cross-signed\n */\n public checkIfOwnDeviceCrossSigned(deviceId: string): boolean {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.checkIfOwnDeviceCrossSigned(deviceId);\n }\n\n /**\n * Check the copy of our cross-signing key that we have in the device list and\n * see if we can get the private key. If so, mark it as trusted.\n * @param opts - ICheckOwnCrossSigningTrustOpts object\n */\n public checkOwnCrossSigningTrust(opts?: ICheckOwnCrossSigningTrustOpts): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.checkOwnCrossSigningTrust(opts);\n }\n\n /**\n * Checks that a given cross-signing private key matches a given public key.\n * This can be used by the getCrossSigningKey callback to verify that the\n * private key it is about to supply is the one that was requested.\n * @param privateKey - The private key\n * @param expectedPublicKey - The public key\n * @returns true if the key matches, otherwise false\n */\n public checkCrossSigningPrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.checkCrossSigningPrivateKey(privateKey, expectedPublicKey);\n }\n\n // deprecated: use requestVerification instead\n public legacyDeviceVerification(\n userId: string,\n deviceId: string,\n method: VerificationMethod,\n ): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.legacyDeviceVerification(userId, deviceId, method);\n }\n\n /**\n * Perform any background tasks that can be done before a message is ready to\n * send, in order to speed up sending of the message.\n * @param room - the room the event is in\n *\n * @deprecated Prefer {@link CryptoApi.prepareToEncrypt | `CryptoApi.prepareToEncrypt`}:\n *\n * ```javascript\n * client.getCrypto().prepareToEncrypt(room);\n * ```\n */\n public prepareToEncrypt(room: Room): void {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n this.cryptoBackend.prepareToEncrypt(room);\n }\n\n /**\n * Checks if the user has previously published cross-signing keys\n *\n * This means downloading the devicelist for the user and checking if the list includes\n * the cross-signing pseudo-device.\n *\n * @deprecated Prefer {@link CryptoApi.userHasCrossSigningKeys | `CryptoApi.userHasCrossSigningKeys`}:\n *\n * ```javascript\n * result = client.getCrypto().userHasCrossSigningKeys();\n * ```\n */\n public userHasCrossSigningKeys(): Promise {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.userHasCrossSigningKeys();\n }\n\n /**\n * Checks whether cross signing:\n * - is enabled on this account and trusted by this device\n * - has private keys either cached locally or stored in secret storage\n *\n * If this function returns false, bootstrapCrossSigning() can be used\n * to fix things such that it returns true. That is to say, after\n * bootstrapCrossSigning() completes successfully, this function should\n * return true.\n * @returns True if cross-signing is ready to be used on this device\n */\n public isCrossSigningReady(): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.isCrossSigningReady();\n }\n\n /**\n * Bootstrap cross-signing by creating keys if needed. If everything is already\n * set up, then no changes are made, so this is safe to run to ensure\n * cross-signing is ready for use.\n *\n * This function:\n * - creates new cross-signing keys if they are not found locally cached nor in\n * secret storage (if it has been setup)\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n */\n public bootstrapCrossSigning(opts: IBootstrapCrossSigningOpts): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.bootstrapCrossSigning(opts);\n }\n\n /**\n * Whether to trust a others users signatures of their devices.\n * If false, devices will only be considered 'verified' if we have\n * verified that device individually (effectively disabling cross-signing).\n *\n * Default: true\n *\n * @returns True if trusting cross-signed devices\n */\n public getCryptoTrustCrossSignedDevices(): boolean {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getCryptoTrustCrossSignedDevices();\n }\n\n /**\n * See getCryptoTrustCrossSignedDevices\n *\n * @param val - True to trust cross-signed devices\n */\n public setCryptoTrustCrossSignedDevices(val: boolean): void {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n this.crypto.setCryptoTrustCrossSignedDevices(val);\n }\n\n /**\n * Counts the number of end to end session keys that are waiting to be backed up\n * @returns Promise which resolves to the number of sessions requiring backup\n */\n public countSessionsNeedingBackup(): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.countSessionsNeedingBackup();\n }\n\n /**\n * Get information about the encryption of an event\n *\n * @param event - event to be checked\n * @returns The event information.\n */\n public getEventEncryptionInfo(event: MatrixEvent): IEncryptedEventInfo {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.cryptoBackend.getEventEncryptionInfo(event);\n }\n\n /**\n * Create a recovery key from a user-supplied passphrase.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param password - Passphrase string that can be entered by the user\n * when restoring the backup as an alternative to entering the recovery key.\n * Optional.\n * @returns Object with public key metadata, encoded private\n * recovery key which should be disposed of after displaying to the user,\n * and raw private key to avoid round tripping if needed.\n */\n public createRecoveryKeyFromPassphrase(password?: string): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.createRecoveryKeyFromPassphrase(password);\n }\n\n /**\n * Checks whether secret storage:\n * - is enabled on this account\n * - is storing cross-signing private keys\n * - is storing session backup key (if enabled)\n *\n * If this function returns false, bootstrapSecretStorage() can be used\n * to fix things such that it returns true. That is to say, after\n * bootstrapSecretStorage() completes successfully, this function should\n * return true.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @returns True if secret storage is ready to be used on this device\n */\n public isSecretStorageReady(): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.isSecretStorageReady();\n }\n\n /**\n * Bootstrap Secure Secret Storage if needed by creating a default key. If everything is\n * already set up, then no changes are made, so this is safe to run to ensure secret\n * storage is ready for use.\n *\n * This function\n * - creates a new Secure Secret Storage key if no default key exists\n * - if a key backup exists, it is migrated to store the key in the Secret\n * Storage\n * - creates a backup if none exists, and one is requested\n * - migrates Secure Secret Storage to use the latest algorithm, if an outdated\n * algorithm is found\n *\n */\n public bootstrapSecretStorage(opts: ICreateSecretStorageOpts): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.bootstrapSecretStorage(opts);\n }\n\n /**\n * Add a key for encrypting secrets.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param algorithm - the algorithm used by the key\n * @param opts - the options for the algorithm. The properties used\n * depend on the algorithm given.\n * @param keyName - the name of the key. If not given, a random name will be generated.\n *\n * @returns An object with:\n * keyId: the ID of the key\n * keyInfo: details about the key (iv, mac, passphrase)\n */\n public addSecretStorageKey(\n algorithm: string,\n opts: IAddSecretStorageKeyOpts,\n keyName?: string,\n ): Promise<{ keyId: string; keyInfo: SecretStorageKeyDescription }> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.addSecretStorageKey(algorithm, opts, keyName);\n }\n\n /**\n * Check whether we have a key with a given ID.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param keyId - The ID of the key to check\n * for. Defaults to the default key ID if not provided.\n * @returns Whether we have the key.\n */\n public hasSecretStorageKey(keyId?: string): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.hasSecretStorageKey(keyId);\n }\n\n /**\n * Store an encrypted secret on the server.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param name - The name of the secret\n * @param secret - The secret contents.\n * @param keys - The IDs of the keys to use to encrypt the secret or null/undefined\n * to use the default (will throw if no default key is set).\n */\n public storeSecret(name: string, secret: string, keys?: string[]): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.storeSecret(name, secret, keys);\n }\n\n /**\n * Get a secret from storage.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param name - the name of the secret\n *\n * @returns the contents of the secret\n */\n public getSecret(name: string): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getSecret(name);\n }\n\n /**\n * Check if a secret is stored on the server.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param name - the name of the secret\n * @returns map of key name to key info the secret is encrypted\n * with, or null if it is not present or not encrypted with a trusted\n * key\n */\n public isSecretStored(name: string): Promise | null> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.isSecretStored(name);\n }\n\n /**\n * Request a secret from another device.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param name - the name of the secret to request\n * @param devices - the devices to request the secret from\n *\n * @returns the secret request object\n */\n public requestSecret(name: string, devices: string[]): ISecretRequest {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.requestSecret(name, devices);\n }\n\n /**\n * Get the current default key ID for encrypting secrets.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @returns The default key ID or null if no default key ID is set\n */\n public getDefaultSecretStorageKeyId(): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.getDefaultSecretStorageKeyId();\n }\n\n /**\n * Set the current default key ID for encrypting secrets.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param keyId - The new default key ID\n */\n public setDefaultSecretStorageKeyId(keyId: string): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.setDefaultSecretStorageKeyId(keyId);\n }\n\n /**\n * Checks that a given secret storage private key matches a given public key.\n * This can be used by the getSecretStorageKey callback to verify that the\n * private key it is about to supply is the one that was requested.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param privateKey - The private key\n * @param expectedPublicKey - The public key\n * @returns true if the key matches, otherwise false\n */\n public checkSecretStoragePrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.checkSecretStoragePrivateKey(privateKey, expectedPublicKey);\n }\n\n /**\n * Get e2e information on the device that sent an event\n *\n * @param event - event to be checked\n */\n public async getEventSenderDeviceInfo(event: MatrixEvent): Promise {\n if (!this.crypto) {\n return null;\n }\n return this.crypto.getEventSenderDeviceInfo(event);\n }\n\n /**\n * Check if the sender of an event is verified\n *\n * @param event - event to be checked\n *\n * @returns true if the sender of this event has been verified using\n * {@link MatrixClient#setDeviceVerified}.\n */\n public async isEventSenderVerified(event: MatrixEvent): Promise {\n const device = await this.getEventSenderDeviceInfo(event);\n if (!device) {\n return false;\n }\n return device.isVerified();\n }\n\n /**\n * Get outgoing room key request for this event if there is one.\n * @param event - The event to check for\n *\n * @returns A room key request, or null if there is none\n */\n public getOutgoingRoomKeyRequest(event: MatrixEvent): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-End encryption disabled\");\n }\n const wireContent = event.getWireContent();\n const requestBody: IRoomKeyRequestBody = {\n session_id: wireContent.session_id,\n sender_key: wireContent.sender_key,\n algorithm: wireContent.algorithm,\n room_id: event.getRoomId()!,\n };\n if (!requestBody.session_id || !requestBody.sender_key || !requestBody.algorithm || !requestBody.room_id) {\n return Promise.resolve(null);\n }\n return this.crypto.cryptoStore.getOutgoingRoomKeyRequest(requestBody);\n }\n\n /**\n * Cancel a room key request for this event if one is ongoing and resend the\n * request.\n * @param event - event of which to cancel and resend the room\n * key request.\n * @returns A promise that will resolve when the key request is queued\n */\n public cancelAndResendEventRoomKeyRequest(event: MatrixEvent): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-End encryption disabled\");\n }\n return event.cancelAndResendKeyRequest(this.crypto, this.getUserId()!);\n }\n\n /**\n * Enable end-to-end encryption for a room. This does not modify room state.\n * Any messages sent before the returned promise resolves will be sent unencrypted.\n * @param roomId - The room ID to enable encryption in.\n * @param config - The encryption config for the room.\n * @returns A promise that will resolve when encryption is set up.\n */\n public setRoomEncryption(roomId: string, config: IRoomEncryption): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-End encryption disabled\");\n }\n return this.crypto.setRoomEncryption(roomId, config);\n }\n\n /**\n * Whether encryption is enabled for a room.\n * @param roomId - the room id to query.\n * @returns whether encryption is enabled.\n */\n public isRoomEncrypted(roomId: string): boolean {\n const room = this.getRoom(roomId);\n if (!room) {\n // we don't know about this room, so can't determine if it should be\n // encrypted. Let's assume not.\n return false;\n }\n\n // if there is an 'm.room.encryption' event in this room, it should be\n // encrypted (independently of whether we actually support encryption)\n const ev = room.currentState.getStateEvents(EventType.RoomEncryption, \"\");\n if (ev) {\n return true;\n }\n\n // we don't have an m.room.encrypted event, but that might be because\n // the server is hiding it from us. Check the store to see if it was\n // previously encrypted.\n return this.roomList.isRoomEncrypted(roomId);\n }\n\n /**\n * Encrypts and sends a given object via Olm to-device messages to a given\n * set of devices.\n *\n * @param userDeviceMap - mapping from userId to deviceInfo\n *\n * @param payload - fields to include in the encrypted payload\n *\n * @returns Promise which\n * resolves once the message has been encrypted and sent to the given\n * userDeviceMap, and returns the `{ contentMap, deviceInfoByDeviceId }`\n * of the successfully sent messages.\n */\n public encryptAndSendToDevices(userDeviceInfoArr: IOlmDevice[], payload: object): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-End encryption disabled\");\n }\n return this.crypto.encryptAndSendToDevices(userDeviceInfoArr, payload);\n }\n\n /**\n * Forces the current outbound group session to be discarded such\n * that another one will be created next time an event is sent.\n *\n * @param roomId - The ID of the room to discard the session for\n *\n * @deprecated Prefer {@link CryptoApi.forceDiscardSession | `CryptoApi.forceDiscardSession`}:\n *\n */\n public forceDiscardSession(roomId: string): void {\n if (!this.cryptoBackend) {\n throw new Error(\"End-to-End encryption disabled\");\n }\n this.cryptoBackend.forceDiscardSession(roomId);\n }\n\n /**\n * Get a list containing all of the room keys\n *\n * This should be encrypted before returning it to the user.\n *\n * @returns a promise which resolves to a list of session export objects\n *\n * @deprecated Prefer {@link CryptoApi.exportRoomKeys | `CryptoApi.exportRoomKeys`}:\n *\n * ```javascript\n * sessionData = await client.getCrypto().exportRoomKeys();\n * ```\n */\n public exportRoomKeys(): Promise {\n if (!this.cryptoBackend) {\n return Promise.reject(new Error(\"End-to-end encryption disabled\"));\n }\n return this.cryptoBackend.exportRoomKeys();\n }\n\n /**\n * Import a list of room keys previously exported by exportRoomKeys\n *\n * @param keys - a list of session export objects\n *\n * @returns a promise which resolves when the keys have been imported\n */\n public importRoomKeys(keys: IMegolmSessionData[], opts?: IImportRoomKeysOpts): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.importRoomKeys(keys, opts);\n }\n\n /**\n * Force a re-check of the local key backup status against\n * what's on the server.\n *\n * @returns Object with backup info (as returned by\n * getKeyBackupVersion) in backupInfo and\n * trust information (as returned by isKeyBackupTrusted)\n * in trustInfo.\n */\n public checkKeyBackup(): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.backupManager.checkKeyBackup();\n }\n\n /**\n * Get information about the current key backup.\n * @returns Information object from API or null\n */\n public async getKeyBackupVersion(): Promise {\n let res: IKeyBackupInfo;\n try {\n res = await this.http.authedRequest(\n Method.Get,\n \"/room_keys/version\",\n undefined,\n undefined,\n { prefix: ClientPrefix.V3 },\n );\n } catch (e) {\n if ((e).errcode === \"M_NOT_FOUND\") {\n return null;\n } else {\n throw e;\n }\n }\n BackupManager.checkBackupVersion(res);\n return res;\n }\n\n /**\n * @param info - key backup info dict from getKeyBackupVersion()\n */\n public isKeyBackupTrusted(info: IKeyBackupInfo): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.backupManager.isKeyBackupTrusted(info);\n }\n\n /**\n * @returns true if the client is configured to back up keys to\n * the server, otherwise false. If we haven't completed a successful check\n * of key backup status yet, returns null.\n */\n public getKeyBackupEnabled(): boolean | null {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n return this.crypto.backupManager.getKeyBackupEnabled();\n }\n\n /**\n * Enable backing up of keys, using data previously returned from\n * getKeyBackupVersion.\n *\n * @param info - Backup information object as returned by getKeyBackupVersion\n * @returns Promise which resolves when complete.\n */\n public enableKeyBackup(info: IKeyBackupInfo): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n return this.crypto.backupManager.enableKeyBackup(info);\n }\n\n /**\n * Disable backing up of keys.\n */\n public disableKeyBackup(): void {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n this.crypto.backupManager.disableKeyBackup();\n }\n\n /**\n * Set up the data required to create a new backup version. The backup version\n * will not be created and enabled until createKeyBackupVersion is called.\n *\n * @param password - Passphrase string that can be entered by the user\n * when restoring the backup as an alternative to entering the recovery key.\n * Optional.\n *\n * @returns Object that can be passed to createKeyBackupVersion and\n * additionally has a 'recovery_key' member with the user-facing recovery key string.\n */\n public async prepareKeyBackupVersion(\n password?: string | Uint8Array | null,\n opts: IKeyBackupPrepareOpts = { secureSecretStorage: false },\n ): Promise> {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n // eslint-disable-next-line camelcase\n const { algorithm, auth_data, recovery_key, privateKey } =\n await this.crypto.backupManager.prepareKeyBackupVersion(password);\n\n if (opts.secureSecretStorage) {\n await this.storeSecret(\"m.megolm_backup.v1\", encodeBase64(privateKey));\n logger.info(\"Key backup private key stored in secret storage\");\n }\n\n return {\n algorithm,\n /* eslint-disable camelcase */\n auth_data,\n recovery_key,\n /* eslint-enable camelcase */\n };\n }\n\n /**\n * Check whether the key backup private key is stored in secret storage.\n * @returns map of key name to key info the secret is\n * encrypted with, or null if it is not present or not encrypted with a\n * trusted key\n */\n public isKeyBackupKeyStored(): Promise | null> {\n return Promise.resolve(this.isSecretStored(\"m.megolm_backup.v1\"));\n }\n\n /**\n * Create a new key backup version and enable it, using the information return\n * from prepareKeyBackupVersion.\n *\n * @param info - Info object from prepareKeyBackupVersion\n * @returns Object with 'version' param indicating the version created\n */\n public async createKeyBackupVersion(info: IKeyBackupInfo): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n await this.crypto.backupManager.createKeyBackupVersion(info);\n\n const data = {\n algorithm: info.algorithm,\n auth_data: info.auth_data,\n };\n\n // Sign the backup auth data with the device key for backwards compat with\n // older devices with cross-signing. This can probably go away very soon in\n // favour of just signing with the cross-singing master key.\n // XXX: Private member access\n await this.crypto.signObject(data.auth_data);\n\n if (\n this.cryptoCallbacks.getCrossSigningKey &&\n // XXX: Private member access\n this.crypto.crossSigningInfo.getId()\n ) {\n // now also sign the auth data with the cross-signing master key\n // we check for the callback explicitly here because we still want to be able\n // to create an un-cross-signed key backup if there is a cross-signing key but\n // no callback supplied.\n // XXX: Private member access\n await this.crypto.crossSigningInfo.signObject(data.auth_data, \"master\");\n }\n\n const res = await this.http.authedRequest(Method.Post, \"/room_keys/version\", undefined, data, {\n prefix: ClientPrefix.V3,\n });\n\n // We could assume everything's okay and enable directly, but this ensures\n // we run the same signature verification that will be used for future\n // sessions.\n await this.checkKeyBackup();\n if (!this.getKeyBackupEnabled()) {\n logger.error(\"Key backup not usable even though we just created it\");\n }\n\n return res;\n }\n\n public async deleteKeyBackupVersion(version: string): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n // If we're currently backing up to this backup... stop.\n // (We start using it automatically in createKeyBackupVersion\n // so this is symmetrical).\n if (this.crypto.backupManager.version) {\n this.crypto.backupManager.disableKeyBackup();\n }\n\n const path = utils.encodeUri(\"/room_keys/version/$version\", {\n $version: version,\n });\n\n await this.http.authedRequest(Method.Delete, path, undefined, undefined, { prefix: ClientPrefix.V3 });\n }\n\n private makeKeyBackupPath(roomId: undefined, sessionId: undefined, version?: string): IKeyBackupPath;\n private makeKeyBackupPath(roomId: string, sessionId: undefined, version?: string): IKeyBackupPath;\n private makeKeyBackupPath(roomId: string, sessionId: string, version?: string): IKeyBackupPath;\n private makeKeyBackupPath(roomId?: string, sessionId?: string, version?: string): IKeyBackupPath {\n let path: string;\n if (sessionId !== undefined) {\n path = utils.encodeUri(\"/room_keys/keys/$roomId/$sessionId\", {\n $roomId: roomId!,\n $sessionId: sessionId,\n });\n } else if (roomId !== undefined) {\n path = utils.encodeUri(\"/room_keys/keys/$roomId\", {\n $roomId: roomId,\n });\n } else {\n path = \"/room_keys/keys\";\n }\n const queryData = version === undefined ? undefined : { version };\n return { path, queryData };\n }\n\n /**\n * Back up session keys to the homeserver.\n * @param roomId - ID of the room that the keys are for Optional.\n * @param sessionId - ID of the session that the keys are for Optional.\n * @param version - backup version Optional.\n * @param data - Object keys to send\n * @returns a promise that will resolve when the keys\n * are uploaded\n */\n public sendKeyBackup(\n roomId: undefined,\n sessionId: undefined,\n version: string | undefined,\n data: IKeyBackup,\n ): Promise;\n public sendKeyBackup(\n roomId: string,\n sessionId: undefined,\n version: string | undefined,\n data: IKeyBackup,\n ): Promise;\n public sendKeyBackup(\n roomId: string,\n sessionId: string,\n version: string | undefined,\n data: IKeyBackup,\n ): Promise;\n public async sendKeyBackup(\n roomId: string | undefined,\n sessionId: string | undefined,\n version: string | undefined,\n data: IKeyBackup,\n ): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n const path = this.makeKeyBackupPath(roomId!, sessionId!, version);\n await this.http.authedRequest(Method.Put, path.path, path.queryData, data, { prefix: ClientPrefix.V3 });\n }\n\n /**\n * Marks all group sessions as needing to be backed up and schedules them to\n * upload in the background as soon as possible.\n */\n public async scheduleAllGroupSessionsForBackup(): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n await this.crypto.backupManager.scheduleAllGroupSessionsForBackup();\n }\n\n /**\n * Marks all group sessions as needing to be backed up without scheduling\n * them to upload in the background.\n * @returns Promise which resolves to the number of sessions requiring a backup.\n */\n public flagAllGroupSessionsForBackup(): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n return this.crypto.backupManager.flagAllGroupSessionsForBackup();\n }\n\n public isValidRecoveryKey(recoveryKey: string): boolean {\n try {\n decodeRecoveryKey(recoveryKey);\n return true;\n } catch (e) {\n return false;\n }\n }\n\n /**\n * Get the raw key for a key backup from the password\n * Used when migrating key backups into SSSS\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param password - Passphrase\n * @param backupInfo - Backup metadata from `checkKeyBackup`\n * @returns key backup key\n */\n public keyBackupKeyFromPassword(password: string, backupInfo: IKeyBackupInfo): Promise {\n return keyFromAuthData(backupInfo.auth_data, password);\n }\n\n /**\n * Get the raw key for a key backup from the recovery key\n * Used when migrating key backups into SSSS\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param recoveryKey - The recovery key\n * @returns key backup key\n */\n public keyBackupKeyFromRecoveryKey(recoveryKey: string): Uint8Array {\n return decodeRecoveryKey(recoveryKey);\n }\n\n /**\n * Restore from an existing key backup via a passphrase.\n *\n * @param password - Passphrase\n * @param targetRoomId - Room ID to target a specific room.\n * Restores all rooms if omitted.\n * @param targetSessionId - Session ID to target a specific session.\n * Restores all sessions if omitted.\n * @param backupInfo - Backup metadata from `checkKeyBackup`\n * @param opts - Optional params such as callbacks\n * @returns Status of restoration with `total` and `imported`\n * key counts.\n */\n public async restoreKeyBackupWithPassword(\n password: string,\n targetRoomId: undefined,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts: IKeyBackupRestoreOpts,\n ): Promise;\n public async restoreKeyBackupWithPassword(\n password: string,\n targetRoomId: string,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts: IKeyBackupRestoreOpts,\n ): Promise;\n public async restoreKeyBackupWithPassword(\n password: string,\n targetRoomId: string,\n targetSessionId: string,\n backupInfo: IKeyBackupInfo,\n opts: IKeyBackupRestoreOpts,\n ): Promise;\n public async restoreKeyBackupWithPassword(\n password: string,\n targetRoomId: string | undefined,\n targetSessionId: string | undefined,\n backupInfo: IKeyBackupInfo,\n opts: IKeyBackupRestoreOpts,\n ): Promise {\n const privKey = await keyFromAuthData(backupInfo.auth_data, password);\n return this.restoreKeyBackup(privKey, targetRoomId!, targetSessionId!, backupInfo, opts);\n }\n\n /**\n * Restore from an existing key backup via a private key stored in secret\n * storage.\n *\n * @param backupInfo - Backup metadata from `checkKeyBackup`\n * @param targetRoomId - Room ID to target a specific room.\n * Restores all rooms if omitted.\n * @param targetSessionId - Session ID to target a specific session.\n * Restores all sessions if omitted.\n * @param opts - Optional params such as callbacks\n * @returns Status of restoration with `total` and `imported`\n * key counts.\n */\n public async restoreKeyBackupWithSecretStorage(\n backupInfo: IKeyBackupInfo,\n targetRoomId?: string,\n targetSessionId?: string,\n opts?: IKeyBackupRestoreOpts,\n ): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n const storedKey = await this.getSecret(\"m.megolm_backup.v1\");\n\n // ensure that the key is in the right format. If not, fix the key and\n // store the fixed version\n const fixedKey = fixBackupKey(storedKey);\n if (fixedKey) {\n const keys = await this.crypto.getSecretStorageKey();\n await this.storeSecret(\"m.megolm_backup.v1\", fixedKey, [keys![0]]);\n }\n\n const privKey = decodeBase64(fixedKey || storedKey!);\n return this.restoreKeyBackup(privKey, targetRoomId!, targetSessionId!, backupInfo, opts);\n }\n\n /**\n * Restore from an existing key backup via an encoded recovery key.\n *\n * @param recoveryKey - Encoded recovery key\n * @param targetRoomId - Room ID to target a specific room.\n * Restores all rooms if omitted.\n * @param targetSessionId - Session ID to target a specific session.\n * Restores all sessions if omitted.\n * @param backupInfo - Backup metadata from `checkKeyBackup`\n * @param opts - Optional params such as callbacks\n\n * @returns Status of restoration with `total` and `imported`\n * key counts.\n */\n public restoreKeyBackupWithRecoveryKey(\n recoveryKey: string,\n targetRoomId: undefined,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise;\n public restoreKeyBackupWithRecoveryKey(\n recoveryKey: string,\n targetRoomId: string,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise;\n public restoreKeyBackupWithRecoveryKey(\n recoveryKey: string,\n targetRoomId: string,\n targetSessionId: string,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise;\n public restoreKeyBackupWithRecoveryKey(\n recoveryKey: string,\n targetRoomId: string | undefined,\n targetSessionId: string | undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise {\n const privKey = decodeRecoveryKey(recoveryKey);\n return this.restoreKeyBackup(privKey, targetRoomId!, targetSessionId!, backupInfo, opts);\n }\n\n public async restoreKeyBackupWithCache(\n targetRoomId: undefined,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise;\n public async restoreKeyBackupWithCache(\n targetRoomId: string,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise;\n public async restoreKeyBackupWithCache(\n targetRoomId: string,\n targetSessionId: string,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise;\n public async restoreKeyBackupWithCache(\n targetRoomId: string | undefined,\n targetSessionId: string | undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n const privKey = await this.crypto.getSessionBackupPrivateKey();\n if (!privKey) {\n throw new Error(\"Couldn't get key\");\n }\n return this.restoreKeyBackup(privKey, targetRoomId!, targetSessionId!, backupInfo, opts);\n }\n\n private async restoreKeyBackup(\n privKey: ArrayLike,\n targetRoomId: undefined,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise;\n private async restoreKeyBackup(\n privKey: ArrayLike,\n targetRoomId: string,\n targetSessionId: undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise;\n private async restoreKeyBackup(\n privKey: ArrayLike,\n targetRoomId: string,\n targetSessionId: string,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise;\n private async restoreKeyBackup(\n privKey: ArrayLike,\n targetRoomId: string | undefined,\n targetSessionId: string | undefined,\n backupInfo: IKeyBackupInfo,\n opts?: IKeyBackupRestoreOpts,\n ): Promise {\n const cacheCompleteCallback = opts?.cacheCompleteCallback;\n const progressCallback = opts?.progressCallback;\n\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n let totalKeyCount = 0;\n let keys: IMegolmSessionData[] = [];\n\n const path = this.makeKeyBackupPath(targetRoomId!, targetSessionId!, backupInfo.version);\n\n const algorithm = await BackupManager.makeAlgorithm(backupInfo, async () => {\n return privKey;\n });\n\n const untrusted = algorithm.untrusted;\n\n try {\n // If the pubkey computed from the private data we've been given\n // doesn't match the one in the auth_data, the user has entered\n // a different recovery key / the wrong passphrase.\n if (!(await algorithm.keyMatches(privKey))) {\n return Promise.reject(new MatrixError({ errcode: MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY }));\n }\n\n // Cache the key, if possible.\n // This is async.\n this.crypto\n .storeSessionBackupPrivateKey(privKey)\n .catch((e) => {\n logger.warn(\"Error caching session backup key:\", e);\n })\n .then(cacheCompleteCallback);\n\n if (progressCallback) {\n progressCallback({\n stage: \"fetch\",\n });\n }\n\n const res = await this.http.authedRequest(\n Method.Get,\n path.path,\n path.queryData,\n undefined,\n { prefix: ClientPrefix.V3 },\n );\n\n if ((res as IRoomsKeysResponse).rooms) {\n const rooms = (res as IRoomsKeysResponse).rooms;\n for (const [roomId, roomData] of Object.entries(rooms)) {\n if (!roomData.sessions) continue;\n\n totalKeyCount += Object.keys(roomData.sessions).length;\n const roomKeys = await algorithm.decryptSessions(roomData.sessions);\n for (const k of roomKeys) {\n k.room_id = roomId;\n keys.push(k);\n }\n }\n } else if ((res as IRoomKeysResponse).sessions) {\n const sessions = (res as IRoomKeysResponse).sessions;\n totalKeyCount = Object.keys(sessions).length;\n keys = await algorithm.decryptSessions(sessions);\n for (const k of keys) {\n k.room_id = targetRoomId!;\n }\n } else {\n totalKeyCount = 1;\n try {\n const [key] = await algorithm.decryptSessions({\n [targetSessionId!]: res as IKeyBackupSession,\n });\n key.room_id = targetRoomId!;\n key.session_id = targetSessionId!;\n keys.push(key);\n } catch (e) {\n logger.log(\"Failed to decrypt megolm session from backup\", e);\n }\n }\n } finally {\n algorithm.free();\n }\n\n await this.importRoomKeys(keys, {\n progressCallback,\n untrusted,\n source: \"backup\",\n });\n\n await this.checkKeyBackup();\n\n return { total: totalKeyCount, imported: keys.length };\n }\n\n public deleteKeysFromBackup(roomId: undefined, sessionId: undefined, version?: string): Promise;\n public deleteKeysFromBackup(roomId: string, sessionId: undefined, version?: string): Promise;\n public deleteKeysFromBackup(roomId: string, sessionId: string, version?: string): Promise;\n public async deleteKeysFromBackup(roomId?: string, sessionId?: string, version?: string): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n const path = this.makeKeyBackupPath(roomId!, sessionId!, version);\n await this.http.authedRequest(Method.Delete, path.path, path.queryData, undefined, { prefix: ClientPrefix.V3 });\n }\n\n /**\n * Share shared-history decryption keys with the given users.\n *\n * @param roomId - the room for which keys should be shared.\n * @param userIds - a list of users to share with. The keys will be sent to\n * all of the user's current devices.\n */\n public async sendSharedHistoryKeys(roomId: string, userIds: string[]): Promise {\n if (!this.crypto) {\n throw new Error(\"End-to-end encryption disabled\");\n }\n\n const roomEncryption = this.roomList.getRoomEncryption(roomId);\n if (!roomEncryption) {\n // unknown room, or unencrypted room\n logger.error(\"Unknown room. Not sharing decryption keys\");\n return;\n }\n\n const deviceInfos = await this.crypto.downloadKeys(userIds);\n const devicesByUser: Map = new Map();\n for (const [userId, devices] of deviceInfos) {\n devicesByUser.set(userId, Array.from(devices.values()));\n }\n\n // XXX: Private member access\n const alg = this.crypto.getRoomDecryptor(roomId, roomEncryption.algorithm);\n if (alg.sendSharedHistoryInboundSessions) {\n await alg.sendSharedHistoryInboundSessions(devicesByUser);\n } else {\n logger.warn(\"Algorithm does not support sharing previous keys\", roomEncryption.algorithm);\n }\n }\n\n /**\n * Get the config for the media repository.\n * @returns Promise which resolves with an object containing the config.\n */\n public getMediaConfig(): Promise {\n return this.http.authedRequest(Method.Get, \"/config\", undefined, undefined, {\n prefix: MediaPrefix.R0,\n });\n }\n\n /**\n * Get the room for the given room ID.\n * This function will return a valid room for any room for which a Room event\n * has been emitted. Note in particular that other events, eg. RoomState.members\n * will be emitted for a room before this function will return the given room.\n * @param roomId - The room ID\n * @returns The Room or null if it doesn't exist or there is no data store.\n */\n public getRoom(roomId: string | undefined): Room | null {\n if (!roomId) {\n return null;\n }\n return this.store.getRoom(roomId);\n }\n\n /**\n * Retrieve all known rooms.\n * @returns A list of rooms, or an empty list if there is no data store.\n */\n public getRooms(): Room[] {\n return this.store.getRooms();\n }\n\n /**\n * Retrieve all rooms that should be displayed to the user\n * This is essentially getRooms() with some rooms filtered out, eg. old versions\n * of rooms that have been replaced or (in future) other rooms that have been\n * marked at the protocol level as not to be displayed to the user.\n *\n * @param msc3946ProcessDynamicPredecessor - if true, look for an\n * m.room.predecessor state event and\n * use it if found (MSC3946).\n * @returns A list of rooms, or an empty list if there is no data store.\n */\n public getVisibleRooms(msc3946ProcessDynamicPredecessor = false): Room[] {\n const allRooms = this.store.getRooms();\n\n const replacedRooms = new Set();\n for (const r of allRooms) {\n const predecessor = r.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n if (predecessor) {\n replacedRooms.add(predecessor);\n }\n }\n\n return allRooms.filter((r) => {\n const tombstone = r.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n if (tombstone && replacedRooms.has(r.roomId)) {\n return false;\n }\n return true;\n });\n }\n\n /**\n * Retrieve a user.\n * @param userId - The user ID to retrieve.\n * @returns A user or null if there is no data store or the user does\n * not exist.\n */\n public getUser(userId: string): User | null {\n return this.store.getUser(userId);\n }\n\n /**\n * Retrieve all known users.\n * @returns A list of users, or an empty list if there is no data store.\n */\n public getUsers(): User[] {\n return this.store.getUsers();\n }\n\n /**\n * Set account data event for the current user.\n * It will retry the request up to 5 times.\n * @param eventType - The event type\n * @param content - the contents object for the event\n * @returns Promise which resolves: an empty object\n * @returns Rejects: with an error response.\n */\n public setAccountData(eventType: EventType | string, content: IContent): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n $userId: this.credentials.userId!,\n $type: eventType,\n });\n return retryNetworkOperation(5, () => {\n return this.http.authedRequest(Method.Put, path, undefined, content);\n });\n }\n\n /**\n * Get account data event of given type for the current user.\n * @param eventType - The event type\n * @returns The contents of the given account data event\n */\n public getAccountData(eventType: string): MatrixEvent | undefined {\n return this.store.getAccountData(eventType);\n }\n\n /**\n * Get account data event of given type for the current user. This variant\n * gets account data directly from the homeserver if the local store is not\n * ready, which can be useful very early in startup before the initial sync.\n * @param eventType - The event type\n * @returns Promise which resolves: The contents of the given account data event.\n * @returns Rejects: with an error response.\n */\n public async getAccountDataFromServer(eventType: string): Promise {\n if (this.isInitialSyncComplete()) {\n const event = this.store.getAccountData(eventType);\n if (!event) {\n return null;\n }\n // The network version below returns just the content, so this branch\n // does the same to match.\n return event.getContent();\n }\n const path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n $userId: this.credentials.userId!,\n $type: eventType,\n });\n try {\n return await this.http.authedRequest(Method.Get, path);\n } catch (e) {\n if ((e).data?.errcode === \"M_NOT_FOUND\") {\n return null;\n }\n throw e;\n }\n }\n\n public async deleteAccountData(eventType: string): Promise {\n const msc3391DeleteAccountDataServerSupport = this.canSupport.get(Feature.AccountDataDeletion);\n // if deletion is not supported overwrite with empty content\n if (msc3391DeleteAccountDataServerSupport === ServerSupport.Unsupported) {\n await this.setAccountData(eventType, {});\n return;\n }\n const path = utils.encodeUri(\"/user/$userId/account_data/$type\", {\n $userId: this.getSafeUserId(),\n $type: eventType,\n });\n const options =\n msc3391DeleteAccountDataServerSupport === ServerSupport.Unstable\n ? { prefix: \"/_matrix/client/unstable/org.matrix.msc3391\" }\n : undefined;\n return await this.http.authedRequest(Method.Delete, path, undefined, undefined, options);\n }\n\n /**\n * Gets the users that are ignored by this client\n * @returns The array of users that are ignored (empty if none)\n */\n public getIgnoredUsers(): string[] {\n const event = this.getAccountData(\"m.ignored_user_list\");\n if (!event || !event.getContent() || !event.getContent()[\"ignored_users\"]) return [];\n return Object.keys(event.getContent()[\"ignored_users\"]);\n }\n\n /**\n * Sets the users that the current user should ignore.\n * @param userIds - the user IDs to ignore\n * @returns Promise which resolves: an empty object\n * @returns Rejects: with an error response.\n */\n public setIgnoredUsers(userIds: string[]): Promise<{}> {\n const content = { ignored_users: {} as Record };\n userIds.forEach((u) => {\n content.ignored_users[u] = {};\n });\n return this.setAccountData(\"m.ignored_user_list\", content);\n }\n\n /**\n * Gets whether or not a specific user is being ignored by this client.\n * @param userId - the user ID to check\n * @returns true if the user is ignored, false otherwise\n */\n public isUserIgnored(userId: string): boolean {\n return this.getIgnoredUsers().includes(userId);\n }\n\n /**\n * Join a room. If you have already joined the room, this will no-op.\n * @param roomIdOrAlias - The room ID or room alias to join.\n * @param opts - Options when joining the room.\n * @returns Promise which resolves: Room object.\n * @returns Rejects: with an error response.\n */\n public async joinRoom(roomIdOrAlias: string, opts: IJoinRoomOpts = {}): Promise {\n if (opts.syncRoom === undefined) {\n opts.syncRoom = true;\n }\n\n const room = this.getRoom(roomIdOrAlias);\n if (room?.hasMembershipState(this.credentials.userId!, \"join\")) {\n return Promise.resolve(room);\n }\n\n let signPromise: Promise = Promise.resolve();\n\n if (opts.inviteSignUrl) {\n const url = new URL(opts.inviteSignUrl);\n url.searchParams.set(\"mxid\", this.credentials.userId!);\n signPromise = this.http.requestOtherUrl(Method.Post, url);\n }\n\n const queryString: Record = {};\n if (opts.viaServers) {\n queryString[\"server_name\"] = opts.viaServers;\n }\n\n try {\n const data: IJoinRequestBody = {};\n const signedInviteObj = await signPromise;\n if (signedInviteObj) {\n data.third_party_signed = signedInviteObj;\n }\n\n const path = utils.encodeUri(\"/join/$roomid\", { $roomid: roomIdOrAlias });\n const res = await this.http.authedRequest<{ room_id: string }>(Method.Post, path, queryString, data);\n\n const roomId = res.room_id;\n const syncApi = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n const room = syncApi.createRoom(roomId);\n if (opts.syncRoom) {\n // v2 will do this for us\n // return syncApi.syncRoom(room);\n }\n return room;\n } catch (e) {\n throw e; // rethrow for reject\n }\n }\n\n /**\n * Resend an event. Will also retry any to-device messages waiting to be sent.\n * @param event - The event to resend.\n * @param room - Optional. The room the event is in. Will update the\n * timeline entry if provided.\n * @returns Promise which resolves: to an ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public resendEvent(event: MatrixEvent, room: Room): Promise {\n // also kick the to-device queue to retry\n this.toDeviceMessageQueue.sendQueue();\n\n this.updatePendingEventStatus(room, event, EventStatus.SENDING);\n return this.encryptAndSendEvent(room, event);\n }\n\n /**\n * Cancel a queued or unsent event.\n *\n * @param event - Event to cancel\n * @throws Error if the event is not in QUEUED, NOT_SENT or ENCRYPTING state\n */\n public cancelPendingEvent(event: MatrixEvent): void {\n if (![EventStatus.QUEUED, EventStatus.NOT_SENT, EventStatus.ENCRYPTING].includes(event.status!)) {\n throw new Error(\"cannot cancel an event with status \" + event.status);\n }\n\n // if the event is currently being encrypted then\n if (event.status === EventStatus.ENCRYPTING) {\n this.pendingEventEncryption.delete(event.getId()!);\n } else if (this.scheduler && event.status === EventStatus.QUEUED) {\n // tell the scheduler to forget about it, if it's queued\n this.scheduler.removeEventFromQueue(event);\n }\n\n // then tell the room about the change of state, which will remove it\n // from the room's list of pending events.\n const room = this.getRoom(event.getRoomId());\n this.updatePendingEventStatus(room, event, EventStatus.CANCELLED);\n }\n\n /**\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public setRoomName(roomId: string, name: string): Promise {\n return this.sendStateEvent(roomId, EventType.RoomName, { name: name });\n }\n\n /**\n * @param htmlTopic - Optional.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public setRoomTopic(roomId: string, topic: string, htmlTopic?: string): Promise {\n const content = ContentHelpers.makeTopicContent(topic, htmlTopic);\n return this.sendStateEvent(roomId, EventType.RoomTopic, content);\n }\n\n /**\n * @returns Promise which resolves: to an object keyed by tagId with objects containing a numeric order field.\n * @returns Rejects: with an error response.\n */\n public getRoomTags(roomId: string): Promise {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * @param tagName - name of room tag to be set\n * @param metadata - associated with that tag to be stored\n * @returns Promise which resolves: to an empty object\n * @returns Rejects: with an error response.\n */\n public setRoomTag(roomId: string, tagName: string, metadata: ITagMetadata): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags/$tag\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n $tag: tagName,\n });\n return this.http.authedRequest(Method.Put, path, undefined, metadata);\n }\n\n /**\n * @param tagName - name of room tag to be removed\n * @returns Promise which resolves: to an empty object\n * @returns Rejects: with an error response.\n */\n public deleteRoomTag(roomId: string, tagName: string): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/tags/$tag\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n $tag: tagName,\n });\n return this.http.authedRequest(Method.Delete, path);\n }\n\n /**\n * @param eventType - event type to be set\n * @param content - event content\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setRoomAccountData(roomId: string, eventType: string, content: Record): Promise<{}> {\n const path = utils.encodeUri(\"/user/$userId/rooms/$roomId/account_data/$type\", {\n $userId: this.credentials.userId!,\n $roomId: roomId,\n $type: eventType,\n });\n return this.http.authedRequest(Method.Put, path, undefined, content);\n }\n\n /**\n * Set a power level to one or multiple users.\n * @returns Promise which resolves: to an ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public setPowerLevel(\n roomId: string,\n userId: string | string[],\n powerLevel: number | undefined,\n event: MatrixEvent | null,\n ): Promise {\n let content = {\n users: {} as Record,\n };\n if (event?.getType() === EventType.RoomPowerLevels) {\n // take a copy of the content to ensure we don't corrupt\n // existing client state with a failed power level change\n content = utils.deepCopy(event.getContent());\n }\n\n const users = Array.isArray(userId) ? userId : [userId];\n for (const user of users) {\n if (powerLevel == null) {\n delete content.users[user];\n } else {\n content.users[user] = powerLevel;\n }\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/state/m.room.power_levels\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, content);\n }\n\n /**\n * Create an m.beacon_info event\n * @returns\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public async unstable_createLiveBeacon(\n roomId: Room[\"roomId\"],\n beaconInfoContent: MBeaconInfoEventContent,\n ): Promise {\n return this.unstable_setLiveBeacon(roomId, beaconInfoContent);\n }\n\n /**\n * Upsert a live beacon event\n * using a specific m.beacon_info.* event variable type\n * @param roomId - string\n * @returns\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public async unstable_setLiveBeacon(\n roomId: string,\n beaconInfoContent: MBeaconInfoEventContent,\n ): Promise {\n return this.sendStateEvent(roomId, M_BEACON_INFO.name, beaconInfoContent, this.getUserId()!);\n }\n\n public sendEvent(roomId: string, eventType: string, content: IContent, txnId?: string): Promise;\n public sendEvent(\n roomId: string,\n threadId: string | null,\n eventType: string,\n content: IContent,\n txnId?: string,\n ): Promise;\n public sendEvent(\n roomId: string,\n threadIdOrEventType: string | null,\n eventTypeOrContent: string | IContent,\n contentOrTxnId?: IContent | string,\n txnIdOrVoid?: string,\n ): Promise {\n let threadId: string | null;\n let eventType: string;\n let content: IContent;\n let txnId: string | undefined;\n if (!threadIdOrEventType?.startsWith(EVENT_ID_PREFIX) && threadIdOrEventType !== null) {\n txnId = contentOrTxnId as string;\n content = eventTypeOrContent as IContent;\n eventType = threadIdOrEventType;\n threadId = null;\n } else {\n txnId = txnIdOrVoid;\n content = contentOrTxnId as IContent;\n eventType = eventTypeOrContent as string;\n threadId = threadIdOrEventType;\n }\n\n // If we expect that an event is part of a thread but is missing the relation\n // we need to add it manually, as well as the reply fallback\n if (threadId && !content![\"m.relates_to\"]?.rel_type) {\n const isReply = !!content![\"m.relates_to\"]?.[\"m.in_reply_to\"];\n content![\"m.relates_to\"] = {\n ...content![\"m.relates_to\"],\n rel_type: THREAD_RELATION_TYPE.name,\n event_id: threadId,\n // Set is_falling_back to true unless this is actually intended to be a reply\n is_falling_back: !isReply,\n };\n const thread = this.getRoom(roomId)?.getThread(threadId);\n if (thread && !isReply) {\n content![\"m.relates_to\"][\"m.in_reply_to\"] = {\n event_id:\n thread\n .lastReply((ev: MatrixEvent) => {\n return ev.isRelation(THREAD_RELATION_TYPE.name) && !ev.status;\n })\n ?.getId() ?? threadId,\n };\n }\n }\n\n return this.sendCompleteEvent(roomId, threadId, { type: eventType, content }, txnId);\n }\n\n /**\n * @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.\n * @param txnId - Optional.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n private sendCompleteEvent(\n roomId: string,\n threadId: string | null,\n eventObject: any,\n txnId?: string,\n ): Promise {\n if (!txnId) {\n txnId = this.makeTxnId();\n }\n\n // We always construct a MatrixEvent when sending because the store and scheduler use them.\n // We'll extract the params back out if it turns out the client has no scheduler or store.\n const localEvent = new MatrixEvent(\n Object.assign(eventObject, {\n event_id: \"~\" + roomId + \":\" + txnId,\n user_id: this.credentials.userId,\n sender: this.credentials.userId,\n room_id: roomId,\n origin_server_ts: new Date().getTime(),\n }),\n );\n\n const room = this.getRoom(roomId);\n const thread = threadId ? room?.getThread(threadId) : undefined;\n if (thread) {\n localEvent.setThread(thread);\n }\n\n // set up re-emitter for this new event - this is normally the job of EventMapper but we don't use it here\n this.reEmitter.reEmit(localEvent, [MatrixEventEvent.Replaced, MatrixEventEvent.VisibilityChange]);\n room?.reEmitter.reEmit(localEvent, [MatrixEventEvent.BeforeRedaction]);\n\n // if this is a relation or redaction of an event\n // that hasn't been sent yet (e.g. with a local id starting with a ~)\n // then listen for the remote echo of that event so that by the time\n // this event does get sent, we have the correct event_id\n const targetId = localEvent.getAssociatedId();\n if (targetId?.startsWith(\"~\")) {\n const target = room?.getPendingEvents().find((e) => e.getId() === targetId);\n target?.once(MatrixEventEvent.LocalEventIdReplaced, () => {\n localEvent.updateAssociatedId(target.getId()!);\n });\n }\n\n const type = localEvent.getType();\n logger.log(`sendEvent of type ${type} in ${roomId} with txnId ${txnId}`);\n\n localEvent.setTxnId(txnId);\n localEvent.setStatus(EventStatus.SENDING);\n\n // add this event immediately to the local store as 'sending'.\n room?.addPendingEvent(localEvent, txnId);\n\n // addPendingEvent can change the state to NOT_SENT if it believes\n // that there's other events that have failed. We won't bother to\n // try sending the event if the state has changed as such.\n if (localEvent.status === EventStatus.NOT_SENT) {\n return Promise.reject(new Error(\"Event blocked by other events not yet sent\"));\n }\n\n return this.encryptAndSendEvent(room, localEvent);\n }\n\n /**\n * encrypts the event if necessary; adds the event to the queue, or sends it; marks the event as sent/unsent\n * @returns returns a promise which resolves with the result of the send request\n */\n protected encryptAndSendEvent(room: Room | null, event: MatrixEvent): Promise {\n let cancelled = false;\n // Add an extra Promise.resolve() to turn synchronous exceptions into promise rejections,\n // so that we can handle synchronous and asynchronous exceptions with the\n // same code path.\n return Promise.resolve()\n .then(() => {\n const encryptionPromise = this.encryptEventIfNeeded(event, room ?? undefined);\n if (!encryptionPromise) return null; // doesn't need encryption\n\n this.pendingEventEncryption.set(event.getId()!, encryptionPromise);\n this.updatePendingEventStatus(room, event, EventStatus.ENCRYPTING);\n return encryptionPromise.then(() => {\n if (!this.pendingEventEncryption.has(event.getId()!)) {\n // cancelled via MatrixClient::cancelPendingEvent\n cancelled = true;\n return;\n }\n this.updatePendingEventStatus(room, event, EventStatus.SENDING);\n });\n })\n .then(() => {\n if (cancelled) return {} as ISendEventResponse;\n let promise: Promise | null = null;\n if (this.scheduler) {\n // if this returns a promise then the scheduler has control now and will\n // resolve/reject when it is done. Internally, the scheduler will invoke\n // processFn which is set to this._sendEventHttpRequest so the same code\n // path is executed regardless.\n promise = this.scheduler.queueEvent(event);\n if (promise && this.scheduler.getQueueForEvent(event)!.length > 1) {\n // event is processed FIFO so if the length is 2 or more we know\n // this event is stuck behind an earlier event.\n this.updatePendingEventStatus(room, event, EventStatus.QUEUED);\n }\n }\n\n if (!promise) {\n promise = this.sendEventHttpRequest(event);\n if (room) {\n promise = promise.then((res) => {\n room.updatePendingEvent(event, EventStatus.SENT, res[\"event_id\"]);\n return res;\n });\n }\n }\n\n return promise;\n })\n .catch((err) => {\n logger.error(\"Error sending event\", err.stack || err);\n try {\n // set the error on the event before we update the status:\n // updating the status emits the event, so the state should be\n // consistent at that point.\n event.error = err;\n this.updatePendingEventStatus(room, event, EventStatus.NOT_SENT);\n } catch (e) {\n logger.error(\"Exception in error handler!\", (e).stack || err);\n }\n if (err instanceof MatrixError) {\n err.event = event;\n }\n throw err;\n });\n }\n\n private encryptEventIfNeeded(event: MatrixEvent, room?: Room): Promise | null {\n if (event.isEncrypted()) {\n // this event has already been encrypted; this happens if the\n // encryption step succeeded, but the send step failed on the first\n // attempt.\n return null;\n }\n\n if (event.isRedaction()) {\n // Redactions do not support encryption in the spec at this time,\n // whilst it mostly worked in some clients, it wasn't compliant.\n return null;\n }\n\n if (!room || !this.isRoomEncrypted(event.getRoomId()!)) {\n return null;\n }\n\n if (!this.cryptoBackend && this.usingExternalCrypto) {\n // The client has opted to allow sending messages to encrypted\n // rooms even if the room is encrypted, and we haven't setup\n // crypto. This is useful for users of matrix-org/pantalaimon\n return null;\n }\n\n if (event.getType() === EventType.Reaction) {\n // For reactions, there is a very little gained by encrypting the entire\n // event, as relation data is already kept in the clear. Event\n // encryption for a reaction effectively only obscures the event type,\n // but the purpose is still obvious from the relation data, so nothing\n // is really gained. It also causes quite a few problems, such as:\n // * triggers notifications via default push rules\n // * prevents server-side bundling for reactions\n // The reaction key / content / emoji value does warrant encrypting, but\n // this will be handled separately by encrypting just this value.\n // See https://github.com/matrix-org/matrix-doc/pull/1849#pullrequestreview-248763642\n return null;\n }\n\n if (!this.cryptoBackend) {\n throw new Error(\"This room is configured to use encryption, but your client does not support encryption.\");\n }\n\n return this.cryptoBackend.encryptEvent(event, room);\n }\n\n /**\n * Returns the eventType that should be used taking encryption into account\n * for a given eventType.\n * @param roomId - the room for the events `eventType` relates to\n * @param eventType - the event type\n * @returns the event type taking encryption into account\n */\n private getEncryptedIfNeededEventType(\n roomId: string,\n eventType?: EventType | string | null,\n ): EventType | string | null | undefined {\n if (eventType === EventType.Reaction) return eventType;\n return this.isRoomEncrypted(roomId) ? EventType.RoomMessageEncrypted : eventType;\n }\n\n protected updatePendingEventStatus(room: Room | null, event: MatrixEvent, newStatus: EventStatus): void {\n if (room) {\n room.updatePendingEvent(event, newStatus);\n } else {\n event.setStatus(newStatus);\n }\n }\n\n private sendEventHttpRequest(event: MatrixEvent): Promise {\n let txnId = event.getTxnId();\n if (!txnId) {\n txnId = this.makeTxnId();\n event.setTxnId(txnId);\n }\n\n const pathParams = {\n $roomId: event.getRoomId()!,\n $eventType: event.getWireType(),\n $stateKey: event.getStateKey()!,\n $txnId: txnId,\n };\n\n let path: string;\n\n if (event.isState()) {\n let pathTemplate = \"/rooms/$roomId/state/$eventType\";\n if (event.getStateKey() && event.getStateKey()!.length > 0) {\n pathTemplate = \"/rooms/$roomId/state/$eventType/$stateKey\";\n }\n path = utils.encodeUri(pathTemplate, pathParams);\n } else if (event.isRedaction()) {\n const pathTemplate = `/rooms/$roomId/redact/$redactsEventId/$txnId`;\n path = utils.encodeUri(pathTemplate, {\n $redactsEventId: event.event.redacts!,\n ...pathParams,\n });\n } else {\n path = utils.encodeUri(\"/rooms/$roomId/send/$eventType/$txnId\", pathParams);\n }\n\n return this.http\n .authedRequest(Method.Put, path, undefined, event.getWireContent())\n .then((res) => {\n logger.log(`Event sent to ${event.getRoomId()} with event id ${res.event_id}`);\n return res;\n });\n }\n\n /**\n * @param txnId - transaction id. One will be made up if not supplied.\n * @param opts - Options to pass on, may contain `reason` and `with_relations` (MSC3912)\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n * @throws Error if called with `with_relations` (MSC3912) but the server does not support it.\n * Callers should check whether the server supports MSC3912 via `MatrixClient.canSupport`.\n */\n public redactEvent(\n roomId: string,\n eventId: string,\n txnId?: string | undefined,\n opts?: IRedactOpts,\n ): Promise;\n public redactEvent(\n roomId: string,\n threadId: string | null,\n eventId: string,\n txnId?: string | undefined,\n opts?: IRedactOpts,\n ): Promise;\n public redactEvent(\n roomId: string,\n threadId: string | null,\n eventId?: string,\n txnId?: string | IRedactOpts,\n opts?: IRedactOpts,\n ): Promise {\n if (!eventId?.startsWith(EVENT_ID_PREFIX)) {\n opts = txnId as IRedactOpts;\n txnId = eventId;\n eventId = threadId!;\n threadId = null;\n }\n const reason = opts?.reason;\n\n if (\n opts?.with_relations &&\n this.canSupport.get(Feature.RelationBasedRedactions) === ServerSupport.Unsupported\n ) {\n throw new Error(\n \"Server does not support relation based redactions \" +\n `roomId ${roomId} eventId ${eventId} txnId: ${txnId} threadId ${threadId}`,\n );\n }\n\n const withRelations = opts?.with_relations\n ? {\n [this.canSupport.get(Feature.RelationBasedRedactions) === ServerSupport.Stable\n ? MSC3912_RELATION_BASED_REDACTIONS_PROP.stable!\n : MSC3912_RELATION_BASED_REDACTIONS_PROP.unstable!]: opts?.with_relations,\n }\n : {};\n\n return this.sendCompleteEvent(\n roomId,\n threadId,\n {\n type: EventType.RoomRedaction,\n content: {\n ...withRelations,\n reason,\n },\n redacts: eventId,\n },\n txnId as string,\n );\n }\n\n /**\n * @param txnId - Optional.\n * @returns Promise which resolves: to an ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendMessage(roomId: string, content: IContent, txnId?: string): Promise;\n public sendMessage(\n roomId: string,\n threadId: string | null,\n content: IContent,\n txnId?: string,\n ): Promise;\n public sendMessage(\n roomId: string,\n threadId: string | null | IContent,\n content?: IContent | string,\n txnId?: string,\n ): Promise {\n if (typeof threadId !== \"string\" && threadId !== null) {\n txnId = content as string;\n content = threadId as IContent;\n threadId = null;\n }\n\n const eventType: string = EventType.RoomMessage;\n const sendContent: IContent = content as IContent;\n\n return this.sendEvent(roomId, threadId as string | null, eventType, sendContent, txnId);\n }\n\n /**\n * @param txnId - Optional.\n * @returns\n * @returns Rejects: with an error response.\n */\n public sendTextMessage(roomId: string, body: string, txnId?: string): Promise;\n public sendTextMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise;\n public sendTextMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n txnId = body;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeTextMessage(body);\n return this.sendMessage(roomId, threadId, content, txnId);\n }\n\n /**\n * @param txnId - Optional.\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendNotice(roomId: string, body: string, txnId?: string): Promise;\n public sendNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise;\n public sendNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n txnId = body;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeNotice(body);\n return this.sendMessage(roomId, threadId, content, txnId);\n }\n\n /**\n * @param txnId - Optional.\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendEmoteMessage(roomId: string, body: string, txnId?: string): Promise;\n public sendEmoteMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise;\n public sendEmoteMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n txnId?: string,\n ): Promise {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n txnId = body;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeEmoteMessage(body);\n return this.sendMessage(roomId, threadId, content, txnId);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendImageMessage(roomId: string, url: string, info?: IImageInfo, text?: string): Promise;\n public sendImageMessage(\n roomId: string,\n threadId: string | null,\n url: string,\n info?: IImageInfo,\n text?: string,\n ): Promise;\n public sendImageMessage(\n roomId: string,\n threadId: string | null,\n url?: string | IImageInfo,\n info?: IImageInfo | string,\n text = \"Image\",\n ): Promise {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n text = (info as string) || \"Image\";\n info = url as IImageInfo;\n url = threadId as string;\n threadId = null;\n }\n const content = {\n msgtype: MsgType.Image,\n url: url,\n info: info,\n body: text,\n };\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendStickerMessage(\n roomId: string,\n url: string,\n info?: IImageInfo,\n text?: string,\n ): Promise;\n public sendStickerMessage(\n roomId: string,\n threadId: string | null,\n url: string,\n info?: IImageInfo,\n text?: string,\n ): Promise;\n public sendStickerMessage(\n roomId: string,\n threadId: string | null,\n url?: string | IImageInfo,\n info?: IImageInfo | string,\n text = \"Sticker\",\n ): Promise {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n text = (info as string) || \"Sticker\";\n info = url as IImageInfo;\n url = threadId as string;\n threadId = null;\n }\n const content = {\n url: url,\n info: info,\n body: text,\n };\n\n return this.sendEvent(roomId, threadId, EventType.Sticker, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendHtmlMessage(roomId: string, body: string, htmlBody: string): Promise;\n public sendHtmlMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody: string,\n ): Promise;\n public sendHtmlMessage(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody?: string,\n ): Promise {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n htmlBody = body as string;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeHtmlMessage(body, htmlBody!);\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendHtmlNotice(roomId: string, body: string, htmlBody: string): Promise;\n public sendHtmlNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody: string,\n ): Promise;\n public sendHtmlNotice(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody?: string,\n ): Promise {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n htmlBody = body as string;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeHtmlNotice(body, htmlBody!);\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * @returns Promise which resolves: to a ISendEventResponse object\n * @returns Rejects: with an error response.\n */\n public sendHtmlEmote(roomId: string, body: string, htmlBody: string): Promise;\n public sendHtmlEmote(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody: string,\n ): Promise;\n public sendHtmlEmote(\n roomId: string,\n threadId: string | null,\n body: string,\n htmlBody?: string,\n ): Promise {\n if (!threadId?.startsWith(EVENT_ID_PREFIX) && threadId !== null) {\n htmlBody = body as string;\n body = threadId;\n threadId = null;\n }\n const content = ContentHelpers.makeHtmlEmote(body, htmlBody!);\n return this.sendMessage(roomId, threadId, content);\n }\n\n /**\n * Send a receipt.\n * @param event - The event being acknowledged\n * @param receiptType - The kind of receipt e.g. \"m.read\". Other than\n * ReceiptType.Read are experimental!\n * @param body - Additional content to send alongside the receipt.\n * @param unthreaded - An unthreaded receipt will clear room+thread notifications\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async sendReceipt(event: MatrixEvent, receiptType: ReceiptType, body: any, unthreaded = false): Promise<{}> {\n if (this.isGuest()) {\n return Promise.resolve({}); // guests cannot send receipts so don't bother.\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/receipt/$receiptType/$eventId\", {\n $roomId: event.getRoomId()!,\n $receiptType: receiptType,\n $eventId: event.getId()!,\n });\n\n if (!unthreaded) {\n const isThread = !!event.threadRootId;\n body = {\n ...body,\n thread_id: isThread ? event.threadRootId : MAIN_ROOM_TIMELINE,\n };\n }\n\n const promise = this.http.authedRequest<{}>(Method.Post, path, undefined, body || {});\n\n const room = this.getRoom(event.getRoomId());\n if (room && this.credentials.userId) {\n room.addLocalEchoReceipt(this.credentials.userId, event, receiptType);\n }\n return promise;\n }\n\n /**\n * Send a read receipt.\n * @param event - The event that has been read.\n * @param receiptType - other than ReceiptType.Read are experimental! Optional.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async sendReadReceipt(\n event: MatrixEvent | null,\n receiptType = ReceiptType.Read,\n unthreaded = false,\n ): Promise<{} | undefined> {\n if (!event) return;\n const eventId = event.getId()!;\n const room = this.getRoom(event.getRoomId());\n if (room?.hasPendingEvent(eventId)) {\n throw new Error(`Cannot set read receipt to a pending event (${eventId})`);\n }\n\n return this.sendReceipt(event, receiptType, {}, unthreaded);\n }\n\n /**\n * Set a marker to indicate the point in a room before which the user has read every\n * event. This can be retrieved from room account data (the event type is `m.fully_read`)\n * and displayed as a horizontal line in the timeline that is visually distinct to the\n * position of the user's own read receipt.\n * @param roomId - ID of the room that has been read\n * @param rmEventId - ID of the event that has been read\n * @param rrEvent - the event tracked by the read receipt. This is here for\n * convenience because the RR and the RM are commonly updated at the same time as each\n * other. The local echo of this receipt will be done if set. Optional.\n * @param rpEvent - the m.read.private read receipt event for when we don't\n * want other users to see the read receipts. This is experimental. Optional.\n * @returns Promise which resolves: the empty object, `{}`.\n */\n public async setRoomReadMarkers(\n roomId: string,\n rmEventId: string,\n rrEvent?: MatrixEvent,\n rpEvent?: MatrixEvent,\n ): Promise<{}> {\n const room = this.getRoom(roomId);\n if (room && room.hasPendingEvent(rmEventId)) {\n throw new Error(`Cannot set read marker to a pending event (${rmEventId})`);\n }\n\n // Add the optional RR update, do local echo like `sendReceipt`\n let rrEventId: string | undefined;\n if (rrEvent) {\n rrEventId = rrEvent.getId()!;\n if (room?.hasPendingEvent(rrEventId)) {\n throw new Error(`Cannot set read receipt to a pending event (${rrEventId})`);\n }\n room?.addLocalEchoReceipt(this.credentials.userId!, rrEvent, ReceiptType.Read);\n }\n\n // Add the optional private RR update, do local echo like `sendReceipt`\n let rpEventId: string | undefined;\n if (rpEvent) {\n rpEventId = rpEvent.getId()!;\n if (room?.hasPendingEvent(rpEventId)) {\n throw new Error(`Cannot set read receipt to a pending event (${rpEventId})`);\n }\n room?.addLocalEchoReceipt(this.credentials.userId!, rpEvent, ReceiptType.ReadPrivate);\n }\n\n return await this.setRoomReadMarkersHttpRequest(roomId, rmEventId, rrEventId, rpEventId);\n }\n\n /**\n * Get a preview of the given URL as of (roughly) the given point in time,\n * described as an object with OpenGraph keys and associated values.\n * Attributes may be synthesized where actual OG metadata is lacking.\n * Caches results to prevent hammering the server.\n * @param url - The URL to get preview data for\n * @param ts - The preferred point in time that the preview should\n * describe (ms since epoch). The preview returned will either be the most\n * recent one preceding this timestamp if available, or failing that the next\n * most recent available preview.\n * @returns Promise which resolves: Object of OG metadata.\n * @returns Rejects: with an error response.\n * May return synthesized attributes if the URL lacked OG meta.\n */\n public getUrlPreview(url: string, ts: number): Promise {\n // bucket the timestamp to the nearest minute to prevent excessive spam to the server\n // Surely 60-second accuracy is enough for anyone.\n ts = Math.floor(ts / 60000) * 60000;\n\n const parsed = new URL(url);\n parsed.hash = \"\"; // strip the hash as it won't affect the preview\n url = parsed.toString();\n\n const key = ts + \"_\" + url;\n\n // If there's already a request in flight (or we've handled it), return that instead.\n const cachedPreview = this.urlPreviewCache[key];\n if (cachedPreview) {\n return cachedPreview;\n }\n\n const resp = this.http.authedRequest(\n Method.Get,\n \"/preview_url\",\n {\n url,\n ts: ts.toString(),\n },\n undefined,\n {\n prefix: MediaPrefix.R0,\n },\n );\n // TODO: Expire the URL preview cache sometimes\n this.urlPreviewCache[key] = resp;\n return resp;\n }\n\n /**\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public sendTyping(roomId: string, isTyping: boolean, timeoutMs: number): Promise<{}> {\n if (this.isGuest()) {\n return Promise.resolve({}); // guests cannot send typing notifications so don't bother.\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/typing/$userId\", {\n $roomId: roomId,\n $userId: this.getUserId()!,\n });\n const data: any = {\n typing: isTyping,\n };\n if (isTyping) {\n data.timeout = timeoutMs ? timeoutMs : 20000;\n }\n return this.http.authedRequest(Method.Put, path, undefined, data);\n }\n\n /**\n * Determines the history of room upgrades for a given room, as far as the\n * client can see. Returns an array of Rooms where the first entry is the\n * oldest and the last entry is the newest (likely current) room. If the\n * provided room is not found, this returns an empty list. This works in\n * both directions, looking for older and newer rooms of the given room.\n * @param roomId - The room ID to search from\n * @param verifyLinks - If true, the function will only return rooms\n * which can be proven to be linked. For example, rooms which have a create\n * event pointing to an old room which the client is not aware of or doesn't\n * have a matching tombstone would not be returned.\n * @param msc3946ProcessDynamicPredecessor - if true, look for\n * m.room.predecessor state events as well as create events, and prefer\n * predecessor events where they exist (MSC3946).\n * @returns An array of rooms representing the upgrade\n * history.\n */\n public getRoomUpgradeHistory(\n roomId: string,\n verifyLinks = false,\n msc3946ProcessDynamicPredecessor = false,\n ): Room[] {\n const currentRoom = this.getRoom(roomId);\n if (!currentRoom) return [];\n\n const before = this.findPredecessorRooms(currentRoom, verifyLinks, msc3946ProcessDynamicPredecessor);\n const after = this.findSuccessorRooms(currentRoom, verifyLinks, msc3946ProcessDynamicPredecessor);\n\n return [...before, currentRoom, ...after];\n }\n\n private findPredecessorRooms(room: Room, verifyLinks: boolean, msc3946ProcessDynamicPredecessor: boolean): Room[] {\n const ret: Room[] = [];\n\n // Work backwards from newer to older rooms\n let predecessorRoomId = room.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n while (predecessorRoomId !== null) {\n const predecessorRoom = this.getRoom(predecessorRoomId);\n if (predecessorRoom === null) {\n break;\n }\n if (verifyLinks) {\n const tombstone = predecessorRoom.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n if (!tombstone || tombstone.getContent()[\"replacement_room\"] !== room.roomId) {\n break;\n }\n }\n\n // Insert at the front because we're working backwards from the currentRoom\n ret.splice(0, 0, predecessorRoom);\n\n room = predecessorRoom;\n predecessorRoomId = room.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n }\n return ret;\n }\n\n private findSuccessorRooms(room: Room, verifyLinks: boolean, msc3946ProcessDynamicPredecessor: boolean): Room[] {\n const ret: Room[] = [];\n\n // Work forwards, looking at tombstone events\n let tombstoneEvent = room.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n while (tombstoneEvent) {\n const successorRoom = this.getRoom(tombstoneEvent.getContent()[\"replacement_room\"]);\n if (!successorRoom) break; // end of the chain\n if (successorRoom.roomId === room.roomId) break; // Tombstone is referencing its own room\n\n if (verifyLinks) {\n const predecessorRoomId = successorRoom.findPredecessor(msc3946ProcessDynamicPredecessor)?.roomId;\n if (!predecessorRoomId || predecessorRoomId !== room.roomId) {\n break;\n }\n }\n\n // Push to the end because we're looking forwards\n ret.push(successorRoom);\n const roomIds = new Set(ret.map((ref) => ref.roomId));\n if (roomIds.size < ret.length) {\n // The last room added to the list introduced a previous roomId\n // To avoid recursion, return the last rooms - 1\n return ret.slice(0, ret.length - 1);\n }\n\n // Set the current room to the reference room so we know where we're at\n room = successorRoom;\n tombstoneEvent = room.currentState.getStateEvents(EventType.RoomTombstone, \"\");\n }\n return ret;\n }\n\n /**\n * @param reason - Optional.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public invite(roomId: string, userId: string, reason?: string): Promise<{}> {\n return this.membershipChange(roomId, userId, \"invite\", reason);\n }\n\n /**\n * Invite a user to a room based on their email address.\n * @param roomId - The room to invite the user to.\n * @param email - The email address to invite.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public inviteByEmail(roomId: string, email: string): Promise<{}> {\n return this.inviteByThreePid(roomId, \"email\", email);\n }\n\n /**\n * Invite a user to a room based on a third-party identifier.\n * @param roomId - The room to invite the user to.\n * @param medium - The medium to invite the user e.g. \"email\".\n * @param address - The address for the specified medium.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public async inviteByThreePid(roomId: string, medium: string, address: string): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/invite\", { $roomId: roomId });\n\n const identityServerUrl = this.getIdentityServerUrl(true);\n if (!identityServerUrl) {\n return Promise.reject(\n new MatrixError({\n error: \"No supplied identity server URL\",\n errcode: \"ORG.MATRIX.JSSDK_MISSING_PARAM\",\n }),\n );\n }\n const params: Record = {\n id_server: identityServerUrl,\n medium: medium,\n address: address,\n };\n\n if (this.identityServer?.getAccessToken && (await this.doesServerAcceptIdentityAccessToken())) {\n const identityAccessToken = await this.identityServer.getAccessToken();\n if (identityAccessToken) {\n params[\"id_access_token\"] = identityAccessToken;\n }\n }\n\n return this.http.authedRequest(Method.Post, path, undefined, params);\n }\n\n /**\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public leave(roomId: string): Promise<{}> {\n return this.membershipChange(roomId, undefined, \"leave\");\n }\n\n /**\n * Leaves all rooms in the chain of room upgrades based on the given room. By\n * default, this will leave all the previous and upgraded rooms, including the\n * given room. To only leave the given room and any previous rooms, keeping the\n * upgraded (modern) rooms untouched supply `false` to `includeFuture`.\n * @param roomId - The room ID to start leaving at\n * @param includeFuture - If true, the whole chain (past and future) of\n * upgraded rooms will be left.\n * @returns Promise which resolves when completed with an object keyed\n * by room ID and value of the error encountered when leaving or null.\n */\n public leaveRoomChain(\n roomId: string,\n includeFuture = true,\n ): Promise<{ [roomId: string]: Error | MatrixError | null }> {\n const upgradeHistory = this.getRoomUpgradeHistory(roomId);\n\n let eligibleToLeave = upgradeHistory;\n if (!includeFuture) {\n eligibleToLeave = [];\n for (const room of upgradeHistory) {\n eligibleToLeave.push(room);\n if (room.roomId === roomId) {\n break;\n }\n }\n }\n\n const populationResults: { [roomId: string]: Error } = {};\n const promises: Promise[] = [];\n\n const doLeave = (roomId: string): Promise => {\n return this.leave(roomId)\n .then(() => {\n delete populationResults[roomId];\n })\n .catch((err) => {\n // suppress error\n populationResults[roomId] = err;\n });\n };\n\n for (const room of eligibleToLeave) {\n promises.push(doLeave(room.roomId));\n }\n\n return Promise.all(promises).then(() => populationResults);\n }\n\n /**\n * @param reason - Optional.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public ban(roomId: string, userId: string, reason?: string): Promise<{}> {\n return this.membershipChange(roomId, userId, \"ban\", reason);\n }\n\n /**\n * @param deleteRoom - True to delete the room from the store on success.\n * Default: true.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public forget(roomId: string, deleteRoom = true): Promise<{}> {\n const promise = this.membershipChange(roomId, undefined, \"forget\");\n if (!deleteRoom) {\n return promise;\n }\n return promise.then((response) => {\n this.store.removeRoom(roomId);\n this.emit(ClientEvent.DeleteRoom, roomId);\n return response;\n });\n }\n\n /**\n * @returns Promise which resolves: Object (currently empty)\n * @returns Rejects: with an error response.\n */\n public unban(roomId: string, userId: string): Promise<{}> {\n // unbanning != set their state to leave: this used to be\n // the case, but was then changed so that leaving was always\n // a revoking of privilege, otherwise two people racing to\n // kick / ban someone could end up banning and then un-banning\n // them.\n const path = utils.encodeUri(\"/rooms/$roomId/unban\", {\n $roomId: roomId,\n });\n const data = {\n user_id: userId,\n };\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n /**\n * @param reason - Optional.\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public kick(roomId: string, userId: string, reason?: string): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/kick\", {\n $roomId: roomId,\n });\n const data = {\n user_id: userId,\n reason: reason,\n };\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n private membershipChange(\n roomId: string,\n userId: string | undefined,\n membership: string,\n reason?: string,\n ): Promise<{}> {\n // API returns an empty object\n const path = utils.encodeUri(\"/rooms/$room_id/$membership\", {\n $room_id: roomId,\n $membership: membership,\n });\n return this.http.authedRequest(Method.Post, path, undefined, {\n user_id: userId, // may be undefined e.g. on leave\n reason: reason,\n });\n }\n\n /**\n * Obtain a dict of actions which should be performed for this event according\n * to the push rules for this user. Caches the dict on the event.\n * @param event - The event to get push actions for.\n * @param forceRecalculate - forces to recalculate actions for an event\n * Useful when an event just got decrypted\n * @returns A dict of actions to perform.\n */\n public getPushActionsForEvent(event: MatrixEvent, forceRecalculate = false): IActionsObject | null {\n if (!event.getPushActions() || forceRecalculate) {\n event.setPushActions(this.pushProcessor.actionsForEvent(event));\n }\n return event.getPushActions();\n }\n\n /**\n * @param info - The kind of info to set (e.g. 'avatar_url')\n * @param data - The JSON object to set.\n * @returns\n * @returns Rejects: with an error response.\n */\n // eslint-disable-next-line camelcase\n public setProfileInfo(info: \"avatar_url\", data: { avatar_url: string }): Promise<{}>;\n public setProfileInfo(info: \"displayname\", data: { displayname: string }): Promise<{}>;\n public setProfileInfo(info: \"avatar_url\" | \"displayname\", data: object): Promise<{}> {\n const path = utils.encodeUri(\"/profile/$userId/$info\", {\n $userId: this.credentials.userId!,\n $info: info,\n });\n return this.http.authedRequest(Method.Put, path, undefined, data);\n }\n\n /**\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public async setDisplayName(name: string): Promise<{}> {\n const prom = await this.setProfileInfo(\"displayname\", { displayname: name });\n // XXX: synthesise a profile update for ourselves because Synapse is broken and won't\n const user = this.getUser(this.getUserId()!);\n if (user) {\n user.displayName = name;\n user.emit(UserEvent.DisplayName, user.events.presence, user);\n }\n return prom;\n }\n\n /**\n * @returns Promise which resolves: `{}` an empty object.\n * @returns Rejects: with an error response.\n */\n public async setAvatarUrl(url: string): Promise<{}> {\n const prom = await this.setProfileInfo(\"avatar_url\", { avatar_url: url });\n // XXX: synthesise a profile update for ourselves because Synapse is broken and won't\n const user = this.getUser(this.getUserId()!);\n if (user) {\n user.avatarUrl = url;\n user.emit(UserEvent.AvatarUrl, user.events.presence, user);\n }\n return prom;\n }\n\n /**\n * Turn an MXC URL into an HTTP one. This method is experimental and\n * may change.\n * @param mxcUrl - The MXC URL\n * @param width - The desired width of the thumbnail.\n * @param height - The desired height of the thumbnail.\n * @param resizeMethod - The thumbnail resize method to use, either\n * \"crop\" or \"scale\".\n * @param allowDirectLinks - If true, return any non-mxc URLs\n * directly. Fetching such URLs will leak information about the user to\n * anyone they share a room with. If false, will return null for such URLs.\n * @returns the avatar URL or null.\n */\n public mxcUrlToHttp(\n mxcUrl: string,\n width?: number,\n height?: number,\n resizeMethod?: string,\n allowDirectLinks?: boolean,\n ): string | null {\n return getHttpUriForMxc(this.baseUrl, mxcUrl, width, height, resizeMethod, allowDirectLinks);\n }\n\n /**\n * @param opts - Options to apply\n * @returns Promise which resolves\n * @returns Rejects: with an error response.\n * @throws If 'presence' isn't a valid presence enum value.\n */\n public async setPresence(opts: IPresenceOpts): Promise {\n const path = utils.encodeUri(\"/presence/$userId/status\", {\n $userId: this.credentials.userId!,\n });\n\n const validStates = [\"offline\", \"online\", \"unavailable\"];\n if (validStates.indexOf(opts.presence) === -1) {\n throw new Error(\"Bad presence value: \" + opts.presence);\n }\n await this.http.authedRequest(Method.Put, path, undefined, opts);\n }\n\n /**\n * @param userId - The user to get presence for\n * @returns Promise which resolves: The presence state for this user.\n * @returns Rejects: with an error response.\n */\n public getPresence(userId: string): Promise {\n const path = utils.encodeUri(\"/presence/$userId/status\", {\n $userId: userId,\n });\n\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Retrieve older messages from the given room and put them in the timeline.\n *\n * If this is called multiple times whilst a request is ongoing, the same\n * Promise will be returned. If there was a problem requesting scrollback, there\n * will be a small delay before another request can be made (to prevent tight-looping\n * when there is no connection).\n *\n * @param room - The room to get older messages in.\n * @param limit - Optional. The maximum number of previous events to\n * pull in. Default: 30.\n * @returns Promise which resolves: Room. If you are at the beginning\n * of the timeline, `Room.oldState.paginationToken` will be\n * `null`.\n * @returns Rejects: with an error response.\n */\n public scrollback(room: Room, limit = 30): Promise {\n let timeToWaitMs = 0;\n\n let info = this.ongoingScrollbacks[room.roomId] || {};\n if (info.promise) {\n return info.promise;\n } else if (info.errorTs) {\n const timeWaitedMs = Date.now() - info.errorTs;\n timeToWaitMs = Math.max(SCROLLBACK_DELAY_MS - timeWaitedMs, 0);\n }\n\n if (room.oldState.paginationToken === null) {\n return Promise.resolve(room); // already at the start.\n }\n // attempt to grab more events from the store first\n const numAdded = this.store.scrollback(room, limit).length;\n if (numAdded === limit) {\n // store contained everything we needed.\n return Promise.resolve(room);\n }\n // reduce the required number of events appropriately\n limit = limit - numAdded;\n\n const promise = new Promise((resolve, reject) => {\n // wait for a time before doing this request\n // (which may be 0 in order not to special case the code paths)\n sleep(timeToWaitMs)\n .then(() => {\n return this.createMessagesRequest(\n room.roomId,\n room.oldState.paginationToken,\n limit,\n Direction.Backward,\n );\n })\n .then((res: IMessagesResponse) => {\n const matrixEvents = res.chunk.map(this.getEventMapper());\n if (res.state) {\n const stateEvents = res.state.map(this.getEventMapper());\n room.currentState.setUnknownStateEvents(stateEvents);\n }\n\n const [timelineEvents, threadedEvents] = room.partitionThreadedEvents(matrixEvents);\n\n this.processAggregatedTimelineEvents(room, timelineEvents);\n room.addEventsToTimeline(timelineEvents, true, room.getLiveTimeline());\n this.processThreadEvents(room, threadedEvents, true);\n\n room.oldState.paginationToken = res.end ?? null;\n if (res.chunk.length === 0) {\n room.oldState.paginationToken = null;\n }\n this.store.storeEvents(room, matrixEvents, res.end ?? null, true);\n delete this.ongoingScrollbacks[room.roomId];\n resolve(room);\n })\n .catch((err) => {\n this.ongoingScrollbacks[room.roomId] = {\n errorTs: Date.now(),\n };\n reject(err);\n });\n });\n\n info = { promise };\n\n this.ongoingScrollbacks[room.roomId] = info;\n return promise;\n }\n\n public getEventMapper(options?: MapperOpts): EventMapper {\n return eventMapperFor(this, options || {});\n }\n\n /**\n * Get an EventTimeline for the given event\n *\n *

If the EventTimelineSet object already has the given event in its store, the\n * corresponding timeline will be returned. Otherwise, a /context request is\n * made, and used to construct an EventTimeline.\n * If the event does not belong to this EventTimelineSet then undefined will be returned.\n *\n * @param timelineSet - The timelineSet to look for the event in, must be bound to a room\n * @param eventId - The ID of the event to look for\n *\n * @returns Promise which resolves:\n * {@link EventTimeline} including the given event\n */\n public async getEventTimeline(timelineSet: EventTimelineSet, eventId: string): Promise> {\n // don't allow any timeline support unless it's been enabled.\n if (!this.timelineSupport) {\n throw new Error(\n \"timeline support is disabled. Set the 'timelineSupport'\" +\n \" parameter to true when creating MatrixClient to enable it.\",\n );\n }\n\n if (!timelineSet?.room) {\n throw new Error(\"getEventTimeline only supports room timelines\");\n }\n\n if (timelineSet.getTimelineForEvent(eventId)) {\n return timelineSet.getTimelineForEvent(eventId);\n }\n\n if (timelineSet.thread && this.supportsThreads()) {\n return this.getThreadTimeline(timelineSet, eventId);\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/context/$eventId\", {\n $roomId: timelineSet.room.roomId,\n $eventId: eventId,\n });\n\n let params: Record | undefined = undefined;\n if (this.clientOpts?.lazyLoadMembers) {\n params = { filter: JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER) };\n }\n\n // TODO: we should implement a backoff (as per scrollback()) to deal more nicely with HTTP errors.\n const res = await this.http.authedRequest(Method.Get, path, params);\n if (!res.event) {\n throw new Error(\"'event' not in '/context' result - homeserver too old?\");\n }\n\n // by the time the request completes, the event might have ended up in the timeline.\n if (timelineSet.getTimelineForEvent(eventId)) {\n return timelineSet.getTimelineForEvent(eventId);\n }\n\n const mapper = this.getEventMapper();\n const event = mapper(res.event);\n if (event.isRelation(THREAD_RELATION_TYPE.name)) {\n logger.warn(\"Tried loading a regular timeline at the position of a thread event\");\n return undefined;\n }\n const events = [\n // Order events from most recent to oldest (reverse-chronological).\n // We start with the last event, since that's the point at which we have known state.\n // events_after is already backwards; events_before is forwards.\n ...res.events_after.reverse().map(mapper),\n event,\n ...res.events_before.map(mapper),\n ];\n\n // Here we handle non-thread timelines only, but still process any thread events to populate thread summaries.\n let timeline = timelineSet.getTimelineForEvent(events[0].getId());\n if (timeline) {\n timeline.getState(EventTimeline.BACKWARDS)!.setUnknownStateEvents(res.state.map(mapper));\n } else {\n timeline = timelineSet.addTimeline();\n timeline.initialiseState(res.state.map(mapper));\n timeline.getState(EventTimeline.FORWARDS)!.paginationToken = res.end;\n }\n\n const [timelineEvents, threadedEvents] = timelineSet.room.partitionThreadedEvents(events);\n timelineSet.addEventsToTimeline(timelineEvents, true, timeline, res.start);\n // The target event is not in a thread but process the contextual events, so we can show any threads around it.\n this.processThreadEvents(timelineSet.room, threadedEvents, true);\n this.processAggregatedTimelineEvents(timelineSet.room, timelineEvents);\n\n // There is no guarantee that the event ended up in \"timeline\" (we might have switched to a neighbouring\n // timeline) - so check the room's index again. On the other hand, there's no guarantee the event ended up\n // anywhere, if it was later redacted, so we just return the timeline we first thought of.\n return (\n timelineSet.getTimelineForEvent(eventId) ??\n timelineSet.room.findThreadForEvent(event)?.liveTimeline ?? // for Threads degraded support\n timeline\n );\n }\n\n public async getThreadTimeline(timelineSet: EventTimelineSet, eventId: string): Promise {\n if (!this.supportsThreads()) {\n throw new Error(\"could not get thread timeline: no client support\");\n }\n\n if (!timelineSet.room) {\n throw new Error(\"could not get thread timeline: not a room timeline\");\n }\n\n if (!timelineSet.thread) {\n throw new Error(\"could not get thread timeline: not a thread timeline\");\n }\n\n const path = utils.encodeUri(\"/rooms/$roomId/context/$eventId\", {\n $roomId: timelineSet.room.roomId,\n $eventId: eventId,\n });\n\n const params: Record = {\n limit: \"0\",\n };\n if (this.clientOpts?.lazyLoadMembers) {\n params.filter = JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER);\n }\n\n // TODO: we should implement a backoff (as per scrollback()) to deal more nicely with HTTP errors.\n const res = await this.http.authedRequest(Method.Get, path, params);\n const mapper = this.getEventMapper();\n const event = mapper(res.event);\n\n if (!timelineSet.canContain(event)) {\n return undefined;\n }\n\n if (Thread.hasServerSideSupport) {\n if (Thread.hasServerSideFwdPaginationSupport) {\n if (!timelineSet.thread) {\n throw new Error(\"could not get thread timeline: not a thread timeline\");\n }\n\n const thread = timelineSet.thread;\n const resOlder: IRelationsResponse = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n THREAD_RELATION_TYPE.name,\n null,\n { dir: Direction.Backward, from: res.start },\n );\n const resNewer: IRelationsResponse = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n THREAD_RELATION_TYPE.name,\n null,\n { dir: Direction.Forward, from: res.end },\n );\n const events = [\n // Order events from most recent to oldest (reverse-chronological).\n // We start with the last event, since that's the point at which we have known state.\n // events_after is already backwards; events_before is forwards.\n ...resNewer.chunk.reverse().map(mapper),\n event,\n ...resOlder.chunk.map(mapper),\n ];\n for (const event of events) {\n await timelineSet.thread?.processEvent(event);\n }\n\n // Here we handle non-thread timelines only, but still process any thread events to populate thread summaries.\n let timeline = timelineSet.getTimelineForEvent(event.getId());\n if (timeline) {\n timeline.getState(EventTimeline.BACKWARDS)!.setUnknownStateEvents(res.state.map(mapper));\n } else {\n timeline = timelineSet.addTimeline();\n timeline.initialiseState(res.state.map(mapper));\n }\n\n timelineSet.addEventsToTimeline(events, true, timeline, resNewer.next_batch);\n if (!resOlder.next_batch) {\n const originalEvent = await this.fetchRoomEvent(timelineSet.room.roomId, thread.id);\n timelineSet.addEventsToTimeline([mapper(originalEvent)], true, timeline, null);\n }\n timeline.setPaginationToken(resOlder.next_batch ?? null, Direction.Backward);\n timeline.setPaginationToken(resNewer.next_batch ?? null, Direction.Forward);\n this.processAggregatedTimelineEvents(timelineSet.room, events);\n\n // There is no guarantee that the event ended up in \"timeline\" (we might have switched to a neighbouring\n // timeline) - so check the room's index again. On the other hand, there's no guarantee the event ended up\n // anywhere, if it was later redacted, so we just return the timeline we first thought of.\n return timelineSet.getTimelineForEvent(eventId) ?? timeline;\n } else {\n // Where the event is a thread reply (not a root) and running in MSC-enabled mode the Thread timeline only\n // functions contiguously, so we have to jump through some hoops to get our target event in it.\n // XXX: workaround for https://github.com/vector-im/element-meta/issues/150\n\n const thread = timelineSet.thread;\n\n const resOlder = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n THREAD_RELATION_TYPE.name,\n null,\n { dir: Direction.Backward, from: res.start },\n );\n const eventsNewer: IEvent[] = [];\n let nextBatch: Optional = res.end;\n while (nextBatch) {\n const resNewer: IRelationsResponse = await this.fetchRelations(\n timelineSet.room.roomId,\n thread.id,\n THREAD_RELATION_TYPE.name,\n null,\n { dir: Direction.Forward, from: nextBatch },\n );\n nextBatch = resNewer.next_batch ?? null;\n eventsNewer.push(...resNewer.chunk);\n }\n const events = [\n // Order events from most recent to oldest (reverse-chronological).\n // We start with the last event, since that's the point at which we have known state.\n // events_after is already backwards; events_before is forwards.\n ...eventsNewer.reverse().map(mapper),\n event,\n ...resOlder.chunk.map(mapper),\n ];\n for (const event of events) {\n await timelineSet.thread?.processEvent(event);\n }\n\n // Here we handle non-thread timelines only, but still process any thread events to populate thread\n // summaries.\n const timeline = timelineSet.getLiveTimeline();\n timeline.getState(EventTimeline.BACKWARDS)!.setUnknownStateEvents(res.state.map(mapper));\n\n timelineSet.addEventsToTimeline(events, true, timeline, null);\n if (!resOlder.next_batch) {\n const originalEvent = await this.fetchRoomEvent(timelineSet.room.roomId, thread.id);\n timelineSet.addEventsToTimeline([mapper(originalEvent)], true, timeline, null);\n }\n timeline.setPaginationToken(resOlder.next_batch ?? null, Direction.Backward);\n timeline.setPaginationToken(null, Direction.Forward);\n this.processAggregatedTimelineEvents(timelineSet.room, events);\n\n return timeline;\n }\n }\n }\n\n /**\n * Get an EventTimeline for the latest events in the room. This will just\n * call `/messages` to get the latest message in the room, then use\n * `client.getEventTimeline(...)` to construct a new timeline from it.\n *\n * @param timelineSet - The timelineSet to find or add the timeline to\n *\n * @returns Promise which resolves:\n * {@link EventTimeline} timeline with the latest events in the room\n */\n public async getLatestTimeline(timelineSet: EventTimelineSet): Promise> {\n // don't allow any timeline support unless it's been enabled.\n if (!this.timelineSupport) {\n throw new Error(\n \"timeline support is disabled. Set the 'timelineSupport'\" +\n \" parameter to true when creating MatrixClient to enable it.\",\n );\n }\n\n if (!timelineSet.room) {\n throw new Error(\"getLatestTimeline only supports room timelines\");\n }\n\n let event;\n if (timelineSet.threadListType !== null) {\n const res = await this.createThreadListMessagesRequest(\n timelineSet.room.roomId,\n null,\n 1,\n Direction.Backward,\n timelineSet.threadListType,\n timelineSet.getFilter(),\n );\n event = res.chunk?.[0];\n } else if (timelineSet.thread && Thread.hasServerSideSupport) {\n const res = await this.fetchRelations(\n timelineSet.room.roomId,\n timelineSet.thread.id,\n THREAD_RELATION_TYPE.name,\n null,\n { dir: Direction.Backward, limit: 1 },\n );\n event = res.chunk?.[0];\n } else {\n const messagesPath = utils.encodeUri(\"/rooms/$roomId/messages\", {\n $roomId: timelineSet.room.roomId,\n });\n\n const params: Record = {\n dir: \"b\",\n };\n if (this.clientOpts?.lazyLoadMembers) {\n params.filter = JSON.stringify(Filter.LAZY_LOADING_MESSAGES_FILTER);\n }\n\n const res = await this.http.authedRequest(Method.Get, messagesPath, params);\n event = res.chunk?.[0];\n }\n if (!event) {\n throw new Error(\"No message returned when trying to construct getLatestTimeline\");\n }\n\n return this.getEventTimeline(timelineSet, event.event_id);\n }\n\n /**\n * Makes a request to /messages with the appropriate lazy loading filter set.\n * XXX: if we do get rid of scrollback (as it's not used at the moment),\n * we could inline this method again in paginateEventTimeline as that would\n * then be the only call-site\n * @param limit - the maximum amount of events the retrieve\n * @param dir - 'f' or 'b'\n * @param timelineFilter - the timeline filter to pass\n */\n // XXX: Intended private, used in code.\n public createMessagesRequest(\n roomId: string,\n fromToken: string | null,\n limit = 30,\n dir: Direction,\n timelineFilter?: Filter,\n ): Promise {\n const path = utils.encodeUri(\"/rooms/$roomId/messages\", { $roomId: roomId });\n\n const params: Record = {\n limit: limit.toString(),\n dir: dir,\n };\n\n if (fromToken) {\n params.from = fromToken;\n }\n\n let filter: IRoomEventFilter | null = null;\n if (this.clientOpts?.lazyLoadMembers) {\n // create a shallow copy of LAZY_LOADING_MESSAGES_FILTER,\n // so the timelineFilter doesn't get written into it below\n filter = Object.assign({}, Filter.LAZY_LOADING_MESSAGES_FILTER);\n }\n if (timelineFilter) {\n // XXX: it's horrific that /messages' filter parameter doesn't match\n // /sync's one - see https://matrix.org/jira/browse/SPEC-451\n filter = filter || {};\n Object.assign(filter, timelineFilter.getRoomTimelineFilterComponent()?.toJSON());\n }\n if (filter) {\n params.filter = JSON.stringify(filter);\n }\n return this.http.authedRequest(Method.Get, path, params);\n }\n\n /**\n * Makes a request to /messages with the appropriate lazy loading filter set.\n * XXX: if we do get rid of scrollback (as it's not used at the moment),\n * we could inline this method again in paginateEventTimeline as that would\n * then be the only call-site\n * @param limit - the maximum amount of events the retrieve\n * @param dir - 'f' or 'b'\n * @param timelineFilter - the timeline filter to pass\n */\n // XXX: Intended private, used by room.fetchRoomThreads\n public createThreadListMessagesRequest(\n roomId: string,\n fromToken: string | null,\n limit = 30,\n dir = Direction.Backward,\n threadListType: ThreadFilterType | null = ThreadFilterType.All,\n timelineFilter?: Filter,\n ): Promise {\n const path = utils.encodeUri(\"/rooms/$roomId/threads\", { $roomId: roomId });\n\n const params: Record = {\n limit: limit.toString(),\n dir: dir,\n include: threadFilterTypeToFilter(threadListType),\n };\n\n if (fromToken) {\n params.from = fromToken;\n }\n\n let filter: IRoomEventFilter = {};\n if (this.clientOpts?.lazyLoadMembers) {\n // create a shallow copy of LAZY_LOADING_MESSAGES_FILTER,\n // so the timelineFilter doesn't get written into it below\n filter = {\n ...Filter.LAZY_LOADING_MESSAGES_FILTER,\n };\n }\n if (timelineFilter) {\n // XXX: it's horrific that /messages' filter parameter doesn't match\n // /sync's one - see https://matrix.org/jira/browse/SPEC-451\n filter = {\n ...filter,\n ...timelineFilter.getRoomTimelineFilterComponent()?.toJSON(),\n };\n }\n if (Object.keys(filter).length) {\n params.filter = JSON.stringify(filter);\n }\n\n const opts = {\n prefix:\n Thread.hasServerSideListSupport === FeatureSupport.Stable\n ? \"/_matrix/client/v1\"\n : \"/_matrix/client/unstable/org.matrix.msc3856\",\n };\n\n return this.http\n .authedRequest(Method.Get, path, params, undefined, opts)\n .then((res) => ({\n ...res,\n chunk: res.chunk?.reverse(),\n start: res.prev_batch,\n end: res.next_batch,\n }));\n }\n\n /**\n * Take an EventTimeline, and back/forward-fill results.\n *\n * @param eventTimeline - timeline object to be updated\n *\n * @returns Promise which resolves to a boolean: false if there are no\n * events and we reached either end of the timeline; else true.\n */\n public paginateEventTimeline(eventTimeline: EventTimeline, opts: IPaginateOpts): Promise {\n const isNotifTimeline = eventTimeline.getTimelineSet() === this.notifTimelineSet;\n const room = this.getRoom(eventTimeline.getRoomId()!);\n const threadListType = eventTimeline.getTimelineSet().threadListType;\n const thread = eventTimeline.getTimelineSet().thread;\n\n // TODO: we should implement a backoff (as per scrollback()) to deal more\n // nicely with HTTP errors.\n opts = opts || {};\n const backwards = opts.backwards || false;\n\n if (isNotifTimeline) {\n if (!backwards) {\n throw new Error(\"paginateNotifTimeline can only paginate backwards\");\n }\n }\n\n const dir = backwards ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS;\n\n const token = eventTimeline.getPaginationToken(dir);\n const pendingRequest = eventTimeline.paginationRequests[dir];\n\n if (pendingRequest) {\n // already a request in progress - return the existing promise\n return pendingRequest;\n }\n\n let path: string;\n let params: Record;\n let promise: Promise;\n\n if (isNotifTimeline) {\n path = \"/notifications\";\n params = {\n limit: (opts.limit ?? 30).toString(),\n only: \"highlight\",\n };\n\n if (token && token !== \"end\") {\n params.from = token;\n }\n\n promise = this.http\n .authedRequest(Method.Get, path, params)\n .then(async (res) => {\n const token = res.next_token;\n const matrixEvents: MatrixEvent[] = [];\n\n res.notifications = res.notifications.filter(noUnsafeEventProps);\n\n for (let i = 0; i < res.notifications.length; i++) {\n const notification = res.notifications[i];\n const event = this.getEventMapper()(notification.event);\n event.setPushActions(PushProcessor.actionListToActionsObject(notification.actions));\n event.event.room_id = notification.room_id; // XXX: gutwrenching\n matrixEvents[i] = event;\n }\n\n // No need to partition events for threads here, everything lives\n // in the notification timeline set\n const timelineSet = eventTimeline.getTimelineSet();\n timelineSet.addEventsToTimeline(matrixEvents, backwards, eventTimeline, token);\n this.processAggregatedTimelineEvents(timelineSet.room, matrixEvents);\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && !res.next_token) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return Boolean(res.next_token);\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n } else if (threadListType !== null) {\n if (!room) {\n throw new Error(\"Unknown room \" + eventTimeline.getRoomId());\n }\n\n if (!Thread.hasServerSideFwdPaginationSupport && dir === Direction.Forward) {\n throw new Error(\"Cannot paginate threads forwards without server-side support for MSC 3715\");\n }\n\n promise = this.createThreadListMessagesRequest(\n eventTimeline.getRoomId()!,\n token,\n opts.limit,\n dir,\n threadListType,\n eventTimeline.getFilter(),\n )\n .then((res) => {\n if (res.state) {\n const roomState = eventTimeline.getState(dir)!;\n const stateEvents = res.state.filter(noUnsafeEventProps).map(this.getEventMapper());\n roomState.setUnknownStateEvents(stateEvents);\n }\n const token = res.end;\n const matrixEvents = res.chunk.filter(noUnsafeEventProps).map(this.getEventMapper());\n\n const timelineSet = eventTimeline.getTimelineSet();\n timelineSet.addEventsToTimeline(matrixEvents, backwards, eventTimeline, token);\n this.processAggregatedTimelineEvents(room, matrixEvents);\n this.processThreadRoots(room, matrixEvents, backwards);\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && res.end == res.start) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return res.end !== res.start;\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n } else if (thread) {\n const room = this.getRoom(eventTimeline.getRoomId() ?? undefined);\n if (!room) {\n throw new Error(\"Unknown room \" + eventTimeline.getRoomId());\n }\n\n promise = this.fetchRelations(eventTimeline.getRoomId() ?? \"\", thread.id, THREAD_RELATION_TYPE.name, null, {\n dir,\n limit: opts.limit,\n from: token ?? undefined,\n })\n .then(async (res) => {\n const mapper = this.getEventMapper();\n const matrixEvents = res.chunk.filter(noUnsafeEventProps).map(mapper);\n\n // Process latest events first\n for (const event of matrixEvents.slice().reverse()) {\n await thread?.processEvent(event);\n const sender = event.getSender()!;\n if (!backwards || thread?.getEventReadUpTo(sender) === null) {\n room.addLocalEchoReceipt(sender, event, ReceiptType.Read);\n }\n }\n\n const newToken = res.next_batch;\n\n const timelineSet = eventTimeline.getTimelineSet();\n timelineSet.addEventsToTimeline(matrixEvents, backwards, eventTimeline, newToken ?? null);\n if (!newToken && backwards) {\n const originalEvent = await this.fetchRoomEvent(eventTimeline.getRoomId() ?? \"\", thread.id);\n timelineSet.addEventsToTimeline([mapper(originalEvent)], true, eventTimeline, null);\n }\n this.processAggregatedTimelineEvents(timelineSet.room, matrixEvents);\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && !newToken) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return Boolean(newToken);\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n } else {\n if (!room) {\n throw new Error(\"Unknown room \" + eventTimeline.getRoomId());\n }\n\n promise = this.createMessagesRequest(\n eventTimeline.getRoomId()!,\n token,\n opts.limit,\n dir,\n eventTimeline.getFilter(),\n )\n .then((res) => {\n if (res.state) {\n const roomState = eventTimeline.getState(dir)!;\n const stateEvents = res.state.filter(noUnsafeEventProps).map(this.getEventMapper());\n roomState.setUnknownStateEvents(stateEvents);\n }\n const token = res.end;\n const matrixEvents = res.chunk.filter(noUnsafeEventProps).map(this.getEventMapper());\n\n const timelineSet = eventTimeline.getTimelineSet();\n const [timelineEvents] = room.partitionThreadedEvents(matrixEvents);\n timelineSet.addEventsToTimeline(timelineEvents, backwards, eventTimeline, token);\n this.processAggregatedTimelineEvents(room, timelineEvents);\n this.processThreadRoots(\n room,\n timelineEvents.filter((it) => it.getServerAggregatedRelation(THREAD_RELATION_TYPE.name)),\n false,\n );\n\n const atEnd = res.end === undefined || res.end === res.start;\n\n // if we've hit the end of the timeline, we need to stop trying to\n // paginate. We need to keep the 'forwards' token though, to make sure\n // we can recover from gappy syncs.\n if (backwards && atEnd) {\n eventTimeline.setPaginationToken(null, dir);\n }\n return !atEnd;\n })\n .finally(() => {\n eventTimeline.paginationRequests[dir] = null;\n });\n eventTimeline.paginationRequests[dir] = promise;\n }\n\n return promise;\n }\n\n /**\n * Reset the notifTimelineSet entirely, paginating in some historical notifs as\n * a starting point for subsequent pagination.\n */\n public resetNotifTimelineSet(): void {\n if (!this.notifTimelineSet) {\n return;\n }\n\n // FIXME: This thing is a total hack, and results in duplicate events being\n // added to the timeline both from /sync and /notifications, and lots of\n // slow and wasteful processing and pagination. The correct solution is to\n // extend /messages or /search or something to filter on notifications.\n\n // use the fictitious token 'end'. in practice we would ideally give it\n // the oldest backwards pagination token from /sync, but /sync doesn't\n // know about /notifications, so we have no choice but to start paginating\n // from the current point in time. This may well overlap with historical\n // notifs which are then inserted into the timeline by /sync responses.\n this.notifTimelineSet.resetLiveTimeline(\"end\");\n\n // we could try to paginate a single event at this point in order to get\n // a more valid pagination token, but it just ends up with an out of order\n // timeline. given what a mess this is and given we're going to have duplicate\n // events anyway, just leave it with the dummy token for now.\n /*\n this.paginateNotifTimeline(this._notifTimelineSet.getLiveTimeline(), {\n backwards: true,\n limit: 1\n });\n */\n }\n\n /**\n * Peek into a room and receive updates about the room. This only works if the\n * history visibility for the room is world_readable.\n * @param roomId - The room to attempt to peek into.\n * @returns Promise which resolves: Room object\n * @returns Rejects: with an error response.\n */\n public peekInRoom(roomId: string): Promise {\n this.peekSync?.stopPeeking();\n this.peekSync = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n return this.peekSync.peek(roomId);\n }\n\n /**\n * Stop any ongoing room peeking.\n */\n public stopPeeking(): void {\n if (this.peekSync) {\n this.peekSync.stopPeeking();\n this.peekSync = null;\n }\n }\n\n /**\n * Set r/w flags for guest access in a room.\n * @param roomId - The room to configure guest access in.\n * @param opts - Options\n * @returns Promise which resolves\n * @returns Rejects: with an error response.\n */\n public setGuestAccess(roomId: string, opts: IGuestAccessOpts): Promise {\n const writePromise = this.sendStateEvent(\n roomId,\n EventType.RoomGuestAccess,\n {\n guest_access: opts.allowJoin ? \"can_join\" : \"forbidden\",\n },\n \"\",\n );\n\n let readPromise: Promise = Promise.resolve(undefined);\n if (opts.allowRead) {\n readPromise = this.sendStateEvent(\n roomId,\n EventType.RoomHistoryVisibility,\n {\n history_visibility: \"world_readable\",\n },\n \"\",\n );\n }\n\n return Promise.all([readPromise, writePromise]).then(); // .then() to hide results for contract\n }\n\n /**\n * Requests an email verification token for the purposes of registration.\n * This API requests a token from the homeserver.\n * The doesServerRequireIdServerParam() method can be used to determine if\n * the server requires the id_server parameter to be provided.\n *\n * Parameters and return value are as for requestEmailToken\n\n * @param email - As requestEmailToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestRegisterEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise {\n return this.requestTokenFromEndpoint(\"/register/email/requestToken\", {\n email: email,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests a text message verification token for the purposes of registration.\n * This API requests a token from the homeserver.\n * The doesServerRequireIdServerParam() method can be used to determine if\n * the server requires the id_server parameter to be provided.\n *\n * @param phoneCountry - The ISO 3166-1 alpha-2 code for the country in which\n * phoneNumber should be parsed relative to.\n * @param phoneNumber - The phone number, in national or international format\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestRegisterMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise {\n return this.requestTokenFromEndpoint(\"/register/msisdn/requestToken\", {\n country: phoneCountry,\n phone_number: phoneNumber,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests an email verification token for the purposes of adding a\n * third party identifier to an account.\n * This API requests a token from the homeserver.\n * The doesServerRequireIdServerParam() method can be used to determine if\n * the server requires the id_server parameter to be provided.\n * If an account with the given email address already exists and is\n * associated with an account other than the one the user is authed as,\n * it will either send an email to the address informing them of this\n * or return M_THREEPID_IN_USE (which one is up to the homeserver).\n *\n * @param email - As requestEmailToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestAdd3pidEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise {\n return this.requestTokenFromEndpoint(\"/account/3pid/email/requestToken\", {\n email: email,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests a text message verification token for the purposes of adding a\n * third party identifier to an account.\n * This API proxies the identity server /validate/email/requestToken API,\n * adding specific behaviour for the addition of phone numbers to an\n * account, as requestAdd3pidEmailToken.\n *\n * @param phoneCountry - As requestRegisterMsisdnToken\n * @param phoneNumber - As requestRegisterMsisdnToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestAdd3pidMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise {\n return this.requestTokenFromEndpoint(\"/account/3pid/msisdn/requestToken\", {\n country: phoneCountry,\n phone_number: phoneNumber,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests an email verification token for the purposes of resetting\n * the password on an account.\n * This API proxies the identity server /validate/email/requestToken API,\n * adding specific behaviour for the password resetting. Specifically,\n * if no account with the given email address exists, it may either\n * return M_THREEPID_NOT_FOUND or send an email\n * to the address informing them of this (which one is up to the homeserver).\n *\n * requestEmailToken calls the equivalent API directly on the identity server,\n * therefore bypassing the password reset specific logic.\n *\n * @param email - As requestEmailToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestPasswordEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n ): Promise {\n return this.requestTokenFromEndpoint(\"/account/password/email/requestToken\", {\n email: email,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Requests a text message verification token for the purposes of resetting\n * the password on an account.\n * This API proxies the identity server /validate/email/requestToken API,\n * adding specific behaviour for the password resetting, as requestPasswordEmailToken.\n *\n * @param phoneCountry - As requestRegisterMsisdnToken\n * @param phoneNumber - As requestRegisterMsisdnToken\n * @param clientSecret - As requestEmailToken\n * @param sendAttempt - As requestEmailToken\n * @param nextLink - As requestEmailToken\n * @returns Promise which resolves: As requestEmailToken\n */\n public requestPasswordMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink: string,\n ): Promise {\n return this.requestTokenFromEndpoint(\"/account/password/msisdn/requestToken\", {\n country: phoneCountry,\n phone_number: phoneNumber,\n client_secret: clientSecret,\n send_attempt: sendAttempt,\n next_link: nextLink,\n });\n }\n\n /**\n * Internal utility function for requesting validation tokens from usage-specific\n * requestToken endpoints.\n *\n * @param endpoint - The endpoint to send the request to\n * @param params - Parameters for the POST request\n * @returns Promise which resolves: As requestEmailToken\n */\n private async requestTokenFromEndpoint(\n endpoint: string,\n params: Record,\n ): Promise {\n const postParams = Object.assign({}, params);\n\n // If the HS supports separate add and bind, then requestToken endpoints\n // don't need an IS as they are all validated by the HS directly.\n if (!(await this.doesServerSupportSeparateAddAndBind()) && this.idBaseUrl) {\n const idServerUrl = new URL(this.idBaseUrl);\n postParams.id_server = idServerUrl.host;\n\n if (this.identityServer?.getAccessToken && (await this.doesServerAcceptIdentityAccessToken())) {\n const identityAccessToken = await this.identityServer.getAccessToken();\n if (identityAccessToken) {\n postParams.id_access_token = identityAccessToken;\n }\n }\n }\n\n return this.http.request(Method.Post, endpoint, undefined, postParams);\n }\n\n /**\n * Get the room-kind push rule associated with a room.\n * @param scope - \"global\" or device-specific.\n * @param roomId - the id of the room.\n * @returns the rule or undefined.\n */\n public getRoomPushRule(scope: \"global\" | \"device\", roomId: string): IPushRule | undefined {\n // There can be only room-kind push rule per room\n // and its id is the room id.\n if (this.pushRules) {\n return this.pushRules[scope]?.room?.find((rule) => rule.rule_id === roomId);\n } else {\n throw new Error(\"SyncApi.sync() must be done before accessing to push rules.\");\n }\n }\n\n /**\n * Set a room-kind muting push rule in a room.\n * The operation also updates MatrixClient.pushRules at the end.\n * @param scope - \"global\" or device-specific.\n * @param roomId - the id of the room.\n * @param mute - the mute state.\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public setRoomMutePushRule(scope: \"global\" | \"device\", roomId: string, mute: boolean): Promise | undefined {\n let promise: Promise | undefined;\n let hasDontNotifyRule = false;\n\n // Get the existing room-kind push rule if any\n const roomPushRule = this.getRoomPushRule(scope, roomId);\n if (roomPushRule?.actions.includes(PushRuleActionName.DontNotify)) {\n hasDontNotifyRule = true;\n }\n\n if (!mute) {\n // Remove the rule only if it is a muting rule\n if (hasDontNotifyRule) {\n promise = this.deletePushRule(scope, PushRuleKind.RoomSpecific, roomPushRule!.rule_id);\n }\n } else {\n if (!roomPushRule) {\n promise = this.addPushRule(scope, PushRuleKind.RoomSpecific, roomId, {\n actions: [PushRuleActionName.DontNotify],\n });\n } else if (!hasDontNotifyRule) {\n // Remove the existing one before setting the mute push rule\n // This is a workaround to SYN-590 (Push rule update fails)\n const deferred = utils.defer();\n this.deletePushRule(scope, PushRuleKind.RoomSpecific, roomPushRule.rule_id)\n .then(() => {\n this.addPushRule(scope, PushRuleKind.RoomSpecific, roomId, {\n actions: [PushRuleActionName.DontNotify],\n })\n .then(() => {\n deferred.resolve();\n })\n .catch((err) => {\n deferred.reject(err);\n });\n })\n .catch((err) => {\n deferred.reject(err);\n });\n\n promise = deferred.promise;\n }\n }\n\n if (promise) {\n return new Promise((resolve, reject) => {\n // Update this.pushRules when the operation completes\n promise!\n .then(() => {\n this.getPushRules()\n .then((result) => {\n this.pushRules = result;\n resolve();\n })\n .catch((err) => {\n reject(err);\n });\n })\n .catch((err: Error) => {\n // Update it even if the previous operation fails. This can help the\n // app to recover when push settings has been modified from another client\n this.getPushRules()\n .then((result) => {\n this.pushRules = result;\n reject(err);\n })\n .catch((err2) => {\n reject(err);\n });\n });\n });\n }\n }\n\n public searchMessageText(opts: ISearchOpts): Promise {\n const roomEvents: ISearchRequestBody[\"search_categories\"][\"room_events\"] = {\n search_term: opts.query,\n };\n\n if (\"keys\" in opts) {\n roomEvents.keys = opts.keys;\n }\n\n return this.search({\n body: {\n search_categories: {\n room_events: roomEvents,\n },\n },\n });\n }\n\n /**\n * Perform a server-side search for room events.\n *\n * The returned promise resolves to an object containing the fields:\n *\n * * count: estimate of the number of results\n * * next_batch: token for back-pagination; if undefined, there are no more results\n * * highlights: a list of words to highlight from the stemming algorithm\n * * results: a list of results\n *\n * Each entry in the results list is a SearchResult.\n *\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public searchRoomEvents(opts: IEventSearchOpts): Promise {\n // TODO: support search groups\n\n const body = {\n search_categories: {\n room_events: {\n search_term: opts.term,\n filter: opts.filter,\n order_by: SearchOrderBy.Recent,\n event_context: {\n before_limit: 1,\n after_limit: 1,\n include_profile: true,\n },\n },\n },\n };\n\n const searchResults: ISearchResults = {\n _query: body,\n results: [],\n highlights: [],\n };\n\n return this.search({ body: body }).then((res) => this.processRoomEventsSearch(searchResults, res));\n }\n\n /**\n * Take a result from an earlier searchRoomEvents call, and backfill results.\n *\n * @param searchResults - the results object to be updated\n * @returns Promise which resolves: updated result object\n * @returns Rejects: with an error response.\n */\n public backPaginateRoomEventsSearch(searchResults: T): Promise {\n // TODO: we should implement a backoff (as per scrollback()) to deal more\n // nicely with HTTP errors.\n\n if (!searchResults.next_batch) {\n return Promise.reject(new Error(\"Cannot backpaginate event search any further\"));\n }\n\n if (searchResults.pendingRequest) {\n // already a request in progress - return the existing promise\n return searchResults.pendingRequest as Promise;\n }\n\n const searchOpts = {\n body: searchResults._query!,\n next_batch: searchResults.next_batch,\n };\n\n const promise = this.search(searchOpts, searchResults.abortSignal)\n .then((res) => this.processRoomEventsSearch(searchResults, res))\n .finally(() => {\n searchResults.pendingRequest = undefined;\n });\n searchResults.pendingRequest = promise;\n\n return promise;\n }\n\n /**\n * helper for searchRoomEvents and backPaginateRoomEventsSearch. Processes the\n * response from the API call and updates the searchResults\n *\n * @returns searchResults\n * @internal\n */\n // XXX: Intended private, used in code\n public processRoomEventsSearch(searchResults: T, response: ISearchResponse): T {\n const roomEvents = response.search_categories.room_events;\n\n searchResults.count = roomEvents.count;\n searchResults.next_batch = roomEvents.next_batch;\n\n // combine the highlight list with our existing list;\n const highlights = new Set(roomEvents.highlights);\n searchResults.highlights.forEach((hl) => {\n highlights.add(hl);\n });\n\n // turn it back into a list.\n searchResults.highlights = Array.from(highlights);\n\n const mapper = this.getEventMapper();\n\n // append the new results to our existing results\n const resultsLength = roomEvents.results?.length ?? 0;\n for (let i = 0; i < resultsLength; i++) {\n const sr = SearchResult.fromJson(roomEvents.results[i], mapper);\n const room = this.getRoom(sr.context.getEvent().getRoomId());\n if (room) {\n // Copy over a known event sender if we can\n for (const ev of sr.context.getTimeline()) {\n const sender = room.getMember(ev.getSender()!);\n if (!ev.sender && sender) ev.sender = sender;\n }\n }\n searchResults.results.push(sr);\n }\n return searchResults;\n }\n\n /**\n * Populate the store with rooms the user has left.\n * @returns Promise which resolves: TODO - Resolved when the rooms have\n * been added to the data store.\n * @returns Rejects: with an error response.\n */\n public syncLeftRooms(): Promise {\n // Guard against multiple calls whilst ongoing and multiple calls post success\n if (this.syncedLeftRooms) {\n return Promise.resolve([]); // don't call syncRooms again if it succeeded.\n }\n if (this.syncLeftRoomsPromise) {\n return this.syncLeftRoomsPromise; // return the ongoing request\n }\n const syncApi = new SyncApi(this, this.clientOpts, this.buildSyncApiOptions());\n this.syncLeftRoomsPromise = syncApi.syncLeftRooms();\n\n // cleanup locks\n this.syncLeftRoomsPromise\n .then(() => {\n logger.log(\"Marking success of sync left room request\");\n this.syncedLeftRooms = true; // flip the bit on success\n })\n .finally(() => {\n this.syncLeftRoomsPromise = undefined; // cleanup ongoing request state\n });\n\n return this.syncLeftRoomsPromise;\n }\n\n /**\n * Create a new filter.\n * @param content - The HTTP body for the request\n * @returns Promise which resolves to a Filter object.\n * @returns Rejects: with an error response.\n */\n public createFilter(content: IFilterDefinition): Promise {\n const path = utils.encodeUri(\"/user/$userId/filter\", {\n $userId: this.credentials.userId!,\n });\n return this.http.authedRequest(Method.Post, path, undefined, content).then((response) => {\n // persist the filter\n const filter = Filter.fromJson(this.credentials.userId, response.filter_id, content);\n this.store.storeFilter(filter);\n return filter;\n });\n }\n\n /**\n * Retrieve a filter.\n * @param userId - The user ID of the filter owner\n * @param filterId - The filter ID to retrieve\n * @param allowCached - True to allow cached filters to be returned.\n * Default: True.\n * @returns Promise which resolves: a Filter object\n * @returns Rejects: with an error response.\n */\n public getFilter(userId: string, filterId: string, allowCached: boolean): Promise {\n if (allowCached) {\n const filter = this.store.getFilter(userId, filterId);\n if (filter) {\n return Promise.resolve(filter);\n }\n }\n\n const path = utils.encodeUri(\"/user/$userId/filter/$filterId\", {\n $userId: userId,\n $filterId: filterId,\n });\n\n return this.http.authedRequest(Method.Get, path).then((response) => {\n // persist the filter\n const filter = Filter.fromJson(userId, filterId, response);\n this.store.storeFilter(filter);\n return filter;\n });\n }\n\n /**\n * @returns Filter ID\n */\n public async getOrCreateFilter(filterName: string, filter: Filter): Promise {\n const filterId = this.store.getFilterIdByName(filterName);\n let existingId: string | undefined;\n\n if (filterId) {\n // check that the existing filter matches our expectations\n try {\n const existingFilter = await this.getFilter(this.credentials.userId!, filterId, true);\n if (existingFilter) {\n const oldDef = existingFilter.getDefinition();\n const newDef = filter.getDefinition();\n\n if (utils.deepCompare(oldDef, newDef)) {\n // super, just use that.\n // debuglog(\"Using existing filter ID %s: %s\", filterId,\n // JSON.stringify(oldDef));\n existingId = filterId;\n }\n }\n } catch (error) {\n // Synapse currently returns the following when the filter cannot be found:\n // {\n // errcode: \"M_UNKNOWN\",\n // name: \"M_UNKNOWN\",\n // message: \"No row found\",\n // }\n if ((error).errcode !== \"M_UNKNOWN\" && (error).errcode !== \"M_NOT_FOUND\") {\n throw error;\n }\n }\n // if the filter doesn't exist anymore on the server, remove from store\n if (!existingId) {\n this.store.setFilterIdByName(filterName, undefined);\n }\n }\n\n if (existingId) {\n return existingId;\n }\n\n // create a new filter\n const createdFilter = await this.createFilter(filter.getDefinition());\n\n this.store.setFilterIdByName(filterName, createdFilter.filterId);\n return createdFilter.filterId!;\n }\n\n /**\n * Gets a bearer token from the homeserver that the user can\n * present to a third party in order to prove their ownership\n * of the Matrix account they are logged into.\n * @returns Promise which resolves: Token object\n * @returns Rejects: with an error response.\n */\n public getOpenIdToken(): Promise {\n const path = utils.encodeUri(\"/user/$userId/openid/request_token\", {\n $userId: this.credentials.userId!,\n });\n\n return this.http.authedRequest(Method.Post, path, undefined, {});\n }\n\n private startCallEventHandler = (): void => {\n if (this.isInitialSyncComplete()) {\n this.callEventHandler!.start();\n this.groupCallEventHandler!.start();\n this.off(ClientEvent.Sync, this.startCallEventHandler);\n }\n };\n\n /**\n * Once the client has been initialised, we want to clear notifications we\n * know for a fact should be here.\n * This issue should also be addressed on synapse's side and is tracked as part\n * of https://github.com/matrix-org/synapse/issues/14837\n *\n * We consider a room or a thread as fully read if the current user has sent\n * the last event in the live timeline of that context and if the read receipt\n * we have on record matches.\n */\n private fixupRoomNotifications = (): void => {\n if (this.isInitialSyncComplete()) {\n const unreadRooms = (this.getRooms() ?? []).filter((room) => {\n return room.getUnreadNotificationCount(NotificationCountType.Total) > 0;\n });\n\n for (const room of unreadRooms) {\n const currentUserId = this.getSafeUserId();\n room.fixupNotifications(currentUserId);\n }\n\n this.off(ClientEvent.Sync, this.fixupRoomNotifications);\n }\n };\n\n /**\n * @returns Promise which resolves: ITurnServerResponse object\n * @returns Rejects: with an error response.\n */\n public turnServer(): Promise {\n return this.http.authedRequest(Method.Get, \"/voip/turnServer\");\n }\n\n /**\n * Get the TURN servers for this homeserver.\n * @returns The servers or an empty list.\n */\n public getTurnServers(): ITurnServer[] {\n return this.turnServers || [];\n }\n\n /**\n * Get the unix timestamp (in milliseconds) at which the current\n * TURN credentials (from getTurnServers) expire\n * @returns The expiry timestamp in milliseconds\n */\n public getTurnServersExpiry(): number {\n return this.turnServersExpiry;\n }\n\n public get pollingTurnServers(): boolean {\n return this.checkTurnServersIntervalID !== undefined;\n }\n\n // XXX: Intended private, used in code.\n public async checkTurnServers(): Promise {\n if (!this.canSupportVoip) {\n return;\n }\n\n let credentialsGood = false;\n const remainingTime = this.turnServersExpiry - Date.now();\n if (remainingTime > TURN_CHECK_INTERVAL) {\n logger.debug(\"TURN creds are valid for another \" + remainingTime + \" ms: not fetching new ones.\");\n credentialsGood = true;\n } else {\n logger.debug(\"Fetching new TURN credentials\");\n try {\n const res = await this.turnServer();\n if (res.uris) {\n logger.log(\"Got TURN URIs: \" + res.uris + \" refresh in \" + res.ttl + \" secs\");\n // map the response to a format that can be fed to RTCPeerConnection\n const servers: ITurnServer = {\n urls: res.uris,\n username: res.username,\n credential: res.password,\n };\n this.turnServers = [servers];\n // The TTL is in seconds but we work in ms\n this.turnServersExpiry = Date.now() + res.ttl * 1000;\n credentialsGood = true;\n this.emit(ClientEvent.TurnServers, this.turnServers);\n }\n } catch (err) {\n logger.error(\"Failed to get TURN URIs\", err);\n if ((err).httpStatus === 403) {\n // We got a 403, so there's no point in looping forever.\n logger.info(\"TURN access unavailable for this account: stopping credentials checks\");\n if (this.checkTurnServersIntervalID !== null) global.clearInterval(this.checkTurnServersIntervalID);\n this.checkTurnServersIntervalID = undefined;\n this.emit(ClientEvent.TurnServersError, err, true); // fatal\n } else {\n // otherwise, if we failed for whatever reason, try again the next time we're called.\n this.emit(ClientEvent.TurnServersError, err, false); // non-fatal\n }\n }\n }\n\n return credentialsGood;\n }\n\n /**\n * Set whether to allow a fallback ICE server should be used for negotiating a\n * WebRTC connection if the homeserver doesn't provide any servers. Defaults to\n * false.\n *\n */\n public setFallbackICEServerAllowed(allow: boolean): void {\n this.fallbackICEServerAllowed = allow;\n }\n\n /**\n * Get whether to allow a fallback ICE server should be used for negotiating a\n * WebRTC connection if the homeserver doesn't provide any servers. Defaults to\n * false.\n *\n * @returns\n */\n public isFallbackICEServerAllowed(): boolean {\n return this.fallbackICEServerAllowed;\n }\n\n /**\n * Determines if the current user is an administrator of the Synapse homeserver.\n * Returns false if untrue or the homeserver does not appear to be a Synapse\n * homeserver. This function is implementation specific and may change\n * as a result.\n * @returns true if the user appears to be a Synapse administrator.\n */\n public isSynapseAdministrator(): Promise {\n const path = utils.encodeUri(\"/_synapse/admin/v1/users/$userId/admin\", { $userId: this.getUserId()! });\n return this.http\n .authedRequest<{ admin: boolean }>(Method.Get, path, undefined, undefined, { prefix: \"\" })\n .then((r) => r.admin); // pull out the specific boolean we want\n }\n\n /**\n * Performs a whois lookup on a user using Synapse's administrator API.\n * This function is implementation specific and may change as a\n * result.\n * @param userId - the User ID to look up.\n * @returns the whois response - see Synapse docs for information.\n */\n public whoisSynapseUser(userId: string): Promise {\n const path = utils.encodeUri(\"/_synapse/admin/v1/whois/$userId\", { $userId: userId });\n return this.http.authedRequest(Method.Get, path, undefined, undefined, { prefix: \"\" });\n }\n\n /**\n * Deactivates a user using Synapse's administrator API. This\n * function is implementation specific and may change as a result.\n * @param userId - the User ID to deactivate.\n * @returns the deactivate response - see Synapse docs for information.\n */\n public deactivateSynapseUser(userId: string): Promise {\n const path = utils.encodeUri(\"/_synapse/admin/v1/deactivate/$userId\", { $userId: userId });\n return this.http.authedRequest(Method.Post, path, undefined, undefined, { prefix: \"\" });\n }\n\n private async fetchClientWellKnown(): Promise {\n // `getRawClientConfig` does not throw or reject on network errors, instead\n // it absorbs errors and returns `{}`.\n this.clientWellKnownPromise = AutoDiscovery.getRawClientConfig(this.getDomain() ?? undefined);\n this.clientWellKnown = await this.clientWellKnownPromise;\n this.emit(ClientEvent.ClientWellKnown, this.clientWellKnown);\n }\n\n public getClientWellKnown(): IClientWellKnown | undefined {\n return this.clientWellKnown;\n }\n\n public waitForClientWellKnown(): Promise {\n if (!this.clientRunning) {\n throw new Error(\"Client is not running\");\n }\n return this.clientWellKnownPromise!;\n }\n\n /**\n * store client options with boolean/string/numeric values\n * to know in the next session what flags the sync data was\n * created with (e.g. lazy loading)\n * @param opts - the complete set of client options\n * @returns for store operation\n */\n public storeClientOptions(): Promise {\n // XXX: Intended private, used in code\n const primTypes = [\"boolean\", \"string\", \"number\"];\n const serializableOpts = Object.entries(this.clientOpts!)\n .filter(([key, value]) => {\n return primTypes.includes(typeof value);\n })\n .reduce>((obj, [key, value]) => {\n obj[key] = value;\n return obj;\n }, {});\n return this.store.storeClientOptions(serializableOpts);\n }\n\n /**\n * Gets a set of room IDs in common with another user\n * @param userId - The userId to check.\n * @returns Promise which resolves to a set of rooms\n * @returns Rejects: with an error response.\n */\n // eslint-disable-next-line\n public async _unstable_getSharedRooms(userId: string): Promise {\n const sharedRoomsSupport = await this.doesServerSupportUnstableFeature(\"uk.half-shot.msc2666\");\n const mutualRoomsSupport = await this.doesServerSupportUnstableFeature(\"uk.half-shot.msc2666.mutual_rooms\");\n\n if (!sharedRoomsSupport && !mutualRoomsSupport) {\n throw Error(\"Server does not support mutual_rooms API\");\n }\n\n const path = utils.encodeUri(\n `/uk.half-shot.msc2666/user/${mutualRoomsSupport ? \"mutual_rooms\" : \"shared_rooms\"}/$userId`,\n { $userId: userId },\n );\n\n const res = await this.http.authedRequest<{ joined: string[] }>(Method.Get, path, undefined, undefined, {\n prefix: ClientPrefix.Unstable,\n });\n return res.joined;\n }\n\n /**\n * Get the API versions supported by the server, along with any\n * unstable APIs it supports\n * @returns The server /versions response\n */\n public async getVersions(): Promise {\n if (this.serverVersionsPromise) {\n return this.serverVersionsPromise;\n }\n\n this.serverVersionsPromise = this.http\n .request(\n Method.Get,\n \"/_matrix/client/versions\",\n undefined, // queryParams\n undefined, // data\n {\n prefix: \"\",\n },\n )\n .catch((e) => {\n // Need to unset this if it fails, otherwise we'll never retry\n this.serverVersionsPromise = undefined;\n // but rethrow the exception to anything that was waiting\n throw e;\n });\n\n const serverVersions = await this.serverVersionsPromise;\n this.canSupport = await buildFeatureSupportMap(serverVersions);\n\n return this.serverVersionsPromise;\n }\n\n /**\n * Check if a particular spec version is supported by the server.\n * @param version - The spec version (such as \"r0.5.0\") to check for.\n * @returns Whether it is supported\n */\n public async isVersionSupported(version: string): Promise {\n const { versions } = await this.getVersions();\n return versions && versions.includes(version);\n }\n\n /**\n * Query the server to see if it supports members lazy loading\n * @returns true if server supports lazy loading\n */\n public async doesServerSupportLazyLoading(): Promise {\n const response = await this.getVersions();\n if (!response) return false;\n\n const versions = response[\"versions\"];\n const unstableFeatures = response[\"unstable_features\"];\n\n return (\n (versions && versions.includes(\"r0.5.0\")) || (unstableFeatures && unstableFeatures[\"m.lazy_load_members\"])\n );\n }\n\n /**\n * Query the server to see if the `id_server` parameter is required\n * when registering with an 3pid, adding a 3pid or resetting password.\n * @returns true if id_server parameter is required\n */\n public async doesServerRequireIdServerParam(): Promise {\n const response = await this.getVersions();\n if (!response) return true;\n\n const versions = response[\"versions\"];\n\n // Supporting r0.6.0 is the same as having the flag set to false\n if (versions && versions.includes(\"r0.6.0\")) {\n return false;\n }\n\n const unstableFeatures = response[\"unstable_features\"];\n if (!unstableFeatures) return true;\n if (unstableFeatures[\"m.require_identity_server\"] === undefined) {\n return true;\n } else {\n return unstableFeatures[\"m.require_identity_server\"];\n }\n }\n\n /**\n * Query the server to see if the `id_access_token` parameter can be safely\n * passed to the homeserver. Some homeservers may trigger errors if they are not\n * prepared for the new parameter.\n * @returns true if id_access_token can be sent\n */\n public async doesServerAcceptIdentityAccessToken(): Promise {\n const response = await this.getVersions();\n if (!response) return false;\n\n const versions = response[\"versions\"];\n const unstableFeatures = response[\"unstable_features\"];\n return (versions && versions.includes(\"r0.6.0\")) || (unstableFeatures && unstableFeatures[\"m.id_access_token\"]);\n }\n\n /**\n * Query the server to see if it supports separate 3PID add and bind functions.\n * This affects the sequence of API calls clients should use for these operations,\n * so it's helpful to be able to check for support.\n * @returns true if separate functions are supported\n */\n public async doesServerSupportSeparateAddAndBind(): Promise {\n const response = await this.getVersions();\n if (!response) return false;\n\n const versions = response[\"versions\"];\n const unstableFeatures = response[\"unstable_features\"];\n\n return versions?.includes(\"r0.6.0\") || unstableFeatures?.[\"m.separate_add_and_bind\"];\n }\n\n /**\n * Query the server to see if it lists support for an unstable feature\n * in the /versions response\n * @param feature - the feature name\n * @returns true if the feature is supported\n */\n public async doesServerSupportUnstableFeature(feature: string): Promise {\n const response = await this.getVersions();\n if (!response) return false;\n const unstableFeatures = response[\"unstable_features\"];\n return unstableFeatures && !!unstableFeatures[feature];\n }\n\n /**\n * Query the server to see if it is forcing encryption to be enabled for\n * a given room preset, based on the /versions response.\n * @param presetName - The name of the preset to check.\n * @returns true if the server is forcing encryption\n * for the preset.\n */\n public async doesServerForceEncryptionForPreset(presetName: Preset): Promise {\n const response = await this.getVersions();\n if (!response) return false;\n const unstableFeatures = response[\"unstable_features\"];\n\n // The preset name in the versions response will be without the _chat suffix.\n const versionsPresetName = presetName.includes(\"_chat\")\n ? presetName.substring(0, presetName.indexOf(\"_chat\"))\n : presetName;\n\n return unstableFeatures && !!unstableFeatures[`io.element.e2ee_forced.${versionsPresetName}`];\n }\n\n public async doesServerSupportThread(): Promise<{\n threads: FeatureSupport;\n list: FeatureSupport;\n fwdPagination: FeatureSupport;\n }> {\n if (await this.isVersionSupported(\"v1.4\")) {\n return {\n threads: FeatureSupport.Stable,\n list: FeatureSupport.Stable,\n fwdPagination: FeatureSupport.Stable,\n };\n }\n\n try {\n const [threadUnstable, threadStable, listUnstable, listStable, fwdPaginationUnstable, fwdPaginationStable] =\n await Promise.all([\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3440\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3440.stable\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3856\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3856.stable\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3715\"),\n this.doesServerSupportUnstableFeature(\"org.matrix.msc3715.stable\"),\n ]);\n\n return {\n threads: determineFeatureSupport(threadStable, threadUnstable),\n list: determineFeatureSupport(listStable, listUnstable),\n fwdPagination: determineFeatureSupport(fwdPaginationStable, fwdPaginationUnstable),\n };\n } catch (e) {\n return {\n threads: FeatureSupport.None,\n list: FeatureSupport.None,\n fwdPagination: FeatureSupport.None,\n };\n }\n }\n\n /**\n * Query the server to see if it supports the MSC2457 `logout_devices` parameter when setting password\n * @returns true if server supports the `logout_devices` parameter\n */\n public doesServerSupportLogoutDevices(): Promise {\n return this.isVersionSupported(\"r0.6.1\");\n }\n\n /**\n * Get if lazy loading members is being used.\n * @returns Whether or not members are lazy loaded by this client\n */\n public hasLazyLoadMembersEnabled(): boolean {\n return !!this.clientOpts?.lazyLoadMembers;\n }\n\n /**\n * Set a function which is called when /sync returns a 'limited' response.\n * It is called with a room ID and returns a boolean. It should return 'true' if the SDK\n * can SAFELY remove events from this room. It may not be safe to remove events if there\n * are other references to the timelines for this room, e.g because the client is\n * actively viewing events in this room.\n * Default: returns false.\n * @param cb - The callback which will be invoked.\n */\n public setCanResetTimelineCallback(cb: ResetTimelineCallback): void {\n this.canResetTimelineCallback = cb;\n }\n\n /**\n * Get the callback set via `setCanResetTimelineCallback`.\n * @returns The callback or null\n */\n public getCanResetTimelineCallback(): ResetTimelineCallback | undefined {\n return this.canResetTimelineCallback;\n }\n\n /**\n * Returns relations for a given event. Handles encryption transparently,\n * with the caveat that the amount of events returned might be 0, even though you get a nextBatch.\n * When the returned promise resolves, all messages should have finished trying to decrypt.\n * @param roomId - the room of the event\n * @param eventId - the id of the event\n * @param relationType - the rel_type of the relations requested\n * @param eventType - the event type of the relations requested\n * @param opts - options with optional values for the request.\n * @returns an object with `events` as `MatrixEvent[]` and optionally `nextBatch` if more relations are available.\n */\n public async relations(\n roomId: string,\n eventId: string,\n relationType?: RelationType | string | null,\n eventType?: EventType | string | null,\n opts: IRelationsRequestOpts = { dir: Direction.Backward },\n ): Promise<{\n originalEvent?: MatrixEvent | null;\n events: MatrixEvent[];\n nextBatch?: string | null;\n prevBatch?: string | null;\n }> {\n const fetchedEventType = eventType ? this.getEncryptedIfNeededEventType(roomId, eventType) : null;\n const [eventResult, result] = await Promise.all([\n this.fetchRoomEvent(roomId, eventId),\n this.fetchRelations(roomId, eventId, relationType, fetchedEventType, opts),\n ]);\n const mapper = this.getEventMapper();\n\n const originalEvent = eventResult ? mapper(eventResult) : undefined;\n let events = result.chunk.map(mapper);\n\n if (fetchedEventType === EventType.RoomMessageEncrypted) {\n const allEvents = originalEvent ? events.concat(originalEvent) : events;\n await Promise.all(allEvents.map((e) => this.decryptEventIfNeeded(e)));\n if (eventType !== null) {\n events = events.filter((e) => e.getType() === eventType);\n }\n }\n\n if (originalEvent && relationType === RelationType.Replace) {\n events = events.filter((e) => e.getSender() === originalEvent.getSender());\n }\n return {\n originalEvent: originalEvent ?? null,\n events,\n nextBatch: result.next_batch ?? null,\n prevBatch: result.prev_batch ?? null,\n };\n }\n\n /**\n * The app may wish to see if we have a key cached without\n * triggering a user interaction.\n */\n public getCrossSigningCacheCallbacks(): ICacheCallbacks | undefined {\n // XXX: Private member access\n return this.crypto?.crossSigningInfo.getCacheCallbacks();\n }\n\n /**\n * Generates a random string suitable for use as a client secret. This\n * method is experimental and may change.\n * @returns A new client secret\n */\n public generateClientSecret(): string {\n return randomString(32);\n }\n\n /**\n * Attempts to decrypt an event\n * @param event - The event to decrypt\n * @returns A decryption promise\n */\n public decryptEventIfNeeded(event: MatrixEvent, options?: IDecryptOptions): Promise {\n if (event.shouldAttemptDecryption() && this.isCryptoEnabled()) {\n event.attemptDecryption(this.cryptoBackend!, options);\n }\n\n if (event.isBeingDecrypted()) {\n return event.getDecryptionPromise()!;\n } else {\n return Promise.resolve();\n }\n }\n\n private termsUrlForService(serviceType: SERVICE_TYPES, baseUrl: string): URL {\n switch (serviceType) {\n case SERVICE_TYPES.IS:\n return this.http.getUrl(\"/terms\", undefined, IdentityPrefix.V2, baseUrl);\n case SERVICE_TYPES.IM:\n return this.http.getUrl(\"/terms\", undefined, \"/_matrix/integrations/v1\", baseUrl);\n default:\n throw new Error(\"Unsupported service type\");\n }\n }\n\n /**\n * Get the Homeserver URL of this client\n * @returns Homeserver URL of this client\n */\n public getHomeserverUrl(): string {\n return this.baseUrl;\n }\n\n /**\n * Get the identity server URL of this client\n * @param stripProto - whether or not to strip the protocol from the URL\n * @returns Identity server URL of this client\n */\n public getIdentityServerUrl(stripProto = false): string | undefined {\n if (stripProto && (this.idBaseUrl?.startsWith(\"http://\") || this.idBaseUrl?.startsWith(\"https://\"))) {\n return this.idBaseUrl.split(\"://\")[1];\n }\n return this.idBaseUrl;\n }\n\n /**\n * Set the identity server URL of this client\n * @param url - New identity server URL\n */\n public setIdentityServerUrl(url: string): void {\n this.idBaseUrl = utils.ensureNoTrailingSlash(url);\n this.http.setIdBaseUrl(this.idBaseUrl);\n }\n\n /**\n * Get the access token associated with this account.\n * @returns The access_token or null\n */\n public getAccessToken(): string | null {\n return this.http.opts.accessToken || null;\n }\n\n /**\n * Set the access token associated with this account.\n * @param token - The new access token.\n */\n public setAccessToken(token: string): void {\n this.http.opts.accessToken = token;\n }\n\n /**\n * @returns true if there is a valid access_token for this client.\n */\n public isLoggedIn(): boolean {\n return this.http.opts.accessToken !== undefined;\n }\n\n /**\n * Make up a new transaction id\n *\n * @returns a new, unique, transaction id\n */\n public makeTxnId(): string {\n return \"m\" + new Date().getTime() + \".\" + this.txnCtr++;\n }\n\n /**\n * Check whether a username is available prior to registration. An error response\n * indicates an invalid/unavailable username.\n * @param username - The username to check the availability of.\n * @returns Promise which resolves: to boolean of whether the username is available.\n */\n public isUsernameAvailable(username: string): Promise {\n return this.http\n .authedRequest<{ available: true }>(Method.Get, \"/register/available\", { username })\n .then((response) => {\n return response.available;\n })\n .catch((response) => {\n if (response.errcode === \"M_USER_IN_USE\") {\n return false;\n }\n return Promise.reject(response);\n });\n }\n\n /**\n * @param bindThreepids - Set key 'email' to true to bind any email\n * threepid uses during registration in the identity server. Set 'msisdn' to\n * true to bind msisdn.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public register(\n username: string,\n password: string,\n sessionId: string | null,\n auth: { session?: string; type: string },\n bindThreepids?: boolean | null | { email?: boolean; msisdn?: boolean },\n guestAccessToken?: string,\n inhibitLogin?: boolean,\n ): Promise {\n // backwards compat\n if (bindThreepids === true) {\n bindThreepids = { email: true };\n } else if (bindThreepids === null || bindThreepids === undefined || bindThreepids === false) {\n bindThreepids = {};\n }\n if (sessionId) {\n auth.session = sessionId;\n }\n\n const params: IRegisterRequestParams = {\n auth: auth,\n refresh_token: true, // always ask for a refresh token - does nothing if unsupported\n };\n if (username !== undefined && username !== null) {\n params.username = username;\n }\n if (password !== undefined && password !== null) {\n params.password = password;\n }\n if (bindThreepids.email) {\n params.bind_email = true;\n }\n if (bindThreepids.msisdn) {\n params.bind_msisdn = true;\n }\n if (guestAccessToken !== undefined && guestAccessToken !== null) {\n params.guest_access_token = guestAccessToken;\n }\n if (inhibitLogin !== undefined && inhibitLogin !== null) {\n params.inhibit_login = inhibitLogin;\n }\n // Temporary parameter added to make the register endpoint advertise\n // msisdn flows. This exists because there are clients that break\n // when given stages they don't recognise. This parameter will cease\n // to be necessary once these old clients are gone.\n // Only send it if we send any params at all (the password param is\n // mandatory, so if we send any params, we'll send the password param)\n if (password !== undefined && password !== null) {\n params.x_show_msisdn = true;\n }\n\n return this.registerRequest(params);\n }\n\n /**\n * Register a guest account.\n * This method returns the auth info needed to create a new authenticated client,\n * Remember to call `setGuest(true)` on the (guest-)authenticated client, e.g:\n * ```javascript\n * const tmpClient = await sdk.createClient(MATRIX_INSTANCE);\n * const { user_id, device_id, access_token } = tmpClient.registerGuest();\n * const client = createClient({\n * baseUrl: MATRIX_INSTANCE,\n * accessToken: access_token,\n * userId: user_id,\n * deviceId: device_id,\n * })\n * client.setGuest(true);\n * ```\n *\n * @param body - JSON HTTP body to provide.\n * @returns Promise which resolves: JSON object that contains:\n * `{ user_id, device_id, access_token, home_server }`\n * @returns Rejects: with an error response.\n */\n public registerGuest({ body }: { body?: any } = {}): Promise {\n // TODO: Types\n return this.registerRequest(body || {}, \"guest\");\n }\n\n /**\n * @param data - parameters for registration request\n * @param kind - type of user to register. may be \"guest\"\n * @returns Promise which resolves: to the /register response\n * @returns Rejects: with an error response.\n */\n public registerRequest(data: IRegisterRequestParams, kind?: string): Promise {\n const params: { kind?: string } = {};\n if (kind) {\n params.kind = kind;\n }\n\n return this.http.request(Method.Post, \"/register\", params, data);\n }\n\n /**\n * Refreshes an access token using a provided refresh token. The refresh token\n * must be valid for the current access token known to the client instance.\n *\n * Note that this function will not cause a logout if the token is deemed\n * unknown by the server - the caller is responsible for managing logout\n * actions on error.\n * @param refreshToken - The refresh token.\n * @returns Promise which resolves to the new token.\n * @returns Rejects with an error response.\n */\n public refreshToken(refreshToken: string): Promise {\n return this.http.authedRequest(\n Method.Post,\n \"/refresh\",\n undefined,\n { refresh_token: refreshToken },\n {\n prefix: ClientPrefix.V1,\n inhibitLogoutEmit: true, // we don't want to cause logout loops\n },\n );\n }\n\n /**\n * @returns Promise which resolves to the available login flows\n * @returns Rejects: with an error response.\n */\n public loginFlows(): Promise {\n return this.http.request(Method.Get, \"/login\");\n }\n\n /**\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public login(loginType: string, data: any): Promise {\n // TODO: Types\n const loginData = {\n type: loginType,\n };\n\n // merge data into loginData\n Object.assign(loginData, data);\n\n return this.http\n .authedRequest<{\n access_token?: string;\n user_id?: string;\n }>(Method.Post, \"/login\", undefined, loginData)\n .then((response) => {\n if (response.access_token && response.user_id) {\n this.http.opts.accessToken = response.access_token;\n this.credentials = {\n userId: response.user_id,\n };\n }\n return response;\n });\n }\n\n /**\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public loginWithPassword(user: string, password: string): Promise {\n // TODO: Types\n return this.login(\"m.login.password\", {\n user: user,\n password: password,\n });\n }\n\n /**\n * @param relayState - URL Callback after SAML2 Authentication\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public loginWithSAML2(relayState: string): Promise {\n // TODO: Types\n return this.login(\"m.login.saml2\", {\n relay_state: relayState,\n });\n }\n\n /**\n * @param redirectUrl - The URL to redirect to after the HS\n * authenticates with CAS.\n * @returns The HS URL to hit to begin the CAS login process.\n */\n public getCasLoginUrl(redirectUrl: string): string {\n return this.getSsoLoginUrl(redirectUrl, \"cas\");\n }\n\n /**\n * @param redirectUrl - The URL to redirect to after the HS\n * authenticates with the SSO.\n * @param loginType - The type of SSO login we are doing (sso or cas).\n * Defaults to 'sso'.\n * @param idpId - The ID of the Identity Provider being targeted, optional.\n * @param action - the SSO flow to indicate to the IdP, optional.\n * @returns The HS URL to hit to begin the SSO login process.\n */\n public getSsoLoginUrl(redirectUrl: string, loginType = \"sso\", idpId?: string, action?: SSOAction): string {\n let url = \"/login/\" + loginType + \"/redirect\";\n if (idpId) {\n url += \"/\" + idpId;\n }\n\n const params = {\n redirectUrl,\n [SSO_ACTION_PARAM.unstable!]: action,\n };\n\n return this.http.getUrl(url, params, ClientPrefix.R0).href;\n }\n\n /**\n * @param token - Login token previously received from homeserver\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public loginWithToken(token: string): Promise {\n // TODO: Types\n return this.login(\"m.login.token\", {\n token: token,\n });\n }\n\n /**\n * Logs out the current session.\n * Obviously, further calls that require authorisation should fail after this\n * method is called. The state of the MatrixClient object is not affected:\n * it is up to the caller to either reset or destroy the MatrixClient after\n * this method succeeds.\n * @param stopClient - whether to stop the client before calling /logout to prevent invalid token errors.\n * @returns Promise which resolves: On success, the empty object `{}`\n */\n public async logout(stopClient = false): Promise<{}> {\n if (this.crypto?.backupManager?.getKeyBackupEnabled()) {\n try {\n while ((await this.crypto.backupManager.backupPendingKeys(200)) > 0);\n } catch (err) {\n logger.error(\"Key backup request failed when logging out. Some keys may be missing from backup\", err);\n }\n }\n\n if (stopClient) {\n this.stopClient();\n this.http.abort();\n }\n\n return this.http.authedRequest(Method.Post, \"/logout\");\n }\n\n /**\n * Deactivates the logged-in account.\n * Obviously, further calls that require authorisation should fail after this\n * method is called. The state of the MatrixClient object is not affected:\n * it is up to the caller to either reset or destroy the MatrixClient after\n * this method succeeds.\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @param erase - Optional. If set, send as `erase` attribute in the\n * JSON request body, indicating whether the account should be erased. Defaults\n * to false.\n * @returns Promise which resolves: On success, the empty object\n */\n public deactivateAccount(auth?: any, erase?: boolean): Promise<{}> {\n const body: any = {};\n if (auth) {\n body.auth = auth;\n }\n if (erase !== undefined) {\n body.erase = erase;\n }\n\n return this.http.authedRequest(Method.Post, \"/account/deactivate\", undefined, body);\n }\n\n /**\n * Make a request for an `m.login.token` to be issued as per\n * [MSC3882](https://github.com/matrix-org/matrix-spec-proposals/pull/3882).\n * The server may require User-Interactive auth.\n * Note that this is UNSTABLE and subject to breaking changes without notice.\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @returns Promise which resolves: On success, the token response\n * or UIA auth data.\n */\n public requestLoginToken(auth?: IAuthData): Promise> {\n const body: UIARequest<{}> = { auth };\n return this.http.authedRequest(\n Method.Post,\n \"/org.matrix.msc3882/login/token\",\n undefined, // no query params\n body,\n { prefix: ClientPrefix.Unstable },\n );\n }\n\n /**\n * Get the fallback URL to use for unknown interactive-auth stages.\n *\n * @param loginType - the type of stage being attempted\n * @param authSessionId - the auth session ID provided by the homeserver\n *\n * @returns HS URL to hit to for the fallback interface\n */\n public getFallbackAuthUrl(loginType: string, authSessionId: string): string {\n const path = utils.encodeUri(\"/auth/$loginType/fallback/web\", {\n $loginType: loginType,\n });\n\n return this.http.getUrl(\n path,\n {\n session: authSessionId,\n },\n ClientPrefix.R0,\n ).href;\n }\n\n /**\n * Create a new room.\n * @param options - a list of options to pass to the /createRoom API.\n * @returns Promise which resolves: `{room_id: {string}}`\n * @returns Rejects: with an error response.\n */\n public async createRoom(options: ICreateRoomOpts): Promise<{ room_id: string }> {\n // eslint-disable-line camelcase\n // some valid options include: room_alias_name, visibility, invite\n\n // inject the id_access_token if inviting 3rd party addresses\n const invitesNeedingToken = (options.invite_3pid || []).filter((i) => !i.id_access_token);\n if (\n invitesNeedingToken.length > 0 &&\n this.identityServer?.getAccessToken &&\n (await this.doesServerAcceptIdentityAccessToken())\n ) {\n const identityAccessToken = await this.identityServer.getAccessToken();\n if (identityAccessToken) {\n for (const invite of invitesNeedingToken) {\n invite.id_access_token = identityAccessToken;\n }\n }\n }\n\n return this.http.authedRequest(Method.Post, \"/createRoom\", undefined, options);\n }\n\n /**\n * Fetches relations for a given event\n * @param roomId - the room of the event\n * @param eventId - the id of the event\n * @param relationType - the rel_type of the relations requested\n * @param eventType - the event type of the relations requested\n * @param opts - options with optional values for the request.\n * @returns the response, with chunk, prev_batch and, next_batch.\n */\n public fetchRelations(\n roomId: string,\n eventId: string,\n relationType?: RelationType | string | null,\n eventType?: EventType | string | null,\n opts: IRelationsRequestOpts = { dir: Direction.Backward },\n ): Promise {\n let params = opts as QueryDict;\n if (Thread.hasServerSideFwdPaginationSupport === FeatureSupport.Experimental) {\n params = replaceParam(\"dir\", \"org.matrix.msc3715.dir\", params);\n }\n const queryString = utils.encodeParams(params);\n\n let templatedUrl = \"/rooms/$roomId/relations/$eventId\";\n if (relationType !== null) {\n templatedUrl += \"/$relationType\";\n if (eventType !== null) {\n templatedUrl += \"/$eventType\";\n }\n } else if (eventType !== null) {\n logger.warn(`eventType: ${eventType} ignored when fetching\n relations as relationType is null`);\n eventType = null;\n }\n\n const path = utils.encodeUri(templatedUrl + \"?\" + queryString, {\n $roomId: roomId,\n $eventId: eventId,\n $relationType: relationType!,\n $eventType: eventType!,\n });\n return this.http.authedRequest(Method.Get, path, undefined, undefined, {\n prefix: ClientPrefix.V1,\n });\n }\n\n /**\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public roomState(roomId: string): Promise {\n const path = utils.encodeUri(\"/rooms/$roomId/state\", { $roomId: roomId });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Get an event in a room by its event id.\n *\n * @returns Promise which resolves to an object containing the event.\n * @returns Rejects: with an error response.\n */\n public fetchRoomEvent(roomId: string, eventId: string): Promise> {\n const path = utils.encodeUri(\"/rooms/$roomId/event/$eventId\", {\n $roomId: roomId,\n $eventId: eventId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * @param includeMembership - the membership type to include in the response\n * @param excludeMembership - the membership type to exclude from the response\n * @param atEventId - the id of the event for which moment in the timeline the members should be returned for\n * @returns Promise which resolves: dictionary of userid to profile information\n * @returns Rejects: with an error response.\n */\n public members(\n roomId: string,\n includeMembership?: string,\n excludeMembership?: string,\n atEventId?: string,\n ): Promise<{ [userId: string]: IStateEventWithRoomId[] }> {\n const queryParams: Record = {};\n if (includeMembership) {\n queryParams.membership = includeMembership;\n }\n if (excludeMembership) {\n queryParams.not_membership = excludeMembership;\n }\n if (atEventId) {\n queryParams.at = atEventId;\n }\n\n const queryString = utils.encodeParams(queryParams);\n\n const path = utils.encodeUri(\"/rooms/$roomId/members?\" + queryString, { $roomId: roomId });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Upgrades a room to a new protocol version\n * @param newVersion - The target version to upgrade to\n * @returns Promise which resolves: Object with key 'replacement_room'\n * @returns Rejects: with an error response.\n */\n public upgradeRoom(roomId: string, newVersion: string): Promise<{ replacement_room: string }> {\n // eslint-disable-line camelcase\n const path = utils.encodeUri(\"/rooms/$roomId/upgrade\", { $roomId: roomId });\n return this.http.authedRequest(Method.Post, path, undefined, { new_version: newVersion });\n }\n\n /**\n * Retrieve a state event.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public getStateEvent(roomId: string, eventType: string, stateKey: string): Promise> {\n const pathParams = {\n $roomId: roomId,\n $eventType: eventType,\n $stateKey: stateKey,\n };\n let path = utils.encodeUri(\"/rooms/$roomId/state/$eventType\", pathParams);\n if (stateKey !== undefined) {\n path = utils.encodeUri(path + \"/$stateKey\", pathParams);\n }\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * @param opts - Options for the request function.\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public sendStateEvent(\n roomId: string,\n eventType: string,\n content: any,\n stateKey = \"\",\n opts: IRequestOpts = {},\n ): Promise {\n const pathParams = {\n $roomId: roomId,\n $eventType: eventType,\n $stateKey: stateKey,\n };\n let path = utils.encodeUri(\"/rooms/$roomId/state/$eventType\", pathParams);\n if (stateKey !== undefined) {\n path = utils.encodeUri(path + \"/$stateKey\", pathParams);\n }\n return this.http.authedRequest(Method.Put, path, undefined, content, opts);\n }\n\n /**\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public roomInitialSync(roomId: string, limit: number): Promise {\n const path = utils.encodeUri(\"/rooms/$roomId/initialSync\", { $roomId: roomId });\n\n return this.http.authedRequest(Method.Get, path, { limit: limit?.toString() ?? \"30\" });\n }\n\n /**\n * Set a marker to indicate the point in a room before which the user has read every\n * event. This can be retrieved from room account data (the event type is `m.fully_read`)\n * and displayed as a horizontal line in the timeline that is visually distinct to the\n * position of the user's own read receipt.\n * @param roomId - ID of the room that has been read\n * @param rmEventId - ID of the event that has been read\n * @param rrEventId - ID of the event tracked by the read receipt. This is here\n * for convenience because the RR and the RM are commonly updated at the same time as\n * each other. Optional.\n * @param rpEventId - rpEvent the m.read.private read receipt event for when we\n * don't want other users to see the read receipts. This is experimental. Optional.\n * @returns Promise which resolves: the empty object, `{}`.\n */\n public async setRoomReadMarkersHttpRequest(\n roomId: string,\n rmEventId: string,\n rrEventId?: string,\n rpEventId?: string,\n ): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/read_markers\", {\n $roomId: roomId,\n });\n\n const content: IContent = {\n [ReceiptType.FullyRead]: rmEventId,\n [ReceiptType.Read]: rrEventId,\n };\n\n if (\n (await this.doesServerSupportUnstableFeature(\"org.matrix.msc2285.stable\")) ||\n (await this.isVersionSupported(\"v1.4\"))\n ) {\n content[ReceiptType.ReadPrivate] = rpEventId;\n }\n\n return this.http.authedRequest(Method.Post, path, undefined, content);\n }\n\n /**\n * @returns Promise which resolves: A list of the user's current rooms\n * @returns Rejects: with an error response.\n */\n public getJoinedRooms(): Promise {\n const path = utils.encodeUri(\"/joined_rooms\", {});\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Retrieve membership info. for a room.\n * @param roomId - ID of the room to get membership for\n * @returns Promise which resolves: A list of currently joined users\n * and their profile data.\n * @returns Rejects: with an error response.\n */\n public getJoinedRoomMembers(roomId: string): Promise {\n const path = utils.encodeUri(\"/rooms/$roomId/joined_members\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * @param options - Options for this request\n * @param server - The remote server to query for the room list.\n * Optional. If unspecified, get the local home\n * server's public room list.\n * @param limit - Maximum number of entries to return\n * @param since - Token to paginate from\n * @returns Promise which resolves: IPublicRoomsResponse\n * @returns Rejects: with an error response.\n */\n public publicRooms({\n server,\n limit,\n since,\n ...options\n }: IRoomDirectoryOptions = {}): Promise {\n const queryParams: QueryDict = { server, limit, since };\n if (Object.keys(options).length === 0) {\n return this.http.authedRequest(Method.Get, \"/publicRooms\", queryParams);\n } else {\n return this.http.authedRequest(Method.Post, \"/publicRooms\", queryParams, options);\n }\n }\n\n /**\n * Create an alias to room ID mapping.\n * @param alias - The room alias to create.\n * @param roomId - The room ID to link the alias to.\n * @returns Promise which resolves: an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public createAlias(alias: string, roomId: string): Promise<{}> {\n const path = utils.encodeUri(\"/directory/room/$alias\", {\n $alias: alias,\n });\n const data = {\n room_id: roomId,\n };\n return this.http.authedRequest(Method.Put, path, undefined, data);\n }\n\n /**\n * Delete an alias to room ID mapping. This alias must be on your local server,\n * and you must have sufficient access to do this operation.\n * @param alias - The room alias to delete.\n * @returns Promise which resolves: an empty object `{}`.\n * @returns Rejects: with an error response.\n */\n public deleteAlias(alias: string): Promise<{}> {\n const path = utils.encodeUri(\"/directory/room/$alias\", {\n $alias: alias,\n });\n return this.http.authedRequest(Method.Delete, path);\n }\n\n /**\n * Gets the local aliases for the room. Note: this includes all local aliases, unlike the\n * curated list from the m.room.canonical_alias state event.\n * @param roomId - The room ID to get local aliases for.\n * @returns Promise which resolves: an object with an `aliases` property, containing an array of local aliases\n * @returns Rejects: with an error response.\n */\n public getLocalAliases(roomId: string): Promise<{ aliases: string[] }> {\n const path = utils.encodeUri(\"/rooms/$roomId/aliases\", { $roomId: roomId });\n const prefix = ClientPrefix.V3;\n return this.http.authedRequest(Method.Get, path, undefined, undefined, { prefix });\n }\n\n /**\n * Get room info for the given alias.\n * @param alias - The room alias to resolve.\n * @returns Promise which resolves: Object with room_id and servers.\n * @returns Rejects: with an error response.\n */\n public getRoomIdForAlias(alias: string): Promise<{ room_id: string; servers: string[] }> {\n // eslint-disable-line camelcase\n // TODO: deprecate this or resolveRoomAlias\n const path = utils.encodeUri(\"/directory/room/$alias\", {\n $alias: alias,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * @returns Promise which resolves: Object with room_id and servers.\n * @returns Rejects: with an error response.\n */\n // eslint-disable-next-line camelcase\n public resolveRoomAlias(roomAlias: string): Promise<{ room_id: string; servers: string[] }> {\n // TODO: deprecate this or getRoomIdForAlias\n const path = utils.encodeUri(\"/directory/room/$alias\", { $alias: roomAlias });\n return this.http.request(Method.Get, path);\n }\n\n /**\n * Get the visibility of a room in the current HS's room directory\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public getRoomDirectoryVisibility(roomId: string): Promise<{ visibility: Visibility }> {\n const path = utils.encodeUri(\"/directory/list/room/$roomId\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Set the visbility of a room in the current HS's room directory\n * @param visibility - \"public\" to make the room visible\n * in the public directory, or \"private\" to make\n * it invisible.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setRoomDirectoryVisibility(roomId: string, visibility: Visibility): Promise<{}> {\n const path = utils.encodeUri(\"/directory/list/room/$roomId\", {\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, { visibility });\n }\n\n /**\n * Set the visbility of a room bridged to a 3rd party network in\n * the current HS's room directory.\n * @param networkId - the network ID of the 3rd party\n * instance under which this room is published under.\n * @param visibility - \"public\" to make the room visible\n * in the public directory, or \"private\" to make\n * it invisible.\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public setRoomDirectoryVisibilityAppService(\n networkId: string,\n roomId: string,\n visibility: \"public\" | \"private\",\n ): Promise {\n // TODO: Types\n const path = utils.encodeUri(\"/directory/list/appservice/$networkId/$roomId\", {\n $networkId: networkId,\n $roomId: roomId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, { visibility: visibility });\n }\n\n /**\n * Query the user directory with a term matching user IDs, display names and domains.\n * @param term - the term with which to search.\n * @param limit - the maximum number of results to return. The server will\n * apply a limit if unspecified.\n * @returns Promise which resolves: an array of results.\n */\n public searchUserDirectory({ term, limit }: { term: string; limit?: number }): Promise {\n const body: any = {\n search_term: term,\n };\n\n if (limit !== undefined) {\n body.limit = limit;\n }\n\n return this.http.authedRequest(Method.Post, \"/user_directory/search\", undefined, body);\n }\n\n /**\n * Upload a file to the media repository on the homeserver.\n *\n * @param file - The object to upload. On a browser, something that\n * can be sent to XMLHttpRequest.send (typically a File). Under node.js,\n * a a Buffer, String or ReadStream.\n *\n * @param opts - options object\n *\n * @returns Promise which resolves to response object, as\n * determined by this.opts.onlyData, opts.rawResponse, and\n * opts.onlyContentUri. Rejects with an error (usually a MatrixError).\n */\n public uploadContent(file: FileType, opts?: UploadOpts): Promise {\n return this.http.uploadContent(file, opts);\n }\n\n /**\n * Cancel a file upload in progress\n * @param upload - The object returned from uploadContent\n * @returns true if canceled, otherwise false\n */\n public cancelUpload(upload: Promise): boolean {\n return this.http.cancelUpload(upload);\n }\n\n /**\n * Get a list of all file uploads in progress\n * @returns Array of objects representing current uploads.\n * Currently in progress is element 0. Keys:\n * - promise: The promise associated with the upload\n * - loaded: Number of bytes uploaded\n * - total: Total number of bytes to upload\n */\n public getCurrentUploads(): Upload[] {\n return this.http.getCurrentUploads();\n }\n\n /**\n * @param info - The kind of info to retrieve (e.g. 'displayname',\n * 'avatar_url').\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n */\n public getProfileInfo(\n userId: string,\n info?: string,\n // eslint-disable-next-line camelcase\n ): Promise<{ avatar_url?: string; displayname?: string }> {\n const path = info\n ? utils.encodeUri(\"/profile/$userId/$info\", { $userId: userId, $info: info })\n : utils.encodeUri(\"/profile/$userId\", { $userId: userId });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * @returns Promise which resolves to a list of the user's threepids.\n * @returns Rejects: with an error response.\n */\n public getThreePids(): Promise<{ threepids: IThreepid[] }> {\n return this.http.authedRequest(Method.Get, \"/account/3pid\");\n }\n\n /**\n * Add a 3PID to your homeserver account and optionally bind it to an identity\n * server as well. An identity server is required as part of the `creds` object.\n *\n * This API is deprecated, and you should instead use `addThreePidOnly`\n * for homeservers that support it.\n *\n * @returns Promise which resolves: on success\n * @returns Rejects: with an error response.\n */\n public addThreePid(creds: any, bind: boolean): Promise {\n // TODO: Types\n const path = \"/account/3pid\";\n const data = {\n threePidCreds: creds,\n bind: bind,\n };\n return this.http.authedRequest(Method.Post, path, undefined, data);\n }\n\n /**\n * Add a 3PID to your homeserver account. This API does not use an identity\n * server, as the homeserver is expected to handle 3PID ownership validation.\n *\n * You can check whether a homeserver supports this API via\n * `doesServerSupportSeparateAddAndBind`.\n *\n * @param data - A object with 3PID validation data from having called\n * `account/3pid//requestToken` on the homeserver.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async addThreePidOnly(data: IAddThreePidOnlyBody): Promise<{}> {\n const path = \"/account/3pid/add\";\n const prefix = (await this.isVersionSupported(\"r0.6.0\")) ? ClientPrefix.R0 : ClientPrefix.Unstable;\n return this.http.authedRequest(Method.Post, path, undefined, data, { prefix });\n }\n\n /**\n * Bind a 3PID for discovery onto an identity server via the homeserver. The\n * identity server handles 3PID ownership validation and the homeserver records\n * the new binding to track where all 3PIDs for the account are bound.\n *\n * You can check whether a homeserver supports this API via\n * `doesServerSupportSeparateAddAndBind`.\n *\n * @param data - A object with 3PID validation data from having called\n * `validate//requestToken` on the identity server. It should also\n * contain `id_server` and `id_access_token` fields as well.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public async bindThreePid(data: IBindThreePidBody): Promise<{}> {\n const path = \"/account/3pid/bind\";\n const prefix = (await this.isVersionSupported(\"r0.6.0\")) ? ClientPrefix.R0 : ClientPrefix.Unstable;\n return this.http.authedRequest(Method.Post, path, undefined, data, { prefix });\n }\n\n /**\n * Unbind a 3PID for discovery on an identity server via the homeserver. The\n * homeserver removes its record of the binding to keep an updated record of\n * where all 3PIDs for the account are bound.\n *\n * @param medium - The threepid medium (eg. 'email')\n * @param address - The threepid address (eg. 'bob\\@example.com')\n * this must be as returned by getThreePids.\n * @returns Promise which resolves: on success\n * @returns Rejects: with an error response.\n */\n public async unbindThreePid(\n medium: string,\n address: string,\n // eslint-disable-next-line camelcase\n ): Promise<{ id_server_unbind_result: IdServerUnbindResult }> {\n const path = \"/account/3pid/unbind\";\n const data = {\n medium,\n address,\n id_server: this.getIdentityServerUrl(true),\n };\n const prefix = (await this.isVersionSupported(\"r0.6.0\")) ? ClientPrefix.R0 : ClientPrefix.Unstable;\n return this.http.authedRequest(Method.Post, path, undefined, data, { prefix });\n }\n\n /**\n * @param medium - The threepid medium (eg. 'email')\n * @param address - The threepid address (eg. 'bob\\@example.com')\n * this must be as returned by getThreePids.\n * @returns Promise which resolves: The server response on success\n * (generally the empty JSON object)\n * @returns Rejects: with an error response.\n */\n public deleteThreePid(\n medium: string,\n address: string,\n // eslint-disable-next-line camelcase\n ): Promise<{ id_server_unbind_result: IdServerUnbindResult }> {\n const path = \"/account/3pid/delete\";\n return this.http.authedRequest(Method.Post, path, undefined, { medium, address });\n }\n\n /**\n * Make a request to change your password.\n * @param newPassword - The new desired password.\n * @param logoutDevices - Should all sessions be logged out after the password change. Defaults to true.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setPassword(authDict: IAuthDict, newPassword: string, logoutDevices?: boolean): Promise<{}> {\n const path = \"/account/password\";\n const data = {\n auth: authDict,\n new_password: newPassword,\n logout_devices: logoutDevices,\n };\n\n return this.http.authedRequest<{}>(Method.Post, path, undefined, data);\n }\n\n /**\n * Gets all devices recorded for the logged-in user\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public getDevices(): Promise<{ devices: IMyDevice[] }> {\n return this.http.authedRequest(Method.Get, \"/devices\");\n }\n\n /**\n * Gets specific device details for the logged-in user\n * @param deviceId - device to query\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public getDevice(deviceId: string): Promise {\n const path = utils.encodeUri(\"/devices/$device_id\", {\n $device_id: deviceId,\n });\n return this.http.authedRequest(Method.Get, path);\n }\n\n /**\n * Update the given device\n *\n * @param deviceId - device to update\n * @param body - body of request\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n // eslint-disable-next-line camelcase\n public setDeviceDetails(deviceId: string, body: { display_name: string }): Promise<{}> {\n const path = utils.encodeUri(\"/devices/$device_id\", {\n $device_id: deviceId,\n });\n\n return this.http.authedRequest(Method.Put, path, undefined, body);\n }\n\n /**\n * Delete the given device\n *\n * @param deviceId - device to delete\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public deleteDevice(deviceId: string, auth?: IAuthDict): Promise {\n const path = utils.encodeUri(\"/devices/$device_id\", {\n $device_id: deviceId,\n });\n\n const body: any = {};\n\n if (auth) {\n body.auth = auth;\n }\n\n return this.http.authedRequest(Method.Delete, path, undefined, body);\n }\n\n /**\n * Delete multiple device\n *\n * @param devices - IDs of the devices to delete\n * @param auth - Optional. Auth data to supply for User-Interactive auth.\n * @returns Promise which resolves: result object\n * @returns Rejects: with an error response.\n */\n public deleteMultipleDevices(devices: string[], auth?: IAuthDict): Promise {\n const body: any = { devices };\n\n if (auth) {\n body.auth = auth;\n }\n\n const path = \"/delete_devices\";\n return this.http.authedRequest(Method.Post, path, undefined, body);\n }\n\n /**\n * Gets all pushers registered for the logged-in user\n *\n * @returns Promise which resolves: Array of objects representing pushers\n * @returns Rejects: with an error response.\n */\n public async getPushers(): Promise<{ pushers: IPusher[] }> {\n const response = await this.http.authedRequest<{ pushers: IPusher[] }>(Method.Get, \"/pushers\");\n\n // Migration path for clients that connect to a homeserver that does not support\n // MSC3881 yet, see https://github.com/matrix-org/matrix-spec-proposals/blob/kerry/remote-push-toggle/proposals/3881-remote-push-notification-toggling.md#migration\n if (!(await this.doesServerSupportUnstableFeature(\"org.matrix.msc3881\"))) {\n response.pushers = response.pushers.map((pusher) => {\n if (!pusher.hasOwnProperty(PUSHER_ENABLED.name)) {\n pusher[PUSHER_ENABLED.name] = true;\n }\n return pusher;\n });\n }\n\n return response;\n }\n\n /**\n * Adds a new pusher or updates an existing pusher\n *\n * @param pusher - Object representing a pusher\n * @returns Promise which resolves: Empty json object on success\n * @returns Rejects: with an error response.\n */\n public setPusher(pusher: IPusherRequest): Promise<{}> {\n const path = \"/pushers/set\";\n return this.http.authedRequest(Method.Post, path, undefined, pusher);\n }\n\n /**\n * Persists local notification settings\n * @returns Promise which resolves: an empty object\n * @returns Rejects: with an error response.\n */\n public setLocalNotificationSettings(\n deviceId: string,\n notificationSettings: LocalNotificationSettings,\n ): Promise<{}> {\n const key = `${LOCAL_NOTIFICATION_SETTINGS_PREFIX.name}.${deviceId}`;\n return this.setAccountData(key, notificationSettings);\n }\n\n /**\n * Get the push rules for the account from the server.\n * @returns Promise which resolves to the push rules.\n * @returns Rejects: with an error response.\n */\n public getPushRules(): Promise {\n return this.http.authedRequest(Method.Get, \"/pushrules/\").then((rules: IPushRules) => {\n this.setPushRules(rules);\n return this.pushRules!;\n });\n }\n\n /**\n * Update the push rules for the account. This should be called whenever\n * updated push rules are available.\n */\n public setPushRules(rules: IPushRules): void {\n // Fix-up defaults, if applicable.\n this.pushRules = PushProcessor.rewriteDefaultRules(rules, this.getUserId()!);\n // Pre-calculate any necessary caches.\n this.pushProcessor.updateCachedPushRuleKeys(this.pushRules);\n }\n\n /**\n * @returns Promise which resolves: an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public addPushRule(\n scope: string,\n kind: PushRuleKind,\n ruleId: Exclude,\n body: Pick,\n ): Promise<{}> {\n // NB. Scope not uri encoded because devices need the '/'\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, body);\n }\n\n /**\n * @returns Promise which resolves: an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public deletePushRule(scope: string, kind: PushRuleKind, ruleId: Exclude): Promise<{}> {\n // NB. Scope not uri encoded because devices need the '/'\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Delete, path);\n }\n\n /**\n * Enable or disable a push notification rule.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setPushRuleEnabled(\n scope: string,\n kind: PushRuleKind,\n ruleId: RuleId | string,\n enabled: boolean,\n ): Promise<{}> {\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId/enabled\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, { enabled: enabled });\n }\n\n /**\n * Set the actions for a push notification rule.\n * @returns Promise which resolves: to an empty object `{}`\n * @returns Rejects: with an error response.\n */\n public setPushRuleActions(\n scope: string,\n kind: PushRuleKind,\n ruleId: RuleId | string,\n actions: PushRuleAction[],\n ): Promise<{}> {\n const path = utils.encodeUri(\"/pushrules/\" + scope + \"/$kind/$ruleId/actions\", {\n $kind: kind,\n $ruleId: ruleId,\n });\n return this.http.authedRequest(Method.Put, path, undefined, { actions: actions });\n }\n\n /**\n * Perform a server-side search.\n * @param next_batch - the batch token to pass in the query string\n * @param body - the JSON object to pass to the request body.\n * @param abortSignal - optional signal used to cancel the http request.\n * @returns Promise which resolves to the search response object.\n * @returns Rejects: with an error response.\n */\n public search(\n { body, next_batch: nextBatch }: { body: ISearchRequestBody; next_batch?: string },\n abortSignal?: AbortSignal,\n ): Promise {\n const queryParams: any = {};\n if (nextBatch) {\n queryParams.next_batch = nextBatch;\n }\n return this.http.authedRequest(Method.Post, \"/search\", queryParams, body, { abortSignal });\n }\n\n /**\n * Upload keys\n *\n * @param content - body of upload request\n *\n * @param opts - this method no longer takes any opts,\n * used to take opts.device_id but this was not removed from the spec as a redundant parameter\n *\n * @returns Promise which resolves: result object. Rejects: with\n * an error response ({@link MatrixError}).\n */\n public uploadKeysRequest(content: IUploadKeysRequest, opts?: void): Promise {\n return this.http.authedRequest(Method.Post, \"/keys/upload\", undefined, content);\n }\n\n public uploadKeySignatures(content: KeySignatures): Promise {\n return this.http.authedRequest(Method.Post, \"/keys/signatures/upload\", undefined, content, {\n prefix: ClientPrefix.V3,\n });\n }\n\n /**\n * Download device keys\n *\n * @param userIds - list of users to get keys for\n *\n * @param token - sync token to pass in the query request, to help\n * the HS give the most recent results\n *\n * @returns Promise which resolves: result object. Rejects: with\n * an error response ({@link MatrixError}).\n */\n public downloadKeysForUsers(userIds: string[], { token }: { token?: string } = {}): Promise {\n const content: IQueryKeysRequest = {\n device_keys: {},\n };\n if (token !== undefined) {\n content.token = token;\n }\n userIds.forEach((u) => {\n content.device_keys[u] = [];\n });\n\n return this.http.authedRequest(Method.Post, \"/keys/query\", undefined, content);\n }\n\n /**\n * Claim one-time keys\n *\n * @param devices - a list of [userId, deviceId] pairs\n *\n * @param keyAlgorithm - desired key type\n *\n * @param timeout - the time (in milliseconds) to wait for keys from remote\n * servers\n *\n * @returns Promise which resolves: result object. Rejects: with\n * an error response ({@link MatrixError}).\n */\n public claimOneTimeKeys(\n devices: [string, string][],\n keyAlgorithm = \"signed_curve25519\",\n timeout?: number,\n ): Promise {\n const queries: Record> = {};\n\n if (keyAlgorithm === undefined) {\n keyAlgorithm = \"signed_curve25519\";\n }\n\n for (const [userId, deviceId] of devices) {\n const query = queries[userId] || {};\n queries[userId] = query;\n query[deviceId] = keyAlgorithm;\n }\n const content: IClaimKeysRequest = { one_time_keys: queries };\n if (timeout) {\n content.timeout = timeout;\n }\n const path = \"/keys/claim\";\n return this.http.authedRequest(Method.Post, path, undefined, content);\n }\n\n /**\n * Ask the server for a list of users who have changed their device lists\n * between a pair of sync tokens\n *\n *\n * @returns Promise which resolves: result object. Rejects: with\n * an error response ({@link MatrixError}).\n */\n public getKeyChanges(oldToken: string, newToken: string): Promise<{ changed: string[]; left: string[] }> {\n const qps = {\n from: oldToken,\n to: newToken,\n };\n\n return this.http.authedRequest(Method.Get, \"/keys/changes\", qps);\n }\n\n public uploadDeviceSigningKeys(auth?: IAuthData, keys?: CrossSigningKeys): Promise<{}> {\n // API returns empty object\n const data = Object.assign({}, keys);\n if (auth) Object.assign(data, { auth });\n return this.http.authedRequest(Method.Post, \"/keys/device_signing/upload\", undefined, data, {\n prefix: ClientPrefix.Unstable,\n });\n }\n\n /**\n * Register with an identity server using the OpenID token from the user's\n * Homeserver, which can be retrieved via\n * {@link MatrixClient#getOpenIdToken}.\n *\n * Note that the `/account/register` endpoint (as well as IS authentication in\n * general) was added as part of the v2 API version.\n *\n * @returns Promise which resolves: with object containing an Identity\n * Server access token.\n * @returns Rejects: with an error response.\n */\n public registerWithIdentityServer(hsOpenIdToken: IOpenIDToken): Promise<{\n access_token: string;\n token: string;\n }> {\n if (!this.idBaseUrl) {\n throw new Error(\"No identity server base URL set\");\n }\n\n const uri = this.http.getUrl(\"/account/register\", undefined, IdentityPrefix.V2, this.idBaseUrl);\n return this.http.requestOtherUrl(Method.Post, uri, hsOpenIdToken);\n }\n\n /**\n * Requests an email verification token directly from an identity server.\n *\n * This API is used as part of binding an email for discovery on an identity\n * server. The validation data that results should be passed to the\n * `bindThreePid` method to complete the binding process.\n *\n * @param email - The email address to request a token for\n * @param clientSecret - A secret binary string generated by the client.\n * It is recommended this be around 16 ASCII characters.\n * @param sendAttempt - If an identity server sees a duplicate request\n * with the same sendAttempt, it will not send another email.\n * To request another email to be sent, use a larger value for\n * the sendAttempt param as was used in the previous request.\n * @param nextLink - Optional If specified, the client will be redirected\n * to this link after validation.\n * @param identityAccessToken - The `access_token` field of the identity\n * server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: TODO\n * @returns Rejects: with an error response.\n * @throws Error if no identity server is set\n */\n public requestEmailToken(\n email: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n identityAccessToken?: string,\n ): Promise {\n const params: Record = {\n client_secret: clientSecret,\n email: email,\n send_attempt: sendAttempt?.toString(),\n };\n if (nextLink) {\n params.next_link = nextLink;\n }\n\n return this.http.idServerRequest(\n Method.Post,\n \"/validate/email/requestToken\",\n params,\n IdentityPrefix.V2,\n identityAccessToken,\n );\n }\n\n /**\n * Requests a MSISDN verification token directly from an identity server.\n *\n * This API is used as part of binding a MSISDN for discovery on an identity\n * server. The validation data that results should be passed to the\n * `bindThreePid` method to complete the binding process.\n *\n * @param phoneCountry - The ISO 3166-1 alpha-2 code for the country in\n * which phoneNumber should be parsed relative to.\n * @param phoneNumber - The phone number, in national or international\n * format\n * @param clientSecret - A secret binary string generated by the client.\n * It is recommended this be around 16 ASCII characters.\n * @param sendAttempt - If an identity server sees a duplicate request\n * with the same sendAttempt, it will not send another SMS.\n * To request another SMS to be sent, use a larger value for\n * the sendAttempt param as was used in the previous request.\n * @param nextLink - Optional If specified, the client will be redirected\n * to this link after validation.\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves to an object with a sid string\n * @returns Rejects: with an error response.\n * @throws Error if no identity server is set\n */\n public requestMsisdnToken(\n phoneCountry: string,\n phoneNumber: string,\n clientSecret: string,\n sendAttempt: number,\n nextLink?: string,\n identityAccessToken?: string,\n ): Promise {\n const params: Record = {\n client_secret: clientSecret,\n country: phoneCountry,\n phone_number: phoneNumber,\n send_attempt: sendAttempt?.toString(),\n };\n if (nextLink) {\n params.next_link = nextLink;\n }\n\n return this.http.idServerRequest(\n Method.Post,\n \"/validate/msisdn/requestToken\",\n params,\n IdentityPrefix.V2,\n identityAccessToken,\n );\n }\n\n /**\n * Submits a MSISDN token to the identity server\n *\n * This is used when submitting the code sent by SMS to a phone number.\n * The identity server has an equivalent API for email but the js-sdk does\n * not expose this, since email is normally validated by the user clicking\n * a link rather than entering a code.\n *\n * @param sid - The sid given in the response to requestToken\n * @param clientSecret - A secret binary string generated by the client.\n * This must be the same value submitted in the requestToken call.\n * @param msisdnToken - The MSISDN token, as enetered by the user.\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: Object, currently with no parameters.\n * @returns Rejects: with an error response.\n * @throws Error if No identity server is set\n */\n public submitMsisdnToken(\n sid: string,\n clientSecret: string,\n msisdnToken: string,\n identityAccessToken: string,\n ): Promise {\n // TODO: Types\n const params = {\n sid: sid,\n client_secret: clientSecret,\n token: msisdnToken,\n };\n\n return this.http.idServerRequest(\n Method.Post,\n \"/validate/msisdn/submitToken\",\n params,\n IdentityPrefix.V2,\n identityAccessToken,\n );\n }\n\n /**\n * Submits a MSISDN token to an arbitrary URL.\n *\n * This is used when submitting the code sent by SMS to a phone number in the\n * newer 3PID flow where the homeserver validates 3PID ownership (as part of\n * `requestAdd3pidMsisdnToken`). The homeserver response may include a\n * `submit_url` to specify where the token should be sent, and this helper can\n * be used to pass the token to this URL.\n *\n * @param url - The URL to submit the token to\n * @param sid - The sid given in the response to requestToken\n * @param clientSecret - A secret binary string generated by the client.\n * This must be the same value submitted in the requestToken call.\n * @param msisdnToken - The MSISDN token, as enetered by the user.\n *\n * @returns Promise which resolves: Object, currently with no parameters.\n * @returns Rejects: with an error response.\n */\n public submitMsisdnTokenOtherUrl(\n url: string,\n sid: string,\n clientSecret: string,\n msisdnToken: string,\n ): Promise {\n // TODO: Types\n const params = {\n sid: sid,\n client_secret: clientSecret,\n token: msisdnToken,\n };\n return this.http.requestOtherUrl(Method.Post, url, params);\n }\n\n /**\n * Gets the V2 hashing information from the identity server. Primarily useful for\n * lookups.\n * @param identityAccessToken - The access token for the identity server.\n * @returns The hashing information for the identity server.\n */\n public getIdentityHashDetails(identityAccessToken: string): Promise {\n // TODO: Types\n return this.http.idServerRequest(\n Method.Get,\n \"/hash_details\",\n undefined,\n IdentityPrefix.V2,\n identityAccessToken,\n );\n }\n\n /**\n * Performs a hashed lookup of addresses against the identity server. This is\n * only supported on identity servers which have at least the version 2 API.\n * @param addressPairs - An array of 2 element arrays.\n * The first element of each pair is the address, the second is the 3PID medium.\n * Eg: `[\"email@example.org\", \"email\"]`\n * @param identityAccessToken - The access token for the identity server.\n * @returns A collection of address mappings to\n * found MXIDs. Results where no user could be found will not be listed.\n */\n public async identityHashedLookup(\n addressPairs: [string, string][],\n identityAccessToken: string,\n ): Promise<{ address: string; mxid: string }[]> {\n const params: Record = {\n // addresses: [\"email@example.org\", \"10005550000\"],\n // algorithm: \"sha256\",\n // pepper: \"abc123\"\n };\n\n // Get hash information first before trying to do a lookup\n const hashes = await this.getIdentityHashDetails(identityAccessToken);\n if (!hashes || !hashes[\"lookup_pepper\"] || !hashes[\"algorithms\"]) {\n throw new Error(\"Unsupported identity server: bad response\");\n }\n\n params[\"pepper\"] = hashes[\"lookup_pepper\"];\n\n const localMapping: Record = {\n // hashed identifier => plain text address\n // For use in this function's return format\n };\n\n // When picking an algorithm, we pick the hashed over no hashes\n if (hashes[\"algorithms\"].includes(\"sha256\")) {\n // Abuse the olm hashing\n const olmutil = new global.Olm.Utility();\n params[\"addresses\"] = addressPairs.map((p) => {\n const addr = p[0].toLowerCase(); // lowercase to get consistent hashes\n const med = p[1].toLowerCase();\n const hashed = olmutil\n .sha256(`${addr} ${med} ${params[\"pepper\"]}`)\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\"); // URL-safe base64\n // Map the hash to a known (case-sensitive) address. We use the case\n // sensitive version because the caller might be expecting that.\n localMapping[hashed] = p[0];\n return hashed;\n });\n params[\"algorithm\"] = \"sha256\";\n } else if (hashes[\"algorithms\"].includes(\"none\")) {\n params[\"addresses\"] = addressPairs.map((p) => {\n const addr = p[0].toLowerCase(); // lowercase to get consistent hashes\n const med = p[1].toLowerCase();\n const unhashed = `${addr} ${med}`;\n // Map the unhashed values to a known (case-sensitive) address. We use\n // the case-sensitive version because the caller might be expecting that.\n localMapping[unhashed] = p[0];\n return unhashed;\n });\n params[\"algorithm\"] = \"none\";\n } else {\n throw new Error(\"Unsupported identity server: unknown hash algorithm\");\n }\n\n const response = await this.http.idServerRequest<{\n mappings: { [address: string]: string };\n }>(Method.Post, \"/lookup\", params, IdentityPrefix.V2, identityAccessToken);\n\n if (!response?.[\"mappings\"]) return []; // no results\n\n const foundAddresses: { address: string; mxid: string }[] = [];\n for (const hashed of Object.keys(response[\"mappings\"])) {\n const mxid = response[\"mappings\"][hashed];\n const plainAddress = localMapping[hashed];\n if (!plainAddress) {\n throw new Error(\"Identity server returned more results than expected\");\n }\n\n foundAddresses.push({ address: plainAddress, mxid });\n }\n return foundAddresses;\n }\n\n /**\n * Looks up the public Matrix ID mapping for a given 3rd party\n * identifier from the identity server\n *\n * @param medium - The medium of the threepid, eg. 'email'\n * @param address - The textual address of the threepid\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: A threepid mapping\n * object or the empty object if no mapping\n * exists\n * @returns Rejects: with an error response.\n */\n public async lookupThreePid(medium: string, address: string, identityAccessToken: string): Promise {\n // TODO: Types\n // Note: we're using the V2 API by calling this function, but our\n // function contract requires a V1 response. We therefore have to\n // convert it manually.\n const response = await this.identityHashedLookup([[address, medium]], identityAccessToken);\n const result = response.find((p) => p.address === address);\n if (!result) {\n return {};\n }\n\n const mapping = {\n address,\n medium,\n mxid: result.mxid,\n\n // We can't reasonably fill these parameters:\n // not_before\n // not_after\n // ts\n // signatures\n };\n\n return mapping;\n }\n\n /**\n * Looks up the public Matrix ID mappings for multiple 3PIDs.\n *\n * @param query - Array of arrays containing\n * [medium, address]\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: Lookup results from IS.\n * @returns Rejects: with an error response.\n */\n public async bulkLookupThreePids(query: [string, string][], identityAccessToken: string): Promise {\n // TODO: Types\n // Note: we're using the V2 API by calling this function, but our\n // function contract requires a V1 response. We therefore have to\n // convert it manually.\n const response = await this.identityHashedLookup(\n // We have to reverse the query order to get [address, medium] pairs\n query.map((p) => [p[1], p[0]]),\n identityAccessToken,\n );\n\n const v1results: [medium: string, address: string, mxid: string][] = [];\n for (const mapping of response) {\n const originalQuery = query.find((p) => p[1] === mapping.address);\n if (!originalQuery) {\n throw new Error(\"Identity sever returned unexpected results\");\n }\n\n v1results.push([\n originalQuery[0], // medium\n mapping.address,\n mapping.mxid,\n ]);\n }\n\n return { threepids: v1results };\n }\n\n /**\n * Get account info from the identity server. This is useful as a neutral check\n * to verify that other APIs are likely to approve access by testing that the\n * token is valid, terms have been agreed, etc.\n *\n * @param identityAccessToken - The `access_token` field of the Identity\n * Server `/account/register` response (see {@link registerWithIdentityServer}).\n *\n * @returns Promise which resolves: an object with account info.\n * @returns Rejects: with an error response.\n */\n public getIdentityAccount(identityAccessToken: string): Promise {\n // TODO: Types\n return this.http.idServerRequest(Method.Get, \"/account\", undefined, IdentityPrefix.V2, identityAccessToken);\n }\n\n /**\n * Send an event to a specific list of devices.\n * This is a low-level API that simply wraps the HTTP API\n * call to send to-device messages. We recommend using\n * queueToDevice() which is a higher level API.\n *\n * @param eventType - type of event to send\n * content to send. Map from user_id to device_id to content object.\n * @param txnId - transaction id. One will be made up if not\n * supplied.\n * @returns Promise which resolves: to an empty object `{}`\n */\n public sendToDevice(eventType: string, contentMap: SendToDeviceContentMap, txnId?: string): Promise<{}> {\n const path = utils.encodeUri(\"/sendToDevice/$eventType/$txnId\", {\n $eventType: eventType,\n $txnId: txnId ? txnId : this.makeTxnId(),\n });\n\n const body = {\n messages: utils.recursiveMapToObject(contentMap),\n };\n\n const targets = new Map();\n\n for (const [userId, deviceMessages] of contentMap) {\n targets.set(userId, Array.from(deviceMessages.keys()));\n }\n\n logger.log(`PUT ${path}`, targets);\n\n return this.http.authedRequest(Method.Put, path, undefined, body);\n }\n\n /**\n * Sends events directly to specific devices using Matrix's to-device\n * messaging system. The batch will be split up into appropriately sized\n * batches for sending and stored in the store so they can be retried\n * later if they fail to send. Retries will happen automatically.\n * @param batch - The to-device messages to send\n */\n public queueToDevice(batch: ToDeviceBatch): Promise {\n return this.toDeviceMessageQueue.queueBatch(batch);\n }\n\n /**\n * Get the third party protocols that can be reached using\n * this HS\n * @returns Promise which resolves to the result object\n */\n public getThirdpartyProtocols(): Promise<{ [protocol: string]: IProtocol }> {\n return this.http\n .authedRequest>(Method.Get, \"/thirdparty/protocols\")\n .then((response) => {\n // sanity check\n if (!response || typeof response !== \"object\") {\n throw new Error(`/thirdparty/protocols did not return an object: ${response}`);\n }\n return response;\n });\n }\n\n /**\n * Get information on how a specific place on a third party protocol\n * may be reached.\n * @param protocol - The protocol given in getThirdpartyProtocols()\n * @param params - Protocol-specific parameters, as given in the\n * response to getThirdpartyProtocols()\n * @returns Promise which resolves to the result object\n */\n public getThirdpartyLocation(\n protocol: string,\n params: { searchFields?: string[] },\n ): Promise {\n const path = utils.encodeUri(\"/thirdparty/location/$protocol\", {\n $protocol: protocol,\n });\n\n return this.http.authedRequest(Method.Get, path, params);\n }\n\n /**\n * Get information on how a specific user on a third party protocol\n * may be reached.\n * @param protocol - The protocol given in getThirdpartyProtocols()\n * @param params - Protocol-specific parameters, as given in the\n * response to getThirdpartyProtocols()\n * @returns Promise which resolves to the result object\n */\n public getThirdpartyUser(protocol: string, params: any): Promise {\n // TODO: Types\n const path = utils.encodeUri(\"/thirdparty/user/$protocol\", {\n $protocol: protocol,\n });\n\n return this.http.authedRequest(Method.Get, path, params);\n }\n\n public getTerms(serviceType: SERVICE_TYPES, baseUrl: string): Promise {\n // TODO: Types\n const url = this.termsUrlForService(serviceType, baseUrl);\n return this.http.requestOtherUrl(Method.Get, url);\n }\n\n public agreeToTerms(\n serviceType: SERVICE_TYPES,\n baseUrl: string,\n accessToken: string,\n termsUrls: string[],\n ): Promise<{}> {\n const url = this.termsUrlForService(serviceType, baseUrl);\n const headers = {\n Authorization: \"Bearer \" + accessToken,\n };\n return this.http.requestOtherUrl(\n Method.Post,\n url,\n {\n user_accepts: termsUrls,\n },\n { headers },\n );\n }\n\n /**\n * Reports an event as inappropriate to the server, which may then notify the appropriate people.\n * @param roomId - The room in which the event being reported is located.\n * @param eventId - The event to report.\n * @param score - The score to rate this content as where -100 is most offensive and 0 is inoffensive.\n * @param reason - The reason the content is being reported. May be blank.\n * @returns Promise which resolves to an empty object if successful\n */\n public reportEvent(roomId: string, eventId: string, score: number, reason: string): Promise<{}> {\n const path = utils.encodeUri(\"/rooms/$roomId/report/$eventId\", {\n $roomId: roomId,\n $eventId: eventId,\n });\n\n return this.http.authedRequest(Method.Post, path, undefined, { score, reason });\n }\n\n /**\n * Fetches or paginates a room hierarchy as defined by MSC2946.\n * Falls back gracefully to sourcing its data from `getSpaceSummary` if this API is not yet supported by the server.\n * @param roomId - The ID of the space-room to use as the root of the summary.\n * @param limit - The maximum number of rooms to return per page.\n * @param maxDepth - The maximum depth in the tree from the root room to return.\n * @param suggestedOnly - Whether to only return rooms with suggested=true.\n * @param fromToken - The opaque token to paginate a previous request.\n * @returns the response, with next_batch & rooms fields.\n */\n public getRoomHierarchy(\n roomId: string,\n limit?: number,\n maxDepth?: number,\n suggestedOnly = false,\n fromToken?: string,\n ): Promise {\n const path = utils.encodeUri(\"/rooms/$roomId/hierarchy\", {\n $roomId: roomId,\n });\n\n const queryParams: QueryDict = {\n suggested_only: String(suggestedOnly),\n max_depth: maxDepth?.toString(),\n from: fromToken,\n limit: limit?.toString(),\n };\n\n return this.http\n .authedRequest(Method.Get, path, queryParams, undefined, {\n prefix: ClientPrefix.V1,\n })\n .catch((e) => {\n if (e.errcode === \"M_UNRECOGNIZED\") {\n // fall back to the prefixed hierarchy API.\n return this.http.authedRequest(Method.Get, path, queryParams, undefined, {\n prefix: \"/_matrix/client/unstable/org.matrix.msc2946\",\n });\n }\n\n throw e;\n });\n }\n\n /**\n * Creates a new file tree space with the given name. The client will pick\n * defaults for how it expects to be able to support the remaining API offered\n * by the returned class.\n *\n * Note that this is UNSTABLE and may have breaking changes without notice.\n * @param name - The name of the tree space.\n * @returns Promise which resolves to the created space.\n */\n public async unstableCreateFileTree(name: string): Promise {\n const { room_id: roomId } = await this.createRoom({\n name: name,\n preset: Preset.PrivateChat,\n power_level_content_override: {\n ...DEFAULT_TREE_POWER_LEVELS_TEMPLATE,\n users: {\n [this.getUserId()!]: 100,\n },\n },\n creation_content: {\n [RoomCreateTypeField]: RoomType.Space,\n },\n initial_state: [\n {\n type: UNSTABLE_MSC3088_PURPOSE.name,\n state_key: UNSTABLE_MSC3089_TREE_SUBTYPE.name,\n content: {\n [UNSTABLE_MSC3088_ENABLED.name]: true,\n },\n },\n {\n type: EventType.RoomEncryption,\n state_key: \"\",\n content: {\n algorithm: olmlib.MEGOLM_ALGORITHM,\n },\n },\n ],\n });\n return new MSC3089TreeSpace(this, roomId);\n }\n\n /**\n * Gets a reference to a tree space, if the room ID given is a tree space. If the room\n * does not appear to be a tree space then null is returned.\n *\n * Note that this is UNSTABLE and may have breaking changes without notice.\n * @param roomId - The room ID to get a tree space reference for.\n * @returns The tree space, or null if not a tree space.\n */\n public unstableGetFileTreeSpace(roomId: string): MSC3089TreeSpace | null {\n const room = this.getRoom(roomId);\n if (room?.getMyMembership() !== \"join\") return null;\n\n const createEvent = room.currentState.getStateEvents(EventType.RoomCreate, \"\");\n const purposeEvent = room.currentState.getStateEvents(\n UNSTABLE_MSC3088_PURPOSE.name,\n UNSTABLE_MSC3089_TREE_SUBTYPE.name,\n );\n\n if (!createEvent) throw new Error(\"Expected single room create event\");\n\n if (!purposeEvent?.getContent()?.[UNSTABLE_MSC3088_ENABLED.name]) return null;\n if (createEvent.getContent()?.[RoomCreateTypeField] !== RoomType.Space) return null;\n\n return new MSC3089TreeSpace(this, roomId);\n }\n\n /**\n * Perform a single MSC3575 sliding sync request.\n * @param req - The request to make.\n * @param proxyBaseUrl - The base URL for the sliding sync proxy.\n * @param abortSignal - Optional signal to abort request mid-flight.\n * @returns The sliding sync response, or a standard error.\n * @throws on non 2xx status codes with an object with a field \"httpStatus\":number.\n */\n public slidingSync(\n req: MSC3575SlidingSyncRequest,\n proxyBaseUrl?: string,\n abortSignal?: AbortSignal,\n ): Promise {\n const qps: Record = {};\n if (req.pos) {\n qps.pos = req.pos;\n delete req.pos;\n }\n if (req.timeout) {\n qps.timeout = req.timeout;\n delete req.timeout;\n }\n const clientTimeout = req.clientTimeout;\n delete req.clientTimeout;\n return this.http.authedRequest(Method.Post, \"/sync\", qps, req, {\n prefix: \"/_matrix/client/unstable/org.matrix.msc3575\",\n baseUrl: proxyBaseUrl,\n localTimeoutMs: clientTimeout,\n abortSignal,\n });\n }\n\n /**\n * @deprecated use supportsThreads() instead\n */\n public supportsExperimentalThreads(): boolean {\n logger.warn(`supportsExperimentalThreads() is deprecated, use supportThreads() instead`);\n return this.clientOpts?.experimentalThreadSupport || false;\n }\n\n /**\n * A helper to determine thread support\n * @returns a boolean to determine if threads are enabled\n */\n public supportsThreads(): boolean {\n return this.clientOpts?.threadSupport || false;\n }\n\n /**\n * A helper to determine intentional mentions support\n * @returns a boolean to determine if intentional mentions are enabled\n * @experimental\n */\n public supportsIntentionalMentions(): boolean {\n return this.clientOpts?.intentionalMentions || false;\n }\n\n /**\n * Fetches the summary of a room as defined by an initial version of MSC3266 and implemented in Synapse\n * Proposed at https://github.com/matrix-org/matrix-doc/pull/3266\n * @param roomIdOrAlias - The ID or alias of the room to get the summary of.\n * @param via - The list of servers which know about the room if only an ID was provided.\n */\n public async getRoomSummary(roomIdOrAlias: string, via?: string[]): Promise {\n const path = utils.encodeUri(\"/rooms/$roomid/summary\", { $roomid: roomIdOrAlias });\n return this.http.authedRequest(Method.Get, path, { via }, undefined, {\n prefix: \"/_matrix/client/unstable/im.nheko.summary\",\n });\n }\n\n /**\n * Processes a list of threaded events and adds them to their respective timelines\n * @param room - the room the adds the threaded events\n * @param threadedEvents - an array of the threaded events\n * @param toStartOfTimeline - the direction in which we want to add the events\n */\n public processThreadEvents(room: Room, threadedEvents: MatrixEvent[], toStartOfTimeline: boolean): void {\n room.processThreadedEvents(threadedEvents, toStartOfTimeline);\n }\n\n /**\n * Processes a list of thread roots and creates a thread model\n * @param room - the room to create the threads in\n * @param threadedEvents - an array of thread roots\n * @param toStartOfTimeline - the direction\n */\n public processThreadRoots(room: Room, threadedEvents: MatrixEvent[], toStartOfTimeline: boolean): void {\n room.processThreadRoots(threadedEvents, toStartOfTimeline);\n }\n\n public processBeaconEvents(room?: Room, events?: MatrixEvent[]): void {\n this.processAggregatedTimelineEvents(room, events);\n }\n\n /**\n * Calls aggregation functions for event types that are aggregated\n * Polls and location beacons\n * @param room - room the events belong to\n * @param events - timeline events to be processed\n * @returns\n */\n public processAggregatedTimelineEvents(room?: Room, events?: MatrixEvent[]): void {\n if (!events?.length) return;\n if (!room) return;\n\n room.currentState.processBeaconEvents(events, this);\n room.processPollEvents(events);\n }\n\n /**\n * Fetches information about the user for the configured access token.\n */\n public async whoami(): Promise {\n return this.http.authedRequest(Method.Get, \"/account/whoami\");\n }\n\n /**\n * Find the event_id closest to the given timestamp in the given direction.\n * @returns Resolves: A promise of an object containing the event_id and\n * origin_server_ts of the closest event to the timestamp in the given direction\n * @returns Rejects: when the request fails (module:http-api.MatrixError)\n */\n public async timestampToEvent(\n roomId: string,\n timestamp: number,\n dir: Direction,\n ): Promise {\n const path = utils.encodeUri(\"/rooms/$roomId/timestamp_to_event\", {\n $roomId: roomId,\n });\n const queryParams = {\n ts: timestamp.toString(),\n dir: dir,\n };\n\n try {\n return await this.http.authedRequest(Method.Get, path, queryParams, undefined, {\n prefix: ClientPrefix.V1,\n });\n } catch (err) {\n // Fallback to the prefixed unstable endpoint. Since the stable endpoint is\n // new, we should also try the unstable endpoint before giving up. We can\n // remove this fallback request in a year (remove after 2023-11-28).\n if (\n (err).errcode === \"M_UNRECOGNIZED\" &&\n // XXX: The 400 status code check should be removed in the future\n // when Synapse is compliant with MSC3743.\n ((err).httpStatus === 400 ||\n // This the correct standard status code for an unsupported\n // endpoint according to MSC3743. Not Found and Method Not Allowed\n // both indicate that this endpoint+verb combination is\n // not supported.\n (err).httpStatus === 404 ||\n (err).httpStatus === 405)\n ) {\n return await this.http.authedRequest(Method.Get, path, queryParams, undefined, {\n prefix: \"/_matrix/client/unstable/org.matrix.msc3030\",\n });\n }\n\n throw err;\n }\n }\n}\n\n/**\n * recalculates an accurate notifications count on event decryption.\n * Servers do not have enough knowledge about encrypted events to calculate an\n * accurate notification_count\n */\nexport function fixNotificationCountOnDecryption(cli: MatrixClient, event: MatrixEvent): void {\n const ourUserId = cli.getUserId();\n const eventId = event.getId();\n\n const room = cli.getRoom(event.getRoomId());\n if (!room || !ourUserId || !eventId) return;\n\n const oldActions = event.getPushActions();\n const actions = cli.getPushActionsForEvent(event, true);\n\n const isThreadEvent = !!event.threadRootId && !event.isThreadRoot;\n\n const currentHighlightCount = room.getUnreadCountForEventContext(NotificationCountType.Highlight, event);\n\n // Ensure the unread counts are kept up to date if the event is encrypted\n // We also want to make sure that the notification count goes up if we already\n // have encrypted events to avoid other code from resetting 'highlight' to zero.\n const oldHighlight = !!oldActions?.tweaks?.highlight;\n const newHighlight = !!actions?.tweaks?.highlight;\n\n let hasReadEvent;\n if (isThreadEvent) {\n const thread = room.getThread(event.threadRootId);\n hasReadEvent = thread\n ? thread.hasUserReadEvent(ourUserId, eventId)\n : // If the thread object does not exist in the room yet, we don't\n // want to calculate notification for this event yet. We have not\n // restored the read receipts yet and can't accurately calculate\n // notifications at this stage.\n //\n // This issue can likely go away when MSC3874 is implemented\n true;\n } else {\n hasReadEvent = room.hasUserReadEvent(ourUserId, eventId);\n }\n\n if (hasReadEvent) {\n // If the event has been read, ignore it.\n return;\n }\n\n if (oldHighlight !== newHighlight || currentHighlightCount > 0) {\n // TODO: Handle mentions received while the client is offline\n // See also https://github.com/vector-im/element-web/issues/9069\n let newCount = currentHighlightCount;\n if (newHighlight && !oldHighlight) newCount++;\n if (!newHighlight && oldHighlight) newCount--;\n\n if (isThreadEvent) {\n room.setThreadUnreadNotificationCount(event.threadRootId, NotificationCountType.Highlight, newCount);\n } else {\n room.setUnreadNotificationCount(NotificationCountType.Highlight, newCount);\n }\n }\n\n // Total count is used to typically increment a room notification counter, but not loudly highlight it.\n const currentTotalCount = room.getUnreadCountForEventContext(NotificationCountType.Total, event);\n\n // `notify` is used in practice for incrementing the total count\n const newNotify = !!actions?.notify;\n\n // The room total count is NEVER incremented by the server for encrypted rooms. We basically ignore\n // the server here as it's always going to tell us to increment for encrypted events.\n if (newNotify) {\n if (isThreadEvent) {\n room.setThreadUnreadNotificationCount(\n event.threadRootId,\n NotificationCountType.Total,\n currentTotalCount + 1,\n );\n } else {\n room.setUnreadNotificationCount(NotificationCountType.Total, currentTotalCount + 1);\n }\n }\n}\n", - "/*\nCopyright 2018 - 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MBeaconEventContent, MBeaconInfoContent, MBeaconInfoEventContent } from \"./@types/beacon\";\nimport { MsgType } from \"./@types/event\";\nimport { M_TEXT, REFERENCE_RELATION } from \"./@types/extensible_events\";\nimport { isProvided } from \"./extensible_events_v1/utilities\";\nimport {\n M_ASSET,\n LocationAssetType,\n M_LOCATION,\n M_TIMESTAMP,\n LocationEventWireContent,\n MLocationEventContent,\n MLocationContent,\n MAssetContent,\n LegacyLocationEventContent,\n} from \"./@types/location\";\nimport { MRoomTopicEventContent, MTopicContent, M_TOPIC } from \"./@types/topic\";\nimport { IContent } from \"./models/event\";\n\n/**\n * Generates the content for a HTML Message event\n * @param body - the plaintext body of the message\n * @param htmlBody - the HTML representation of the message\n * @returns\n */\nexport function makeHtmlMessage(body: string, htmlBody: string): IContent {\n return {\n msgtype: MsgType.Text,\n format: \"org.matrix.custom.html\",\n body: body,\n formatted_body: htmlBody,\n };\n}\n\n/**\n * Generates the content for a HTML Notice event\n * @param body - the plaintext body of the notice\n * @param htmlBody - the HTML representation of the notice\n * @returns\n */\nexport function makeHtmlNotice(body: string, htmlBody: string): IContent {\n return {\n msgtype: MsgType.Notice,\n format: \"org.matrix.custom.html\",\n body: body,\n formatted_body: htmlBody,\n };\n}\n\n/**\n * Generates the content for a HTML Emote event\n * @param body - the plaintext body of the emote\n * @param htmlBody - the HTML representation of the emote\n * @returns\n */\nexport function makeHtmlEmote(body: string, htmlBody: string): IContent {\n return {\n msgtype: MsgType.Emote,\n format: \"org.matrix.custom.html\",\n body: body,\n formatted_body: htmlBody,\n };\n}\n\n/**\n * Generates the content for a Plaintext Message event\n * @param body - the plaintext body of the emote\n * @returns\n */\nexport function makeTextMessage(body: string): IContent {\n return {\n msgtype: MsgType.Text,\n body: body,\n };\n}\n\n/**\n * Generates the content for a Plaintext Notice event\n * @param body - the plaintext body of the notice\n * @returns\n */\nexport function makeNotice(body: string): IContent {\n return {\n msgtype: MsgType.Notice,\n body: body,\n };\n}\n\n/**\n * Generates the content for a Plaintext Emote event\n * @param body - the plaintext body of the emote\n * @returns\n */\nexport function makeEmoteMessage(body: string): IContent {\n return {\n msgtype: MsgType.Emote,\n body: body,\n };\n}\n\n/** Location content helpers */\n\nexport const getTextForLocationEvent = (\n uri: string | undefined,\n assetType: LocationAssetType,\n timestamp?: number,\n description?: string | null,\n): string => {\n const date = `at ${new Date(timestamp!).toISOString()}`;\n const assetName = assetType === LocationAssetType.Self ? \"User\" : undefined;\n const quotedDescription = description ? `\"${description}\"` : undefined;\n\n return [assetName, \"Location\", quotedDescription, uri, date].filter(Boolean).join(\" \");\n};\n\n/**\n * Generates the content for a Location event\n * @param uri - a geo:// uri for the location\n * @param timestamp - the timestamp when the location was correct (milliseconds since the UNIX epoch)\n * @param description - the (optional) label for this location on the map\n * @param assetType - the (optional) asset type of this location e.g. \"m.self\"\n * @param text - optional. A text for the location\n */\nexport const makeLocationContent = (\n // this is first but optional\n // to avoid a breaking change\n text?: string,\n uri?: string,\n timestamp?: number,\n description?: string | null,\n assetType?: LocationAssetType,\n): LegacyLocationEventContent & MLocationEventContent => {\n const defaultedText =\n text ?? getTextForLocationEvent(uri, assetType || LocationAssetType.Self, timestamp, description);\n const timestampEvent = timestamp ? { [M_TIMESTAMP.name]: timestamp } : {};\n return {\n msgtype: MsgType.Location,\n body: defaultedText,\n geo_uri: uri,\n [M_LOCATION.name]: {\n description,\n uri,\n },\n [M_ASSET.name]: {\n type: assetType || LocationAssetType.Self,\n },\n [M_TEXT.name]: defaultedText,\n ...timestampEvent,\n } as LegacyLocationEventContent & MLocationEventContent;\n};\n\n/**\n * Parse location event content and transform to\n * a backwards compatible modern m.location event format\n */\nexport const parseLocationEvent = (wireEventContent: LocationEventWireContent): MLocationEventContent => {\n const location = M_LOCATION.findIn(wireEventContent);\n const asset = M_ASSET.findIn(wireEventContent);\n const timestamp = M_TIMESTAMP.findIn(wireEventContent);\n const text = M_TEXT.findIn(wireEventContent);\n\n const geoUri = location?.uri ?? wireEventContent?.geo_uri;\n const description = location?.description;\n const assetType = asset?.type ?? LocationAssetType.Self;\n const fallbackText = text ?? wireEventContent.body;\n\n return makeLocationContent(fallbackText, geoUri, timestamp ?? undefined, description, assetType);\n};\n\n/**\n * Topic event helpers\n */\nexport type MakeTopicContent = (topic: string, htmlTopic?: string) => MRoomTopicEventContent;\n\nexport const makeTopicContent: MakeTopicContent = (topic, htmlTopic) => {\n const renderings = [{ body: topic, mimetype: \"text/plain\" }];\n if (isProvided(htmlTopic)) {\n renderings.push({ body: htmlTopic!, mimetype: \"text/html\" });\n }\n return { topic, [M_TOPIC.name]: renderings };\n};\n\nexport type TopicState = {\n text: string;\n html?: string;\n};\n\nexport const parseTopicContent = (content: MRoomTopicEventContent): TopicState => {\n const mtopic = M_TOPIC.findIn(content);\n if (!Array.isArray(mtopic)) {\n return { text: content.topic };\n }\n const text = mtopic?.find((r) => !isProvided(r.mimetype) || r.mimetype === \"text/plain\")?.body ?? content.topic;\n const html = mtopic?.find((r) => r.mimetype === \"text/html\")?.body;\n return { text, html };\n};\n\n/**\n * Beacon event helpers\n */\nexport type MakeBeaconInfoContent = (\n timeout: number,\n isLive?: boolean,\n description?: string,\n assetType?: LocationAssetType,\n timestamp?: number,\n) => MBeaconInfoEventContent;\n\nexport const makeBeaconInfoContent: MakeBeaconInfoContent = (timeout, isLive, description, assetType, timestamp) => ({\n description,\n timeout,\n live: isLive,\n [M_TIMESTAMP.name]: timestamp || Date.now(),\n [M_ASSET.name]: {\n type: assetType ?? LocationAssetType.Self,\n },\n});\n\nexport type BeaconInfoState = MBeaconInfoContent & {\n assetType?: LocationAssetType;\n timestamp?: number;\n};\n/**\n * Flatten beacon info event content\n */\nexport const parseBeaconInfoContent = (content: MBeaconInfoEventContent): BeaconInfoState => {\n const { description, timeout, live } = content;\n const timestamp = M_TIMESTAMP.findIn(content) ?? undefined;\n const asset = M_ASSET.findIn(content);\n\n return {\n description,\n timeout,\n live,\n assetType: asset?.type,\n timestamp,\n };\n};\n\nexport type MakeBeaconContent = (\n uri: string,\n timestamp: number,\n beaconInfoEventId: string,\n description?: string,\n) => MBeaconEventContent;\n\nexport const makeBeaconContent: MakeBeaconContent = (uri, timestamp, beaconInfoEventId, description) => ({\n [M_LOCATION.name]: {\n description,\n uri,\n },\n [M_TIMESTAMP.name]: timestamp,\n \"m.relates_to\": {\n rel_type: REFERENCE_RELATION.name,\n event_id: beaconInfoEventId,\n },\n});\n\nexport type BeaconLocationState = Omit & {\n uri?: string; // override from MLocationContent to allow optionals\n timestamp?: number;\n};\n\nexport const parseBeaconContent = (content: MBeaconEventContent): BeaconLocationState => {\n const location = M_LOCATION.findIn(content);\n const timestamp = M_TIMESTAMP.findIn(content) ?? undefined;\n\n return {\n description: location?.description,\n uri: location?.uri,\n timestamp,\n };\n};\n", - "/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport * as utils from \"./utils\";\n\n/**\n * Get the HTTP URL for an MXC URI.\n * @param baseUrl - The base homeserver url which has a content repo.\n * @param mxc - The mxc:// URI.\n * @param width - The desired width of the thumbnail.\n * @param height - The desired height of the thumbnail.\n * @param resizeMethod - The thumbnail resize method to use, either\n * \"crop\" or \"scale\".\n * @param allowDirectLinks - If true, return any non-mxc URLs\n * directly. Fetching such URLs will leak information about the user to\n * anyone they share a room with. If false, will return the emptry string\n * for such URLs.\n * @returns The complete URL to the content.\n */\nexport function getHttpUriForMxc(\n baseUrl: string,\n mxc?: string,\n width?: number,\n height?: number,\n resizeMethod?: string,\n allowDirectLinks = false,\n): string {\n if (typeof mxc !== \"string\" || !mxc) {\n return \"\";\n }\n if (mxc.indexOf(\"mxc://\") !== 0) {\n if (allowDirectLinks) {\n return mxc;\n } else {\n return \"\";\n }\n }\n let serverAndMediaId = mxc.slice(6); // strips mxc://\n let prefix = \"/_matrix/media/r0/download/\";\n const params: Record = {};\n\n if (width) {\n params[\"width\"] = Math.round(width).toString();\n }\n if (height) {\n params[\"height\"] = Math.round(height).toString();\n }\n if (resizeMethod) {\n params[\"method\"] = resizeMethod;\n }\n if (Object.keys(params).length > 0) {\n // these are thumbnailing params so they probably want the\n // thumbnailing API...\n prefix = \"/_matrix/media/r0/thumbnail/\";\n }\n\n const fragmentOffset = serverAndMediaId.indexOf(\"#\");\n let fragment = \"\";\n if (fragmentOffset >= 0) {\n fragment = serverAndMediaId.slice(fragmentOffset);\n serverAndMediaId = serverAndMediaId.slice(0, fragmentOffset);\n }\n\n const urlParams = Object.keys(params).length === 0 ? \"\" : \"?\" + utils.encodeParams(params);\n return baseUrl + prefix + serverAndMediaId + urlParams + fragment;\n}\n", - "/*\nCopyright 2019 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Cross signing methods\n */\n\nimport { PkSigning } from \"@matrix-org/olm\";\n\nimport { decodeBase64, encodeBase64, IObject, pkSign, pkVerify } from \"./olmlib\";\nimport { logger } from \"../logger\";\nimport { IndexedDBCryptoStore } from \"../crypto/store/indexeddb-crypto-store\";\nimport { decryptAES, encryptAES } from \"./aes\";\nimport { DeviceInfo } from \"./deviceinfo\";\nimport { SecretStorage } from \"./SecretStorage\";\nimport { ICrossSigningKey, ISignedKey, MatrixClient } from \"../client\";\nimport { OlmDevice } from \"./OlmDevice\";\nimport { ICryptoCallbacks } from \".\";\nimport { ISignatures } from \"../@types/signed\";\nimport { CryptoStore, SecretStorePrivateKeys } from \"./store/base\";\nimport { SecretStorageKeyDescription } from \"../secret-storage\";\n\nconst KEY_REQUEST_TIMEOUT_MS = 1000 * 60;\n\nfunction publicKeyFromKeyInfo(keyInfo: ICrossSigningKey): string {\n // `keys` is an object with { [`ed25519:${pubKey}`]: pubKey }\n // We assume only a single key, and we want the bare form without type\n // prefix, so we select the values.\n return Object.values(keyInfo.keys)[0];\n}\n\nexport interface ICacheCallbacks {\n getCrossSigningKeyCache?(type: string, expectedPublicKey?: string): Promise;\n storeCrossSigningKeyCache?(type: string, key?: Uint8Array): Promise;\n}\n\nexport interface ICrossSigningInfo {\n keys: Record;\n firstUse: boolean;\n crossSigningVerifiedBefore: boolean;\n}\n\nexport class CrossSigningInfo {\n public keys: Record = {};\n public firstUse = true;\n // This tracks whether we've ever verified this user with any identity.\n // When you verify a user, any devices online at the time that receive\n // the verifying signature via the homeserver will latch this to true\n // and can use it in the future to detect cases where the user has\n // become unverified later for any reason.\n private crossSigningVerifiedBefore = false;\n\n /**\n * Information about a user's cross-signing keys\n *\n * @param userId - the user that the information is about\n * @param callbacks - Callbacks used to interact with the app\n * Requires getCrossSigningKey and saveCrossSigningKeys\n * @param cacheCallbacks - Callbacks used to interact with the cache\n */\n public constructor(\n public readonly userId: string,\n private callbacks: ICryptoCallbacks = {},\n private cacheCallbacks: ICacheCallbacks = {},\n ) {}\n\n public static fromStorage(obj: ICrossSigningInfo, userId: string): CrossSigningInfo {\n const res = new CrossSigningInfo(userId);\n for (const prop in obj) {\n if (obj.hasOwnProperty(prop)) {\n // @ts-ignore - ts doesn't like this and nor should we\n res[prop] = obj[prop];\n }\n }\n return res;\n }\n\n public toStorage(): ICrossSigningInfo {\n return {\n keys: this.keys,\n firstUse: this.firstUse,\n crossSigningVerifiedBefore: this.crossSigningVerifiedBefore,\n };\n }\n\n /**\n * Calls the app callback to ask for a private key\n *\n * @param type - The key type (\"master\", \"self_signing\", or \"user_signing\")\n * @param expectedPubkey - The matching public key or undefined to use\n * the stored public key for the given key type.\n * @returns An array with [ public key, Olm.PkSigning ]\n */\n public async getCrossSigningKey(type: string, expectedPubkey?: string): Promise<[string, PkSigning]> {\n const shouldCache = [\"master\", \"self_signing\", \"user_signing\"].indexOf(type) >= 0;\n\n if (!this.callbacks.getCrossSigningKey) {\n throw new Error(\"No getCrossSigningKey callback supplied\");\n }\n\n if (expectedPubkey === undefined) {\n expectedPubkey = this.getId(type)!;\n }\n\n function validateKey(key: Uint8Array | null): [string, PkSigning] | undefined {\n if (!key) return;\n const signing = new global.Olm.PkSigning();\n const gotPubkey = signing.init_with_seed(key);\n if (gotPubkey === expectedPubkey) {\n return [gotPubkey, signing];\n }\n signing.free();\n }\n\n let privkey: Uint8Array | null = null;\n if (this.cacheCallbacks.getCrossSigningKeyCache && shouldCache) {\n privkey = await this.cacheCallbacks.getCrossSigningKeyCache(type, expectedPubkey);\n }\n\n const cacheresult = validateKey(privkey);\n if (cacheresult) {\n return cacheresult;\n }\n\n privkey = await this.callbacks.getCrossSigningKey(type, expectedPubkey);\n const result = validateKey(privkey);\n if (result) {\n if (this.cacheCallbacks.storeCrossSigningKeyCache && shouldCache) {\n await this.cacheCallbacks.storeCrossSigningKeyCache(type, privkey!);\n }\n return result;\n }\n\n /* No keysource even returned a key */\n if (!privkey) {\n throw new Error(\"getCrossSigningKey callback for \" + type + \" returned falsey\");\n }\n\n /* We got some keys from the keysource, but none of them were valid */\n throw new Error(\"Key type \" + type + \" from getCrossSigningKey callback did not match\");\n }\n\n /**\n * Check whether the private keys exist in secret storage.\n * XXX: This could be static, be we often seem to have an instance when we\n * want to know this anyway...\n *\n * @param secretStorage - The secret store using account data\n * @returns map of key name to key info the secret is encrypted\n * with, or null if it is not present or not encrypted with a trusted\n * key\n */\n public async isStoredInSecretStorage(\n secretStorage: SecretStorage,\n ): Promise | null> {\n // check what SSSS keys have encrypted the master key (if any)\n const stored = (await secretStorage.isStored(\"m.cross_signing.master\")) || {};\n // then check which of those SSSS keys have also encrypted the SSK and USK\n function intersect(s: Record): void {\n for (const k of Object.keys(stored)) {\n if (!s[k]) {\n delete stored[k];\n }\n }\n }\n for (const type of [\"self_signing\", \"user_signing\"]) {\n intersect((await secretStorage.isStored(`m.cross_signing.${type}`)) || {});\n }\n return Object.keys(stored).length ? stored : null;\n }\n\n /**\n * Store private keys in secret storage for use by other devices. This is\n * typically called in conjunction with the creation of new cross-signing\n * keys.\n *\n * @param keys - The keys to store\n * @param secretStorage - The secret store using account data\n */\n public static async storeInSecretStorage(\n keys: Map,\n secretStorage: SecretStorage,\n ): Promise {\n for (const [type, privateKey] of keys) {\n const encodedKey = encodeBase64(privateKey);\n await secretStorage.store(`m.cross_signing.${type}`, encodedKey);\n }\n }\n\n /**\n * Get private keys from secret storage created by some other device. This\n * also passes the private keys to the app-specific callback.\n *\n * @param type - The type of key to get. One of \"master\",\n * \"self_signing\", or \"user_signing\".\n * @param secretStorage - The secret store using account data\n * @returns The private key\n */\n public static async getFromSecretStorage(type: string, secretStorage: SecretStorage): Promise {\n const encodedKey = await secretStorage.get(`m.cross_signing.${type}`);\n if (!encodedKey) {\n return null;\n }\n return decodeBase64(encodedKey);\n }\n\n /**\n * Check whether the private keys exist in the local key cache.\n *\n * @param type - The type of key to get. One of \"master\",\n * \"self_signing\", or \"user_signing\". Optional, will check all by default.\n * @returns True if all keys are stored in the local cache.\n */\n public async isStoredInKeyCache(type?: string): Promise {\n const cacheCallbacks = this.cacheCallbacks;\n if (!cacheCallbacks) return false;\n const types = type ? [type] : [\"master\", \"self_signing\", \"user_signing\"];\n for (const t of types) {\n if (!(await cacheCallbacks.getCrossSigningKeyCache?.(t))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Get cross-signing private keys from the local cache.\n *\n * @returns A map from key type (string) to private key (Uint8Array)\n */\n public async getCrossSigningKeysFromCache(): Promise> {\n const keys = new Map();\n const cacheCallbacks = this.cacheCallbacks;\n if (!cacheCallbacks) return keys;\n for (const type of [\"master\", \"self_signing\", \"user_signing\"]) {\n const privKey = await cacheCallbacks.getCrossSigningKeyCache?.(type);\n if (!privKey) {\n continue;\n }\n keys.set(type, privKey);\n }\n return keys;\n }\n\n /**\n * Get the ID used to identify the user. This can also be used to test for\n * the existence of a given key type.\n *\n * @param type - The type of key to get the ID of. One of \"master\",\n * \"self_signing\", or \"user_signing\". Defaults to \"master\".\n *\n * @returns the ID\n */\n public getId(type = \"master\"): string | null {\n if (!this.keys[type]) return null;\n const keyInfo = this.keys[type];\n return publicKeyFromKeyInfo(keyInfo);\n }\n\n /**\n * Create new cross-signing keys for the given key types. The public keys\n * will be held in this class, while the private keys are passed off to the\n * `saveCrossSigningKeys` application callback.\n *\n * @param level - The key types to reset\n */\n public async resetKeys(level?: CrossSigningLevel): Promise {\n if (!this.callbacks.saveCrossSigningKeys) {\n throw new Error(\"No saveCrossSigningKeys callback supplied\");\n }\n\n // If we're resetting the master key, we reset all keys\n if (level === undefined || level & CrossSigningLevel.MASTER || !this.keys.master) {\n level = CrossSigningLevel.MASTER | CrossSigningLevel.USER_SIGNING | CrossSigningLevel.SELF_SIGNING;\n } else if (level === (0 as CrossSigningLevel)) {\n return;\n }\n\n const privateKeys: Record = {};\n const keys: Record = {};\n let masterSigning;\n let masterPub;\n\n try {\n if (level & CrossSigningLevel.MASTER) {\n masterSigning = new global.Olm.PkSigning();\n privateKeys.master = masterSigning.generate_seed();\n masterPub = masterSigning.init_with_seed(privateKeys.master);\n keys.master = {\n user_id: this.userId,\n usage: [\"master\"],\n keys: {\n [\"ed25519:\" + masterPub]: masterPub,\n },\n };\n } else {\n [masterPub, masterSigning] = await this.getCrossSigningKey(\"master\");\n }\n\n if (level & CrossSigningLevel.SELF_SIGNING) {\n const sskSigning = new global.Olm.PkSigning();\n try {\n privateKeys.self_signing = sskSigning.generate_seed();\n const sskPub = sskSigning.init_with_seed(privateKeys.self_signing);\n keys.self_signing = {\n user_id: this.userId,\n usage: [\"self_signing\"],\n keys: {\n [\"ed25519:\" + sskPub]: sskPub,\n },\n };\n pkSign(keys.self_signing, masterSigning, this.userId, masterPub);\n } finally {\n sskSigning.free();\n }\n }\n\n if (level & CrossSigningLevel.USER_SIGNING) {\n const uskSigning = new global.Olm.PkSigning();\n try {\n privateKeys.user_signing = uskSigning.generate_seed();\n const uskPub = uskSigning.init_with_seed(privateKeys.user_signing);\n keys.user_signing = {\n user_id: this.userId,\n usage: [\"user_signing\"],\n keys: {\n [\"ed25519:\" + uskPub]: uskPub,\n },\n };\n pkSign(keys.user_signing, masterSigning, this.userId, masterPub);\n } finally {\n uskSigning.free();\n }\n }\n\n Object.assign(this.keys, keys);\n this.callbacks.saveCrossSigningKeys(privateKeys);\n } finally {\n if (masterSigning) {\n masterSigning.free();\n }\n }\n }\n\n /**\n * unsets the keys, used when another session has reset the keys, to disable cross-signing\n */\n public clearKeys(): void {\n this.keys = {};\n }\n\n public setKeys(keys: Record): void {\n const signingKeys: Record = {};\n if (keys.master) {\n if (keys.master.user_id !== this.userId) {\n const error = \"Mismatched user ID \" + keys.master.user_id + \" in master key from \" + this.userId;\n logger.error(error);\n throw new Error(error);\n }\n if (!this.keys.master) {\n // this is the first key we've seen, so first-use is true\n this.firstUse = true;\n } else if (publicKeyFromKeyInfo(keys.master) !== this.getId()) {\n // this is a different key, so first-use is false\n this.firstUse = false;\n } // otherwise, same key, so no change\n signingKeys.master = keys.master;\n } else if (this.keys.master) {\n signingKeys.master = this.keys.master;\n } else {\n throw new Error(\"Tried to set cross-signing keys without a master key\");\n }\n const masterKey = publicKeyFromKeyInfo(signingKeys.master);\n\n // verify signatures\n if (keys.user_signing) {\n if (keys.user_signing.user_id !== this.userId) {\n const error = \"Mismatched user ID \" + keys.master.user_id + \" in user_signing key from \" + this.userId;\n logger.error(error);\n throw new Error(error);\n }\n try {\n pkVerify(keys.user_signing, masterKey, this.userId);\n } catch (e) {\n logger.error(\"invalid signature on user-signing key\");\n // FIXME: what do we want to do here?\n throw e;\n }\n }\n if (keys.self_signing) {\n if (keys.self_signing.user_id !== this.userId) {\n const error = \"Mismatched user ID \" + keys.master.user_id + \" in self_signing key from \" + this.userId;\n logger.error(error);\n throw new Error(error);\n }\n try {\n pkVerify(keys.self_signing, masterKey, this.userId);\n } catch (e) {\n logger.error(\"invalid signature on self-signing key\");\n // FIXME: what do we want to do here?\n throw e;\n }\n }\n\n // if everything checks out, then save the keys\n if (keys.master) {\n this.keys.master = keys.master;\n // if the master key is set, then the old self-signing and user-signing keys are obsolete\n delete this.keys[\"self_signing\"];\n delete this.keys[\"user_signing\"];\n }\n if (keys.self_signing) {\n this.keys.self_signing = keys.self_signing;\n }\n if (keys.user_signing) {\n this.keys.user_signing = keys.user_signing;\n }\n }\n\n public updateCrossSigningVerifiedBefore(isCrossSigningVerified: boolean): void {\n // It is critical that this value latches forward from false to true but\n // never back to false to avoid a downgrade attack.\n if (!this.crossSigningVerifiedBefore && isCrossSigningVerified) {\n this.crossSigningVerifiedBefore = true;\n }\n }\n\n public async signObject(data: T, type: string): Promise {\n if (!this.keys[type]) {\n throw new Error(\"Attempted to sign with \" + type + \" key but no such key present\");\n }\n const [pubkey, signing] = await this.getCrossSigningKey(type);\n try {\n pkSign(data, signing, this.userId, pubkey);\n return data as T & { signatures: ISignatures };\n } finally {\n signing.free();\n }\n }\n\n public async signUser(key: CrossSigningInfo): Promise {\n if (!this.keys.user_signing) {\n logger.info(\"No user signing key: not signing user\");\n return;\n }\n return this.signObject(key.keys.master, \"user_signing\");\n }\n\n public async signDevice(userId: string, device: DeviceInfo): Promise {\n if (userId !== this.userId) {\n throw new Error(`Trying to sign ${userId}'s device; can only sign our own device`);\n }\n if (!this.keys.self_signing) {\n logger.info(\"No self signing key: not signing device\");\n return;\n }\n return this.signObject>(\n {\n algorithms: device.algorithms,\n keys: device.keys,\n device_id: device.deviceId,\n user_id: userId,\n },\n \"self_signing\",\n );\n }\n\n /**\n * Check whether a given user is trusted.\n *\n * @param userCrossSigning - Cross signing info for user\n *\n * @returns\n */\n public checkUserTrust(userCrossSigning: CrossSigningInfo): UserTrustLevel {\n // if we're checking our own key, then it's trusted if the master key\n // and self-signing key match\n if (\n this.userId === userCrossSigning.userId &&\n this.getId() &&\n this.getId() === userCrossSigning.getId() &&\n this.getId(\"self_signing\") &&\n this.getId(\"self_signing\") === userCrossSigning.getId(\"self_signing\")\n ) {\n return new UserTrustLevel(true, true, this.firstUse);\n }\n\n if (!this.keys.user_signing) {\n // If there's no user signing key, they can't possibly be verified.\n // They may be TOFU trusted though.\n return new UserTrustLevel(false, false, userCrossSigning.firstUse);\n }\n\n let userTrusted: boolean;\n const userMaster = userCrossSigning.keys.master;\n const uskId = this.getId(\"user_signing\")!;\n try {\n pkVerify(userMaster, uskId, this.userId);\n userTrusted = true;\n } catch (e) {\n userTrusted = false;\n }\n return new UserTrustLevel(userTrusted, userCrossSigning.crossSigningVerifiedBefore, userCrossSigning.firstUse);\n }\n\n /**\n * Check whether a given device is trusted.\n *\n * @param userCrossSigning - Cross signing info for user\n * @param device - The device to check\n * @param localTrust - Whether the device is trusted locally\n * @param trustCrossSignedDevices - Whether we trust cross signed devices\n *\n * @returns\n */\n public checkDeviceTrust(\n userCrossSigning: CrossSigningInfo,\n device: DeviceInfo,\n localTrust: boolean,\n trustCrossSignedDevices: boolean,\n ): DeviceTrustLevel {\n const userTrust = this.checkUserTrust(userCrossSigning);\n\n const userSSK = userCrossSigning.keys.self_signing;\n if (!userSSK) {\n // if the user has no self-signing key then we cannot make any\n // trust assertions about this device from cross-signing\n return new DeviceTrustLevel(false, false, localTrust, trustCrossSignedDevices);\n }\n\n const deviceObj = deviceToObject(device, userCrossSigning.userId);\n try {\n // if we can verify the user's SSK from their master key...\n pkVerify(userSSK, userCrossSigning.getId()!, userCrossSigning.userId);\n // ...and this device's key from their SSK...\n pkVerify(deviceObj, publicKeyFromKeyInfo(userSSK), userCrossSigning.userId);\n // ...then we trust this device as much as far as we trust the user\n return DeviceTrustLevel.fromUserTrustLevel(userTrust, localTrust, trustCrossSignedDevices);\n } catch (e) {\n return new DeviceTrustLevel(false, false, localTrust, trustCrossSignedDevices);\n }\n }\n\n /**\n * @returns Cache callbacks\n */\n public getCacheCallbacks(): ICacheCallbacks {\n return this.cacheCallbacks;\n }\n}\n\ninterface DeviceObject extends IObject {\n algorithms: string[];\n keys: Record;\n device_id: string;\n user_id: string;\n}\n\nfunction deviceToObject(device: DeviceInfo, userId: string): DeviceObject {\n return {\n algorithms: device.algorithms,\n keys: device.keys,\n device_id: device.deviceId,\n user_id: userId,\n signatures: device.signatures,\n };\n}\n\nexport enum CrossSigningLevel {\n MASTER = 4,\n USER_SIGNING = 2,\n SELF_SIGNING = 1,\n}\n\n/**\n * Represents the ways in which we trust a user\n */\nexport class UserTrustLevel {\n public constructor(\n private readonly crossSigningVerified: boolean,\n private readonly crossSigningVerifiedBefore: boolean,\n private readonly tofu: boolean,\n ) {}\n\n /**\n * @returns true if this user is verified via any means\n */\n public isVerified(): boolean {\n return this.isCrossSigningVerified();\n }\n\n /**\n * @returns true if this user is verified via cross signing\n */\n public isCrossSigningVerified(): boolean {\n return this.crossSigningVerified;\n }\n\n /**\n * @returns true if we ever verified this user before (at least for\n * the history of verifications observed by this device).\n */\n public wasCrossSigningVerified(): boolean {\n return this.crossSigningVerifiedBefore;\n }\n\n /**\n * @returns true if this user's key is trusted on first use\n */\n public isTofu(): boolean {\n return this.tofu;\n }\n}\n\n/**\n * Represents the ways in which we trust a device\n */\nexport class DeviceTrustLevel {\n public constructor(\n public readonly crossSigningVerified: boolean,\n public readonly tofu: boolean,\n private readonly localVerified: boolean,\n private readonly trustCrossSignedDevices: boolean,\n ) {}\n\n public static fromUserTrustLevel(\n userTrustLevel: UserTrustLevel,\n localVerified: boolean,\n trustCrossSignedDevices: boolean,\n ): DeviceTrustLevel {\n return new DeviceTrustLevel(\n userTrustLevel.isCrossSigningVerified(),\n userTrustLevel.isTofu(),\n localVerified,\n trustCrossSignedDevices,\n );\n }\n\n /**\n * @returns true if this device is verified via any means\n */\n public isVerified(): boolean {\n return Boolean(this.isLocallyVerified() || (this.trustCrossSignedDevices && this.isCrossSigningVerified()));\n }\n\n /**\n * @returns true if this device is verified via cross signing\n */\n public isCrossSigningVerified(): boolean {\n return this.crossSigningVerified;\n }\n\n /**\n * @returns true if this device is verified locally\n */\n public isLocallyVerified(): boolean {\n return this.localVerified;\n }\n\n /**\n * @returns true if this device is trusted from a user's key\n * that is trusted on first use\n */\n public isTofu(): boolean {\n return this.tofu;\n }\n}\n\nexport function createCryptoStoreCacheCallbacks(store: CryptoStore, olmDevice: OlmDevice): ICacheCallbacks {\n return {\n getCrossSigningKeyCache: async function (\n type: keyof SecretStorePrivateKeys,\n _expectedPublicKey: string,\n ): Promise {\n const key = await new Promise((resolve) => {\n return store.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n store.getSecretStorePrivateKey(txn, resolve, type);\n });\n });\n\n if (key && key.ciphertext) {\n const pickleKey = Buffer.from(olmDevice.pickleKey);\n const decrypted = await decryptAES(key, pickleKey, type);\n return decodeBase64(decrypted);\n } else {\n return key;\n }\n },\n storeCrossSigningKeyCache: async function (\n type: keyof SecretStorePrivateKeys,\n key?: Uint8Array,\n ): Promise {\n if (!(key instanceof Uint8Array)) {\n throw new Error(`storeCrossSigningKeyCache expects Uint8Array, got ${key}`);\n }\n const pickleKey = Buffer.from(olmDevice.pickleKey);\n const encryptedKey = await encryptAES(encodeBase64(key), pickleKey, type);\n return store.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n store.storeSecretStorePrivateKey(txn, type, encryptedKey);\n });\n },\n };\n}\n\nexport type KeysDuringVerification = [[string, PkSigning], [string, PkSigning], [string, PkSigning], void];\n\n/**\n * Request cross-signing keys from another device during verification.\n *\n * @param baseApis - base Matrix API interface\n * @param userId - The user ID being verified\n * @param deviceId - The device ID being verified\n */\nexport async function requestKeysDuringVerification(\n baseApis: MatrixClient,\n userId: string,\n deviceId: string,\n): Promise {\n // If this is a self-verification, ask the other party for keys\n if (baseApis.getUserId() !== userId) {\n return;\n }\n logger.log(\"Cross-signing: Self-verification done; requesting keys\");\n // This happens asynchronously, and we're not concerned about waiting for\n // it. We return here in order to test.\n return new Promise((resolve, reject) => {\n const client = baseApis;\n const original = client.crypto!.crossSigningInfo;\n\n // We already have all of the infrastructure we need to validate and\n // cache cross-signing keys, so instead of replicating that, here we set\n // up callbacks that request them from the other device and call\n // CrossSigningInfo.getCrossSigningKey() to validate/cache\n const crossSigning = new CrossSigningInfo(\n original.userId,\n {\n getCrossSigningKey: async (type): Promise => {\n logger.debug(\"Cross-signing: requesting secret\", type, deviceId);\n const { promise } = client.requestSecret(`m.cross_signing.${type}`, [deviceId]);\n const result = await promise;\n const decoded = decodeBase64(result);\n return Uint8Array.from(decoded);\n },\n },\n original.getCacheCallbacks(),\n );\n crossSigning.keys = original.keys;\n\n // XXX: get all keys out if we get one key out\n // https://github.com/vector-im/element-web/issues/12604\n // then change here to reject on the timeout\n // Requests can be ignored, so don't wait around forever\n const timeout = new Promise((resolve) => {\n setTimeout(resolve, KEY_REQUEST_TIMEOUT_MS, new Error(\"Timeout\"));\n });\n\n // also request and cache the key backup key\n const backupKeyPromise = (async (): Promise => {\n const cachedKey = await client.crypto!.getSessionBackupPrivateKey();\n if (!cachedKey) {\n logger.info(\"No cached backup key found. Requesting...\");\n const secretReq = client.requestSecret(\"m.megolm_backup.v1\", [deviceId]);\n const base64Key = await secretReq.promise;\n logger.info(\"Got key backup key, decoding...\");\n const decodedKey = decodeBase64(base64Key);\n logger.info(\"Decoded backup key, storing...\");\n await client.crypto!.storeSessionBackupPrivateKey(Uint8Array.from(decodedKey));\n logger.info(\"Backup key stored. Starting backup restore...\");\n const backupInfo = await client.getKeyBackupVersion();\n // no need to await for this - just let it go in the bg\n client.restoreKeyBackupWithCache(undefined, undefined, backupInfo!).then(() => {\n logger.info(\"Backup restored.\");\n });\n }\n })();\n\n // We call getCrossSigningKey() for its side-effects\n return Promise.race([\n Promise.all([\n crossSigning.getCrossSigningKey(\"master\"),\n crossSigning.getCrossSigningKey(\"self_signing\"),\n crossSigning.getCrossSigningKey(\"user_signing\"),\n backupKeyPromise,\n ]) as Promise,\n timeout,\n ]).then(resolve, reject);\n }).catch((e) => {\n logger.warn(\"Cross-signing: failure while requesting keys:\", e);\n });\n}\n", - "/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Manages the list of other users' devices\n */\n\nimport { logger } from \"../logger\";\nimport { DeviceInfo, IDevice } from \"./deviceinfo\";\nimport { CrossSigningInfo, ICrossSigningInfo } from \"./CrossSigning\";\nimport * as olmlib from \"./olmlib\";\nimport { IndexedDBCryptoStore } from \"./store/indexeddb-crypto-store\";\nimport { chunkPromises, defer, IDeferred, sleep } from \"../utils\";\nimport { DeviceKeys, IDownloadKeyResult, Keys, MatrixClient, SigningKeys } from \"../client\";\nimport { OlmDevice } from \"./OlmDevice\";\nimport { CryptoStore } from \"./store/base\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter\";\nimport { CryptoEvent, CryptoEventHandlerMap } from \"./index\";\n\n/* State transition diagram for DeviceList.deviceTrackingStatus\n *\n * |\n * stopTrackingDeviceList V\n * +---------------------> NOT_TRACKED\n * | |\n * +<--------------------+ | startTrackingDeviceList\n * | | V\n * | +-------------> PENDING_DOWNLOAD <--------------------+-+\n * | | ^ | | |\n * | | restart download | | start download | | invalidateUserDeviceList\n * | | client failed | | | |\n * | | | V | |\n * | +------------ DOWNLOAD_IN_PROGRESS -------------------+ |\n * | | | |\n * +<-------------------+ | download successful |\n * ^ V |\n * +----------------------- UP_TO_DATE ------------------------+\n */\n\n// constants for DeviceList.deviceTrackingStatus\nexport enum TrackingStatus {\n NotTracked,\n PendingDownload,\n DownloadInProgress,\n UpToDate,\n}\n\n// user-Id → device-Id → DeviceInfo\nexport type DeviceInfoMap = Map>;\n\ntype EmittedEvents = CryptoEvent.WillUpdateDevices | CryptoEvent.DevicesUpdated | CryptoEvent.UserCrossSigningUpdated;\n\nexport class DeviceList extends TypedEventEmitter {\n private devices: { [userId: string]: { [deviceId: string]: IDevice } } = {};\n\n public crossSigningInfo: { [userId: string]: ICrossSigningInfo } = {};\n\n // map of identity keys to the user who owns it\n private userByIdentityKey: Record = {};\n\n // which users we are tracking device status for.\n private deviceTrackingStatus: { [userId: string]: TrackingStatus } = {}; // loaded from storage in load()\n\n // The 'next_batch' sync token at the point the data was written,\n // ie. a token representing the point immediately after the\n // moment represented by the snapshot in the db.\n private syncToken: string | null = null;\n\n private keyDownloadsInProgressByUser = new Map>();\n\n // Set whenever changes are made other than setting the sync token\n private dirty = false;\n\n // Promise resolved when device data is saved\n private savePromise: Promise | null = null;\n // Function that resolves the save promise\n private resolveSavePromise: ((saved: boolean) => void) | null = null;\n // The time the save is scheduled for\n private savePromiseTime: number | null = null;\n // The timer used to delay the save\n private saveTimer: ReturnType | null = null;\n // True if we have fetched data from the server or loaded a non-empty\n // set of device data from the store\n private hasFetched: boolean | null = null;\n\n private readonly serialiser: DeviceListUpdateSerialiser;\n\n public constructor(\n baseApis: MatrixClient,\n private readonly cryptoStore: CryptoStore,\n olmDevice: OlmDevice,\n // Maximum number of user IDs per request to prevent server overload (#1619)\n public readonly keyDownloadChunkSize = 250,\n ) {\n super();\n\n this.serialiser = new DeviceListUpdateSerialiser(baseApis, olmDevice, this);\n }\n\n /**\n * Load the device tracking state from storage\n */\n public async load(): Promise {\n await this.cryptoStore.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_DEVICE_DATA], (txn) => {\n this.cryptoStore.getEndToEndDeviceData(txn, (deviceData) => {\n this.hasFetched = Boolean(deviceData && deviceData.devices);\n this.devices = deviceData ? deviceData.devices : {};\n this.crossSigningInfo = deviceData ? deviceData.crossSigningInfo || {} : {};\n this.deviceTrackingStatus = deviceData ? deviceData.trackingStatus : {};\n this.syncToken = deviceData?.syncToken ?? null;\n this.userByIdentityKey = {};\n for (const user of Object.keys(this.devices)) {\n const userDevices = this.devices[user];\n for (const device of Object.keys(userDevices)) {\n const idKey = userDevices[device].keys[\"curve25519:\" + device];\n if (idKey !== undefined) {\n this.userByIdentityKey[idKey] = user;\n }\n }\n }\n });\n });\n\n for (const u of Object.keys(this.deviceTrackingStatus)) {\n // if a download was in progress when we got shut down, it isn't any more.\n if (this.deviceTrackingStatus[u] == TrackingStatus.DownloadInProgress) {\n this.deviceTrackingStatus[u] = TrackingStatus.PendingDownload;\n }\n }\n }\n\n public stop(): void {\n if (this.saveTimer !== null) {\n clearTimeout(this.saveTimer);\n }\n }\n\n /**\n * Save the device tracking state to storage, if any changes are\n * pending other than updating the sync token\n *\n * The actual save will be delayed by a short amount of time to\n * aggregate multiple writes to the database.\n *\n * @param delay - Time in ms before which the save actually happens.\n * By default, the save is delayed for a short period in order to batch\n * multiple writes, but this behaviour can be disabled by passing 0.\n *\n * @returns true if the data was saved, false if\n * it was not (eg. because no changes were pending). The promise\n * will only resolve once the data is saved, so may take some time\n * to resolve.\n */\n public async saveIfDirty(delay = 500): Promise {\n if (!this.dirty) return Promise.resolve(false);\n // Delay saves for a bit so we can aggregate multiple saves that happen\n // in quick succession (eg. when a whole room's devices are marked as known)\n\n const targetTime = Date.now() + delay;\n if (this.savePromiseTime && targetTime < this.savePromiseTime) {\n // There's a save scheduled but for after we would like: cancel\n // it & schedule one for the time we want\n clearTimeout(this.saveTimer!);\n this.saveTimer = null;\n this.savePromiseTime = null;\n // (but keep the save promise since whatever called save before\n // will still want to know when the save is done)\n }\n\n let savePromise = this.savePromise;\n if (savePromise === null) {\n savePromise = new Promise((resolve) => {\n this.resolveSavePromise = resolve;\n });\n this.savePromise = savePromise;\n }\n\n if (this.saveTimer === null) {\n const resolveSavePromise = this.resolveSavePromise;\n this.savePromiseTime = targetTime;\n this.saveTimer = setTimeout(() => {\n logger.log(\"Saving device tracking data\", this.syncToken);\n\n // null out savePromise now (after the delay but before the write),\n // otherwise we could return the existing promise when the save has\n // actually already happened.\n this.savePromiseTime = null;\n this.saveTimer = null;\n this.savePromise = null;\n this.resolveSavePromise = null;\n\n this.cryptoStore\n .doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_DEVICE_DATA], (txn) => {\n this.cryptoStore.storeEndToEndDeviceData(\n {\n devices: this.devices,\n crossSigningInfo: this.crossSigningInfo,\n trackingStatus: this.deviceTrackingStatus,\n syncToken: this.syncToken ?? undefined,\n },\n txn,\n );\n })\n .then(\n () => {\n // The device list is considered dirty until the write completes.\n this.dirty = false;\n resolveSavePromise?.(true);\n },\n (err) => {\n logger.error(\"Failed to save device tracking data\", this.syncToken);\n logger.error(err);\n },\n );\n }, delay);\n }\n\n return savePromise;\n }\n\n /**\n * Gets the sync token last set with setSyncToken\n *\n * @returns The sync token\n */\n public getSyncToken(): string | null {\n return this.syncToken;\n }\n\n /**\n * Sets the sync token that the app will pass as the 'since' to the /sync\n * endpoint next time it syncs.\n * The sync token must always be set after any changes made as a result of\n * data in that sync since setting the sync token to a newer one will mean\n * those changed will not be synced from the server if a new client starts\n * up with that data.\n *\n * @param st - The sync token\n */\n public setSyncToken(st: string | null): void {\n this.syncToken = st;\n }\n\n /**\n * Ensures up to date keys for a list of users are stored in the session store,\n * downloading and storing them if they're not (or if forceDownload is\n * true).\n * @param userIds - The users to fetch.\n * @param forceDownload - Always download the keys even if cached.\n *\n * @returns A promise which resolves to a map userId-\\>deviceId-\\>{@link DeviceInfo}.\n */\n public downloadKeys(userIds: string[], forceDownload: boolean): Promise {\n const usersToDownload: string[] = [];\n const promises: Promise[] = [];\n\n userIds.forEach((u) => {\n const trackingStatus = this.deviceTrackingStatus[u];\n if (this.keyDownloadsInProgressByUser.has(u)) {\n // already a key download in progress/queued for this user; its results\n // will be good enough for us.\n logger.log(`downloadKeys: already have a download in progress for ` + `${u}: awaiting its result`);\n promises.push(this.keyDownloadsInProgressByUser.get(u)!);\n } else if (forceDownload || trackingStatus != TrackingStatus.UpToDate) {\n usersToDownload.push(u);\n }\n });\n\n if (usersToDownload.length != 0) {\n logger.log(\"downloadKeys: downloading for\", usersToDownload);\n const downloadPromise = this.doKeyDownload(usersToDownload);\n promises.push(downloadPromise);\n }\n\n if (promises.length === 0) {\n logger.log(\"downloadKeys: already have all necessary keys\");\n }\n\n return Promise.all(promises).then(() => {\n return this.getDevicesFromStore(userIds);\n });\n }\n\n /**\n * Get the stored device keys for a list of user ids\n *\n * @param userIds - the list of users to list keys for.\n *\n * @returns userId-\\>deviceId-\\>{@link DeviceInfo}.\n */\n private getDevicesFromStore(userIds: string[]): DeviceInfoMap {\n const stored: DeviceInfoMap = new Map();\n userIds.forEach((userId) => {\n const deviceMap = new Map();\n this.getStoredDevicesForUser(userId)?.forEach(function (device) {\n deviceMap.set(device.deviceId, device);\n });\n stored.set(userId, deviceMap);\n });\n return stored;\n }\n\n /**\n * Returns a list of all user IDs the DeviceList knows about\n *\n * @returns All known user IDs\n */\n public getKnownUserIds(): string[] {\n return Object.keys(this.devices);\n }\n\n /**\n * Get the stored device keys for a user id\n *\n * @param userId - the user to list keys for.\n *\n * @returns list of devices, or null if we haven't\n * managed to get a list of devices for this user yet.\n */\n public getStoredDevicesForUser(userId: string): DeviceInfo[] | null {\n const devs = this.devices[userId];\n if (!devs) {\n return null;\n }\n const res: DeviceInfo[] = [];\n for (const deviceId in devs) {\n if (devs.hasOwnProperty(deviceId)) {\n res.push(DeviceInfo.fromStorage(devs[deviceId], deviceId));\n }\n }\n return res;\n }\n\n /**\n * Get the stored device data for a user, in raw object form\n *\n * @param userId - the user to get data for\n *\n * @returns `deviceId->{object}` devices, or undefined if\n * there is no data for this user.\n */\n public getRawStoredDevicesForUser(userId: string): Record {\n return this.devices[userId];\n }\n\n public getStoredCrossSigningForUser(userId: string): CrossSigningInfo | null {\n if (!this.crossSigningInfo[userId]) return null;\n\n return CrossSigningInfo.fromStorage(this.crossSigningInfo[userId], userId);\n }\n\n public storeCrossSigningForUser(userId: string, info: ICrossSigningInfo): void {\n this.crossSigningInfo[userId] = info;\n this.dirty = true;\n }\n\n /**\n * Get the stored keys for a single device\n *\n *\n * @returns device, or undefined\n * if we don't know about this device\n */\n public getStoredDevice(userId: string, deviceId: string): DeviceInfo | undefined {\n const devs = this.devices[userId];\n if (!devs?.[deviceId]) {\n return undefined;\n }\n return DeviceInfo.fromStorage(devs[deviceId], deviceId);\n }\n\n /**\n * Get a user ID by one of their device's curve25519 identity key\n *\n * @param algorithm - encryption algorithm\n * @param senderKey - curve25519 key to match\n *\n * @returns user ID\n */\n public getUserByIdentityKey(algorithm: string, senderKey: string): string | null {\n if (algorithm !== olmlib.OLM_ALGORITHM && algorithm !== olmlib.MEGOLM_ALGORITHM) {\n // we only deal in olm keys\n return null;\n }\n\n return this.userByIdentityKey[senderKey];\n }\n\n /**\n * Find a device by curve25519 identity key\n *\n * @param algorithm - encryption algorithm\n * @param senderKey - curve25519 key to match\n */\n public getDeviceByIdentityKey(algorithm: string, senderKey: string): DeviceInfo | null {\n const userId = this.getUserByIdentityKey(algorithm, senderKey);\n if (!userId) {\n return null;\n }\n\n const devices = this.devices[userId];\n if (!devices) {\n return null;\n }\n\n for (const deviceId in devices) {\n if (!devices.hasOwnProperty(deviceId)) {\n continue;\n }\n\n const device = devices[deviceId];\n for (const keyId in device.keys) {\n if (!device.keys.hasOwnProperty(keyId)) {\n continue;\n }\n if (keyId.indexOf(\"curve25519:\") !== 0) {\n continue;\n }\n const deviceKey = device.keys[keyId];\n if (deviceKey == senderKey) {\n return DeviceInfo.fromStorage(device, deviceId);\n }\n }\n }\n\n // doesn't match a known device\n return null;\n }\n\n /**\n * Replaces the list of devices for a user with the given device list\n *\n * @param userId - The user ID\n * @param devices - New device info for user\n */\n public storeDevicesForUser(userId: string, devices: Record): void {\n this.setRawStoredDevicesForUser(userId, devices);\n this.dirty = true;\n }\n\n /**\n * flag the given user for device-list tracking, if they are not already.\n *\n * This will mean that a subsequent call to refreshOutdatedDeviceLists()\n * will download the device list for the user, and that subsequent calls to\n * invalidateUserDeviceList will trigger more updates.\n *\n */\n public startTrackingDeviceList(userId: string): void {\n // sanity-check the userId. This is mostly paranoia, but if synapse\n // can't parse the userId we give it as an mxid, it 500s the whole\n // request and we can never update the device lists again (because\n // the broken userId is always 'invalid' and always included in any\n // refresh request).\n // By checking it is at least a string, we can eliminate a class of\n // silly errors.\n if (typeof userId !== \"string\") {\n throw new Error(\"userId must be a string; was \" + userId);\n }\n if (!this.deviceTrackingStatus[userId]) {\n logger.log(\"Now tracking device list for \" + userId);\n this.deviceTrackingStatus[userId] = TrackingStatus.PendingDownload;\n // we don't yet persist the tracking status, since there may be a lot\n // of calls; we save all data together once the sync is done\n this.dirty = true;\n }\n }\n\n /**\n * Mark the given user as no longer being tracked for device-list updates.\n *\n * This won't affect any in-progress downloads, which will still go on to\n * complete; it will just mean that we don't think that we have an up-to-date\n * list for future calls to downloadKeys.\n *\n */\n public stopTrackingDeviceList(userId: string): void {\n if (this.deviceTrackingStatus[userId]) {\n logger.log(\"No longer tracking device list for \" + userId);\n this.deviceTrackingStatus[userId] = TrackingStatus.NotTracked;\n\n // we don't yet persist the tracking status, since there may be a lot\n // of calls; we save all data together once the sync is done\n this.dirty = true;\n }\n }\n\n /**\n * Set all users we're currently tracking to untracked\n *\n * This will flag each user whose devices we are tracking as in need of an\n * update.\n */\n public stopTrackingAllDeviceLists(): void {\n for (const userId of Object.keys(this.deviceTrackingStatus)) {\n this.deviceTrackingStatus[userId] = TrackingStatus.NotTracked;\n }\n this.dirty = true;\n }\n\n /**\n * Mark the cached device list for the given user outdated.\n *\n * If we are not tracking this user's devices, we'll do nothing. Otherwise\n * we flag the user as needing an update.\n *\n * This doesn't actually set off an update, so that several users can be\n * batched together. Call refreshOutdatedDeviceLists() for that.\n *\n */\n public invalidateUserDeviceList(userId: string): void {\n if (this.deviceTrackingStatus[userId]) {\n logger.log(\"Marking device list outdated for\", userId);\n this.deviceTrackingStatus[userId] = TrackingStatus.PendingDownload;\n\n // we don't yet persist the tracking status, since there may be a lot\n // of calls; we save all data together once the sync is done\n this.dirty = true;\n }\n }\n\n /**\n * If we have users who have outdated device lists, start key downloads for them\n *\n * @returns which completes when the download completes; normally there\n * is no need to wait for this (it's mostly for the unit tests).\n */\n public refreshOutdatedDeviceLists(): Promise {\n this.saveIfDirty();\n\n const usersToDownload: string[] = [];\n for (const userId of Object.keys(this.deviceTrackingStatus)) {\n const stat = this.deviceTrackingStatus[userId];\n if (stat == TrackingStatus.PendingDownload) {\n usersToDownload.push(userId);\n }\n }\n\n return this.doKeyDownload(usersToDownload);\n }\n\n /**\n * Set the stored device data for a user, in raw object form\n * Used only by internal class DeviceListUpdateSerialiser\n *\n * @param userId - the user to get data for\n *\n * @param devices - `deviceId->{object}` the new devices\n */\n public setRawStoredDevicesForUser(userId: string, devices: Record): void {\n // remove old devices from userByIdentityKey\n if (this.devices[userId] !== undefined) {\n for (const [deviceId, dev] of Object.entries(this.devices[userId])) {\n const identityKey = dev.keys[\"curve25519:\" + deviceId];\n\n delete this.userByIdentityKey[identityKey];\n }\n }\n\n this.devices[userId] = devices;\n\n // add new devices into userByIdentityKey\n for (const [deviceId, dev] of Object.entries(devices)) {\n const identityKey = dev.keys[\"curve25519:\" + deviceId];\n\n this.userByIdentityKey[identityKey] = userId;\n }\n }\n\n public setRawStoredCrossSigningForUser(userId: string, info: ICrossSigningInfo): void {\n this.crossSigningInfo[userId] = info;\n }\n\n /**\n * Fire off download update requests for the given users, and update the\n * device list tracking status for them, and the\n * keyDownloadsInProgressByUser map for them.\n *\n * @param users - list of userIds\n *\n * @returns resolves when all the users listed have\n * been updated. rejects if there was a problem updating any of the\n * users.\n */\n private doKeyDownload(users: string[]): Promise {\n if (users.length === 0) {\n // nothing to do\n return Promise.resolve();\n }\n\n const prom = this.serialiser.updateDevicesForUsers(users, this.syncToken!).then(\n () => {\n finished(true);\n },\n (e) => {\n logger.error(\"Error downloading keys for \" + users + \":\", e);\n finished(false);\n throw e;\n },\n );\n\n users.forEach((u) => {\n this.keyDownloadsInProgressByUser.set(u, prom);\n const stat = this.deviceTrackingStatus[u];\n if (stat == TrackingStatus.PendingDownload) {\n this.deviceTrackingStatus[u] = TrackingStatus.DownloadInProgress;\n }\n });\n\n const finished = (success: boolean): void => {\n this.emit(CryptoEvent.WillUpdateDevices, users, !this.hasFetched);\n users.forEach((u) => {\n this.dirty = true;\n\n // we may have queued up another download request for this user\n // since we started this request. If that happens, we should\n // ignore the completion of the first one.\n if (this.keyDownloadsInProgressByUser.get(u) !== prom) {\n logger.log(\"Another update in the queue for\", u, \"- not marking up-to-date\");\n return;\n }\n this.keyDownloadsInProgressByUser.delete(u);\n const stat = this.deviceTrackingStatus[u];\n if (stat == TrackingStatus.DownloadInProgress) {\n if (success) {\n // we didn't get any new invalidations since this download started:\n // this user's device list is now up to date.\n this.deviceTrackingStatus[u] = TrackingStatus.UpToDate;\n logger.log(\"Device list for\", u, \"now up to date\");\n } else {\n this.deviceTrackingStatus[u] = TrackingStatus.PendingDownload;\n }\n }\n });\n this.saveIfDirty();\n this.emit(CryptoEvent.DevicesUpdated, users, !this.hasFetched);\n this.hasFetched = true;\n };\n\n return prom;\n }\n}\n\n/**\n * Serialises updates to device lists\n *\n * Ensures that results from /keys/query are not overwritten if a second call\n * completes *before* an earlier one.\n *\n * It currently does this by ensuring only one call to /keys/query happens at a\n * time (and queuing other requests up).\n */\nclass DeviceListUpdateSerialiser {\n private downloadInProgress = false;\n\n // users which are queued for download\n // userId -> true\n private keyDownloadsQueuedByUser: Record = {};\n\n // deferred which is resolved when the queued users are downloaded.\n // non-null indicates that we have users queued for download.\n private queuedQueryDeferred?: IDeferred;\n\n private syncToken?: string; // The sync token we send with the requests\n\n /*\n * @param baseApis - Base API object\n * @param olmDevice - The Olm Device\n * @param deviceList - The device list object, the device list to be updated\n */\n public constructor(\n private readonly baseApis: MatrixClient,\n private readonly olmDevice: OlmDevice,\n private readonly deviceList: DeviceList,\n ) {}\n\n /**\n * Make a key query request for the given users\n *\n * @param users - list of user ids\n *\n * @param syncToken - sync token to pass in the query request, to\n * help the HS give the most recent results\n *\n * @returns resolves when all the users listed have\n * been updated. rejects if there was a problem updating any of the\n * users.\n */\n public updateDevicesForUsers(users: string[], syncToken: string): Promise {\n users.forEach((u) => {\n this.keyDownloadsQueuedByUser[u] = true;\n });\n\n if (!this.queuedQueryDeferred) {\n this.queuedQueryDeferred = defer();\n }\n\n // We always take the new sync token and just use the latest one we've\n // been given, since it just needs to be at least as recent as the\n // sync response the device invalidation message arrived in\n this.syncToken = syncToken;\n\n if (this.downloadInProgress) {\n // just queue up these users\n logger.log(\"Queued key download for\", users);\n return this.queuedQueryDeferred.promise;\n }\n\n // start a new download.\n return this.doQueuedQueries();\n }\n\n private doQueuedQueries(): Promise {\n if (this.downloadInProgress) {\n throw new Error(\"DeviceListUpdateSerialiser.doQueuedQueries called with request active\");\n }\n\n const downloadUsers = Object.keys(this.keyDownloadsQueuedByUser);\n this.keyDownloadsQueuedByUser = {};\n const deferred = this.queuedQueryDeferred;\n this.queuedQueryDeferred = undefined;\n\n logger.log(\"Starting key download for\", downloadUsers);\n this.downloadInProgress = true;\n\n const opts: Parameters[1] = {};\n if (this.syncToken) {\n opts.token = this.syncToken;\n }\n\n const factories: Array<() => Promise> = [];\n for (let i = 0; i < downloadUsers.length; i += this.deviceList.keyDownloadChunkSize) {\n const userSlice = downloadUsers.slice(i, i + this.deviceList.keyDownloadChunkSize);\n factories.push(() => this.baseApis.downloadKeysForUsers(userSlice, opts));\n }\n\n chunkPromises(factories, 3)\n .then(async (responses: IDownloadKeyResult[]) => {\n const dk: IDownloadKeyResult[\"device_keys\"] = Object.assign(\n {},\n ...responses.map((res) => res.device_keys || {}),\n );\n const masterKeys: IDownloadKeyResult[\"master_keys\"] = Object.assign(\n {},\n ...responses.map((res) => res.master_keys || {}),\n );\n const ssks: IDownloadKeyResult[\"self_signing_keys\"] = Object.assign(\n {},\n ...responses.map((res) => res.self_signing_keys || {}),\n );\n const usks: IDownloadKeyResult[\"user_signing_keys\"] = Object.assign(\n {},\n ...responses.map((res) => res.user_signing_keys || {}),\n );\n\n // yield to other things that want to execute in between users, to\n // avoid wedging the CPU\n // (https://github.com/vector-im/element-web/issues/3158)\n //\n // of course we ought to do this in a web worker or similar, but\n // this serves as an easy solution for now.\n for (const userId of downloadUsers) {\n await sleep(5);\n try {\n await this.processQueryResponseForUser(userId, dk[userId], {\n master: masterKeys?.[userId],\n self_signing: ssks?.[userId],\n user_signing: usks?.[userId],\n });\n } catch (e) {\n // log the error but continue, so that one bad key\n // doesn't kill the whole process\n logger.error(`Error processing keys for ${userId}:`, e);\n }\n }\n })\n .then(\n () => {\n logger.log(\"Completed key download for \" + downloadUsers);\n\n this.downloadInProgress = false;\n deferred?.resolve();\n\n // if we have queued users, fire off another request.\n if (this.queuedQueryDeferred) {\n this.doQueuedQueries();\n }\n },\n (e) => {\n logger.warn(\"Error downloading keys for \" + downloadUsers + \":\", e);\n this.downloadInProgress = false;\n deferred?.reject(e);\n },\n );\n\n return deferred!.promise;\n }\n\n private async processQueryResponseForUser(\n userId: string,\n dkResponse: DeviceKeys,\n crossSigningResponse: {\n master?: Keys;\n self_signing?: SigningKeys;\n user_signing?: SigningKeys;\n },\n ): Promise {\n logger.log(\"got device keys for \" + userId + \":\", dkResponse);\n logger.log(\"got cross-signing keys for \" + userId + \":\", crossSigningResponse);\n\n {\n // map from deviceid -> deviceinfo for this user\n const userStore: Record = {};\n const devs = this.deviceList.getRawStoredDevicesForUser(userId);\n if (devs) {\n Object.keys(devs).forEach((deviceId) => {\n const d = DeviceInfo.fromStorage(devs[deviceId], deviceId);\n userStore[deviceId] = d;\n });\n }\n\n await updateStoredDeviceKeysForUser(\n this.olmDevice,\n userId,\n userStore,\n dkResponse || {},\n this.baseApis.getUserId()!,\n this.baseApis.deviceId!,\n );\n\n // put the updates into the object that will be returned as our results\n const storage: Record = {};\n Object.keys(userStore).forEach((deviceId) => {\n storage[deviceId] = userStore[deviceId].toStorage();\n });\n\n this.deviceList.setRawStoredDevicesForUser(userId, storage);\n }\n\n // now do the same for the cross-signing keys\n {\n // FIXME: should we be ignoring empty cross-signing responses, or\n // should we be dropping the keys?\n if (\n crossSigningResponse &&\n (crossSigningResponse.master || crossSigningResponse.self_signing || crossSigningResponse.user_signing)\n ) {\n const crossSigning =\n this.deviceList.getStoredCrossSigningForUser(userId) || new CrossSigningInfo(userId);\n\n crossSigning.setKeys(crossSigningResponse);\n\n this.deviceList.setRawStoredCrossSigningForUser(userId, crossSigning.toStorage());\n\n // NB. Unlike most events in the js-sdk, this one is internal to the\n // js-sdk and is not re-emitted\n this.deviceList.emit(CryptoEvent.UserCrossSigningUpdated, userId);\n }\n }\n }\n}\n\nasync function updateStoredDeviceKeysForUser(\n olmDevice: OlmDevice,\n userId: string,\n userStore: Record,\n userResult: IDownloadKeyResult[\"device_keys\"][\"user_id\"],\n localUserId: string,\n localDeviceId: string,\n): Promise {\n let updated = false;\n\n // remove any devices in the store which aren't in the response\n for (const deviceId in userStore) {\n if (!userStore.hasOwnProperty(deviceId)) {\n continue;\n }\n\n if (!(deviceId in userResult)) {\n if (userId === localUserId && deviceId === localDeviceId) {\n logger.warn(`Local device ${deviceId} missing from sync, skipping removal`);\n continue;\n }\n\n logger.log(\"Device \" + userId + \":\" + deviceId + \" has been removed\");\n delete userStore[deviceId];\n updated = true;\n }\n }\n\n for (const deviceId in userResult) {\n if (!userResult.hasOwnProperty(deviceId)) {\n continue;\n }\n\n const deviceResult = userResult[deviceId];\n\n // check that the user_id and device_id in the response object are\n // correct\n if (deviceResult.user_id !== userId) {\n logger.warn(\"Mismatched user_id \" + deviceResult.user_id + \" in keys from \" + userId + \":\" + deviceId);\n continue;\n }\n if (deviceResult.device_id !== deviceId) {\n logger.warn(\"Mismatched device_id \" + deviceResult.device_id + \" in keys from \" + userId + \":\" + deviceId);\n continue;\n }\n\n if (await storeDeviceKeys(olmDevice, userStore, deviceResult)) {\n updated = true;\n }\n }\n\n return updated;\n}\n\n/*\n * Process a device in a /query response, and add it to the userStore\n *\n * returns (a promise for) true if a change was made, else false\n */\nasync function storeDeviceKeys(\n olmDevice: OlmDevice,\n userStore: Record,\n deviceResult: IDownloadKeyResult[\"device_keys\"][\"user_id\"][\"device_id\"],\n): Promise {\n if (!deviceResult.keys) {\n // no keys?\n return false;\n }\n\n const deviceId = deviceResult.device_id;\n const userId = deviceResult.user_id;\n\n const signKeyId = \"ed25519:\" + deviceId;\n const signKey = deviceResult.keys[signKeyId];\n if (!signKey) {\n logger.warn(\"Device \" + userId + \":\" + deviceId + \" has no ed25519 key\");\n return false;\n }\n\n const unsigned = deviceResult.unsigned || {};\n const signatures = deviceResult.signatures || {};\n\n try {\n await olmlib.verifySignature(olmDevice, deviceResult, userId, deviceId, signKey);\n } catch (e) {\n logger.warn(\"Unable to verify signature on device \" + userId + \":\" + deviceId + \":\" + e);\n return false;\n }\n\n // DeviceInfo\n let deviceStore;\n\n if (deviceId in userStore) {\n // already have this device.\n deviceStore = userStore[deviceId];\n\n if (deviceStore.getFingerprint() != signKey) {\n // this should only happen if the list has been MITMed; we are\n // best off sticking with the original keys.\n //\n // Should we warn the user about it somehow?\n logger.warn(\"Ed25519 key for device \" + userId + \":\" + deviceId + \" has changed\");\n return false;\n }\n } else {\n userStore[deviceId] = deviceStore = new DeviceInfo(deviceId);\n }\n\n deviceStore.keys = deviceResult.keys || {};\n deviceStore.algorithms = deviceResult.algorithms || [];\n deviceStore.unsigned = unsigned;\n deviceStore.signatures = signatures;\n return true;\n}\n", - "/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from \"../logger\";\nimport { IContent, MatrixEvent } from \"../models/event\";\nimport { createCryptoStoreCacheCallbacks, ICacheCallbacks } from \"./CrossSigning\";\nimport { IndexedDBCryptoStore } from \"./store/indexeddb-crypto-store\";\nimport { Method, ClientPrefix } from \"../http-api\";\nimport { Crypto, ICryptoCallbacks, IBootstrapCrossSigningOpts } from \"./index\";\nimport {\n ClientEvent,\n ClientEventHandlerMap,\n CrossSigningKeys,\n ICrossSigningKey,\n ISignedKey,\n KeySignatures,\n} from \"../client\";\nimport { IKeyBackupInfo } from \"./keybackup\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter\";\nimport { IAccountDataClient } from \"./SecretStorage\";\nimport { SecretStorageKeyDescription } from \"../secret-storage\";\n\ninterface ICrossSigningKeys {\n authUpload: IBootstrapCrossSigningOpts[\"authUploadDeviceSigningKeys\"];\n keys: Record<\"master\" | \"self_signing\" | \"user_signing\", ICrossSigningKey>;\n}\n\n/**\n * Builds an EncryptionSetupOperation by calling any of the add.. methods.\n * Once done, `buildOperation()` can be called which allows to apply to operation.\n *\n * This is used as a helper by Crypto to keep track of all the network requests\n * and other side-effects of bootstrapping, so it can be applied in one go (and retried in the future)\n * Also keeps track of all the private keys created during bootstrapping, so we don't need to prompt for them\n * more than once.\n */\nexport class EncryptionSetupBuilder {\n public readonly accountDataClientAdapter: AccountDataClientAdapter;\n public readonly crossSigningCallbacks: CrossSigningCallbacks;\n public readonly ssssCryptoCallbacks: SSSSCryptoCallbacks;\n\n private crossSigningKeys?: ICrossSigningKeys;\n private keySignatures?: KeySignatures;\n private keyBackupInfo?: IKeyBackupInfo;\n private sessionBackupPrivateKey?: Uint8Array;\n\n /**\n * @param accountData - pre-existing account data, will only be read, not written.\n * @param delegateCryptoCallbacks - crypto callbacks to delegate to if the key isn't in cache yet\n */\n public constructor(accountData: Map, delegateCryptoCallbacks?: ICryptoCallbacks) {\n this.accountDataClientAdapter = new AccountDataClientAdapter(accountData);\n this.crossSigningCallbacks = new CrossSigningCallbacks();\n this.ssssCryptoCallbacks = new SSSSCryptoCallbacks(delegateCryptoCallbacks);\n }\n\n /**\n * Adds new cross-signing public keys\n *\n * @param authUpload - Function called to await an interactive auth\n * flow when uploading device signing keys.\n * Args:\n * A function that makes the request requiring auth. Receives\n * the auth data as an object. Can be called multiple times, first with\n * an empty authDict, to obtain the flows.\n * @param keys - the new keys\n */\n public addCrossSigningKeys(authUpload: ICrossSigningKeys[\"authUpload\"], keys: ICrossSigningKeys[\"keys\"]): void {\n this.crossSigningKeys = { authUpload, keys };\n }\n\n /**\n * Adds the key backup info to be updated on the server\n *\n * Used either to create a new key backup, or add signatures\n * from the new MSK.\n *\n * @param keyBackupInfo - as received from/sent to the server\n */\n public addSessionBackup(keyBackupInfo: IKeyBackupInfo): void {\n this.keyBackupInfo = keyBackupInfo;\n }\n\n /**\n * Adds the session backup private key to be updated in the local cache\n *\n * Used after fixing the format of the key\n *\n */\n public addSessionBackupPrivateKeyToCache(privateKey: Uint8Array): void {\n this.sessionBackupPrivateKey = privateKey;\n }\n\n /**\n * Add signatures from a given user and device/x-sign key\n * Used to sign the new cross-signing key with the device key\n *\n */\n public addKeySignature(userId: string, deviceId: string, signature: ISignedKey): void {\n if (!this.keySignatures) {\n this.keySignatures = {};\n }\n const userSignatures = this.keySignatures[userId] || {};\n this.keySignatures[userId] = userSignatures;\n userSignatures[deviceId] = signature;\n }\n\n public async setAccountData(type: string, content: object): Promise {\n await this.accountDataClientAdapter.setAccountData(type, content);\n }\n\n /**\n * builds the operation containing all the parts that have been added to the builder\n */\n public buildOperation(): EncryptionSetupOperation {\n const accountData = this.accountDataClientAdapter.values;\n return new EncryptionSetupOperation(accountData, this.crossSigningKeys, this.keyBackupInfo, this.keySignatures);\n }\n\n /**\n * Stores the created keys locally.\n *\n * This does not yet store the operation in a way that it can be restored,\n * but that is the idea in the future.\n */\n public async persist(crypto: Crypto): Promise {\n // store private keys in cache\n if (this.crossSigningKeys) {\n const cacheCallbacks = createCryptoStoreCacheCallbacks(crypto.cryptoStore, crypto.olmDevice);\n for (const type of [\"master\", \"self_signing\", \"user_signing\"]) {\n logger.log(`Cache ${type} cross-signing private key locally`);\n const privateKey = this.crossSigningCallbacks.privateKeys.get(type);\n await cacheCallbacks.storeCrossSigningKeyCache?.(type, privateKey);\n }\n // store own cross-sign pubkeys as trusted\n await crypto.cryptoStore.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n crypto.cryptoStore.storeCrossSigningKeys(txn, this.crossSigningKeys!.keys);\n });\n }\n // store session backup key in cache\n if (this.sessionBackupPrivateKey) {\n await crypto.storeSessionBackupPrivateKey(this.sessionBackupPrivateKey);\n }\n }\n}\n\n/**\n * Can be created from EncryptionSetupBuilder, or\n * (in a follow-up PR, not implemented yet) restored from storage, to retry.\n *\n * It does not have knowledge of any private keys, unlike the builder.\n */\nexport class EncryptionSetupOperation {\n /**\n */\n public constructor(\n private readonly accountData: Map,\n private readonly crossSigningKeys?: ICrossSigningKeys,\n private readonly keyBackupInfo?: IKeyBackupInfo,\n private readonly keySignatures?: KeySignatures,\n ) {}\n\n /**\n * Runs the (remaining part of, in the future) operation by sending requests to the server.\n */\n public async apply(crypto: Crypto): Promise {\n const baseApis = crypto.baseApis;\n // upload cross-signing keys\n if (this.crossSigningKeys) {\n const keys: Partial = {};\n for (const [name, key] of Object.entries(this.crossSigningKeys.keys)) {\n keys[((name as keyof ICrossSigningKeys[\"keys\"]) + \"_key\") as keyof CrossSigningKeys] = key;\n }\n\n // We must only call `uploadDeviceSigningKeys` from inside this auth\n // helper to ensure we properly handle auth errors.\n await this.crossSigningKeys.authUpload?.((authDict) => {\n return baseApis.uploadDeviceSigningKeys(authDict, keys as CrossSigningKeys);\n });\n\n // pass the new keys to the main instance of our own CrossSigningInfo.\n crypto.crossSigningInfo.setKeys(this.crossSigningKeys.keys);\n }\n // set account data\n if (this.accountData) {\n for (const [type, content] of this.accountData) {\n await baseApis.setAccountData(type, content);\n }\n }\n // upload first cross-signing signatures with the new key\n // (e.g. signing our own device)\n if (this.keySignatures) {\n await baseApis.uploadKeySignatures(this.keySignatures);\n }\n // need to create/update key backup info\n if (this.keyBackupInfo) {\n if (this.keyBackupInfo.version) {\n // session backup signature\n // The backup is trusted because the user provided the private key.\n // Sign the backup with the cross signing key so the key backup can\n // be trusted via cross-signing.\n await baseApis.http.authedRequest(\n Method.Put,\n \"/room_keys/version/\" + this.keyBackupInfo.version,\n undefined,\n {\n algorithm: this.keyBackupInfo.algorithm,\n auth_data: this.keyBackupInfo.auth_data,\n },\n { prefix: ClientPrefix.V3 },\n );\n } else {\n // add new key backup\n await baseApis.http.authedRequest(Method.Post, \"/room_keys/version\", undefined, this.keyBackupInfo, {\n prefix: ClientPrefix.V3,\n });\n }\n }\n }\n}\n\n/**\n * Catches account data set by SecretStorage during bootstrapping by\n * implementing the methods related to account data in MatrixClient\n */\nclass AccountDataClientAdapter\n extends TypedEventEmitter\n implements IAccountDataClient\n{\n //\n public readonly values = new Map();\n\n /**\n * @param existingValues - existing account data\n */\n public constructor(private readonly existingValues: Map) {\n super();\n }\n\n /**\n * @returns the content of the account data\n */\n public getAccountDataFromServer(type: string): Promise {\n return Promise.resolve(this.getAccountData(type) as T);\n }\n\n /**\n * @returns the content of the account data\n */\n public getAccountData(type: string): IContent | null {\n const modifiedValue = this.values.get(type);\n if (modifiedValue) {\n return modifiedValue;\n }\n const existingValue = this.existingValues.get(type);\n if (existingValue) {\n return existingValue.getContent();\n }\n return null;\n }\n\n public setAccountData(type: string, content: any): Promise<{}> {\n const lastEvent = this.values.get(type);\n this.values.set(type, content);\n // ensure accountData is emitted on the next tick,\n // as SecretStorage listens for it while calling this method\n // and it seems to rely on this.\n return Promise.resolve().then(() => {\n const event = new MatrixEvent({ type, content });\n this.emit(ClientEvent.AccountData, event, lastEvent);\n return {};\n });\n }\n}\n\n/**\n * Catches the private cross-signing keys set during bootstrapping\n * by both cache callbacks (see createCryptoStoreCacheCallbacks) as non-cache callbacks.\n * See CrossSigningInfo constructor\n */\nclass CrossSigningCallbacks implements ICryptoCallbacks, ICacheCallbacks {\n public readonly privateKeys = new Map();\n\n // cache callbacks\n public getCrossSigningKeyCache(type: string, expectedPublicKey: string): Promise {\n return this.getCrossSigningKey(type, expectedPublicKey);\n }\n\n public storeCrossSigningKeyCache(type: string, key: Uint8Array): Promise {\n this.privateKeys.set(type, key);\n return Promise.resolve();\n }\n\n // non-cache callbacks\n public getCrossSigningKey(type: string, expectedPubkey: string): Promise {\n return Promise.resolve(this.privateKeys.get(type) ?? null);\n }\n\n public saveCrossSigningKeys(privateKeys: Record): void {\n for (const [type, privateKey] of Object.entries(privateKeys)) {\n this.privateKeys.set(type, privateKey);\n }\n }\n}\n\n/**\n * Catches the 4S private key set during bootstrapping by implementing\n * the SecretStorage crypto callbacks\n */\nclass SSSSCryptoCallbacks {\n private readonly privateKeys = new Map();\n\n public constructor(private readonly delegateCryptoCallbacks?: ICryptoCallbacks) {}\n\n public async getSecretStorageKey(\n { keys }: { keys: Record },\n name: string,\n ): Promise<[string, Uint8Array] | null> {\n for (const keyId of Object.keys(keys)) {\n const privateKey = this.privateKeys.get(keyId);\n if (privateKey) {\n return [keyId, privateKey];\n }\n }\n // if we don't have the key cached yet, ask\n // for it to the general crypto callbacks and cache it\n if (this?.delegateCryptoCallbacks?.getSecretStorageKey) {\n const result = await this.delegateCryptoCallbacks.getSecretStorageKey({ keys }, name);\n if (result) {\n const [keyId, privateKey] = result;\n this.privateKeys.set(keyId, privateKey);\n }\n return result;\n }\n return null;\n }\n\n public addPrivateKey(keyId: string, keyInfo: SecretStorageKeyDescription, privKey: Uint8Array): void {\n this.privateKeys.set(keyId, privKey);\n // Also pass along to application to cache if it wishes\n this.delegateCryptoCallbacks?.cacheSecretStorageKey?.(keyId, keyInfo, privKey);\n }\n}\n", - "/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { Account, InboundGroupSession, OutboundGroupSession, Session, Utility } from \"@matrix-org/olm\";\n\nimport { logger, PrefixedLogger } from \"../logger\";\nimport { IndexedDBCryptoStore } from \"./store/indexeddb-crypto-store\";\nimport * as algorithms from \"./algorithms\";\nimport { CryptoStore, IProblem, ISessionInfo, IWithheld } from \"./store/base\";\nimport { IOlmDevice, IOutboundGroupSessionKey } from \"./algorithms/megolm\";\nimport { IMegolmSessionData, OlmGroupSessionExtraData } from \"../@types/crypto\";\nimport { IMessage } from \"./algorithms/olm\";\n\n// The maximum size of an event is 65K, and we base64 the content, so this is a\n// reasonable approximation to the biggest plaintext we can encrypt.\nconst MAX_PLAINTEXT_LENGTH = (65536 * 3) / 4;\n\nexport class PayloadTooLargeError extends Error {\n public readonly data = {\n errcode: \"M_TOO_LARGE\",\n error: \"Payload too large for encrypted message\",\n };\n}\n\nfunction checkPayloadLength(payloadString: string): void {\n if (payloadString === undefined) {\n throw new Error(\"payloadString undefined\");\n }\n\n if (payloadString.length > MAX_PLAINTEXT_LENGTH) {\n // might as well fail early here rather than letting the olm library throw\n // a cryptic memory allocation error.\n //\n // Note that even if we manage to do the encryption, the message send may fail,\n // because by the time we've wrapped the ciphertext in the event object, it may\n // exceed 65K. But at least we won't just fail with \"abort()\" in that case.\n throw new PayloadTooLargeError(\n `Message too long (${payloadString.length} bytes). ` +\n `The maximum for an encrypted message is ${MAX_PLAINTEXT_LENGTH} bytes.`,\n );\n }\n}\n\ninterface IInitOpts {\n fromExportedDevice?: IExportedDevice;\n pickleKey?: string;\n}\n\n/** data stored in the session store about an inbound group session */\nexport interface InboundGroupSessionData {\n room_id: string; // eslint-disable-line camelcase\n /** pickled Olm.InboundGroupSession */\n session: string;\n keysClaimed: Record;\n /** Devices involved in forwarding this session to us (normally empty). */\n forwardingCurve25519KeyChain: string[];\n /** whether this session is untrusted. */\n untrusted?: boolean;\n /** whether this session exists during the room being set to shared history. */\n sharedHistory?: boolean;\n}\n\nexport interface IDecryptedGroupMessage {\n result: string;\n keysClaimed: Record;\n senderKey: string;\n forwardingCurve25519KeyChain: string[];\n untrusted: boolean;\n}\n\nexport interface IInboundSession {\n payload: string;\n session_id: string;\n}\n\nexport interface IExportedDevice {\n pickleKey: string;\n pickledAccount: string;\n sessions: ISessionInfo[];\n}\n\ninterface IUnpickledSessionInfo extends Omit {\n session: Session;\n}\n\n/* eslint-disable camelcase */\ninterface IInboundGroupSessionKey {\n chain_index: number;\n key: string;\n forwarding_curve25519_key_chain: string[];\n sender_claimed_ed25519_key: string | null;\n shared_history: boolean;\n untrusted?: boolean;\n}\n/* eslint-enable camelcase */\n\ntype OneTimeKeys = { curve25519: { [keyId: string]: string } };\n\n/**\n * Manages the olm cryptography functions. Each OlmDevice has a single\n * OlmAccount and a number of OlmSessions.\n *\n * Accounts and sessions are kept pickled in the cryptoStore.\n */\nexport class OlmDevice {\n public pickleKey = \"DEFAULT_KEY\"; // set by consumers\n\n /** Curve25519 key for the account, unknown until we load the account from storage in init() */\n public deviceCurve25519Key: string | null = null;\n /** Ed25519 key for the account, unknown until we load the account from storage in init() */\n public deviceEd25519Key: string | null = null;\n private maxOneTimeKeys: number | null = null;\n\n // we don't bother stashing outboundgroupsessions in the cryptoStore -\n // instead we keep them here.\n private outboundGroupSessionStore: Record = {};\n\n // Store a set of decrypted message indexes for each group session.\n // This partially mitigates a replay attack where a MITM resends a group\n // message into the room.\n //\n // When we decrypt a message and the message index matches a previously\n // decrypted message, one possible cause of that is that we are decrypting\n // the same event, and may not indicate an actual replay attack. For\n // example, this could happen if we receive events, forget about them, and\n // then re-fetch them when we backfill. So we store the event ID and\n // timestamp corresponding to each message index when we first decrypt it,\n // and compare these against the event ID and timestamp every time we use\n // that same index. If they match, then we're probably decrypting the same\n // event and we don't consider it a replay attack.\n //\n // Keys are strings of form \"||\"\n // Values are objects of the form \"{id: , timestamp: }\"\n private inboundGroupSessionMessageIndexes: Record = {};\n\n // Keep track of sessions that we're starting, so that we don't start\n // multiple sessions for the same device at the same time.\n public sessionsInProgress: Record> = {}; // set by consumers\n\n // Used by olm to serialise prekey message decryptions\n public olmPrekeyPromise: Promise = Promise.resolve(); // set by consumers\n\n public constructor(private readonly cryptoStore: CryptoStore) {}\n\n /**\n * @returns The version of Olm.\n */\n public static getOlmVersion(): [number, number, number] {\n return global.Olm.get_library_version();\n }\n\n /**\n * Initialise the OlmAccount. This must be called before any other operations\n * on the OlmDevice.\n *\n * Data from an exported Olm device can be provided\n * in order to re-create this device.\n *\n * Attempts to load the OlmAccount from the crypto store, or creates one if none is\n * found.\n *\n * Reads the device keys from the OlmAccount object.\n *\n * @param fromExportedDevice - (Optional) data from exported device\n * that must be re-created.\n * If present, opts.pickleKey is ignored\n * (exported data already provides a pickle key)\n * @param pickleKey - (Optional) pickle key to set instead of default one\n */\n public async init({ pickleKey, fromExportedDevice }: IInitOpts = {}): Promise {\n let e2eKeys;\n const account = new global.Olm.Account();\n\n try {\n if (fromExportedDevice) {\n if (pickleKey) {\n logger.warn(\"ignoring opts.pickleKey\" + \" because opts.fromExportedDevice is present.\");\n }\n this.pickleKey = fromExportedDevice.pickleKey;\n await this.initialiseFromExportedDevice(fromExportedDevice, account);\n } else {\n if (pickleKey) {\n this.pickleKey = pickleKey;\n }\n await this.initialiseAccount(account);\n }\n e2eKeys = JSON.parse(account.identity_keys());\n\n this.maxOneTimeKeys = account.max_number_of_one_time_keys();\n } finally {\n account.free();\n }\n\n this.deviceCurve25519Key = e2eKeys.curve25519;\n this.deviceEd25519Key = e2eKeys.ed25519;\n }\n\n /**\n * Populates the crypto store using data that was exported from an existing device.\n * Note that for now only the “account” and “sessions” stores are populated;\n * Other stores will be as with a new device.\n *\n * @param exportedData - Data exported from another device\n * through the “export” method.\n * @param account - an olm account to initialize\n */\n private async initialiseFromExportedDevice(exportedData: IExportedDevice, account: Account): Promise {\n await this.cryptoStore.doTxn(\n \"readwrite\",\n [IndexedDBCryptoStore.STORE_ACCOUNT, IndexedDBCryptoStore.STORE_SESSIONS],\n (txn) => {\n this.cryptoStore.storeAccount(txn, exportedData.pickledAccount);\n exportedData.sessions.forEach((session) => {\n const { deviceKey, sessionId } = session;\n const sessionInfo = {\n session: session.session,\n lastReceivedMessageTs: session.lastReceivedMessageTs,\n };\n this.cryptoStore.storeEndToEndSession(deviceKey!, sessionId!, sessionInfo, txn);\n });\n },\n );\n account.unpickle(this.pickleKey, exportedData.pickledAccount);\n }\n\n private async initialiseAccount(account: Account): Promise {\n await this.cryptoStore.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n this.cryptoStore.getAccount(txn, (pickledAccount) => {\n if (pickledAccount !== null) {\n account.unpickle(this.pickleKey, pickledAccount);\n } else {\n account.create();\n pickledAccount = account.pickle(this.pickleKey);\n this.cryptoStore.storeAccount(txn, pickledAccount);\n }\n });\n });\n }\n\n /**\n * extract our OlmAccount from the crypto store and call the given function\n * with the account object\n * The `account` object is usable only within the callback passed to this\n * function and will be freed as soon the callback returns. It is *not*\n * usable for the rest of the lifetime of the transaction.\n * This function requires a live transaction object from cryptoStore.doTxn()\n * and therefore may only be called in a doTxn() callback.\n *\n * @param txn - Opaque transaction object from cryptoStore.doTxn()\n * @internal\n */\n private getAccount(txn: unknown, func: (account: Account) => void): void {\n this.cryptoStore.getAccount(txn, (pickledAccount: string | null) => {\n const account = new global.Olm.Account();\n try {\n account.unpickle(this.pickleKey, pickledAccount!);\n func(account);\n } finally {\n account.free();\n }\n });\n }\n\n /*\n * Saves an account to the crypto store.\n * This function requires a live transaction object from cryptoStore.doTxn()\n * and therefore may only be called in a doTxn() callback.\n *\n * @param txn - Opaque transaction object from cryptoStore.doTxn()\n * @param Olm.Account object\n * @internal\n */\n private storeAccount(txn: unknown, account: Account): void {\n this.cryptoStore.storeAccount(txn, account.pickle(this.pickleKey));\n }\n\n /**\n * Export data for re-creating the Olm device later.\n * TODO export data other than just account and (P2P) sessions.\n *\n * @returns The exported data\n */\n public async export(): Promise {\n const result: Partial = {\n pickleKey: this.pickleKey,\n };\n\n await this.cryptoStore.doTxn(\n \"readonly\",\n [IndexedDBCryptoStore.STORE_ACCOUNT, IndexedDBCryptoStore.STORE_SESSIONS],\n (txn) => {\n this.cryptoStore.getAccount(txn, (pickledAccount: string | null) => {\n result.pickledAccount = pickledAccount!;\n });\n result.sessions = [];\n // Note that the pickledSession object we get in the callback\n // is not exactly the same thing you get in method _getSession\n // see documentation of IndexedDBCryptoStore.getAllEndToEndSessions\n this.cryptoStore.getAllEndToEndSessions(txn, (pickledSession) => {\n result.sessions!.push(pickledSession!);\n });\n },\n );\n return result as IExportedDevice;\n }\n\n /**\n * extract an OlmSession from the session store and call the given function\n * The session is usable only within the callback passed to this\n * function and will be freed as soon the callback returns. It is *not*\n * usable for the rest of the lifetime of the transaction.\n *\n * @param txn - Opaque transaction object from cryptoStore.doTxn()\n * @internal\n */\n private getSession(\n deviceKey: string,\n sessionId: string,\n txn: unknown,\n func: (unpickledSessionInfo: IUnpickledSessionInfo) => void,\n ): void {\n this.cryptoStore.getEndToEndSession(deviceKey, sessionId, txn, (sessionInfo: ISessionInfo | null) => {\n this.unpickleSession(sessionInfo!, func);\n });\n }\n\n /**\n * Creates a session object from a session pickle and executes the given\n * function with it. The session object is destroyed once the function\n * returns.\n *\n * @internal\n */\n private unpickleSession(\n sessionInfo: ISessionInfo,\n func: (unpickledSessionInfo: IUnpickledSessionInfo) => void,\n ): void {\n const session = new global.Olm.Session();\n try {\n session.unpickle(this.pickleKey, sessionInfo.session!);\n const unpickledSessInfo: IUnpickledSessionInfo = Object.assign({}, sessionInfo, { session });\n\n func(unpickledSessInfo);\n } finally {\n session.free();\n }\n }\n\n /**\n * store our OlmSession in the session store\n *\n * @param sessionInfo - `{session: OlmSession, lastReceivedMessageTs: int}`\n * @param txn - Opaque transaction object from cryptoStore.doTxn()\n * @internal\n */\n private saveSession(deviceKey: string, sessionInfo: IUnpickledSessionInfo, txn: unknown): void {\n const sessionId = sessionInfo.session.session_id();\n logger.debug(`Saving Olm session ${sessionId} with device ${deviceKey}: ${sessionInfo.session.describe()}`);\n\n // Why do we re-use the input object for this, overwriting the same key with a different\n // type? Is it because we want to erase the unpickled session to enforce that it's no longer\n // used? A comment would be great.\n const pickledSessionInfo = Object.assign(sessionInfo, {\n session: sessionInfo.session.pickle(this.pickleKey),\n });\n this.cryptoStore.storeEndToEndSession(deviceKey, sessionId, pickledSessionInfo, txn);\n }\n\n /**\n * get an OlmUtility and call the given function\n *\n * @returns result of func\n * @internal\n */\n private getUtility(func: (utility: Utility) => T): T {\n const utility = new global.Olm.Utility();\n try {\n return func(utility);\n } finally {\n utility.free();\n }\n }\n\n /**\n * Signs a message with the ed25519 key for this account.\n *\n * @param message - message to be signed\n * @returns base64-encoded signature\n */\n public async sign(message: string): Promise {\n let result: string;\n await this.cryptoStore.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n this.getAccount(txn, (account: Account) => {\n result = account.sign(message);\n });\n });\n return result!;\n }\n\n /**\n * Get the current (unused, unpublished) one-time keys for this account.\n *\n * @returns one time keys; an object with the single property\n * curve25519, which is itself an object mapping key id to Curve25519\n * key.\n */\n public async getOneTimeKeys(): Promise {\n let result: OneTimeKeys;\n await this.cryptoStore.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n this.getAccount(txn, (account) => {\n result = JSON.parse(account.one_time_keys());\n });\n });\n\n return result!;\n }\n\n /**\n * Get the maximum number of one-time keys we can store.\n *\n * @returns number of keys\n */\n public maxNumberOfOneTimeKeys(): number {\n return this.maxOneTimeKeys ?? -1;\n }\n\n /**\n * Marks all of the one-time keys as published.\n */\n public async markKeysAsPublished(): Promise {\n await this.cryptoStore.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n this.getAccount(txn, (account: Account) => {\n account.mark_keys_as_published();\n this.storeAccount(txn, account);\n });\n });\n }\n\n /**\n * Generate some new one-time keys\n *\n * @param numKeys - number of keys to generate\n * @returns Resolved once the account is saved back having generated the keys\n */\n public generateOneTimeKeys(numKeys: number): Promise {\n return this.cryptoStore.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n this.getAccount(txn, (account) => {\n account.generate_one_time_keys(numKeys);\n this.storeAccount(txn, account);\n });\n });\n }\n\n /**\n * Generate a new fallback keys\n *\n * @returns Resolved once the account is saved back having generated the key\n */\n public async generateFallbackKey(): Promise {\n await this.cryptoStore.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n this.getAccount(txn, (account) => {\n account.generate_fallback_key();\n this.storeAccount(txn, account);\n });\n });\n }\n\n public async getFallbackKey(): Promise>> {\n let result: Record>;\n await this.cryptoStore.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n this.getAccount(txn, (account: Account) => {\n result = JSON.parse(account.unpublished_fallback_key());\n });\n });\n return result!;\n }\n\n public async forgetOldFallbackKey(): Promise {\n await this.cryptoStore.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n this.getAccount(txn, (account: Account) => {\n account.forget_old_fallback_key();\n this.storeAccount(txn, account);\n });\n });\n }\n\n /**\n * Generate a new outbound session\n *\n * The new session will be stored in the cryptoStore.\n *\n * @param theirIdentityKey - remote user's Curve25519 identity key\n * @param theirOneTimeKey - remote user's one-time Curve25519 key\n * @returns sessionId for the outbound session.\n */\n public async createOutboundSession(theirIdentityKey: string, theirOneTimeKey: string): Promise {\n let newSessionId: string;\n await this.cryptoStore.doTxn(\n \"readwrite\",\n [IndexedDBCryptoStore.STORE_ACCOUNT, IndexedDBCryptoStore.STORE_SESSIONS],\n (txn) => {\n this.getAccount(txn, (account: Account) => {\n const session = new global.Olm.Session();\n try {\n session.create_outbound(account, theirIdentityKey, theirOneTimeKey);\n newSessionId = session.session_id();\n this.storeAccount(txn, account);\n const sessionInfo: IUnpickledSessionInfo = {\n session,\n // Pretend we've received a message at this point, otherwise\n // if we try to send a message to the device, it won't use\n // this session\n lastReceivedMessageTs: Date.now(),\n };\n this.saveSession(theirIdentityKey, sessionInfo, txn);\n } finally {\n session.free();\n }\n });\n },\n logger.withPrefix(\"[createOutboundSession]\"),\n );\n return newSessionId!;\n }\n\n /**\n * Generate a new inbound session, given an incoming message\n *\n * @param theirDeviceIdentityKey - remote user's Curve25519 identity key\n * @param messageType - messageType field from the received message (must be 0)\n * @param ciphertext - base64-encoded body from the received message\n *\n * @returns decrypted payload, and\n * session id of new session\n *\n * @throws Error if the received message was not valid (for instance, it didn't use a valid one-time key).\n */\n public async createInboundSession(\n theirDeviceIdentityKey: string,\n messageType: number,\n ciphertext: string,\n ): Promise {\n if (messageType !== 0) {\n throw new Error(\"Need messageType == 0 to create inbound session\");\n }\n\n let result: { payload: string; session_id: string }; // eslint-disable-line camelcase\n await this.cryptoStore.doTxn(\n \"readwrite\",\n [IndexedDBCryptoStore.STORE_ACCOUNT, IndexedDBCryptoStore.STORE_SESSIONS],\n (txn) => {\n this.getAccount(txn, (account: Account) => {\n const session = new global.Olm.Session();\n try {\n session.create_inbound_from(account, theirDeviceIdentityKey, ciphertext);\n account.remove_one_time_keys(session);\n this.storeAccount(txn, account);\n\n const payloadString = session.decrypt(messageType, ciphertext);\n\n const sessionInfo: IUnpickledSessionInfo = {\n session,\n // this counts as a received message: set last received message time\n // to now\n lastReceivedMessageTs: Date.now(),\n };\n this.saveSession(theirDeviceIdentityKey, sessionInfo, txn);\n\n result = {\n payload: payloadString,\n session_id: session.session_id(),\n };\n } finally {\n session.free();\n }\n });\n },\n logger.withPrefix(\"[createInboundSession]\"),\n );\n\n return result!;\n }\n\n /**\n * Get a list of known session IDs for the given device\n *\n * @param theirDeviceIdentityKey - Curve25519 identity key for the\n * remote device\n * @returns a list of known session ids for the device\n */\n public async getSessionIdsForDevice(theirDeviceIdentityKey: string): Promise {\n const log = logger.withPrefix(\"[getSessionIdsForDevice]\");\n\n if (theirDeviceIdentityKey in this.sessionsInProgress) {\n log.debug(`Waiting for Olm session for ${theirDeviceIdentityKey} to be created`);\n try {\n await this.sessionsInProgress[theirDeviceIdentityKey];\n } catch (e) {\n // if the session failed to be created, just fall through and\n // return an empty result\n }\n }\n let sessionIds: string[];\n await this.cryptoStore.doTxn(\n \"readonly\",\n [IndexedDBCryptoStore.STORE_SESSIONS],\n (txn) => {\n this.cryptoStore.getEndToEndSessions(theirDeviceIdentityKey, txn, (sessions) => {\n sessionIds = Object.keys(sessions);\n });\n },\n log,\n );\n\n return sessionIds!;\n }\n\n /**\n * Get the right olm session id for encrypting messages to the given identity key\n *\n * @param theirDeviceIdentityKey - Curve25519 identity key for the\n * remote device\n * @param nowait - Don't wait for an in-progress session to complete.\n * This should only be set to true of the calling function is the function\n * that marked the session as being in-progress.\n * @param log - A possibly customised log\n * @returns session id, or null if no established session\n */\n public async getSessionIdForDevice(\n theirDeviceIdentityKey: string,\n nowait = false,\n log?: PrefixedLogger,\n ): Promise {\n const sessionInfos = await this.getSessionInfoForDevice(theirDeviceIdentityKey, nowait, log);\n\n if (sessionInfos.length === 0) {\n return null;\n }\n // Use the session that has most recently received a message\n let idxOfBest = 0;\n for (let i = 1; i < sessionInfos.length; i++) {\n const thisSessInfo = sessionInfos[i];\n const thisLastReceived =\n thisSessInfo.lastReceivedMessageTs === undefined ? 0 : thisSessInfo.lastReceivedMessageTs;\n\n const bestSessInfo = sessionInfos[idxOfBest];\n const bestLastReceived =\n bestSessInfo.lastReceivedMessageTs === undefined ? 0 : bestSessInfo.lastReceivedMessageTs;\n if (\n thisLastReceived > bestLastReceived ||\n (thisLastReceived === bestLastReceived && thisSessInfo.sessionId < bestSessInfo.sessionId)\n ) {\n idxOfBest = i;\n }\n }\n return sessionInfos[idxOfBest].sessionId;\n }\n\n /**\n * Get information on the active Olm sessions for a device.\n *

\n * Returns an array, with an entry for each active session. The first entry in\n * the result will be the one used for outgoing messages. Each entry contains\n * the keys 'hasReceivedMessage' (true if the session has received an incoming\n * message and is therefore past the pre-key stage), and 'sessionId'.\n *\n * @param deviceIdentityKey - Curve25519 identity key for the device\n * @param nowait - Don't wait for an in-progress session to complete.\n * This should only be set to true of the calling function is the function\n * that marked the session as being in-progress.\n * @param log - A possibly customised log\n */\n public async getSessionInfoForDevice(\n deviceIdentityKey: string,\n nowait = false,\n log = logger,\n ): Promise<{ sessionId: string; lastReceivedMessageTs: number; hasReceivedMessage: boolean }[]> {\n log = log.withPrefix(\"[getSessionInfoForDevice]\");\n\n if (deviceIdentityKey in this.sessionsInProgress && !nowait) {\n log.debug(`Waiting for Olm session for ${deviceIdentityKey} to be created`);\n try {\n await this.sessionsInProgress[deviceIdentityKey];\n } catch (e) {\n // if the session failed to be created, then just fall through and\n // return an empty result\n }\n }\n const info: {\n lastReceivedMessageTs: number;\n hasReceivedMessage: boolean;\n sessionId: string;\n }[] = [];\n\n await this.cryptoStore.doTxn(\n \"readonly\",\n [IndexedDBCryptoStore.STORE_SESSIONS],\n (txn) => {\n this.cryptoStore.getEndToEndSessions(deviceIdentityKey, txn, (sessions) => {\n const sessionIds = Object.keys(sessions).sort();\n for (const sessionId of sessionIds) {\n this.unpickleSession(sessions[sessionId], (sessInfo: IUnpickledSessionInfo) => {\n info.push({\n lastReceivedMessageTs: sessInfo.lastReceivedMessageTs!,\n hasReceivedMessage: sessInfo.session.has_received_message(),\n sessionId,\n });\n });\n }\n });\n },\n log,\n );\n\n return info;\n }\n\n /**\n * Encrypt an outgoing message using an existing session\n *\n * @param theirDeviceIdentityKey - Curve25519 identity key for the\n * remote device\n * @param sessionId - the id of the active session\n * @param payloadString - payload to be encrypted and sent\n *\n * @returns ciphertext\n */\n public async encryptMessage(\n theirDeviceIdentityKey: string,\n sessionId: string,\n payloadString: string,\n ): Promise {\n checkPayloadLength(payloadString);\n\n let res: IMessage;\n await this.cryptoStore.doTxn(\n \"readwrite\",\n [IndexedDBCryptoStore.STORE_SESSIONS],\n (txn) => {\n this.getSession(theirDeviceIdentityKey, sessionId, txn, (sessionInfo) => {\n const sessionDesc = sessionInfo.session.describe();\n logger.log(\n \"encryptMessage: Olm Session ID \" +\n sessionId +\n \" to \" +\n theirDeviceIdentityKey +\n \": \" +\n sessionDesc,\n );\n res = sessionInfo.session.encrypt(payloadString);\n this.saveSession(theirDeviceIdentityKey, sessionInfo, txn);\n });\n },\n logger.withPrefix(\"[encryptMessage]\"),\n );\n return res!;\n }\n\n /**\n * Decrypt an incoming message using an existing session\n *\n * @param theirDeviceIdentityKey - Curve25519 identity key for the\n * remote device\n * @param sessionId - the id of the active session\n * @param messageType - messageType field from the received message\n * @param ciphertext - base64-encoded body from the received message\n *\n * @returns decrypted payload.\n */\n public async decryptMessage(\n theirDeviceIdentityKey: string,\n sessionId: string,\n messageType: number,\n ciphertext: string,\n ): Promise {\n let payloadString: string;\n await this.cryptoStore.doTxn(\n \"readwrite\",\n [IndexedDBCryptoStore.STORE_SESSIONS],\n (txn) => {\n this.getSession(theirDeviceIdentityKey, sessionId, txn, (sessionInfo: IUnpickledSessionInfo) => {\n const sessionDesc = sessionInfo.session.describe();\n logger.log(\n \"decryptMessage: Olm Session ID \" +\n sessionId +\n \" from \" +\n theirDeviceIdentityKey +\n \": \" +\n sessionDesc,\n );\n payloadString = sessionInfo.session.decrypt(messageType, ciphertext);\n sessionInfo.lastReceivedMessageTs = Date.now();\n this.saveSession(theirDeviceIdentityKey, sessionInfo, txn);\n });\n },\n logger.withPrefix(\"[decryptMessage]\"),\n );\n return payloadString!;\n }\n\n /**\n * Determine if an incoming messages is a prekey message matching an existing session\n *\n * @param theirDeviceIdentityKey - Curve25519 identity key for the\n * remote device\n * @param sessionId - the id of the active session\n * @param messageType - messageType field from the received message\n * @param ciphertext - base64-encoded body from the received message\n *\n * @returns true if the received message is a prekey message which matches\n * the given session.\n */\n public async matchesSession(\n theirDeviceIdentityKey: string,\n sessionId: string,\n messageType: number,\n ciphertext: string,\n ): Promise {\n if (messageType !== 0) {\n return false;\n }\n\n let matches: boolean;\n await this.cryptoStore.doTxn(\n \"readonly\",\n [IndexedDBCryptoStore.STORE_SESSIONS],\n (txn) => {\n this.getSession(theirDeviceIdentityKey, sessionId, txn, (sessionInfo) => {\n matches = sessionInfo.session.matches_inbound(ciphertext);\n });\n },\n logger.withPrefix(\"[matchesSession]\"),\n );\n return matches!;\n }\n\n public async recordSessionProblem(deviceKey: string, type: string, fixed: boolean): Promise {\n logger.info(`Recording problem on olm session with ${deviceKey} of type ${type}. Recreating: ${fixed}`);\n await this.cryptoStore.storeEndToEndSessionProblem(deviceKey, type, fixed);\n }\n\n public sessionMayHaveProblems(deviceKey: string, timestamp: number): Promise {\n return this.cryptoStore.getEndToEndSessionProblem(deviceKey, timestamp);\n }\n\n public filterOutNotifiedErrorDevices(devices: IOlmDevice[]): Promise {\n return this.cryptoStore.filterOutNotifiedErrorDevices(devices);\n }\n\n // Outbound group session\n // ======================\n\n /**\n * store an OutboundGroupSession in outboundGroupSessionStore\n *\n * @internal\n */\n private saveOutboundGroupSession(session: OutboundGroupSession): void {\n this.outboundGroupSessionStore[session.session_id()] = session.pickle(this.pickleKey);\n }\n\n /**\n * extract an OutboundGroupSession from outboundGroupSessionStore and call the\n * given function\n *\n * @returns result of func\n * @internal\n */\n private getOutboundGroupSession(sessionId: string, func: (session: OutboundGroupSession) => T): T {\n const pickled = this.outboundGroupSessionStore[sessionId];\n if (pickled === undefined) {\n throw new Error(\"Unknown outbound group session \" + sessionId);\n }\n\n const session = new global.Olm.OutboundGroupSession();\n try {\n session.unpickle(this.pickleKey, pickled);\n return func(session);\n } finally {\n session.free();\n }\n }\n\n /**\n * Generate a new outbound group session\n *\n * @returns sessionId for the outbound session.\n */\n public createOutboundGroupSession(): string {\n const session = new global.Olm.OutboundGroupSession();\n try {\n session.create();\n this.saveOutboundGroupSession(session);\n return session.session_id();\n } finally {\n session.free();\n }\n }\n\n /**\n * Encrypt an outgoing message with an outbound group session\n *\n * @param sessionId - the id of the outboundgroupsession\n * @param payloadString - payload to be encrypted and sent\n *\n * @returns ciphertext\n */\n public encryptGroupMessage(sessionId: string, payloadString: string): string {\n logger.log(`encrypting msg with megolm session ${sessionId}`);\n\n checkPayloadLength(payloadString);\n\n return this.getOutboundGroupSession(sessionId, (session: OutboundGroupSession) => {\n const res = session.encrypt(payloadString);\n this.saveOutboundGroupSession(session);\n return res;\n });\n }\n\n /**\n * Get the session keys for an outbound group session\n *\n * @param sessionId - the id of the outbound group session\n *\n * @returns current chain index, and\n * base64-encoded secret key.\n */\n public getOutboundGroupSessionKey(sessionId: string): IOutboundGroupSessionKey {\n return this.getOutboundGroupSession(sessionId, function (session: OutboundGroupSession) {\n return {\n chain_index: session.message_index(),\n key: session.session_key(),\n };\n });\n }\n\n // Inbound group session\n // =====================\n\n /**\n * Unpickle a session from a sessionData object and invoke the given function.\n * The session is valid only until func returns.\n *\n * @param sessionData - Object describing the session.\n * @param func - Invoked with the unpickled session\n * @returns result of func\n */\n private unpickleInboundGroupSession(\n sessionData: InboundGroupSessionData,\n func: (session: InboundGroupSession) => T,\n ): T {\n const session = new global.Olm.InboundGroupSession();\n try {\n session.unpickle(this.pickleKey, sessionData.session);\n return func(session);\n } finally {\n session.free();\n }\n }\n\n /**\n * extract an InboundGroupSession from the crypto store and call the given function\n *\n * @param roomId - The room ID to extract the session for, or null to fetch\n * sessions for any room.\n * @param txn - Opaque transaction object from cryptoStore.doTxn()\n * @param func - function to call.\n *\n * @internal\n */\n private getInboundGroupSession(\n roomId: string,\n senderKey: string,\n sessionId: string,\n txn: unknown,\n func: (\n session: InboundGroupSession | null,\n data: InboundGroupSessionData | null,\n withheld: IWithheld | null,\n ) => void,\n ): void {\n this.cryptoStore.getEndToEndInboundGroupSession(\n senderKey,\n sessionId,\n txn,\n (sessionData: InboundGroupSessionData | null, withheld: IWithheld | null) => {\n if (sessionData === null) {\n func(null, null, withheld);\n return;\n }\n\n // if we were given a room ID, check that the it matches the original one for the session. This stops\n // the HS pretending a message was targeting a different room.\n if (roomId !== null && roomId !== sessionData.room_id) {\n throw new Error(\n \"Mismatched room_id for inbound group session (expected \" +\n sessionData.room_id +\n \", was \" +\n roomId +\n \")\",\n );\n }\n\n this.unpickleInboundGroupSession(sessionData, (session: InboundGroupSession) => {\n func(session, sessionData, withheld);\n });\n },\n );\n }\n\n /**\n * Add an inbound group session to the session store\n *\n * @param roomId - room in which this session will be used\n * @param senderKey - base64-encoded curve25519 key of the sender\n * @param forwardingCurve25519KeyChain - Devices involved in forwarding\n * this session to us.\n * @param sessionId - session identifier\n * @param sessionKey - base64-encoded secret key\n * @param keysClaimed - Other keys the sender claims.\n * @param exportFormat - true if the megolm keys are in export format\n * (ie, they lack an ed25519 signature)\n * @param extraSessionData - any other data to be include with the session\n */\n public async addInboundGroupSession(\n roomId: string,\n senderKey: string,\n forwardingCurve25519KeyChain: string[],\n sessionId: string,\n sessionKey: string,\n keysClaimed: Record,\n exportFormat: boolean,\n extraSessionData: OlmGroupSessionExtraData = {},\n ): Promise {\n await this.cryptoStore.doTxn(\n \"readwrite\",\n [\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD,\n IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS,\n ],\n (txn) => {\n /* if we already have this session, consider updating it */\n this.getInboundGroupSession(\n roomId,\n senderKey,\n sessionId,\n txn,\n (\n existingSession: InboundGroupSession | null,\n existingSessionData: InboundGroupSessionData | null,\n ) => {\n // new session.\n const session = new global.Olm.InboundGroupSession();\n try {\n if (exportFormat) {\n session.import_session(sessionKey);\n } else {\n session.create(sessionKey);\n }\n if (sessionId != session.session_id()) {\n throw new Error(\"Mismatched group session ID from senderKey: \" + senderKey);\n }\n\n if (existingSession) {\n logger.log(`Update for megolm session ${senderKey}|${sessionId}`);\n if (existingSession.first_known_index() <= session.first_known_index()) {\n if (!existingSessionData!.untrusted || extraSessionData.untrusted) {\n // existing session has less-than-or-equal index\n // (i.e. can decrypt at least as much), and the\n // new session's trust does not win over the old\n // session's trust, so keep it\n logger.log(`Keeping existing megolm session ${senderKey}|${sessionId}`);\n return;\n }\n if (existingSession.first_known_index() < session.first_known_index()) {\n // We want to upgrade the existing session's trust,\n // but we can't just use the new session because we'll\n // lose the lower index. Check that the sessions connect\n // properly, and then manually set the existing session\n // as trusted.\n if (\n existingSession.export_session(session.first_known_index()) ===\n session.export_session(session.first_known_index())\n ) {\n logger.info(\n \"Upgrading trust of existing megolm session \" +\n `${senderKey}|${sessionId} based on newly-received trusted session`,\n );\n existingSessionData!.untrusted = false;\n this.cryptoStore.storeEndToEndInboundGroupSession(\n senderKey,\n sessionId,\n existingSessionData!,\n txn,\n );\n } else {\n logger.warn(\n `Newly-received megolm session ${senderKey}|$sessionId}` +\n \" does not match existing session! Keeping existing session\",\n );\n }\n return;\n }\n // If the sessions have the same index, go ahead and store the new trusted one.\n }\n }\n\n logger.info(\n `Storing megolm session ${senderKey}|${sessionId} with first index ` +\n session.first_known_index(),\n );\n\n const sessionData = Object.assign({}, extraSessionData, {\n room_id: roomId,\n session: session.pickle(this.pickleKey),\n keysClaimed: keysClaimed,\n forwardingCurve25519KeyChain: forwardingCurve25519KeyChain,\n });\n\n this.cryptoStore.storeEndToEndInboundGroupSession(senderKey, sessionId, sessionData, txn);\n\n if (!existingSession && extraSessionData.sharedHistory) {\n this.cryptoStore.addSharedHistoryInboundGroupSession(roomId, senderKey, sessionId, txn);\n }\n } finally {\n session.free();\n }\n },\n );\n },\n logger.withPrefix(\"[addInboundGroupSession]\"),\n );\n }\n\n /**\n * Record in the data store why an inbound group session was withheld.\n *\n * @param roomId - room that the session belongs to\n * @param senderKey - base64-encoded curve25519 key of the sender\n * @param sessionId - session identifier\n * @param code - reason code\n * @param reason - human-readable version of `code`\n */\n public async addInboundGroupSessionWithheld(\n roomId: string,\n senderKey: string,\n sessionId: string,\n code: string,\n reason: string,\n ): Promise {\n await this.cryptoStore.doTxn(\n \"readwrite\",\n [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],\n (txn) => {\n this.cryptoStore.storeEndToEndInboundGroupSessionWithheld(\n senderKey,\n sessionId,\n {\n room_id: roomId,\n code: code,\n reason: reason,\n },\n txn,\n );\n },\n );\n }\n\n /**\n * Decrypt a received message with an inbound group session\n *\n * @param roomId - room in which the message was received\n * @param senderKey - base64-encoded curve25519 key of the sender\n * @param sessionId - session identifier\n * @param body - base64-encoded body of the encrypted message\n * @param eventId - ID of the event being decrypted\n * @param timestamp - timestamp of the event being decrypted\n *\n * @returns null if the sessionId is unknown\n */\n public async decryptGroupMessage(\n roomId: string,\n senderKey: string,\n sessionId: string,\n body: string,\n eventId: string,\n timestamp: number,\n ): Promise {\n let result: IDecryptedGroupMessage | null = null;\n // when the localstorage crypto store is used as an indexeddb backend,\n // exceptions thrown from within the inner function are not passed through\n // to the top level, so we store exceptions in a variable and raise them at\n // the end\n let error: Error;\n\n await this.cryptoStore.doTxn(\n \"readwrite\",\n [\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD,\n ],\n (txn) => {\n this.getInboundGroupSession(roomId, senderKey, sessionId, txn, (session, sessionData, withheld) => {\n if (session === null || sessionData === null) {\n if (withheld) {\n error = new algorithms.DecryptionError(\n \"MEGOLM_UNKNOWN_INBOUND_SESSION_ID\",\n calculateWithheldMessage(withheld),\n {\n session: senderKey + \"|\" + sessionId,\n },\n );\n }\n result = null;\n return;\n }\n let res: ReturnType;\n try {\n res = session.decrypt(body);\n } catch (e) {\n if ((e)?.message === \"OLM.UNKNOWN_MESSAGE_INDEX\" && withheld) {\n error = new algorithms.DecryptionError(\n \"MEGOLM_UNKNOWN_INBOUND_SESSION_ID\",\n calculateWithheldMessage(withheld),\n {\n session: senderKey + \"|\" + sessionId,\n },\n );\n } else {\n error = e;\n }\n return;\n }\n\n let plaintext: string = res.plaintext;\n if (plaintext === undefined) {\n // @ts-ignore - Compatibility for older olm versions.\n plaintext = res as string;\n } else {\n // Check if we have seen this message index before to detect replay attacks.\n // If the event ID and timestamp are specified, and the match the event ID\n // and timestamp from the last time we used this message index, then we\n // don't consider it a replay attack.\n const messageIndexKey = senderKey + \"|\" + sessionId + \"|\" + res.message_index;\n if (messageIndexKey in this.inboundGroupSessionMessageIndexes) {\n const msgInfo = this.inboundGroupSessionMessageIndexes[messageIndexKey];\n if (msgInfo.id !== eventId || msgInfo.timestamp !== timestamp) {\n error = new Error(\n \"Duplicate message index, possible replay attack: \" + messageIndexKey,\n );\n return;\n }\n }\n this.inboundGroupSessionMessageIndexes[messageIndexKey] = {\n id: eventId,\n timestamp: timestamp,\n };\n }\n\n sessionData.session = session.pickle(this.pickleKey);\n this.cryptoStore.storeEndToEndInboundGroupSession(senderKey, sessionId, sessionData, txn);\n result = {\n result: plaintext,\n keysClaimed: sessionData.keysClaimed || {},\n senderKey: senderKey,\n forwardingCurve25519KeyChain: sessionData.forwardingCurve25519KeyChain || [],\n untrusted: !!sessionData.untrusted,\n };\n });\n },\n logger.withPrefix(\"[decryptGroupMessage]\"),\n );\n\n if (error!) {\n throw error;\n }\n return result!;\n }\n\n /**\n * Determine if we have the keys for a given megolm session\n *\n * @param roomId - room in which the message was received\n * @param senderKey - base64-encoded curve25519 key of the sender\n * @param sessionId - session identifier\n *\n * @returns true if we have the keys to this session\n */\n public async hasInboundSessionKeys(roomId: string, senderKey: string, sessionId: string): Promise {\n let result: boolean;\n await this.cryptoStore.doTxn(\n \"readonly\",\n [\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD,\n ],\n (txn) => {\n this.cryptoStore.getEndToEndInboundGroupSession(senderKey, sessionId, txn, (sessionData) => {\n if (sessionData === null) {\n result = false;\n return;\n }\n\n if (roomId !== sessionData.room_id) {\n logger.warn(\n `requested keys for inbound group session ${senderKey}|` +\n `${sessionId}, with incorrect room_id ` +\n `(expected ${sessionData.room_id}, ` +\n `was ${roomId})`,\n );\n result = false;\n } else {\n result = true;\n }\n });\n },\n logger.withPrefix(\"[hasInboundSessionKeys]\"),\n );\n\n return result!;\n }\n\n /**\n * Extract the keys to a given megolm session, for sharing\n *\n * @param roomId - room in which the message was received\n * @param senderKey - base64-encoded curve25519 key of the sender\n * @param sessionId - session identifier\n * @param chainIndex - The chain index at which to export the session.\n * If omitted, export at the first index we know about.\n *\n * @returns\n * details of the session key. The key is a base64-encoded megolm key in\n * export format.\n *\n * @throws Error If the given chain index could not be obtained from the known\n * index (ie. the given chain index is before the first we have).\n */\n public async getInboundGroupSessionKey(\n roomId: string,\n senderKey: string,\n sessionId: string,\n chainIndex?: number,\n ): Promise {\n let result: IInboundGroupSessionKey | null = null;\n await this.cryptoStore.doTxn(\n \"readonly\",\n [\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD,\n ],\n (txn) => {\n this.getInboundGroupSession(roomId, senderKey, sessionId, txn, (session, sessionData) => {\n if (session === null || sessionData === null) {\n result = null;\n return;\n }\n\n if (chainIndex === undefined) {\n chainIndex = session.first_known_index();\n }\n\n const exportedSession = session.export_session(chainIndex);\n\n const claimedKeys = sessionData.keysClaimed || {};\n const senderEd25519Key = claimedKeys.ed25519 || null;\n\n const forwardingKeyChain = sessionData.forwardingCurve25519KeyChain || [];\n // older forwarded keys didn't set the \"untrusted\"\n // property, but can be identified by having a\n // non-empty forwarding key chain. These keys should\n // be marked as untrusted since we don't know that they\n // can be trusted\n const untrusted =\n \"untrusted\" in sessionData ? sessionData.untrusted : forwardingKeyChain.length > 0;\n\n result = {\n chain_index: chainIndex,\n key: exportedSession,\n forwarding_curve25519_key_chain: forwardingKeyChain,\n sender_claimed_ed25519_key: senderEd25519Key,\n shared_history: sessionData.sharedHistory || false,\n untrusted: untrusted,\n };\n });\n },\n logger.withPrefix(\"[getInboundGroupSessionKey]\"),\n );\n\n return result;\n }\n\n /**\n * Export an inbound group session\n *\n * @param senderKey - base64-encoded curve25519 key of the sender\n * @param sessionId - session identifier\n * @param sessionData - The session object from the store\n * @returns exported session data\n */\n public exportInboundGroupSession(\n senderKey: string,\n sessionId: string,\n sessionData: InboundGroupSessionData,\n ): IMegolmSessionData {\n return this.unpickleInboundGroupSession(sessionData, (session) => {\n const messageIndex = session.first_known_index();\n\n return {\n \"sender_key\": senderKey,\n \"sender_claimed_keys\": sessionData.keysClaimed,\n \"room_id\": sessionData.room_id,\n \"session_id\": sessionId,\n \"session_key\": session.export_session(messageIndex),\n \"forwarding_curve25519_key_chain\": sessionData.forwardingCurve25519KeyChain || [],\n \"first_known_index\": session.first_known_index(),\n \"org.matrix.msc3061.shared_history\": sessionData.sharedHistory || false,\n } as IMegolmSessionData;\n });\n }\n\n public async getSharedHistoryInboundGroupSessions(\n roomId: string,\n ): Promise<[senderKey: string, sessionId: string][]> {\n let result: Promise<[senderKey: string, sessionId: string][]>;\n await this.cryptoStore.doTxn(\n \"readonly\",\n [IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS],\n (txn) => {\n result = this.cryptoStore.getSharedHistoryInboundGroupSessions(roomId, txn);\n },\n logger.withPrefix(\"[getSharedHistoryInboundGroupSessionsForRoom]\"),\n );\n return result!;\n }\n\n // Utilities\n // =========\n\n /**\n * Verify an ed25519 signature.\n *\n * @param key - ed25519 key\n * @param message - message which was signed\n * @param signature - base64-encoded signature to be checked\n *\n * @throws Error if there is a problem with the verification. If the key was\n * too small then the message will be \"OLM.INVALID_BASE64\". If the signature\n * was invalid then the message will be \"OLM.BAD_MESSAGE_MAC\".\n */\n public verifySignature(key: string, message: string, signature: string): void {\n this.getUtility(function (util: Utility) {\n util.ed25519_verify(key, message, signature);\n });\n }\n}\n\nexport const WITHHELD_MESSAGES: Record = {\n \"m.unverified\": \"The sender has disabled encrypting to unverified devices.\",\n \"m.blacklisted\": \"The sender has blocked you.\",\n \"m.unauthorised\": \"You are not authorised to read the message.\",\n \"m.no_olm\": \"Unable to establish a secure channel.\",\n};\n\n/**\n * Calculate the message to use for the exception when a session key is withheld.\n *\n * @param withheld - An object that describes why the key was withheld.\n *\n * @returns the message\n *\n * @internal\n */\nfunction calculateWithheldMessage(withheld: IWithheld): string {\n if (withheld.code && withheld.code in WITHHELD_MESSAGES) {\n return WITHHELD_MESSAGES[withheld.code];\n } else if (withheld.reason) {\n return withheld.reason;\n } else {\n return \"decryption key withheld\";\n }\n}\n", - "/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport { logger } from \"../logger\";\nimport { MatrixClient } from \"../client\";\nimport { IRoomKeyRequestBody, IRoomKeyRequestRecipient } from \"./index\";\nimport { CryptoStore, OutgoingRoomKeyRequest } from \"./store/base\";\nimport { EventType, ToDeviceMessageId } from \"../@types/event\";\nimport { MapWithDefault } from \"../utils\";\n\n/**\n * Internal module. Management of outgoing room key requests.\n *\n * See https://docs.google.com/document/d/1m4gQkcnJkxNuBmb5NoFCIadIY-DyqqNAS3lloE73BlQ\n * for draft documentation on what we're supposed to be implementing here.\n */\n\n// delay between deciding we want some keys, and sending out the request, to\n// allow for (a) it turning up anyway, (b) grouping requests together\nconst SEND_KEY_REQUESTS_DELAY_MS = 500;\n\n/**\n * possible states for a room key request\n *\n * The state machine looks like:\n * ```\n *\n * | (cancellation sent)\n * | .-------------------------------------------------.\n * | | |\n * V V (cancellation requested) |\n * UNSENT -----------------------------+ |\n * | | |\n * | | |\n * | (send successful) | CANCELLATION_PENDING_AND_WILL_RESEND\n * V | Λ\n * SENT | |\n * |-------------------------------- | --------------'\n * | | (cancellation requested with intent\n * | | to resend the original request)\n * | |\n * | (cancellation requested) |\n * V |\n * CANCELLATION_PENDING |\n * | |\n * | (cancellation sent) |\n * V |\n * (deleted) <---------------------------+\n * ```\n */\nexport enum RoomKeyRequestState {\n /** request not yet sent */\n Unsent,\n /** request sent, awaiting reply */\n Sent,\n /** reply received, cancellation not yet sent */\n CancellationPending,\n /**\n * Cancellation not yet sent and will transition to UNSENT instead of\n * being deleted once the cancellation has been sent.\n */\n CancellationPendingAndWillResend,\n}\n\ninterface RequestMessageBase {\n requesting_device_id: string;\n request_id: string;\n}\n\ninterface RequestMessageRequest extends RequestMessageBase {\n action: \"request\";\n body: IRoomKeyRequestBody;\n}\n\ninterface RequestMessageCancellation extends RequestMessageBase {\n action: \"request_cancellation\";\n}\n\ntype RequestMessage = RequestMessageRequest | RequestMessageCancellation;\n\nexport class OutgoingRoomKeyRequestManager {\n // handle for the delayed call to sendOutgoingRoomKeyRequests. Non-null\n // if the callback has been set, or if it is still running.\n private sendOutgoingRoomKeyRequestsTimer?: ReturnType;\n\n // sanity check to ensure that we don't end up with two concurrent runs\n // of sendOutgoingRoomKeyRequests\n private sendOutgoingRoomKeyRequestsRunning = false;\n\n private clientRunning = true;\n\n public constructor(\n private readonly baseApis: MatrixClient,\n private readonly deviceId: string,\n private readonly cryptoStore: CryptoStore,\n ) {}\n\n /**\n * Called when the client is stopped. Stops any running background processes.\n */\n public stop(): void {\n logger.log(\"stopping OutgoingRoomKeyRequestManager\");\n // stop the timer on the next run\n this.clientRunning = false;\n }\n\n /**\n * Send any requests that have been queued\n */\n public sendQueuedRequests(): void {\n this.startTimer();\n }\n\n /**\n * Queue up a room key request, if we haven't already queued or sent one.\n *\n * The `requestBody` is compared (with a deep-equality check) against\n * previous queued or sent requests and if it matches, no change is made.\n * Otherwise, a request is added to the pending list, and a job is started\n * in the background to send it.\n *\n * @param resend - whether to resend the key request if there is\n * already one\n *\n * @returns resolves when the request has been added to the\n * pending list (or we have established that a similar request already\n * exists)\n */\n public async queueRoomKeyRequest(\n requestBody: IRoomKeyRequestBody,\n recipients: IRoomKeyRequestRecipient[],\n resend = false,\n ): Promise {\n const req = await this.cryptoStore.getOutgoingRoomKeyRequest(requestBody);\n if (!req) {\n await this.cryptoStore.getOrAddOutgoingRoomKeyRequest({\n requestBody: requestBody,\n recipients: recipients,\n requestId: this.baseApis.makeTxnId(),\n state: RoomKeyRequestState.Unsent,\n });\n } else {\n switch (req.state) {\n case RoomKeyRequestState.CancellationPendingAndWillResend:\n case RoomKeyRequestState.Unsent:\n // nothing to do here, since we're going to send a request anyways\n return;\n\n case RoomKeyRequestState.CancellationPending: {\n // existing request is about to be cancelled. If we want to\n // resend, then change the state so that it resends after\n // cancelling. Otherwise, just cancel the cancellation.\n const state = resend\n ? RoomKeyRequestState.CancellationPendingAndWillResend\n : RoomKeyRequestState.Sent;\n await this.cryptoStore.updateOutgoingRoomKeyRequest(\n req.requestId,\n RoomKeyRequestState.CancellationPending,\n {\n state,\n cancellationTxnId: this.baseApis.makeTxnId(),\n },\n );\n break;\n }\n case RoomKeyRequestState.Sent: {\n // a request has already been sent. If we don't want to\n // resend, then do nothing. If we do want to, then cancel the\n // existing request and send a new one.\n if (resend) {\n const state = RoomKeyRequestState.CancellationPendingAndWillResend;\n const updatedReq = await this.cryptoStore.updateOutgoingRoomKeyRequest(\n req.requestId,\n RoomKeyRequestState.Sent,\n {\n state,\n cancellationTxnId: this.baseApis.makeTxnId(),\n // need to use a new transaction ID so that\n // the request gets sent\n requestTxnId: this.baseApis.makeTxnId(),\n },\n );\n if (!updatedReq) {\n // updateOutgoingRoomKeyRequest couldn't find the request\n // in state ROOM_KEY_REQUEST_STATES.SENT, so we must have\n // raced with another tab to mark the request cancelled.\n // Try again, to make sure the request is resent.\n return this.queueRoomKeyRequest(requestBody, recipients, resend);\n }\n\n // We don't want to wait for the timer, so we send it\n // immediately. (We might actually end up racing with the timer,\n // but that's ok: even if we make the request twice, we'll do it\n // with the same transaction_id, so only one message will get\n // sent).\n //\n // (We also don't want to wait for the response from the server\n // here, as it will slow down processing of received keys if we\n // do.)\n try {\n await this.sendOutgoingRoomKeyRequestCancellation(updatedReq, true);\n } catch (e) {\n logger.error(\"Error sending room key request cancellation;\" + \" will retry later.\", e);\n }\n // The request has transitioned from\n // CANCELLATION_PENDING_AND_WILL_RESEND to UNSENT. We\n // still need to resend the request which is now UNSENT, so\n // start the timer if it isn't already started.\n }\n break;\n }\n default:\n throw new Error(\"unhandled state: \" + req.state);\n }\n }\n }\n\n /**\n * Cancel room key requests, if any match the given requestBody\n *\n *\n * @returns resolves when the request has been updated in our\n * pending list.\n */\n public cancelRoomKeyRequest(requestBody: IRoomKeyRequestBody): Promise {\n return this.cryptoStore.getOutgoingRoomKeyRequest(requestBody).then((req): unknown => {\n if (!req) {\n // no request was made for this key\n return;\n }\n switch (req.state) {\n case RoomKeyRequestState.CancellationPending:\n case RoomKeyRequestState.CancellationPendingAndWillResend:\n // nothing to do here\n return;\n\n case RoomKeyRequestState.Unsent:\n // just delete it\n\n // FIXME: ghahah we may have attempted to send it, and\n // not yet got a successful response. So the server\n // may have seen it, so we still need to send a cancellation\n // in that case :/\n\n logger.log(\"deleting unnecessary room key request for \" + stringifyRequestBody(requestBody));\n return this.cryptoStore.deleteOutgoingRoomKeyRequest(req.requestId, RoomKeyRequestState.Unsent);\n\n case RoomKeyRequestState.Sent: {\n // send a cancellation.\n return this.cryptoStore\n .updateOutgoingRoomKeyRequest(req.requestId, RoomKeyRequestState.Sent, {\n state: RoomKeyRequestState.CancellationPending,\n cancellationTxnId: this.baseApis.makeTxnId(),\n })\n .then((updatedReq) => {\n if (!updatedReq) {\n // updateOutgoingRoomKeyRequest couldn't find the\n // request in state ROOM_KEY_REQUEST_STATES.SENT,\n // so we must have raced with another tab to mark\n // the request cancelled. There is no point in\n // sending another cancellation since the other tab\n // will do it.\n logger.log(\n \"Tried to cancel room key request for \" +\n stringifyRequestBody(requestBody) +\n \" but it was already cancelled in another tab\",\n );\n return;\n }\n\n // We don't want to wait for the timer, so we send it\n // immediately. (We might actually end up racing with the timer,\n // but that's ok: even if we make the request twice, we'll do it\n // with the same transaction_id, so only one message will get\n // sent).\n //\n // (We also don't want to wait for the response from the server\n // here, as it will slow down processing of received keys if we\n // do.)\n this.sendOutgoingRoomKeyRequestCancellation(updatedReq).catch((e) => {\n logger.error(\"Error sending room key request cancellation;\" + \" will retry later.\", e);\n this.startTimer();\n });\n });\n }\n default:\n throw new Error(\"unhandled state: \" + req.state);\n }\n });\n }\n\n /**\n * Look for room key requests by target device and state\n *\n * @param userId - Target user ID\n * @param deviceId - Target device ID\n *\n * @returns resolves to a list of all the {@link OutgoingRoomKeyRequest}\n */\n public getOutgoingSentRoomKeyRequest(userId: string, deviceId: string): Promise {\n return this.cryptoStore.getOutgoingRoomKeyRequestsByTarget(userId, deviceId, [RoomKeyRequestState.Sent]);\n }\n\n /**\n * Find anything in `sent` state, and kick it around the loop again.\n * This is intended for situations where something substantial has changed, and we\n * don't really expect the other end to even care about the cancellation.\n * For example, after initialization or self-verification.\n * @returns An array of `queueRoomKeyRequest` outputs.\n */\n public async cancelAndResendAllOutgoingRequests(): Promise {\n const outgoings = await this.cryptoStore.getAllOutgoingRoomKeyRequestsByState(RoomKeyRequestState.Sent);\n return Promise.all(\n outgoings.map(({ requestBody, recipients }) => this.queueRoomKeyRequest(requestBody, recipients, true)),\n );\n }\n\n // start the background timer to send queued requests, if the timer isn't\n // already running\n private startTimer(): void {\n if (this.sendOutgoingRoomKeyRequestsTimer) {\n return;\n }\n\n const startSendingOutgoingRoomKeyRequests = (): void => {\n if (this.sendOutgoingRoomKeyRequestsRunning) {\n throw new Error(\"RoomKeyRequestSend already in progress!\");\n }\n this.sendOutgoingRoomKeyRequestsRunning = true;\n\n this.sendOutgoingRoomKeyRequests()\n .finally(() => {\n this.sendOutgoingRoomKeyRequestsRunning = false;\n })\n .catch((e) => {\n // this should only happen if there is an indexeddb error,\n // in which case we're a bit stuffed anyway.\n logger.warn(`error in OutgoingRoomKeyRequestManager: ${e}`);\n });\n };\n\n this.sendOutgoingRoomKeyRequestsTimer = setTimeout(\n startSendingOutgoingRoomKeyRequests,\n SEND_KEY_REQUESTS_DELAY_MS,\n );\n }\n\n // look for and send any queued requests. Runs itself recursively until\n // there are no more requests, or there is an error (in which case, the\n // timer will be restarted before the promise resolves).\n private async sendOutgoingRoomKeyRequests(): Promise {\n if (!this.clientRunning) {\n this.sendOutgoingRoomKeyRequestsTimer = undefined;\n return;\n }\n\n const req = await this.cryptoStore.getOutgoingRoomKeyRequestByState([\n RoomKeyRequestState.CancellationPending,\n RoomKeyRequestState.CancellationPendingAndWillResend,\n RoomKeyRequestState.Unsent,\n ]);\n\n if (!req) {\n this.sendOutgoingRoomKeyRequestsTimer = undefined;\n return;\n }\n\n try {\n switch (req.state) {\n case RoomKeyRequestState.Unsent:\n await this.sendOutgoingRoomKeyRequest(req);\n break;\n case RoomKeyRequestState.CancellationPending:\n await this.sendOutgoingRoomKeyRequestCancellation(req);\n break;\n case RoomKeyRequestState.CancellationPendingAndWillResend:\n await this.sendOutgoingRoomKeyRequestCancellation(req, true);\n break;\n }\n\n // go around the loop again\n return this.sendOutgoingRoomKeyRequests();\n } catch (e) {\n logger.error(\"Error sending room key request; will retry later.\", e);\n this.sendOutgoingRoomKeyRequestsTimer = undefined;\n }\n }\n\n // given a RoomKeyRequest, send it and update the request record\n private sendOutgoingRoomKeyRequest(req: OutgoingRoomKeyRequest): Promise {\n logger.log(\n `Requesting keys for ${stringifyRequestBody(req.requestBody)}` +\n ` from ${stringifyRecipientList(req.recipients)}` +\n `(id ${req.requestId})`,\n );\n\n const requestMessage: RequestMessage = {\n action: \"request\",\n requesting_device_id: this.deviceId,\n request_id: req.requestId,\n body: req.requestBody,\n };\n\n return this.sendMessageToDevices(requestMessage, req.recipients, req.requestTxnId || req.requestId).then(() => {\n return this.cryptoStore.updateOutgoingRoomKeyRequest(req.requestId, RoomKeyRequestState.Unsent, {\n state: RoomKeyRequestState.Sent,\n });\n });\n }\n\n // Given a RoomKeyRequest, cancel it and delete the request record unless\n // andResend is set, in which case transition to UNSENT.\n private sendOutgoingRoomKeyRequestCancellation(req: OutgoingRoomKeyRequest, andResend = false): Promise {\n logger.log(\n `Sending cancellation for key request for ` +\n `${stringifyRequestBody(req.requestBody)} to ` +\n `${stringifyRecipientList(req.recipients)} ` +\n `(cancellation id ${req.cancellationTxnId})`,\n );\n\n const requestMessage: RequestMessage = {\n action: \"request_cancellation\",\n requesting_device_id: this.deviceId,\n request_id: req.requestId,\n };\n\n return this.sendMessageToDevices(requestMessage, req.recipients, req.cancellationTxnId).then(() => {\n if (andResend) {\n // We want to resend, so transition to UNSENT\n return this.cryptoStore.updateOutgoingRoomKeyRequest(\n req.requestId,\n RoomKeyRequestState.CancellationPendingAndWillResend,\n { state: RoomKeyRequestState.Unsent },\n );\n }\n return this.cryptoStore.deleteOutgoingRoomKeyRequest(\n req.requestId,\n RoomKeyRequestState.CancellationPending,\n );\n });\n }\n\n // send a RoomKeyRequest to a list of recipients\n private sendMessageToDevices(\n message: RequestMessage,\n recipients: IRoomKeyRequestRecipient[],\n txnId?: string,\n ): Promise<{}> {\n const contentMap = new MapWithDefault>>(() => new Map());\n for (const recip of recipients) {\n const userDeviceMap = contentMap.getOrCreate(recip.userId);\n userDeviceMap.set(recip.deviceId, {\n ...message,\n [ToDeviceMessageId]: uuidv4(),\n });\n }\n\n return this.baseApis.sendToDevice(EventType.RoomKeyRequest, contentMap, txnId);\n }\n}\n\nfunction stringifyRequestBody(requestBody: IRoomKeyRequestBody): string {\n // we assume that the request is for megolm keys, which are identified by\n // room id and session id\n return requestBody.room_id + \" / \" + requestBody.session_id;\n}\n\nfunction stringifyRecipientList(recipients: IRoomKeyRequestRecipient[]): string {\n return `[${recipients.map((r) => `${r.userId}:${r.deviceId}`).join(\",\")}]`;\n}\n", - "/*\nCopyright 2018 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Manages the list of encrypted rooms\n */\n\nimport { CryptoStore } from \"./store/base\";\nimport { IndexedDBCryptoStore } from \"./store/indexeddb-crypto-store\";\n\n/* eslint-disable camelcase */\nexport interface IRoomEncryption {\n algorithm: string;\n rotation_period_ms?: number;\n rotation_period_msgs?: number;\n}\n/* eslint-enable camelcase */\n\nexport class RoomList {\n // Object of roomId -> room e2e info object (body of the m.room.encryption event)\n private roomEncryption: Record = {};\n\n public constructor(private readonly cryptoStore?: CryptoStore) {}\n\n public async init(): Promise {\n await this.cryptoStore!.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_ROOMS], (txn) => {\n this.cryptoStore!.getEndToEndRooms(txn, (result) => {\n this.roomEncryption = result;\n });\n });\n }\n\n public getRoomEncryption(roomId: string): IRoomEncryption {\n return this.roomEncryption[roomId] || null;\n }\n\n public isRoomEncrypted(roomId: string): boolean {\n return Boolean(this.getRoomEncryption(roomId));\n }\n\n public async setRoomEncryption(roomId: string, roomInfo: IRoomEncryption): Promise {\n // important that this happens before calling into the store\n // as it prevents the Crypto::setRoomEncryption from calling\n // this twice for consecutive m.room.encryption events\n this.roomEncryption[roomId] = roomInfo;\n await this.cryptoStore!.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_ROOMS], (txn) => {\n this.cryptoStore!.storeEndToEndRoom(roomId, roomInfo, txn);\n });\n }\n}\n", - "/*\nCopyright 2019 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport { logger } from \"../logger\";\nimport * as olmlib from \"./olmlib\";\nimport { randomString } from \"../randomstring\";\nimport { calculateKeyCheck, decryptAES, encryptAES, IEncryptedPayload } from \"./aes\";\nimport { ICryptoCallbacks, IEncryptedContent } from \".\";\nimport { IContent, MatrixEvent } from \"../models/event\";\nimport { ClientEvent, ClientEventHandlerMap, MatrixClient } from \"../client\";\nimport { IAddSecretStorageKeyOpts } from \"./api\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter\";\nimport { defer, IDeferred } from \"../utils\";\nimport { ToDeviceMessageId } from \"../@types/event\";\nimport { SecretStorageKeyDescription, SecretStorageKeyDescriptionAesV1 } from \"../secret-storage\";\n\nexport const SECRET_STORAGE_ALGORITHM_V1_AES = \"m.secret_storage.v1.aes-hmac-sha2\";\n\n// Some of the key functions use a tuple and some use an object...\nexport type SecretStorageKeyTuple = [keyId: string, keyInfo: SecretStorageKeyDescription];\nexport type SecretStorageKeyObject = { keyId: string; keyInfo: SecretStorageKeyDescription };\n\nexport interface ISecretRequest {\n requestId: string;\n promise: Promise;\n cancel: (reason: string) => void;\n}\n\nexport interface IAccountDataClient extends TypedEventEmitter {\n // Subset of MatrixClient (which also uses any for the event content)\n getAccountDataFromServer: (eventType: string) => Promise;\n getAccountData: (eventType: string) => IContent | null;\n setAccountData: (eventType: string, content: any) => Promise<{}>;\n}\n\ninterface ISecretRequestInternal {\n name: string;\n devices: string[];\n deferred: IDeferred;\n}\n\ninterface IDecryptors {\n encrypt: (plaintext: string) => Promise;\n decrypt: (ciphertext: IEncryptedPayload) => Promise;\n}\n\ninterface ISecretInfo {\n encrypted: {\n [keyId: string]: IEncryptedPayload;\n };\n}\n\n/**\n * Implements Secure Secret Storage and Sharing (MSC1946)\n */\nexport class SecretStorage {\n private requests = new Map();\n\n // In it's pure javascript days, this was relying on some proper Javascript-style\n // type-abuse where sometimes we'd pass in a fake client object with just the account\n // data methods implemented, which is all this class needs unless you use the secret\n // sharing code, so it was fine. As a low-touch TypeScript migration, this now has\n // an extra, optional param for a real matrix client, so you can not pass it as long\n // as you don't request any secrets.\n // A better solution would probably be to split this class up into secret storage and\n // secret sharing which are really two separate things, even though they share an MSC.\n public constructor(\n private readonly accountDataAdapter: IAccountDataClient,\n private readonly cryptoCallbacks: ICryptoCallbacks,\n private readonly baseApis: B,\n ) {}\n\n public async getDefaultKeyId(): Promise {\n const defaultKey = await this.accountDataAdapter.getAccountDataFromServer<{ key: string }>(\n \"m.secret_storage.default_key\",\n );\n if (!defaultKey) return null;\n return defaultKey.key;\n }\n\n public setDefaultKeyId(keyId: string): Promise {\n return new Promise((resolve, reject) => {\n const listener = (ev: MatrixEvent): void => {\n if (ev.getType() === \"m.secret_storage.default_key\" && ev.getContent().key === keyId) {\n this.accountDataAdapter.removeListener(ClientEvent.AccountData, listener);\n resolve();\n }\n };\n this.accountDataAdapter.on(ClientEvent.AccountData, listener);\n\n this.accountDataAdapter.setAccountData(\"m.secret_storage.default_key\", { key: keyId }).catch((e) => {\n this.accountDataAdapter.removeListener(ClientEvent.AccountData, listener);\n reject(e);\n });\n });\n }\n\n /**\n * Add a key for encrypting secrets.\n *\n * @param algorithm - the algorithm used by the key.\n * @param opts - the options for the algorithm. The properties used\n * depend on the algorithm given.\n * @param keyId - the ID of the key. If not given, a random\n * ID will be generated.\n *\n * @returns An object with:\n * keyId: the ID of the key\n * keyInfo: details about the key (iv, mac, passphrase)\n */\n public async addKey(\n algorithm: string,\n opts: IAddSecretStorageKeyOpts = {},\n keyId?: string,\n ): Promise {\n if (algorithm !== SECRET_STORAGE_ALGORITHM_V1_AES) {\n throw new Error(`Unknown key algorithm ${algorithm}`);\n }\n\n const keyInfo = { algorithm } as SecretStorageKeyDescriptionAesV1;\n\n if (opts.name) {\n keyInfo.name = opts.name;\n }\n\n if (opts.passphrase) {\n keyInfo.passphrase = opts.passphrase;\n }\n if (opts.key) {\n const { iv, mac } = await calculateKeyCheck(opts.key);\n keyInfo.iv = iv;\n keyInfo.mac = mac;\n }\n\n if (!keyId) {\n do {\n keyId = randomString(32);\n } while (\n await this.accountDataAdapter.getAccountDataFromServer(\n `m.secret_storage.key.${keyId}`,\n )\n );\n }\n\n await this.accountDataAdapter.setAccountData(`m.secret_storage.key.${keyId}`, keyInfo);\n\n return {\n keyId,\n keyInfo,\n };\n }\n\n /**\n * Get the key information for a given ID.\n *\n * @param keyId - The ID of the key to check\n * for. Defaults to the default key ID if not provided.\n * @returns If the key was found, the return value is an array of\n * the form [keyId, keyInfo]. Otherwise, null is returned.\n * XXX: why is this an array when addKey returns an object?\n */\n public async getKey(keyId?: string | null): Promise {\n if (!keyId) {\n keyId = await this.getDefaultKeyId();\n }\n if (!keyId) {\n return null;\n }\n\n const keyInfo = await this.accountDataAdapter.getAccountDataFromServer(\n \"m.secret_storage.key.\" + keyId,\n );\n return keyInfo ? [keyId, keyInfo] : null;\n }\n\n /**\n * Check whether we have a key with a given ID.\n *\n * @param keyId - The ID of the key to check\n * for. Defaults to the default key ID if not provided.\n * @returns Whether we have the key.\n */\n public async hasKey(keyId?: string): Promise {\n return Boolean(await this.getKey(keyId));\n }\n\n /**\n * Check whether a key matches what we expect based on the key info\n *\n * @param key - the key to check\n * @param info - the key info\n *\n * @returns whether or not the key matches\n */\n public async checkKey(key: Uint8Array, info: SecretStorageKeyDescription): Promise {\n if (info.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n if (info.mac) {\n const { mac } = await calculateKeyCheck(key, info.iv);\n return info.mac.replace(/=+$/g, \"\") === mac.replace(/=+$/g, \"\");\n } else {\n // if we have no information, we have to assume the key is right\n return true;\n }\n } else {\n throw new Error(\"Unknown algorithm\");\n }\n }\n\n /**\n * Store an encrypted secret on the server\n *\n * @param name - The name of the secret\n * @param secret - The secret contents.\n * @param keys - The IDs of the keys to use to encrypt the secret\n * or null/undefined to use the default key.\n */\n public async store(name: string, secret: string, keys?: string[] | null): Promise {\n const encrypted: Record = {};\n\n if (!keys) {\n const defaultKeyId = await this.getDefaultKeyId();\n if (!defaultKeyId) {\n throw new Error(\"No keys specified and no default key present\");\n }\n keys = [defaultKeyId];\n }\n\n if (keys.length === 0) {\n throw new Error(\"Zero keys given to encrypt with!\");\n }\n\n for (const keyId of keys) {\n // get key information from key storage\n const keyInfo = await this.accountDataAdapter.getAccountDataFromServer(\n \"m.secret_storage.key.\" + keyId,\n );\n if (!keyInfo) {\n throw new Error(\"Unknown key: \" + keyId);\n }\n\n // encrypt secret, based on the algorithm\n if (keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n const keys = { [keyId]: keyInfo };\n const [, encryption] = await this.getSecretStorageKey(keys, name);\n encrypted[keyId] = await encryption.encrypt(secret);\n } else {\n logger.warn(\"unknown algorithm for secret storage key \" + keyId + \": \" + keyInfo.algorithm);\n // do nothing if we don't understand the encryption algorithm\n }\n }\n\n // save encrypted secret\n await this.accountDataAdapter.setAccountData(name, { encrypted });\n }\n\n /**\n * Get a secret from storage.\n *\n * @param name - the name of the secret\n *\n * @returns the contents of the secret\n */\n public async get(name: string): Promise {\n const secretInfo = await this.accountDataAdapter.getAccountDataFromServer(name);\n if (!secretInfo) {\n return;\n }\n if (!secretInfo.encrypted) {\n throw new Error(\"Content is not encrypted!\");\n }\n\n // get possible keys to decrypt\n const keys: Record = {};\n for (const keyId of Object.keys(secretInfo.encrypted)) {\n // get key information from key storage\n const keyInfo = await this.accountDataAdapter.getAccountDataFromServer(\n \"m.secret_storage.key.\" + keyId,\n );\n const encInfo = secretInfo.encrypted[keyId];\n // only use keys we understand the encryption algorithm of\n if (keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n if (encInfo.iv && encInfo.ciphertext && encInfo.mac) {\n keys[keyId] = keyInfo;\n }\n }\n }\n\n if (Object.keys(keys).length === 0) {\n throw new Error(\n `Could not decrypt ${name} because none of ` +\n `the keys it is encrypted with are for a supported algorithm`,\n );\n }\n\n // fetch private key from app\n const [keyId, decryption] = await this.getSecretStorageKey(keys, name);\n const encInfo = secretInfo.encrypted[keyId];\n\n return decryption.decrypt(encInfo);\n }\n\n /**\n * Check if a secret is stored on the server.\n *\n * @param name - the name of the secret\n *\n * @returns map of key name to key info the secret is encrypted\n * with, or null if it is not present or not encrypted with a trusted\n * key\n */\n public async isStored(name: string): Promise | null> {\n // check if secret exists\n const secretInfo = await this.accountDataAdapter.getAccountDataFromServer(name);\n if (!secretInfo?.encrypted) return null;\n\n const ret: Record = {};\n\n // filter secret encryption keys with supported algorithm\n for (const keyId of Object.keys(secretInfo.encrypted)) {\n // get key information from key storage\n const keyInfo = await this.accountDataAdapter.getAccountDataFromServer(\n \"m.secret_storage.key.\" + keyId,\n );\n if (!keyInfo) continue;\n const encInfo = secretInfo.encrypted[keyId];\n\n // only use keys we understand the encryption algorithm of\n if (keyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n if (encInfo.iv && encInfo.ciphertext && encInfo.mac) {\n ret[keyId] = keyInfo;\n }\n }\n }\n return Object.keys(ret).length ? ret : null;\n }\n\n /**\n * Request a secret from another device\n *\n * @param name - the name of the secret to request\n * @param devices - the devices to request the secret from\n */\n public request(this: SecretStorage, name: string, devices: string[]): ISecretRequest {\n const requestId = this.baseApis.makeTxnId();\n\n const deferred = defer();\n this.requests.set(requestId, { name, devices, deferred });\n\n const cancel = (reason: string): void => {\n // send cancellation event\n const cancelData = {\n action: \"request_cancellation\",\n requesting_device_id: this.baseApis.deviceId,\n request_id: requestId,\n };\n const toDevice: Map = new Map();\n for (const device of devices) {\n toDevice.set(device, cancelData);\n }\n this.baseApis.sendToDevice(\"m.secret.request\", new Map([[this.baseApis.getUserId()!, toDevice]]));\n\n // and reject the promise so that anyone waiting on it will be\n // notified\n deferred.reject(new Error(reason || \"Cancelled\"));\n };\n\n // send request to devices\n const requestData = {\n name,\n action: \"request\",\n requesting_device_id: this.baseApis.deviceId,\n request_id: requestId,\n [ToDeviceMessageId]: uuidv4(),\n };\n const toDevice: Map = new Map();\n for (const device of devices) {\n toDevice.set(device, requestData);\n }\n logger.info(`Request secret ${name} from ${devices}, id ${requestId}`);\n this.baseApis.sendToDevice(\"m.secret.request\", new Map([[this.baseApis.getUserId()!, toDevice]]));\n\n return {\n requestId,\n promise: deferred.promise,\n cancel,\n };\n }\n\n public async onRequestReceived(this: SecretStorage, event: MatrixEvent): Promise {\n const sender = event.getSender();\n const content = event.getContent();\n if (\n sender !== this.baseApis.getUserId() ||\n !(content.name && content.action && content.requesting_device_id && content.request_id)\n ) {\n // ignore requests from anyone else, for now\n return;\n }\n const deviceId = content.requesting_device_id;\n // check if it's a cancel\n if (content.action === \"request_cancellation\") {\n /*\n Looks like we intended to emit events when we got cancelations, but\n we never put anything in the _incomingRequests object, and the request\n itself doesn't use events anyway so if we were to wire up cancellations,\n they probably ought to use the same callback interface. I'm leaving them\n disabled for now while converting this file to typescript.\n if (this._incomingRequests[deviceId]\n && this._incomingRequests[deviceId][content.request_id]) {\n logger.info(\n \"received request cancellation for secret (\" + sender +\n \", \" + deviceId + \", \" + content.request_id + \")\",\n );\n this.baseApis.emit(\"crypto.secrets.requestCancelled\", {\n user_id: sender,\n device_id: deviceId,\n request_id: content.request_id,\n });\n }\n */\n } else if (content.action === \"request\") {\n if (deviceId === this.baseApis.deviceId) {\n // no point in trying to send ourself the secret\n return;\n }\n\n // check if we have the secret\n logger.info(\"received request for secret (\" + sender + \", \" + deviceId + \", \" + content.request_id + \")\");\n if (!this.cryptoCallbacks.onSecretRequested) {\n return;\n }\n const secret = await this.cryptoCallbacks.onSecretRequested(\n sender,\n deviceId,\n content.request_id,\n content.name,\n this.baseApis.checkDeviceTrust(sender, deviceId),\n );\n if (secret) {\n logger.info(`Preparing ${content.name} secret for ${deviceId}`);\n const payload = {\n type: \"m.secret.send\",\n content: {\n request_id: content.request_id,\n secret: secret,\n },\n };\n const encryptedContent: IEncryptedContent = {\n algorithm: olmlib.OLM_ALGORITHM,\n sender_key: this.baseApis.crypto!.olmDevice.deviceCurve25519Key!,\n ciphertext: {},\n [ToDeviceMessageId]: uuidv4(),\n };\n await olmlib.ensureOlmSessionsForDevices(\n this.baseApis.crypto!.olmDevice,\n this.baseApis,\n new Map([[sender, [this.baseApis.getStoredDevice(sender, deviceId)!]]]),\n );\n await olmlib.encryptMessageForDevice(\n encryptedContent.ciphertext,\n this.baseApis.getUserId()!,\n this.baseApis.deviceId!,\n this.baseApis.crypto!.olmDevice,\n sender,\n this.baseApis.getStoredDevice(sender, deviceId)!,\n payload,\n );\n const contentMap = new Map([[sender, new Map([[deviceId, encryptedContent]])]]);\n\n logger.info(`Sending ${content.name} secret for ${deviceId}`);\n this.baseApis.sendToDevice(\"m.room.encrypted\", contentMap);\n } else {\n logger.info(`Request denied for ${content.name} secret for ${deviceId}`);\n }\n }\n }\n\n public onSecretReceived(this: SecretStorage, event: MatrixEvent): void {\n if (event.getSender() !== this.baseApis.getUserId()) {\n // we shouldn't be receiving secrets from anyone else, so ignore\n // because someone could be trying to send us bogus data\n return;\n }\n\n if (!olmlib.isOlmEncrypted(event)) {\n logger.error(\"secret event not properly encrypted\");\n return;\n }\n\n const content = event.getContent();\n\n const senderKeyUser = this.baseApis.crypto!.deviceList.getUserByIdentityKey(\n olmlib.OLM_ALGORITHM,\n event.getSenderKey() || \"\",\n );\n if (senderKeyUser !== event.getSender()) {\n logger.error(\"sending device does not belong to the user it claims to be from\");\n return;\n }\n\n logger.log(\"got secret share for request\", content.request_id);\n const requestControl = this.requests.get(content.request_id);\n if (requestControl) {\n // make sure that the device that sent it is one of the devices that\n // we requested from\n const deviceInfo = this.baseApis.crypto!.deviceList.getDeviceByIdentityKey(\n olmlib.OLM_ALGORITHM,\n event.getSenderKey()!,\n );\n if (!deviceInfo) {\n logger.log(\"secret share from unknown device with key\", event.getSenderKey());\n return;\n }\n if (!requestControl.devices.includes(deviceInfo.deviceId)) {\n logger.log(\"unsolicited secret share from device\", deviceInfo.deviceId);\n return;\n }\n // unsure that the sender is trusted. In theory, this check is\n // unnecessary since we only accept secret shares from devices that\n // we requested from, but it doesn't hurt.\n const deviceTrust = this.baseApis.crypto!.checkDeviceInfoTrust(event.getSender()!, deviceInfo);\n if (!deviceTrust.isVerified()) {\n logger.log(\"secret share from unverified device\");\n return;\n }\n\n logger.log(`Successfully received secret ${requestControl.name} ` + `from ${deviceInfo.deviceId}`);\n requestControl.deferred.resolve(content.secret);\n }\n }\n\n private async getSecretStorageKey(\n keys: Record,\n name: string,\n ): Promise<[string, IDecryptors]> {\n if (!this.cryptoCallbacks.getSecretStorageKey) {\n throw new Error(\"No getSecretStorageKey callback supplied\");\n }\n\n const returned = await this.cryptoCallbacks.getSecretStorageKey({ keys }, name);\n\n if (!returned) {\n throw new Error(\"getSecretStorageKey callback returned falsey\");\n }\n if (returned.length < 2) {\n throw new Error(\"getSecretStorageKey callback returned invalid data\");\n }\n\n const [keyId, privateKey] = returned;\n if (!keys[keyId]) {\n throw new Error(\"App returned unknown key from getSecretStorageKey!\");\n }\n\n if (keys[keyId].algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n const decryption = {\n encrypt: function (secret: string): Promise {\n return encryptAES(secret, privateKey, name);\n },\n decrypt: function (encInfo: IEncryptedPayload): Promise {\n return decryptAES(encInfo, privateKey, name);\n },\n };\n return [keyId, decryption];\n } else {\n throw new Error(\"Unknown key type: \" + keys[keyId].algorithm);\n }\n }\n}\n", - "/*\nCopyright 2020 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { decodeBase64, encodeBase64 } from \"./olmlib\";\nimport { subtleCrypto, crypto, TextEncoder } from \"./crypto\";\n\n// salt for HKDF, with 8 bytes of zeros\nconst zeroSalt = new Uint8Array(8);\n\nexport interface IEncryptedPayload {\n [key: string]: any; // extensible\n /** the initialization vector in base64 */\n iv: string;\n /** the ciphertext in base64 */\n ciphertext: string;\n /** the HMAC in base64 */\n mac: string;\n}\n\n/**\n * encrypt a string\n *\n * @param data - the plaintext to encrypt\n * @param key - the encryption key to use\n * @param name - the name of the secret\n * @param ivStr - the initialization vector to use\n */\nexport async function encryptAES(\n data: string,\n key: Uint8Array,\n name: string,\n ivStr?: string,\n): Promise {\n let iv: Uint8Array;\n if (ivStr) {\n iv = decodeBase64(ivStr);\n } else {\n iv = new Uint8Array(16);\n crypto.getRandomValues(iv);\n\n // clear bit 63 of the IV to stop us hitting the 64-bit counter boundary\n // (which would mean we wouldn't be able to decrypt on Android). The loss\n // of a single bit of iv is a price we have to pay.\n iv[8] &= 0x7f;\n }\n\n const [aesKey, hmacKey] = await deriveKeys(key, name);\n const encodedData = new TextEncoder().encode(data);\n\n const ciphertext = await subtleCrypto.encrypt(\n {\n name: \"AES-CTR\",\n counter: iv,\n length: 64,\n },\n aesKey,\n encodedData,\n );\n\n const hmac = await subtleCrypto.sign({ name: \"HMAC\" }, hmacKey, ciphertext);\n\n return {\n iv: encodeBase64(iv),\n ciphertext: encodeBase64(ciphertext),\n mac: encodeBase64(hmac),\n };\n}\n\n/**\n * decrypt a string\n *\n * @param data - the encrypted data\n * @param key - the encryption key to use\n * @param name - the name of the secret\n */\nexport async function decryptAES(data: IEncryptedPayload, key: Uint8Array, name: string): Promise {\n const [aesKey, hmacKey] = await deriveKeys(key, name);\n\n const ciphertext = decodeBase64(data.ciphertext);\n\n if (!(await subtleCrypto.verify({ name: \"HMAC\" }, hmacKey, decodeBase64(data.mac), ciphertext))) {\n throw new Error(`Error decrypting secret ${name}: bad MAC`);\n }\n\n const plaintext = await subtleCrypto.decrypt(\n {\n name: \"AES-CTR\",\n counter: decodeBase64(data.iv),\n length: 64,\n },\n aesKey,\n ciphertext,\n );\n\n return new TextDecoder().decode(new Uint8Array(plaintext));\n}\n\nasync function deriveKeys(key: Uint8Array, name: string): Promise<[CryptoKey, CryptoKey]> {\n const hkdfkey = await subtleCrypto.importKey(\"raw\", key, { name: \"HKDF\" }, false, [\"deriveBits\"]);\n const keybits = await subtleCrypto.deriveBits(\n {\n name: \"HKDF\",\n salt: zeroSalt,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore: https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/879\n info: new TextEncoder().encode(name),\n hash: \"SHA-256\",\n },\n hkdfkey,\n 512,\n );\n\n const aesKey = keybits.slice(0, 32);\n const hmacKey = keybits.slice(32);\n\n const aesProm = subtleCrypto.importKey(\"raw\", aesKey, { name: \"AES-CTR\" }, false, [\"encrypt\", \"decrypt\"]);\n\n const hmacProm = subtleCrypto.importKey(\n \"raw\",\n hmacKey,\n {\n name: \"HMAC\",\n hash: { name: \"SHA-256\" },\n },\n false,\n [\"sign\", \"verify\"],\n );\n\n return Promise.all([aesProm, hmacProm]);\n}\n\n// string of zeroes, for calculating the key check\nconst 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\";\n\n/** Calculate the MAC for checking the key.\n *\n * @param key - the key to use\n * @param iv - The initialization vector as a base64-encoded string.\n * If omitted, a random initialization vector will be created.\n * @returns An object that contains, `mac` and `iv` properties.\n */\nexport function calculateKeyCheck(key: Uint8Array, iv?: string): Promise {\n return encryptAES(ZERO_STR, key, \"\", iv);\n}\n", - "/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Internal module. Defines the base classes of the encryption implementations\n */\n\nimport type { IMegolmSessionData } from \"../../@types/crypto\";\nimport { MatrixClient } from \"../../client\";\nimport { Room } from \"../../models/room\";\nimport { OlmDevice } from \"../OlmDevice\";\nimport { IContent, MatrixEvent, RoomMember } from \"../../matrix\";\nimport { Crypto, IEncryptedContent, IEventDecryptionResult, IncomingRoomKeyRequest } from \"..\";\nimport { DeviceInfo } from \"../deviceinfo\";\nimport { IRoomEncryption } from \"../RoomList\";\nimport { DeviceInfoMap } from \"../DeviceList\";\n\n/**\n * Map of registered encryption algorithm classes. A map from string to {@link EncryptionAlgorithm} class\n */\nexport const ENCRYPTION_CLASSES = new Map EncryptionAlgorithm>();\n\nexport type DecryptionClassParams

= Omit;\n\n/**\n * map of registered encryption algorithm classes. Map from string to {@link DecryptionAlgorithm} class\n */\nexport const DECRYPTION_CLASSES = new Map DecryptionAlgorithm>();\n\nexport interface IParams {\n /** The UserID for the local user */\n userId: string;\n /** The identifier for this device. */\n deviceId: string;\n /** crypto core */\n crypto: Crypto;\n /** olm.js wrapper */\n olmDevice: OlmDevice;\n /** base matrix api interface */\n baseApis: MatrixClient;\n /** The ID of the room we will be sending to */\n roomId?: string;\n /** The body of the m.room.encryption event */\n config: IRoomEncryption & object;\n}\n\n/**\n * base type for encryption implementations\n */\nexport abstract class EncryptionAlgorithm {\n protected readonly userId: string;\n protected readonly deviceId: string;\n protected readonly crypto: Crypto;\n protected readonly olmDevice: OlmDevice;\n protected readonly baseApis: MatrixClient;\n protected readonly roomId?: string;\n\n /**\n * @param params - parameters\n */\n public constructor(params: IParams) {\n this.userId = params.userId;\n this.deviceId = params.deviceId;\n this.crypto = params.crypto;\n this.olmDevice = params.olmDevice;\n this.baseApis = params.baseApis;\n this.roomId = params.roomId;\n }\n\n /**\n * Perform any background tasks that can be done before a message is ready to\n * send, in order to speed up sending of the message.\n *\n * @param room - the room the event is in\n */\n public prepareToEncrypt(room: Room): void {}\n\n /**\n * Encrypt a message event\n *\n * @public\n *\n * @param content - event content\n *\n * @returns Promise which resolves to the new event body\n */\n public abstract encryptMessage(room: Room, eventType: string, content: IContent): Promise;\n\n /**\n * Called when the membership of a member of the room changes.\n *\n * @param event - event causing the change\n * @param member - user whose membership changed\n * @param oldMembership - previous membership\n * @public\n */\n public onRoomMembership(event: MatrixEvent, member: RoomMember, oldMembership?: string): void {}\n\n public reshareKeyWithDevice?(\n senderKey: string,\n sessionId: string,\n userId: string,\n device: DeviceInfo,\n ): Promise;\n\n public forceDiscardSession?(): void;\n}\n\n/**\n * base type for decryption implementations\n */\nexport abstract class DecryptionAlgorithm {\n protected readonly userId: string;\n protected readonly crypto: Crypto;\n protected readonly olmDevice: OlmDevice;\n protected readonly baseApis: MatrixClient;\n protected readonly roomId?: string;\n\n public constructor(params: DecryptionClassParams) {\n this.userId = params.userId;\n this.crypto = params.crypto;\n this.olmDevice = params.olmDevice;\n this.baseApis = params.baseApis;\n this.roomId = params.roomId;\n }\n\n /**\n * Decrypt an event\n *\n * @param event - undecrypted event\n *\n * @returns promise which\n * resolves once we have finished decrypting. Rejects with an\n * `algorithms.DecryptionError` if there is a problem decrypting the event.\n */\n public abstract decryptEvent(event: MatrixEvent): Promise;\n\n /**\n * Handle a key event\n *\n * @param params - event key event\n */\n public async onRoomKeyEvent(params: MatrixEvent): Promise {\n // ignore by default\n }\n\n /**\n * Import a room key\n *\n * @param opts - object\n */\n public async importRoomKey(session: IMegolmSessionData, opts: object): Promise {\n // ignore by default\n }\n\n /**\n * Determine if we have the keys necessary to respond to a room key request\n *\n * @returns true if we have the keys and could (theoretically) share\n * them; else false.\n */\n public hasKeysForKeyRequest(keyRequest: IncomingRoomKeyRequest): Promise {\n return Promise.resolve(false);\n }\n\n /**\n * Send the response to a room key request\n *\n */\n public shareKeysWithDevice(keyRequest: IncomingRoomKeyRequest): void {\n throw new Error(\"shareKeysWithDevice not supported for this DecryptionAlgorithm\");\n }\n\n /**\n * Retry decrypting all the events from a sender that haven't been\n * decrypted yet.\n *\n * @param senderKey - the sender's key\n */\n public async retryDecryptionFromSender(senderKey: string): Promise {\n // ignore by default\n return false;\n }\n\n public onRoomKeyWithheldEvent?(event: MatrixEvent): Promise;\n public sendSharedHistoryInboundSessions?(devicesByUser: Map): Promise;\n}\n\n/**\n * Exception thrown when decryption fails\n *\n * @param msg - user-visible message describing the problem\n *\n * @param details - key/value pairs reported in the logs but not shown\n * to the user.\n */\nexport class DecryptionError extends Error {\n public readonly detailedString: string;\n\n public constructor(public readonly code: string, msg: string, details?: Record) {\n super(msg);\n this.code = code;\n this.name = \"DecryptionError\";\n this.detailedString = detailedStringForDecryptionError(this, details);\n }\n}\n\nfunction detailedStringForDecryptionError(err: DecryptionError, details?: Record): string {\n let result = err.name + \"[msg: \" + err.message;\n\n if (details) {\n result +=\n \", \" +\n Object.keys(details)\n .map((k) => k + \": \" + details[k])\n .join(\", \");\n }\n\n result += \"]\";\n\n return result;\n}\n\nexport class UnknownDeviceError extends Error {\n /**\n * Exception thrown specifically when we want to warn the user to consider\n * the security of their conversation before continuing\n *\n * @param msg - message describing the problem\n * @param devices - set of unknown devices per user we're warning about\n */\n public constructor(msg: string, public readonly devices: DeviceInfoMap, public event?: MatrixEvent) {\n super(msg);\n this.name = \"UnknownDeviceError\";\n this.devices = devices;\n }\n}\n\n/**\n * Registers an encryption/decryption class for a particular algorithm\n *\n * @param algorithm - algorithm tag to register for\n *\n * @param encryptor - {@link EncryptionAlgorithm} implementation\n *\n * @param decryptor - {@link DecryptionAlgorithm} implementation\n */\nexport function registerAlgorithm

(\n algorithm: string,\n encryptor: new (params: P) => EncryptionAlgorithm,\n decryptor: new (params: DecryptionClassParams

) => DecryptionAlgorithm,\n): void {\n ENCRYPTION_CLASSES.set(algorithm, encryptor as new (params: IParams) => EncryptionAlgorithm);\n DECRYPTION_CLASSES.set(algorithm, decryptor as new (params: DecryptionClassParams) => DecryptionAlgorithm);\n}\n", - "/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport \"./olm\";\nimport \"./megolm\";\n\nexport * from \"./base\";\n", - "/*\nCopyright 2015 - 2021, 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Defines m.olm encryption/decryption\n */\n\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport type { IEventDecryptionResult, IMegolmSessionData } from \"../../@types/crypto\";\nimport { logger, PrefixedLogger } from \"../../logger\";\nimport * as olmlib from \"../olmlib\";\nimport {\n DecryptionAlgorithm,\n DecryptionClassParams,\n DecryptionError,\n EncryptionAlgorithm,\n IParams,\n registerAlgorithm,\n UnknownDeviceError,\n} from \"./base\";\nimport { IDecryptedGroupMessage, WITHHELD_MESSAGES } from \"../OlmDevice\";\nimport { Room } from \"../../models/room\";\nimport { DeviceInfo } from \"../deviceinfo\";\nimport { IOlmSessionResult } from \"../olmlib\";\nimport { DeviceInfoMap } from \"../DeviceList\";\nimport { IContent, MatrixEvent } from \"../../models/event\";\nimport { EventType, MsgType, ToDeviceMessageId } from \"../../@types/event\";\nimport { IMegolmEncryptedContent, IncomingRoomKeyRequest, IEncryptedContent } from \"../index\";\nimport { RoomKeyRequestState } from \"../OutgoingRoomKeyRequestManager\";\nimport { OlmGroupSessionExtraData } from \"../../@types/crypto\";\nimport { MatrixError } from \"../../http-api\";\nimport { immediate, MapWithDefault } from \"../../utils\";\n\n// determine whether the key can be shared with invitees\nexport function isRoomSharedHistory(room: Room): boolean {\n const visibilityEvent = room?.currentState?.getStateEvents(\"m.room.history_visibility\", \"\");\n // NOTE: if the room visibility is unset, it would normally default to\n // \"world_readable\".\n // (https://spec.matrix.org/unstable/client-server-api/#server-behaviour-5)\n // But we will be paranoid here, and treat it as a situation where the room\n // is not shared-history\n const visibility = visibilityEvent?.getContent()?.history_visibility;\n return [\"world_readable\", \"shared\"].includes(visibility);\n}\n\ninterface IBlockedDevice {\n code: string;\n reason: string;\n deviceInfo: DeviceInfo;\n}\n\n// map user Id → device Id → IBlockedDevice\ntype BlockedMap = Map>;\n\nexport interface IOlmDevice {\n userId: string;\n deviceInfo: T;\n}\n\n/**\n * Tests whether an encrypted content has a ciphertext.\n * Ciphertext can be a string or object depending on the content type {@link IEncryptedContent}.\n *\n * @param content - Encrypted content\n * @returns true: has ciphertext, else false\n */\nconst hasCiphertext = (content: IEncryptedContent): boolean => {\n return typeof content.ciphertext === \"string\"\n ? !!content.ciphertext.length\n : !!Object.keys(content.ciphertext).length;\n};\n\n/** The result of parsing the an `m.room_key` or `m.forwarded_room_key` to-device event */\ninterface RoomKey {\n /**\n * The Curve25519 key of the megolm session creator.\n *\n * For `m.room_key`, this is also the sender of the `m.room_key` to-device event.\n * For `m.forwarded_room_key`, the two are different (and the key of the sender of the\n * `m.forwarded_room_key` event is included in `forwardingKeyChain`)\n */\n senderKey: string;\n sessionId: string;\n sessionKey: string;\n exportFormat: boolean;\n roomId: string;\n algorithm: string;\n /**\n * A list of the curve25519 keys of the users involved in forwarding this key, most recent last.\n * For `m.room_key` events, this is empty.\n */\n forwardingKeyChain: string[];\n keysClaimed: Partial>;\n extraSessionData: OlmGroupSessionExtraData;\n}\n\nexport interface IOutboundGroupSessionKey {\n chain_index: number;\n key: string;\n}\n\ninterface IMessage {\n type: string;\n content: {\n \"algorithm\": string;\n \"room_id\": string;\n \"sender_key\"?: string;\n \"sender_claimed_ed25519_key\"?: string;\n \"session_id\": string;\n \"session_key\": string;\n \"chain_index\": number;\n \"forwarding_curve25519_key_chain\"?: string[];\n \"org.matrix.msc3061.shared_history\": boolean;\n };\n}\n\ninterface IKeyForwardingMessage extends IMessage {\n type: \"m.forwarded_room_key\";\n}\n\ninterface IPayload extends Partial {\n code?: string;\n reason?: string;\n room_id?: string;\n session_id?: string;\n algorithm?: string;\n sender_key?: string;\n}\n\ninterface SharedWithData {\n // The identity key of the device we shared with\n deviceKey: string;\n // The message index of the ratchet we shared with that device\n messageIndex: number;\n}\n\n/**\n * @internal\n */\nclass OutboundSessionInfo {\n /** number of times this session has been used */\n public useCount = 0;\n /** when the session was created (ms since the epoch) */\n public creationTime: number;\n /** devices with which we have shared the session key `userId -> {deviceId -> SharedWithData}` */\n public sharedWithDevices: MapWithDefault> = new MapWithDefault(() => new Map());\n public blockedDevicesNotified: MapWithDefault> = new MapWithDefault(() => new Map());\n\n /**\n * @param sharedHistory - whether the session can be freely shared with\n * other group members, according to the room history visibility settings\n */\n public constructor(public readonly sessionId: string, public readonly sharedHistory = false) {\n this.creationTime = new Date().getTime();\n }\n\n /**\n * Check if it's time to rotate the session\n */\n public needsRotation(rotationPeriodMsgs: number, rotationPeriodMs: number): boolean {\n const sessionLifetime = new Date().getTime() - this.creationTime;\n\n if (this.useCount >= rotationPeriodMsgs || sessionLifetime >= rotationPeriodMs) {\n logger.log(\"Rotating megolm session after \" + this.useCount + \" messages, \" + sessionLifetime + \"ms\");\n return true;\n }\n\n return false;\n }\n\n public markSharedWithDevice(userId: string, deviceId: string, deviceKey: string, chainIndex: number): void {\n this.sharedWithDevices.getOrCreate(userId).set(deviceId, { deviceKey, messageIndex: chainIndex });\n }\n\n public markNotifiedBlockedDevice(userId: string, deviceId: string): void {\n this.blockedDevicesNotified.getOrCreate(userId).set(deviceId, true);\n }\n\n /**\n * Determine if this session has been shared with devices which it shouldn't\n * have been.\n *\n * @param devicesInRoom - `userId -> {deviceId -> object}`\n * devices we should shared the session with.\n *\n * @returns true if we have shared the session with devices which aren't\n * in devicesInRoom.\n */\n public sharedWithTooManyDevices(devicesInRoom: DeviceInfoMap): boolean {\n for (const [userId, devices] of this.sharedWithDevices) {\n if (!devicesInRoom.has(userId)) {\n logger.log(\"Starting new megolm session because we shared with \" + userId);\n return true;\n }\n\n for (const [deviceId] of devices) {\n if (!devicesInRoom.get(userId)?.get(deviceId)) {\n logger.log(\"Starting new megolm session because we shared with \" + userId + \":\" + deviceId);\n return true;\n }\n }\n }\n\n return false;\n }\n}\n\n/**\n * Megolm encryption implementation\n *\n * @param params - parameters, as per {@link EncryptionAlgorithm}\n */\nexport class MegolmEncryption extends EncryptionAlgorithm {\n // the most recent attempt to set up a session. This is used to serialise\n // the session setups, so that we have a race-free view of which session we\n // are using, and which devices we have shared the keys with. It resolves\n // with an OutboundSessionInfo (or undefined, for the first message in the\n // room).\n private setupPromise = Promise.resolve(null);\n\n // Map of outbound sessions by sessions ID. Used if we need a particular\n // session (the session we're currently using to send is always obtained\n // using setupPromise).\n private outboundSessions: Record = {};\n\n private readonly sessionRotationPeriodMsgs: number;\n private readonly sessionRotationPeriodMs: number;\n private encryptionPreparation?: {\n promise: Promise;\n startTime: number;\n cancel: () => void;\n };\n\n protected readonly roomId: string;\n private readonly prefixedLogger: PrefixedLogger;\n\n public constructor(params: IParams & Required>) {\n super(params);\n this.roomId = params.roomId;\n this.prefixedLogger = logger.withPrefix(`[${this.roomId} encryption]`);\n\n this.sessionRotationPeriodMsgs = params.config?.rotation_period_msgs ?? 100;\n this.sessionRotationPeriodMs = params.config?.rotation_period_ms ?? 7 * 24 * 3600 * 1000;\n }\n\n /**\n * @internal\n *\n * @param devicesInRoom - The devices in this room, indexed by user ID\n * @param blocked - The devices that are blocked, indexed by user ID\n * @param singleOlmCreationPhase - Only perform one round of olm\n * session creation\n *\n * This method updates the setupPromise field of the class by chaining a new\n * call on top of the existing promise, and then catching and discarding any\n * errors that might happen while setting up the outbound group session. This\n * is done to ensure that `setupPromise` always resolves to `null` or the\n * `OutboundSessionInfo`.\n *\n * Using `>>=` to represent the promise chaining operation, it does the\n * following:\n *\n * ```\n * setupPromise = previousSetupPromise >>= setup >>= discardErrors\n * ```\n *\n * The initial value for the `setupPromise` is a promise that resolves to\n * `null`. The forceDiscardSession() resets setupPromise to this initial\n * promise.\n *\n * @returns Promise which resolves to the\n * OutboundSessionInfo when setup is complete.\n */\n private async ensureOutboundSession(\n room: Room,\n devicesInRoom: DeviceInfoMap,\n blocked: BlockedMap,\n singleOlmCreationPhase = false,\n ): Promise {\n // takes the previous OutboundSessionInfo, and considers whether to create\n // a new one. Also shares the key with any (new) devices in the room.\n //\n // returns a promise which resolves once the keyshare is successful.\n const setup = async (oldSession: OutboundSessionInfo | null): Promise => {\n const sharedHistory = isRoomSharedHistory(room);\n const session = await this.prepareSession(devicesInRoom, sharedHistory, oldSession);\n\n await this.shareSession(devicesInRoom, sharedHistory, singleOlmCreationPhase, blocked, session);\n\n return session;\n };\n\n // first wait for the previous share to complete\n const fallible = this.setupPromise.then(setup);\n\n // Ensure any failures are logged for debugging and make sure that the\n // promise chain remains unbroken\n //\n // setupPromise resolves to `null` or the `OutboundSessionInfo` whether\n // or not the share succeeds\n this.setupPromise = fallible.catch((e) => {\n this.prefixedLogger.error(`Failed to setup outbound session`, e);\n return null;\n });\n\n // but we return a promise which only resolves if the share was successful.\n return fallible;\n }\n\n private async prepareSession(\n devicesInRoom: DeviceInfoMap,\n sharedHistory: boolean,\n session: OutboundSessionInfo | null,\n ): Promise {\n // history visibility changed\n if (session && sharedHistory !== session.sharedHistory) {\n session = null;\n }\n\n // need to make a brand new session?\n if (session?.needsRotation(this.sessionRotationPeriodMsgs, this.sessionRotationPeriodMs)) {\n this.prefixedLogger.log(\"Starting new megolm session because we need to rotate.\");\n session = null;\n }\n\n // determine if we have shared with anyone we shouldn't have\n if (session?.sharedWithTooManyDevices(devicesInRoom)) {\n session = null;\n }\n\n if (!session) {\n this.prefixedLogger.log(\"Starting new megolm session\");\n session = await this.prepareNewSession(sharedHistory);\n this.prefixedLogger.log(`Started new megolm session ${session.sessionId}`);\n this.outboundSessions[session.sessionId] = session;\n }\n\n return session;\n }\n\n private async shareSession(\n devicesInRoom: DeviceInfoMap,\n sharedHistory: boolean,\n singleOlmCreationPhase: boolean,\n blocked: BlockedMap,\n session: OutboundSessionInfo,\n ): Promise {\n // now check if we need to share with any devices\n const shareMap: Record = {};\n\n for (const [userId, userDevices] of devicesInRoom) {\n for (const [deviceId, deviceInfo] of userDevices) {\n const key = deviceInfo.getIdentityKey();\n if (key == this.olmDevice.deviceCurve25519Key) {\n // don't bother sending to ourself\n continue;\n }\n\n if (!session.sharedWithDevices.get(userId)?.get(deviceId)) {\n shareMap[userId] = shareMap[userId] || [];\n shareMap[userId].push(deviceInfo);\n }\n }\n }\n\n const key = this.olmDevice.getOutboundGroupSessionKey(session.sessionId);\n const payload: IPayload = {\n type: \"m.room_key\",\n content: {\n \"algorithm\": olmlib.MEGOLM_ALGORITHM,\n \"room_id\": this.roomId,\n \"session_id\": session.sessionId,\n \"session_key\": key.key,\n \"chain_index\": key.chain_index,\n \"org.matrix.msc3061.shared_history\": sharedHistory,\n },\n };\n const [devicesWithoutSession, olmSessions] = await olmlib.getExistingOlmSessions(\n this.olmDevice,\n this.baseApis,\n shareMap,\n );\n\n await Promise.all([\n (async (): Promise => {\n // share keys with devices that we already have a session for\n const olmSessionList = Array.from(olmSessions.entries())\n .map(([userId, sessionsByUser]) =>\n Array.from(sessionsByUser.entries()).map(\n ([deviceId, session]) => `${userId}/${deviceId}: ${session.sessionId}`,\n ),\n )\n .flat(1);\n this.prefixedLogger.debug(\"Sharing keys with devices with existing Olm sessions:\", olmSessionList);\n await this.shareKeyWithOlmSessions(session, key, payload, olmSessions);\n this.prefixedLogger.debug(\"Shared keys with existing Olm sessions\");\n })(),\n (async (): Promise => {\n const deviceList = Array.from(devicesWithoutSession.entries())\n .map(([userId, devicesByUser]) => devicesByUser.map((device) => `${userId}/${device.deviceId}`))\n .flat(1);\n this.prefixedLogger.debug(\n \"Sharing keys (start phase 1) with devices without existing Olm sessions:\",\n deviceList,\n );\n const errorDevices: IOlmDevice[] = [];\n\n // meanwhile, establish olm sessions for devices that we don't\n // already have a session for, and share keys with them. If\n // we're doing two phases of olm session creation, use a\n // shorter timeout when fetching one-time keys for the first\n // phase.\n const start = Date.now();\n const failedServers: string[] = [];\n await this.shareKeyWithDevices(\n session,\n key,\n payload,\n devicesWithoutSession,\n errorDevices,\n singleOlmCreationPhase ? 10000 : 2000,\n failedServers,\n );\n this.prefixedLogger.debug(\"Shared keys (end phase 1) with devices without existing Olm sessions\");\n\n if (!singleOlmCreationPhase && Date.now() - start < 10000) {\n // perform the second phase of olm session creation if requested,\n // and if the first phase didn't take too long\n (async (): Promise => {\n // Retry sending keys to devices that we were unable to establish\n // an olm session for. This time, we use a longer timeout, but we\n // do this in the background and don't block anything else while we\n // do this. We only need to retry users from servers that didn't\n // respond the first time.\n const retryDevices: MapWithDefault = new MapWithDefault(() => []);\n const failedServerMap = new Set();\n for (const server of failedServers) {\n failedServerMap.add(server);\n }\n const failedDevices: IOlmDevice[] = [];\n for (const { userId, deviceInfo } of errorDevices) {\n const userHS = userId.slice(userId.indexOf(\":\") + 1);\n if (failedServerMap.has(userHS)) {\n retryDevices.getOrCreate(userId).push(deviceInfo);\n } else {\n // if we aren't going to retry, then handle it\n // as a failed device\n failedDevices.push({ userId, deviceInfo });\n }\n }\n\n const retryDeviceList = Array.from(retryDevices.entries())\n .map(([userId, devicesByUser]) =>\n devicesByUser.map((device) => `${userId}/${device.deviceId}`),\n )\n .flat(1);\n\n if (retryDeviceList.length > 0) {\n this.prefixedLogger.debug(\n \"Sharing keys (start phase 2) with devices without existing Olm sessions:\",\n retryDeviceList,\n );\n await this.shareKeyWithDevices(session, key, payload, retryDevices, failedDevices, 30000);\n this.prefixedLogger.debug(\n \"Shared keys (end phase 2) with devices without existing Olm sessions\",\n );\n }\n\n await this.notifyFailedOlmDevices(session, key, failedDevices);\n })();\n } else {\n await this.notifyFailedOlmDevices(session, key, errorDevices);\n }\n })(),\n (async (): Promise => {\n this.prefixedLogger.debug(\n `There are ${blocked.size} blocked devices:`,\n Array.from(blocked.entries())\n .map(([userId, blockedByUser]) =>\n Array.from(blockedByUser.entries()).map(\n ([deviceId, _deviceInfo]) => `${userId}/${deviceId}`,\n ),\n )\n .flat(1),\n );\n\n // also, notify newly blocked devices that they're blocked\n const blockedMap: MapWithDefault> = new MapWithDefault(\n () => new Map(),\n );\n let blockedCount = 0;\n for (const [userId, userBlockedDevices] of blocked) {\n for (const [deviceId, device] of userBlockedDevices) {\n if (session.blockedDevicesNotified.get(userId)?.get(deviceId) === undefined) {\n blockedMap.getOrCreate(userId).set(deviceId, { device });\n blockedCount++;\n }\n }\n }\n\n if (blockedCount) {\n this.prefixedLogger.debug(\n `Notifying ${blockedCount} newly blocked devices:`,\n Array.from(blockedMap.entries())\n .map(([userId, blockedByUser]) =>\n Object.entries(blockedByUser).map(([deviceId, _deviceInfo]) => `${userId}/${deviceId}`),\n )\n .flat(1),\n );\n await this.notifyBlockedDevices(session, blockedMap);\n this.prefixedLogger.debug(`Notified ${blockedCount} newly blocked devices`);\n }\n })(),\n ]);\n }\n\n /**\n * @internal\n *\n *\n * @returns session\n */\n private async prepareNewSession(sharedHistory: boolean): Promise {\n const sessionId = this.olmDevice.createOutboundGroupSession();\n const key = this.olmDevice.getOutboundGroupSessionKey(sessionId);\n\n await this.olmDevice.addInboundGroupSession(\n this.roomId,\n this.olmDevice.deviceCurve25519Key!,\n [],\n sessionId,\n key.key,\n { ed25519: this.olmDevice.deviceEd25519Key! },\n false,\n { sharedHistory },\n );\n\n // don't wait for it to complete\n this.crypto.backupManager.backupGroupSession(this.olmDevice.deviceCurve25519Key!, sessionId);\n\n return new OutboundSessionInfo(sessionId, sharedHistory);\n }\n\n /**\n * Determines what devices in devicesByUser don't have an olm session as given\n * in devicemap.\n *\n * @internal\n *\n * @param deviceMap - the devices that have olm sessions, as returned by\n * olmlib.ensureOlmSessionsForDevices.\n * @param devicesByUser - a map of user IDs to array of deviceInfo\n * @param noOlmDevices - an array to fill with devices that don't have\n * olm sessions\n *\n * @returns an array of devices that don't have olm sessions. If\n * noOlmDevices is specified, then noOlmDevices will be returned.\n */\n private getDevicesWithoutSessions(\n deviceMap: Map>,\n devicesByUser: Map,\n noOlmDevices: IOlmDevice[] = [],\n ): IOlmDevice[] {\n for (const [userId, devicesToShareWith] of devicesByUser) {\n const sessionResults = deviceMap.get(userId);\n\n for (const deviceInfo of devicesToShareWith) {\n const deviceId = deviceInfo.deviceId;\n\n const sessionResult = sessionResults?.get(deviceId);\n if (!sessionResult?.sessionId) {\n // no session with this device, probably because there\n // were no one-time keys.\n\n noOlmDevices.push({ userId, deviceInfo });\n sessionResults?.delete(deviceId);\n\n // ensureOlmSessionsForUsers has already done the logging,\n // so just skip it.\n continue;\n }\n }\n }\n\n return noOlmDevices;\n }\n\n /**\n * Splits the user device map into multiple chunks to reduce the number of\n * devices we encrypt to per API call.\n *\n * @internal\n *\n * @param devicesByUser - map from userid to list of devices\n *\n * @returns the blocked devices, split into chunks\n */\n private splitDevices(\n devicesByUser: Map>,\n ): IOlmDevice[][] {\n const maxDevicesPerRequest = 20;\n\n // use an array where the slices of a content map gets stored\n let currentSlice: IOlmDevice[] = [];\n const mapSlices = [currentSlice];\n\n for (const [userId, userDevices] of devicesByUser) {\n for (const deviceInfo of userDevices.values()) {\n currentSlice.push({\n userId: userId,\n deviceInfo: deviceInfo.device,\n });\n }\n\n // We do this in the per-user loop as we prefer that all messages to the\n // same user end up in the same API call to make it easier for the\n // server (e.g. only have to send one EDU if a remote user, etc). This\n // does mean that if a user has many devices we may go over the desired\n // limit, but its not a hard limit so that is fine.\n if (currentSlice.length > maxDevicesPerRequest) {\n // the current slice is filled up. Start inserting into the next slice\n currentSlice = [];\n mapSlices.push(currentSlice);\n }\n }\n if (currentSlice.length === 0) {\n mapSlices.pop();\n }\n return mapSlices;\n }\n\n /**\n * @internal\n *\n *\n * @param chainIndex - current chain index\n *\n * @param userDeviceMap - mapping from userId to deviceInfo\n *\n * @param payload - fields to include in the encrypted payload\n *\n * @returns Promise which resolves once the key sharing\n * for the given userDeviceMap is generated and has been sent.\n */\n private encryptAndSendKeysToDevices(\n session: OutboundSessionInfo,\n chainIndex: number,\n devices: IOlmDevice[],\n payload: IPayload,\n ): Promise {\n return this.crypto\n .encryptAndSendToDevices(devices, payload)\n .then(() => {\n // store that we successfully uploaded the keys of the current slice\n for (const device of devices) {\n session.markSharedWithDevice(\n device.userId,\n device.deviceInfo.deviceId,\n device.deviceInfo.getIdentityKey(),\n chainIndex,\n );\n }\n })\n .catch((error) => {\n this.prefixedLogger.error(\"failed to encryptAndSendToDevices\", error);\n throw error;\n });\n }\n\n /**\n * @internal\n *\n *\n * @param userDeviceMap - list of blocked devices to notify\n *\n * @param payload - fields to include in the notification payload\n *\n * @returns Promise which resolves once the notifications\n * for the given userDeviceMap is generated and has been sent.\n */\n private async sendBlockedNotificationsToDevices(\n session: OutboundSessionInfo,\n userDeviceMap: IOlmDevice[],\n payload: IPayload,\n ): Promise {\n const contentMap: MapWithDefault> = new MapWithDefault(() => new Map());\n\n for (const val of userDeviceMap) {\n const userId = val.userId;\n const blockedInfo = val.deviceInfo;\n const deviceInfo = blockedInfo.deviceInfo;\n const deviceId = deviceInfo.deviceId;\n\n const message = {\n ...payload,\n code: blockedInfo.code,\n reason: blockedInfo.reason,\n [ToDeviceMessageId]: uuidv4(),\n };\n\n if (message.code === \"m.no_olm\") {\n delete message.room_id;\n delete message.session_id;\n }\n\n contentMap.getOrCreate(userId).set(deviceId, message);\n }\n\n await this.baseApis.sendToDevice(\"m.room_key.withheld\", contentMap);\n\n // record the fact that we notified these blocked devices\n for (const [userId, userDeviceMap] of contentMap) {\n for (const deviceId of userDeviceMap.keys()) {\n session.markNotifiedBlockedDevice(userId, deviceId);\n }\n }\n }\n\n /**\n * Re-shares a megolm session key with devices if the key has already been\n * sent to them.\n *\n * @param senderKey - The key of the originating device for the session\n * @param sessionId - ID of the outbound session to share\n * @param userId - ID of the user who owns the target device\n * @param device - The target device\n */\n public async reshareKeyWithDevice(\n senderKey: string,\n sessionId: string,\n userId: string,\n device: DeviceInfo,\n ): Promise {\n const obSessionInfo = this.outboundSessions[sessionId];\n if (!obSessionInfo) {\n this.prefixedLogger.debug(`megolm session ${senderKey}|${sessionId} not found: not re-sharing keys`);\n return;\n }\n\n // The chain index of the key we previously sent this device\n if (!obSessionInfo.sharedWithDevices.has(userId)) {\n this.prefixedLogger.debug(`megolm session ${senderKey}|${sessionId} never shared with user ${userId}`);\n return;\n }\n const sessionSharedData = obSessionInfo.sharedWithDevices.get(userId)?.get(device.deviceId);\n if (sessionSharedData === undefined) {\n this.prefixedLogger.debug(\n `megolm session ${senderKey}|${sessionId} never shared with device ${userId}:${device.deviceId}`,\n );\n return;\n }\n\n if (sessionSharedData.deviceKey !== device.getIdentityKey()) {\n this.prefixedLogger.warn(\n `Megolm session ${senderKey}|${sessionId} has been shared with device ${device.deviceId} but ` +\n `with identity key ${sessionSharedData.deviceKey}. Key is now ${device.getIdentityKey()}!`,\n );\n return;\n }\n\n // get the key from the inbound session: the outbound one will already\n // have been ratcheted to the next chain index.\n const key = await this.olmDevice.getInboundGroupSessionKey(\n this.roomId,\n senderKey,\n sessionId,\n sessionSharedData.messageIndex,\n );\n\n if (!key) {\n this.prefixedLogger.warn(\n `No inbound session key found for megolm session ${senderKey}|${sessionId}: not re-sharing keys`,\n );\n return;\n }\n\n await olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, new Map([[userId, [device]]]));\n\n const payload = {\n type: \"m.forwarded_room_key\",\n content: {\n \"algorithm\": olmlib.MEGOLM_ALGORITHM,\n \"room_id\": this.roomId,\n \"session_id\": sessionId,\n \"session_key\": key.key,\n \"chain_index\": key.chain_index,\n \"sender_key\": senderKey,\n \"sender_claimed_ed25519_key\": key.sender_claimed_ed25519_key,\n \"forwarding_curve25519_key_chain\": key.forwarding_curve25519_key_chain,\n \"org.matrix.msc3061.shared_history\": key.shared_history || false,\n },\n };\n\n const encryptedContent: IEncryptedContent = {\n algorithm: olmlib.OLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key!,\n ciphertext: {},\n [ToDeviceMessageId]: uuidv4(),\n };\n await olmlib.encryptMessageForDevice(\n encryptedContent.ciphertext,\n this.userId,\n this.deviceId,\n this.olmDevice,\n userId,\n device,\n payload,\n );\n\n await this.baseApis.sendToDevice(\n \"m.room.encrypted\",\n new Map([[userId, new Map([[device.deviceId, encryptedContent]])]]),\n );\n this.prefixedLogger.debug(\n `Re-shared key for megolm session ${senderKey}|${sessionId} with ${userId}:${device.deviceId}`,\n );\n }\n\n /**\n * @internal\n *\n *\n * @param key - the session key as returned by\n * OlmDevice.getOutboundGroupSessionKey\n *\n * @param payload - the base to-device message payload for sharing keys\n *\n * @param devicesByUser - map from userid to list of devices\n *\n * @param errorDevices - array that will be populated with the devices that we can't get an\n * olm session for\n *\n * @param otkTimeout - The timeout in milliseconds when requesting\n * one-time keys for establishing new olm sessions.\n *\n * @param failedServers - An array to fill with remote servers that\n * failed to respond to one-time-key requests.\n */\n private async shareKeyWithDevices(\n session: OutboundSessionInfo,\n key: IOutboundGroupSessionKey,\n payload: IPayload,\n devicesByUser: Map,\n errorDevices: IOlmDevice[],\n otkTimeout: number,\n failedServers?: string[],\n ): Promise {\n const devicemap = await olmlib.ensureOlmSessionsForDevices(\n this.olmDevice,\n this.baseApis,\n devicesByUser,\n false,\n otkTimeout,\n failedServers,\n this.prefixedLogger,\n );\n this.getDevicesWithoutSessions(devicemap, devicesByUser, errorDevices);\n await this.shareKeyWithOlmSessions(session, key, payload, devicemap);\n }\n\n private async shareKeyWithOlmSessions(\n session: OutboundSessionInfo,\n key: IOutboundGroupSessionKey,\n payload: IPayload,\n deviceMap: Map>,\n ): Promise {\n const userDeviceMaps = this.splitDevices(deviceMap);\n\n for (let i = 0; i < userDeviceMaps.length; i++) {\n const taskDetail = `megolm keys for ${session.sessionId} (slice ${i + 1}/${userDeviceMaps.length})`;\n try {\n this.prefixedLogger.debug(\n `Sharing ${taskDetail}`,\n userDeviceMaps[i].map((d) => `${d.userId}/${d.deviceInfo.deviceId}`),\n );\n await this.encryptAndSendKeysToDevices(session, key.chain_index, userDeviceMaps[i], payload);\n this.prefixedLogger.debug(`Shared ${taskDetail}`);\n } catch (e) {\n this.prefixedLogger.error(`Failed to share ${taskDetail}`);\n throw e;\n }\n }\n }\n\n /**\n * Notify devices that we weren't able to create olm sessions.\n *\n *\n *\n * @param failedDevices - the devices that we were unable to\n * create olm sessions for, as returned by shareKeyWithDevices\n */\n private async notifyFailedOlmDevices(\n session: OutboundSessionInfo,\n key: IOutboundGroupSessionKey,\n failedDevices: IOlmDevice[],\n ): Promise {\n this.prefixedLogger.debug(`Notifying ${failedDevices.length} devices we failed to create Olm sessions`);\n\n // mark the devices that failed as \"handled\" because we don't want to try\n // to claim a one-time-key for dead devices on every message.\n for (const { userId, deviceInfo } of failedDevices) {\n const deviceId = deviceInfo.deviceId;\n\n session.markSharedWithDevice(userId, deviceId, deviceInfo.getIdentityKey(), key.chain_index);\n }\n\n const unnotifiedFailedDevices = await this.olmDevice.filterOutNotifiedErrorDevices(failedDevices);\n this.prefixedLogger.debug(\n `Need to notify ${unnotifiedFailedDevices.length} failed devices which haven't been notified before`,\n );\n const blockedMap: MapWithDefault> = new MapWithDefault(\n () => new Map(),\n );\n for (const { userId, deviceInfo } of unnotifiedFailedDevices) {\n // we use a similar format to what\n // olmlib.ensureOlmSessionsForDevices returns, so that\n // we can use the same function to split\n blockedMap.getOrCreate(userId).set(deviceInfo.deviceId, {\n device: {\n code: \"m.no_olm\",\n reason: WITHHELD_MESSAGES[\"m.no_olm\"],\n deviceInfo,\n },\n });\n }\n\n // send the notifications\n await this.notifyBlockedDevices(session, blockedMap);\n this.prefixedLogger.debug(\n `Notified ${unnotifiedFailedDevices.length} devices we failed to create Olm sessions`,\n );\n }\n\n /**\n * Notify blocked devices that they have been blocked.\n *\n *\n * @param devicesByUser - map from userid to device ID to blocked data\n */\n private async notifyBlockedDevices(\n session: OutboundSessionInfo,\n devicesByUser: Map>,\n ): Promise {\n const payload: IPayload = {\n room_id: this.roomId,\n session_id: session.sessionId,\n algorithm: olmlib.MEGOLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key!,\n };\n\n const userDeviceMaps = this.splitDevices(devicesByUser);\n\n for (let i = 0; i < userDeviceMaps.length; i++) {\n try {\n await this.sendBlockedNotificationsToDevices(session, userDeviceMaps[i], payload);\n this.prefixedLogger.log(\n `Completed blacklist notification for ${session.sessionId} ` +\n `(slice ${i + 1}/${userDeviceMaps.length})`,\n );\n } catch (e) {\n this.prefixedLogger.log(\n `blacklist notification for ${session.sessionId} ` +\n `(slice ${i + 1}/${userDeviceMaps.length}) failed`,\n );\n\n throw e;\n }\n }\n }\n\n /**\n * Perform any background tasks that can be done before a message is ready to\n * send, in order to speed up sending of the message.\n *\n * @param room - the room the event is in\n * @returns A function that, when called, will stop the preparation\n */\n public prepareToEncrypt(room: Room): () => void {\n if (room.roomId !== this.roomId) {\n throw new Error(\"MegolmEncryption.prepareToEncrypt called on unexpected room\");\n }\n\n if (this.encryptionPreparation != null) {\n // We're already preparing something, so don't do anything else.\n const elapsedTime = Date.now() - this.encryptionPreparation.startTime;\n this.prefixedLogger.debug(\n `Already started preparing to encrypt for this room ${elapsedTime}ms ago, skipping`,\n );\n return this.encryptionPreparation.cancel;\n }\n\n this.prefixedLogger.debug(\"Preparing to encrypt events\");\n\n let cancelled = false;\n const isCancelled = (): boolean => cancelled;\n\n this.encryptionPreparation = {\n startTime: Date.now(),\n promise: (async (): Promise => {\n try {\n // Attempt to enumerate the devices in room, and gracefully\n // handle cancellation if it occurs.\n const getDevicesResult = await this.getDevicesInRoom(room, false, isCancelled);\n if (getDevicesResult === null) return;\n const [devicesInRoom, blocked] = getDevicesResult;\n\n if (this.crypto.globalErrorOnUnknownDevices) {\n // Drop unknown devices for now. When the message gets sent, we'll\n // throw an error, but we'll still be prepared to send to the known\n // devices.\n this.removeUnknownDevices(devicesInRoom);\n }\n\n this.prefixedLogger.debug(\"Ensuring outbound megolm session\");\n await this.ensureOutboundSession(room, devicesInRoom, blocked, true);\n\n this.prefixedLogger.debug(\"Ready to encrypt events\");\n } catch (e) {\n this.prefixedLogger.error(\"Failed to prepare to encrypt events\", e);\n } finally {\n delete this.encryptionPreparation;\n }\n })(),\n\n cancel: (): void => {\n // The caller has indicated that the process should be cancelled,\n // so tell the promise that we'd like to halt, and reset the preparation state.\n cancelled = true;\n delete this.encryptionPreparation;\n },\n };\n\n return this.encryptionPreparation.cancel;\n }\n\n /**\n * @param content - plaintext event content\n *\n * @returns Promise which resolves to the new event body\n */\n public async encryptMessage(room: Room, eventType: string, content: IContent): Promise {\n this.prefixedLogger.log(\"Starting to encrypt event\");\n\n if (this.encryptionPreparation != null) {\n // If we started sending keys, wait for it to be done.\n // FIXME: check if we need to cancel\n // (https://github.com/matrix-org/matrix-js-sdk/issues/1255)\n try {\n await this.encryptionPreparation.promise;\n } catch (e) {\n // ignore any errors -- if the preparation failed, we'll just\n // restart everything here\n }\n }\n\n /**\n * When using in-room messages and the room has encryption enabled,\n * clients should ensure that encryption does not hinder the verification.\n */\n const forceDistributeToUnverified = this.isVerificationEvent(eventType, content);\n const [devicesInRoom, blocked] = await this.getDevicesInRoom(room, forceDistributeToUnverified);\n\n // check if any of these devices are not yet known to the user.\n // if so, warn the user so they can verify or ignore.\n if (this.crypto.globalErrorOnUnknownDevices) {\n this.checkForUnknownDevices(devicesInRoom);\n }\n\n const session = await this.ensureOutboundSession(room, devicesInRoom, blocked);\n const payloadJson = {\n room_id: this.roomId,\n type: eventType,\n content: content,\n };\n\n const ciphertext = this.olmDevice.encryptGroupMessage(session.sessionId, JSON.stringify(payloadJson));\n const encryptedContent: IEncryptedContent = {\n algorithm: olmlib.MEGOLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key!,\n ciphertext: ciphertext,\n session_id: session.sessionId,\n // Include our device ID so that recipients can send us a\n // m.new_device message if they don't have our session key.\n // XXX: Do we still need this now that m.new_device messages\n // no longer exist since #483?\n device_id: this.deviceId,\n };\n\n session.useCount++;\n return encryptedContent;\n }\n\n private isVerificationEvent(eventType: string, content: IContent): boolean {\n switch (eventType) {\n case EventType.KeyVerificationCancel:\n case EventType.KeyVerificationDone:\n case EventType.KeyVerificationMac:\n case EventType.KeyVerificationStart:\n case EventType.KeyVerificationKey:\n case EventType.KeyVerificationReady:\n case EventType.KeyVerificationAccept: {\n return true;\n }\n case EventType.RoomMessage: {\n return content[\"msgtype\"] === MsgType.KeyVerificationRequest;\n }\n default: {\n return false;\n }\n }\n }\n\n /**\n * Forces the current outbound group session to be discarded such\n * that another one will be created next time an event is sent.\n *\n * This should not normally be necessary.\n */\n public forceDiscardSession(): void {\n this.setupPromise = this.setupPromise.then(() => null);\n }\n\n /**\n * Checks the devices we're about to send to and see if any are entirely\n * unknown to the user. If so, warn the user, and mark them as known to\n * give the user a chance to go verify them before re-sending this message.\n *\n * @param devicesInRoom - `userId -> {deviceId -> object}`\n * devices we should shared the session with.\n */\n private checkForUnknownDevices(devicesInRoom: DeviceInfoMap): void {\n const unknownDevices: MapWithDefault> = new MapWithDefault(() => new Map());\n\n for (const [userId, userDevices] of devicesInRoom) {\n for (const [deviceId, device] of userDevices) {\n if (device.isUnverified() && !device.isKnown()) {\n unknownDevices.getOrCreate(userId).set(deviceId, device);\n }\n }\n }\n\n if (unknownDevices.size) {\n // it'd be kind to pass unknownDevices up to the user in this error\n throw new UnknownDeviceError(\n \"This room contains unknown devices which have not been verified. \" +\n \"We strongly recommend you verify them before continuing.\",\n unknownDevices,\n );\n }\n }\n\n /**\n * Remove unknown devices from a set of devices. The devicesInRoom parameter\n * will be modified.\n *\n * @param devicesInRoom - `userId -> {deviceId -> object}`\n * devices we should shared the session with.\n */\n private removeUnknownDevices(devicesInRoom: DeviceInfoMap): void {\n for (const [userId, userDevices] of devicesInRoom) {\n for (const [deviceId, device] of userDevices) {\n if (device.isUnverified() && !device.isKnown()) {\n userDevices.delete(deviceId);\n }\n }\n\n if (userDevices.size === 0) {\n devicesInRoom.delete(userId);\n }\n }\n }\n\n /**\n * Get the list of unblocked devices for all users in the room\n *\n * @param forceDistributeToUnverified - if set to true will include the unverified devices\n * even if setting is set to block them (useful for verification)\n * @param isCancelled - will cause the procedure to abort early if and when it starts\n * returning `true`. If omitted, cancellation won't happen.\n *\n * @returns Promise which resolves to `null`, or an array whose\n * first element is a {@link DeviceInfoMap} indicating\n * the devices that messages should be encrypted to, and whose second\n * element is a map from userId to deviceId to data indicating the devices\n * that are in the room but that have been blocked.\n * If `isCancelled` is provided and returns `true` while processing, `null`\n * will be returned.\n * If `isCancelled` is not provided, the Promise will never resolve to `null`.\n */\n private async getDevicesInRoom(\n room: Room,\n forceDistributeToUnverified?: boolean,\n ): Promise<[DeviceInfoMap, BlockedMap]>;\n private async getDevicesInRoom(\n room: Room,\n forceDistributeToUnverified?: boolean,\n isCancelled?: () => boolean,\n ): Promise;\n private async getDevicesInRoom(\n room: Room,\n forceDistributeToUnverified = false,\n isCancelled?: () => boolean,\n ): Promise {\n const members = await room.getEncryptionTargetMembers();\n this.prefixedLogger.debug(\n `Encrypting for users (shouldEncryptForInvitedMembers: ${room.shouldEncryptForInvitedMembers()}):`,\n members.map((u) => `${u.userId} (${u.membership})`),\n );\n\n const roomMembers = members.map(function (u) {\n return u.userId;\n });\n\n // The global value is treated as a default for when rooms don't specify a value.\n let isBlacklisting = this.crypto.globalBlacklistUnverifiedDevices;\n const isRoomBlacklisting = room.getBlacklistUnverifiedDevices();\n if (typeof isRoomBlacklisting === \"boolean\") {\n isBlacklisting = isRoomBlacklisting;\n }\n\n // We are happy to use a cached version here: we assume that if we already\n // have a list of the user's devices, then we already share an e2e room\n // with them, which means that they will have announced any new devices via\n // device_lists in their /sync response. This cache should then be maintained\n // using all the device_lists changes and left fields.\n // See https://github.com/vector-im/element-web/issues/2305 for details.\n const devices = await this.crypto.downloadKeys(roomMembers, false);\n\n if (isCancelled?.() === true) {\n return null;\n }\n\n const blocked = new MapWithDefault>(() => new Map());\n // remove any blocked devices\n for (const [userId, userDevices] of devices) {\n for (const [deviceId, userDevice] of userDevices) {\n // Yield prior to checking each device so that we don't block\n // updating/rendering for too long.\n // See https://github.com/vector-im/element-web/issues/21612\n if (isCancelled !== undefined) await immediate();\n if (isCancelled?.() === true) return null;\n const deviceTrust = this.crypto.checkDeviceTrust(userId, deviceId);\n\n if (\n userDevice.isBlocked() ||\n (!deviceTrust.isVerified() && isBlacklisting && !forceDistributeToUnverified)\n ) {\n const blockedDevices = blocked.getOrCreate(userId);\n const isBlocked = userDevice.isBlocked();\n blockedDevices.set(deviceId, {\n code: isBlocked ? \"m.blacklisted\" : \"m.unverified\",\n reason: WITHHELD_MESSAGES[isBlocked ? \"m.blacklisted\" : \"m.unverified\"],\n deviceInfo: userDevice,\n });\n userDevices.delete(deviceId);\n }\n }\n }\n\n return [devices, blocked];\n }\n}\n\n/**\n * Megolm decryption implementation\n *\n * @param params - parameters, as per {@link DecryptionAlgorithm}\n */\nexport class MegolmDecryption extends DecryptionAlgorithm {\n // events which we couldn't decrypt due to unknown sessions /\n // indexes, or which we could only decrypt with untrusted keys:\n // map from senderKey|sessionId to Set of MatrixEvents\n private pendingEvents = new Map>>();\n\n // this gets stubbed out by the unit tests.\n private olmlib = olmlib;\n\n protected readonly roomId: string;\n private readonly prefixedLogger: PrefixedLogger;\n\n public constructor(params: DecryptionClassParams>>) {\n super(params);\n this.roomId = params.roomId;\n this.prefixedLogger = logger.withPrefix(`[${this.roomId} decryption]`);\n }\n\n /**\n * returns a promise which resolves to a\n * {@link EventDecryptionResult} once we have finished\n * decrypting, or rejects with an `algorithms.DecryptionError` if there is a\n * problem decrypting the event.\n */\n public async decryptEvent(event: MatrixEvent): Promise {\n const content = event.getWireContent();\n\n if (!content.sender_key || !content.session_id || !content.ciphertext) {\n throw new DecryptionError(\"MEGOLM_MISSING_FIELDS\", \"Missing fields in input\");\n }\n\n // we add the event to the pending list *before* we start decryption.\n //\n // then, if the key turns up while decryption is in progress (and\n // decryption fails), we will schedule a retry.\n // (fixes https://github.com/vector-im/element-web/issues/5001)\n this.addEventToPendingList(event);\n\n let res: IDecryptedGroupMessage | null;\n try {\n res = await this.olmDevice.decryptGroupMessage(\n event.getRoomId()!,\n content.sender_key,\n content.session_id,\n content.ciphertext,\n event.getId()!,\n event.getTs(),\n );\n } catch (e) {\n if ((e).name === \"DecryptionError\") {\n // re-throw decryption errors as-is\n throw e;\n }\n\n let errorCode = \"OLM_DECRYPT_GROUP_MESSAGE_ERROR\";\n\n if ((e)?.message === \"OLM.UNKNOWN_MESSAGE_INDEX\") {\n this.requestKeysForEvent(event);\n\n errorCode = \"OLM_UNKNOWN_MESSAGE_INDEX\";\n }\n\n throw new DecryptionError(errorCode, e instanceof Error ? e.message : \"Unknown Error: Error is undefined\", {\n session: content.sender_key + \"|\" + content.session_id,\n });\n }\n\n if (res === null) {\n // We've got a message for a session we don't have.\n // try and get the missing key from the backup first\n this.crypto.backupManager.queryKeyBackupRateLimited(event.getRoomId(), content.session_id).catch(() => {});\n\n // (XXX: We might actually have received this key since we started\n // decrypting, in which case we'll have scheduled a retry, and this\n // request will be redundant. We could probably check to see if the\n // event is still in the pending list; if not, a retry will have been\n // scheduled, so we needn't send out the request here.)\n this.requestKeysForEvent(event);\n\n // See if there was a problem with the olm session at the time the\n // event was sent. Use a fuzz factor of 2 minutes.\n const problem = await this.olmDevice.sessionMayHaveProblems(content.sender_key, event.getTs() - 120000);\n if (problem) {\n this.prefixedLogger.info(\n `When handling UISI from ${event.getSender()} (sender key ${content.sender_key}): ` +\n `recent session problem with that sender:`,\n problem,\n );\n let problemDescription = PROBLEM_DESCRIPTIONS[problem.type as \"no_olm\"] || PROBLEM_DESCRIPTIONS.unknown;\n if (problem.fixed) {\n problemDescription += \" Trying to create a new secure channel and re-requesting the keys.\";\n }\n throw new DecryptionError(\"MEGOLM_UNKNOWN_INBOUND_SESSION_ID\", problemDescription, {\n session: content.sender_key + \"|\" + content.session_id,\n });\n }\n\n throw new DecryptionError(\n \"MEGOLM_UNKNOWN_INBOUND_SESSION_ID\",\n \"The sender's device has not sent us the keys for this message.\",\n {\n session: content.sender_key + \"|\" + content.session_id,\n },\n );\n }\n\n // Success. We can remove the event from the pending list, if\n // that hasn't already happened. However, if the event was\n // decrypted with an untrusted key, leave it on the pending\n // list so it will be retried if we find a trusted key later.\n if (!res.untrusted) {\n this.removeEventFromPendingList(event);\n }\n\n const payload = JSON.parse(res.result);\n\n // belt-and-braces check that the room id matches that indicated by the HS\n // (this is somewhat redundant, since the megolm session is scoped to the\n // room, so neither the sender nor a MITM can lie about the room_id).\n if (payload.room_id !== event.getRoomId()) {\n throw new DecryptionError(\"MEGOLM_BAD_ROOM\", \"Message intended for room \" + payload.room_id);\n }\n\n return {\n clearEvent: payload,\n senderCurve25519Key: res.senderKey,\n claimedEd25519Key: res.keysClaimed.ed25519,\n forwardingCurve25519KeyChain: res.forwardingCurve25519KeyChain,\n untrusted: res.untrusted,\n };\n }\n\n private requestKeysForEvent(event: MatrixEvent): void {\n const wireContent = event.getWireContent();\n\n const recipients = event.getKeyRequestRecipients(this.userId);\n\n this.crypto.requestRoomKey(\n {\n room_id: event.getRoomId()!,\n algorithm: wireContent.algorithm,\n sender_key: wireContent.sender_key,\n session_id: wireContent.session_id,\n },\n recipients,\n );\n }\n\n /**\n * Add an event to the list of those awaiting their session keys.\n *\n * @internal\n *\n */\n private addEventToPendingList(event: MatrixEvent): void {\n const content = event.getWireContent();\n const senderKey = content.sender_key;\n const sessionId = content.session_id;\n if (!this.pendingEvents.has(senderKey)) {\n this.pendingEvents.set(senderKey, new Map>());\n }\n const senderPendingEvents = this.pendingEvents.get(senderKey)!;\n if (!senderPendingEvents.has(sessionId)) {\n senderPendingEvents.set(sessionId, new Set());\n }\n senderPendingEvents.get(sessionId)?.add(event);\n }\n\n /**\n * Remove an event from the list of those awaiting their session keys.\n *\n * @internal\n *\n */\n private removeEventFromPendingList(event: MatrixEvent): void {\n const content = event.getWireContent();\n const senderKey = content.sender_key;\n const sessionId = content.session_id;\n const senderPendingEvents = this.pendingEvents.get(senderKey);\n const pendingEvents = senderPendingEvents?.get(sessionId);\n if (!pendingEvents) {\n return;\n }\n\n pendingEvents.delete(event);\n if (pendingEvents.size === 0) {\n senderPendingEvents!.delete(sessionId);\n }\n if (senderPendingEvents!.size === 0) {\n this.pendingEvents.delete(senderKey);\n }\n }\n\n /**\n * Parse a RoomKey out of an `m.room_key` event.\n *\n * @param event - the event containing the room key.\n *\n * @returns The `RoomKey` if it could be successfully parsed out of the\n * event.\n *\n * @internal\n *\n */\n private roomKeyFromEvent(event: MatrixEvent): RoomKey | undefined {\n const senderKey = event.getSenderKey()!;\n const content = event.getContent>();\n const extraSessionData: OlmGroupSessionExtraData = {};\n\n if (!content.room_id || !content.session_key || !content.session_id || !content.algorithm) {\n this.prefixedLogger.error(\"key event is missing fields\");\n return;\n }\n\n if (!olmlib.isOlmEncrypted(event)) {\n this.prefixedLogger.error(\"key event not properly encrypted\");\n return;\n }\n\n if (content[\"org.matrix.msc3061.shared_history\"]) {\n extraSessionData.sharedHistory = true;\n }\n\n const roomKey: RoomKey = {\n senderKey: senderKey,\n sessionId: content.session_id,\n sessionKey: content.session_key,\n extraSessionData,\n exportFormat: false,\n roomId: content.room_id,\n algorithm: content.algorithm,\n forwardingKeyChain: [],\n keysClaimed: event.getKeysClaimed(),\n };\n\n return roomKey;\n }\n\n /**\n * Parse a RoomKey out of an `m.forwarded_room_key` event.\n *\n * @param event - the event containing the forwarded room key.\n *\n * @returns The `RoomKey` if it could be successfully parsed out of the\n * event.\n *\n * @internal\n *\n */\n private forwardedRoomKeyFromEvent(event: MatrixEvent): RoomKey | undefined {\n // the properties in m.forwarded_room_key are a superset of those in m.room_key, so\n // start by parsing the m.room_key fields.\n const roomKey = this.roomKeyFromEvent(event);\n\n if (!roomKey) {\n return;\n }\n\n const senderKey = event.getSenderKey()!;\n const content = event.getContent>();\n\n const senderKeyUser = this.baseApis.crypto!.deviceList.getUserByIdentityKey(olmlib.OLM_ALGORITHM, senderKey);\n\n // We received this to-device event from event.getSenderKey(), but the original\n // creator of the room key is claimed in the content.\n const claimedCurve25519Key = content.sender_key;\n const claimedEd25519Key = content.sender_claimed_ed25519_key;\n\n let forwardingKeyChain = Array.isArray(content.forwarding_curve25519_key_chain)\n ? content.forwarding_curve25519_key_chain\n : [];\n\n // copy content before we modify it\n forwardingKeyChain = forwardingKeyChain.slice();\n forwardingKeyChain.push(senderKey);\n\n // Check if we have all the fields we need.\n if (senderKeyUser !== event.getSender()) {\n this.prefixedLogger.error(\"sending device does not belong to the user it claims to be from\");\n return;\n }\n\n if (!claimedCurve25519Key) {\n this.prefixedLogger.error(\"forwarded_room_key event is missing sender_key field\");\n return;\n }\n\n if (!claimedEd25519Key) {\n this.prefixedLogger.error(`forwarded_room_key_event is missing sender_claimed_ed25519_key field`);\n return;\n }\n\n const keysClaimed = {\n ed25519: claimedEd25519Key,\n };\n\n // FIXME: We're reusing the same field to track both:\n //\n // 1. The Olm identity we've received this room key from.\n // 2. The Olm identity deduced (in the trusted case) or claiming (in the\n // untrusted case) to be the original creator of this room key.\n //\n // We now overwrite the value tracking usage 1 with the value tracking usage 2.\n roomKey.senderKey = claimedCurve25519Key;\n // Replace our keysClaimed as well.\n roomKey.keysClaimed = keysClaimed;\n roomKey.exportFormat = true;\n roomKey.forwardingKeyChain = forwardingKeyChain;\n // forwarded keys are always untrusted\n roomKey.extraSessionData.untrusted = true;\n\n return roomKey;\n }\n\n /**\n * Determine if we should accept the forwarded room key that was found in the given\n * event.\n *\n * @param event - An `m.forwarded_room_key` event.\n * @param roomKey - The room key that was found in the event.\n *\n * @returns promise that will resolve to a boolean telling us if it's ok to\n * accept the given forwarded room key.\n *\n * @internal\n *\n */\n private async shouldAcceptForwardedKey(event: MatrixEvent, roomKey: RoomKey): Promise {\n const senderKey = event.getSenderKey()!;\n\n const sendingDevice =\n this.crypto.deviceList.getDeviceByIdentityKey(olmlib.OLM_ALGORITHM, senderKey) ?? undefined;\n const deviceTrust = this.crypto.checkDeviceInfoTrust(event.getSender()!, sendingDevice);\n\n // Using the plaintext sender here is fine since we checked that the\n // sender matches to the user id in the device keys when this event was\n // originally decrypted. This can obviously only happen if the device\n // keys have been downloaded, but if they haven't the\n // `deviceTrust.isVerified()` flag would be false as well.\n //\n // It would still be far nicer if the `sendingDevice` had a user ID\n // attached to it that went through signature checks.\n const fromUs = event.getSender() === this.baseApis.getUserId();\n const keyFromOurVerifiedDevice = deviceTrust.isVerified() && fromUs;\n const weRequested = await this.wasRoomKeyRequested(event, roomKey);\n const fromInviter = this.wasRoomKeyForwardedByInviter(event, roomKey);\n const sharedAsHistory = this.wasRoomKeyForwardedAsHistory(roomKey);\n\n return (weRequested && keyFromOurVerifiedDevice) || (fromInviter && sharedAsHistory);\n }\n\n /**\n * Did we ever request the given room key from the event sender and its\n * accompanying device.\n *\n * @param event - An `m.forwarded_room_key` event.\n * @param roomKey - The room key that was found in the event.\n *\n * @internal\n *\n */\n private async wasRoomKeyRequested(event: MatrixEvent, roomKey: RoomKey): Promise {\n // We send the `m.room_key_request` out as a wildcard to-device request,\n // otherwise we would have to duplicate the same content for each\n // device. This is why we need to pass in \"*\" as the device id here.\n const outgoingRequests = await this.crypto.cryptoStore.getOutgoingRoomKeyRequestsByTarget(\n event.getSender()!,\n \"*\",\n [RoomKeyRequestState.Sent],\n );\n\n return outgoingRequests.some(\n (req) => req.requestBody.room_id === roomKey.roomId && req.requestBody.session_id === roomKey.sessionId,\n );\n }\n\n private wasRoomKeyForwardedByInviter(event: MatrixEvent, roomKey: RoomKey): boolean {\n // TODO: This is supposed to have a time limit. We should only accept\n // such keys if we happen to receive them for a recently joined room.\n const room = this.baseApis.getRoom(roomKey.roomId);\n const senderKey = event.getSenderKey();\n\n if (!senderKey) {\n return false;\n }\n\n const senderKeyUser = this.crypto.deviceList.getUserByIdentityKey(olmlib.OLM_ALGORITHM, senderKey);\n\n if (!senderKeyUser) {\n return false;\n }\n\n const memberEvent = room?.getMember(this.userId)?.events.member;\n const fromInviter =\n memberEvent?.getSender() === senderKeyUser ||\n (memberEvent?.getUnsigned()?.prev_sender === senderKeyUser &&\n memberEvent?.getPrevContent()?.membership === \"invite\");\n\n if (room && fromInviter) {\n return true;\n } else {\n return false;\n }\n }\n\n private wasRoomKeyForwardedAsHistory(roomKey: RoomKey): boolean {\n const room = this.baseApis.getRoom(roomKey.roomId);\n\n // If the key is not for a known room, then something fishy is going on,\n // so we reject the key out of caution. In practice, this is a bit moot\n // because we'll only accept shared_history forwarded by the inviter, and\n // we won't know who was the inviter for an unknown room, so we'll reject\n // it anyway.\n if (room && roomKey.extraSessionData.sharedHistory) {\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Check if a forwarded room key should be parked.\n *\n * A forwarded room key should be parked if it's a key for a room we're not\n * in. We park the forwarded room key in case *this sender* invites us to\n * that room later.\n */\n private shouldParkForwardedKey(roomKey: RoomKey): boolean {\n const room = this.baseApis.getRoom(roomKey.roomId);\n\n if (!room && roomKey.extraSessionData.sharedHistory) {\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * Park the given room key to our store.\n *\n * @param event - An `m.forwarded_room_key` event.\n * @param roomKey - The room key that was found in the event.\n *\n * @internal\n *\n */\n private async parkForwardedKey(event: MatrixEvent, roomKey: RoomKey): Promise {\n const parkedData = {\n senderId: event.getSender()!,\n senderKey: roomKey.senderKey,\n sessionId: roomKey.sessionId,\n sessionKey: roomKey.sessionKey,\n keysClaimed: roomKey.keysClaimed,\n forwardingCurve25519KeyChain: roomKey.forwardingKeyChain,\n };\n await this.crypto.cryptoStore.doTxn(\n \"readwrite\",\n [\"parked_shared_history\"],\n (txn) => this.crypto.cryptoStore.addParkedSharedHistory(roomKey.roomId, parkedData, txn),\n logger.withPrefix(\"[addParkedSharedHistory]\"),\n );\n }\n\n /**\n * Add the given room key to our store.\n *\n * @param roomKey - The room key that should be added to the store.\n *\n * @internal\n *\n */\n private async addRoomKey(roomKey: RoomKey): Promise {\n try {\n await this.olmDevice.addInboundGroupSession(\n roomKey.roomId,\n roomKey.senderKey,\n roomKey.forwardingKeyChain,\n roomKey.sessionId,\n roomKey.sessionKey,\n roomKey.keysClaimed,\n roomKey.exportFormat,\n roomKey.extraSessionData,\n );\n\n // have another go at decrypting events sent with this session.\n if (await this.retryDecryption(roomKey.senderKey, roomKey.sessionId, !roomKey.extraSessionData.untrusted)) {\n // cancel any outstanding room key requests for this session.\n // Only do this if we managed to decrypt every message in the\n // session, because if we didn't, we leave the other key\n // requests in the hopes that someone sends us a key that\n // includes an earlier index.\n this.crypto.cancelRoomKeyRequest({\n algorithm: roomKey.algorithm,\n room_id: roomKey.roomId,\n session_id: roomKey.sessionId,\n sender_key: roomKey.senderKey,\n });\n }\n\n // don't wait for the keys to be backed up for the server\n await this.crypto.backupManager.backupGroupSession(roomKey.senderKey, roomKey.sessionId);\n } catch (e) {\n this.prefixedLogger.error(`Error handling m.room_key_event: ${e}`);\n }\n }\n\n /**\n * Handle room keys that have been forwarded to us as an\n * `m.forwarded_room_key` event.\n *\n * Forwarded room keys need special handling since we have no way of knowing\n * who the original creator of the room key was. This naturally means that\n * forwarded room keys are always untrusted and should only be accepted in\n * some cases.\n *\n * @param event - An `m.forwarded_room_key` event.\n *\n * @internal\n *\n */\n private async onForwardedRoomKey(event: MatrixEvent): Promise {\n const roomKey = this.forwardedRoomKeyFromEvent(event);\n\n if (!roomKey) {\n return;\n }\n\n if (await this.shouldAcceptForwardedKey(event, roomKey)) {\n await this.addRoomKey(roomKey);\n } else if (this.shouldParkForwardedKey(roomKey)) {\n await this.parkForwardedKey(event, roomKey);\n }\n }\n\n public async onRoomKeyEvent(event: MatrixEvent): Promise {\n if (event.getType() == \"m.forwarded_room_key\") {\n await this.onForwardedRoomKey(event);\n } else {\n const roomKey = this.roomKeyFromEvent(event);\n\n if (!roomKey) {\n return;\n }\n\n await this.addRoomKey(roomKey);\n }\n }\n\n /**\n * @param event - key event\n */\n public async onRoomKeyWithheldEvent(event: MatrixEvent): Promise {\n const content = event.getContent();\n const senderKey = content.sender_key;\n\n if (content.code === \"m.no_olm\") {\n await this.onNoOlmWithheldEvent(event);\n } else if (content.code === \"m.unavailable\") {\n // this simply means that the other device didn't have the key, which isn't very useful information. Don't\n // record it in the storage\n } else {\n await this.olmDevice.addInboundGroupSessionWithheld(\n content.room_id,\n senderKey,\n content.session_id,\n content.code,\n content.reason,\n );\n }\n\n // Having recorded the problem, retry decryption on any affected messages.\n // It's unlikely we'll be able to decrypt sucessfully now, but this will\n // update the error message.\n //\n if (content.session_id) {\n await this.retryDecryption(senderKey, content.session_id);\n } else {\n // no_olm messages aren't specific to a given megolm session, so\n // we trigger retrying decryption for all the messages from the sender's\n // key, so that we can update the error message to indicate the olm\n // session problem.\n await this.retryDecryptionFromSender(senderKey);\n }\n }\n\n private async onNoOlmWithheldEvent(event: MatrixEvent): Promise {\n const content = event.getContent();\n const senderKey = content.sender_key;\n const sender = event.getSender()!;\n this.prefixedLogger.warn(`${sender}:${senderKey} was unable to establish an olm session with us`);\n // if the sender says that they haven't been able to establish an olm\n // session, let's proactively establish one\n\n if (await this.olmDevice.getSessionIdForDevice(senderKey)) {\n // a session has already been established, so we don't need to\n // create a new one.\n this.prefixedLogger.debug(\"New session already created. Not creating a new one.\");\n await this.olmDevice.recordSessionProblem(senderKey, \"no_olm\", true);\n return;\n }\n let device = this.crypto.deviceList.getDeviceByIdentityKey(content.algorithm, senderKey);\n if (!device) {\n // if we don't know about the device, fetch the user's devices again\n // and retry before giving up\n await this.crypto.downloadKeys([sender], false);\n device = this.crypto.deviceList.getDeviceByIdentityKey(content.algorithm, senderKey);\n if (!device) {\n this.prefixedLogger.info(\n \"Couldn't find device for identity key \" + senderKey + \": not establishing session\",\n );\n await this.olmDevice.recordSessionProblem(senderKey, \"no_olm\", false);\n return;\n }\n }\n\n // XXX: switch this to use encryptAndSendToDevices() rather than duplicating it?\n\n await olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, new Map([[sender, [device]]]), false);\n const encryptedContent: IEncryptedContent = {\n algorithm: olmlib.OLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key!,\n ciphertext: {},\n [ToDeviceMessageId]: uuidv4(),\n };\n await olmlib.encryptMessageForDevice(\n encryptedContent.ciphertext,\n this.userId,\n undefined,\n this.olmDevice,\n sender,\n device,\n { type: \"m.dummy\" },\n );\n\n await this.olmDevice.recordSessionProblem(senderKey, \"no_olm\", true);\n\n await this.baseApis.sendToDevice(\n \"m.room.encrypted\",\n new Map([[sender, new Map([[device.deviceId, encryptedContent]])]]),\n );\n }\n\n public hasKeysForKeyRequest(keyRequest: IncomingRoomKeyRequest): Promise {\n const body = keyRequest.requestBody;\n\n return this.olmDevice.hasInboundSessionKeys(\n body.room_id,\n body.sender_key,\n body.session_id,\n // TODO: ratchet index\n );\n }\n\n public shareKeysWithDevice(keyRequest: IncomingRoomKeyRequest): void {\n const userId = keyRequest.userId;\n const deviceId = keyRequest.deviceId;\n const deviceInfo = this.crypto.getStoredDevice(userId, deviceId)!;\n const body = keyRequest.requestBody;\n\n // XXX: switch this to use encryptAndSendToDevices()?\n\n this.olmlib\n .ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, new Map([[userId, [deviceInfo]]]))\n .then((devicemap) => {\n const olmSessionResult = devicemap.get(userId)?.get(deviceId);\n if (!olmSessionResult?.sessionId) {\n // no session with this device, probably because there\n // were no one-time keys.\n //\n // ensureOlmSessionsForUsers has already done the logging,\n // so just skip it.\n return null;\n }\n\n this.prefixedLogger.log(\n \"sharing keys for session \" +\n body.sender_key +\n \"|\" +\n body.session_id +\n \" with device \" +\n userId +\n \":\" +\n deviceId,\n );\n\n return this.buildKeyForwardingMessage(body.room_id, body.sender_key, body.session_id);\n })\n .then((payload) => {\n const encryptedContent: IEncryptedContent = {\n algorithm: olmlib.OLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key!,\n ciphertext: {},\n [ToDeviceMessageId]: uuidv4(),\n };\n\n return this.olmlib\n .encryptMessageForDevice(\n encryptedContent.ciphertext,\n this.userId,\n undefined,\n this.olmDevice,\n userId,\n deviceInfo,\n payload!,\n )\n .then(() => {\n // TODO: retries\n return this.baseApis.sendToDevice(\n \"m.room.encrypted\",\n new Map([[userId, new Map([[deviceId, encryptedContent]])]]),\n );\n });\n });\n }\n\n private async buildKeyForwardingMessage(\n roomId: string,\n senderKey: string,\n sessionId: string,\n ): Promise {\n const key = await this.olmDevice.getInboundGroupSessionKey(roomId, senderKey, sessionId);\n\n return {\n type: \"m.forwarded_room_key\",\n content: {\n \"algorithm\": olmlib.MEGOLM_ALGORITHM,\n \"room_id\": roomId,\n \"sender_key\": senderKey,\n \"sender_claimed_ed25519_key\": key!.sender_claimed_ed25519_key!,\n \"session_id\": sessionId,\n \"session_key\": key!.key,\n \"chain_index\": key!.chain_index,\n \"forwarding_curve25519_key_chain\": key!.forwarding_curve25519_key_chain,\n \"org.matrix.msc3061.shared_history\": key!.shared_history || false,\n },\n };\n }\n\n /**\n * @param untrusted - whether the key should be considered as untrusted\n * @param source - where the key came from\n */\n public importRoomKey(\n session: IMegolmSessionData,\n { untrusted, source }: { untrusted?: boolean; source?: string } = {},\n ): Promise {\n const extraSessionData: OlmGroupSessionExtraData = {};\n if (untrusted || session.untrusted) {\n extraSessionData.untrusted = true;\n }\n if (session[\"org.matrix.msc3061.shared_history\"]) {\n extraSessionData.sharedHistory = true;\n }\n return this.olmDevice\n .addInboundGroupSession(\n session.room_id,\n session.sender_key,\n session.forwarding_curve25519_key_chain,\n session.session_id,\n session.session_key,\n session.sender_claimed_keys,\n true,\n extraSessionData,\n )\n .then(() => {\n if (source !== \"backup\") {\n // don't wait for it to complete\n this.crypto.backupManager.backupGroupSession(session.sender_key, session.session_id).catch((e) => {\n // This throws if the upload failed, but this is fine\n // since it will have written it to the db and will retry.\n this.prefixedLogger.log(\"Failed to back up megolm session\", e);\n });\n }\n // have another go at decrypting events sent with this session.\n this.retryDecryption(session.sender_key, session.session_id, !extraSessionData.untrusted);\n });\n }\n\n /**\n * Have another go at decrypting events after we receive a key. Resolves once\n * decryption has been re-attempted on all events.\n *\n * @internal\n * @param forceRedecryptIfUntrusted - whether messages that were already\n * successfully decrypted using untrusted keys should be re-decrypted\n *\n * @returns whether all messages were successfully\n * decrypted with trusted keys\n */\n private async retryDecryption(\n senderKey: string,\n sessionId: string,\n forceRedecryptIfUntrusted?: boolean,\n ): Promise {\n const senderPendingEvents = this.pendingEvents.get(senderKey);\n if (!senderPendingEvents) {\n return true;\n }\n\n const pending = senderPendingEvents.get(sessionId);\n if (!pending) {\n return true;\n }\n\n const pendingList = [...pending];\n this.prefixedLogger.debug(\n \"Retrying decryption on events:\",\n pendingList.map((e) => `${e.getId()}`),\n );\n\n await Promise.all(\n pendingList.map(async (ev) => {\n try {\n await ev.attemptDecryption(this.crypto, { isRetry: true, forceRedecryptIfUntrusted });\n } catch (e) {\n // don't die if something goes wrong\n }\n }),\n );\n\n // If decrypted successfully with trusted keys, they'll have\n // been removed from pendingEvents\n return !this.pendingEvents.get(senderKey)?.has(sessionId);\n }\n\n public async retryDecryptionFromSender(senderKey: string): Promise {\n const senderPendingEvents = this.pendingEvents.get(senderKey);\n if (!senderPendingEvents) {\n return true;\n }\n\n this.pendingEvents.delete(senderKey);\n\n await Promise.all(\n [...senderPendingEvents].map(async ([_sessionId, pending]) => {\n await Promise.all(\n [...pending].map(async (ev) => {\n try {\n await ev.attemptDecryption(this.crypto);\n } catch (e) {\n // don't die if something goes wrong\n }\n }),\n );\n }),\n );\n\n return !this.pendingEvents.has(senderKey);\n }\n\n public async sendSharedHistoryInboundSessions(devicesByUser: Map): Promise {\n await olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, devicesByUser);\n\n const sharedHistorySessions = await this.olmDevice.getSharedHistoryInboundGroupSessions(this.roomId);\n this.prefixedLogger.log(\n `Sharing history in with users ${Array.from(devicesByUser.keys())}`,\n sharedHistorySessions.map(([senderKey, sessionId]) => `${senderKey}|${sessionId}`),\n );\n for (const [senderKey, sessionId] of sharedHistorySessions) {\n const payload = await this.buildKeyForwardingMessage(this.roomId, senderKey, sessionId);\n\n // FIXME: use encryptAndSendToDevices() rather than duplicating it here.\n const promises: Promise[] = [];\n const contentMap: Map> = new Map();\n for (const [userId, devices] of devicesByUser) {\n const deviceMessages = new Map();\n contentMap.set(userId, deviceMessages);\n for (const deviceInfo of devices) {\n const encryptedContent: IEncryptedContent = {\n algorithm: olmlib.OLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key!,\n ciphertext: {},\n [ToDeviceMessageId]: uuidv4(),\n };\n deviceMessages.set(deviceInfo.deviceId, encryptedContent);\n promises.push(\n olmlib.encryptMessageForDevice(\n encryptedContent.ciphertext,\n this.userId,\n undefined,\n this.olmDevice,\n userId,\n deviceInfo,\n payload,\n ),\n );\n }\n }\n await Promise.all(promises);\n\n // prune out any devices that encryptMessageForDevice could not encrypt for,\n // in which case it will have just not added anything to the ciphertext object.\n // There's no point sending messages to devices if we couldn't encrypt to them,\n // since that's effectively a blank message.\n for (const [userId, deviceMessages] of contentMap) {\n for (const [deviceId, content] of deviceMessages) {\n if (!hasCiphertext(content)) {\n this.prefixedLogger.log(\"No ciphertext for device \" + userId + \":\" + deviceId + \": pruning\");\n deviceMessages.delete(deviceId);\n }\n }\n // No devices left for that user? Strip that too.\n if (deviceMessages.size === 0) {\n this.prefixedLogger.log(\"Pruned all devices for user \" + userId);\n contentMap.delete(userId);\n }\n }\n\n // Is there anything left?\n if (contentMap.size === 0) {\n this.prefixedLogger.log(\"No users left to send to: aborting\");\n return;\n }\n\n await this.baseApis.sendToDevice(\"m.room.encrypted\", contentMap);\n }\n }\n}\n\nconst PROBLEM_DESCRIPTIONS = {\n no_olm: \"The sender was unable to establish a secure channel.\",\n unknown: \"The secure channel with the sender was corrupted.\",\n};\n\nregisterAlgorithm(olmlib.MEGOLM_ALGORITHM, MegolmEncryption, MegolmDecryption);\n", - "/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Defines m.olm encryption/decryption\n */\n\nimport type { IEventDecryptionResult } from \"../../@types/crypto\";\nimport { logger } from \"../../logger\";\nimport * as olmlib from \"../olmlib\";\nimport { DeviceInfo } from \"../deviceinfo\";\nimport { DecryptionAlgorithm, DecryptionError, EncryptionAlgorithm, registerAlgorithm } from \"./base\";\nimport { Room } from \"../../models/room\";\nimport { IContent, MatrixEvent } from \"../../models/event\";\nimport { IEncryptedContent, IOlmEncryptedContent } from \"../index\";\nimport { IInboundSession } from \"../OlmDevice\";\n\nconst DeviceVerification = DeviceInfo.DeviceVerification;\n\nexport interface IMessage {\n type: number;\n body: string;\n}\n\n/**\n * Olm encryption implementation\n *\n * @param params - parameters, as per {@link EncryptionAlgorithm}\n */\nclass OlmEncryption extends EncryptionAlgorithm {\n private sessionPrepared = false;\n private prepPromise: Promise | null = null;\n\n /**\n * @internal\n\n * @param roomMembers - list of currently-joined users in the room\n * @returns Promise which resolves when setup is complete\n */\n private ensureSession(roomMembers: string[]): Promise {\n if (this.prepPromise) {\n // prep already in progress\n return this.prepPromise;\n }\n\n if (this.sessionPrepared) {\n // prep already done\n return Promise.resolve();\n }\n\n this.prepPromise = this.crypto\n .downloadKeys(roomMembers)\n .then(() => {\n return this.crypto.ensureOlmSessionsForUsers(roomMembers);\n })\n .then(() => {\n this.sessionPrepared = true;\n })\n .finally(() => {\n this.prepPromise = null;\n });\n\n return this.prepPromise;\n }\n\n /**\n * @param content - plaintext event content\n *\n * @returns Promise which resolves to the new event body\n */\n public async encryptMessage(room: Room, eventType: string, content: IContent): Promise {\n // pick the list of recipients based on the membership list.\n //\n // TODO: there is a race condition here! What if a new user turns up\n // just as you are sending a secret message?\n\n const members = await room.getEncryptionTargetMembers();\n\n const users = members.map(function (u) {\n return u.userId;\n });\n\n await this.ensureSession(users);\n\n const payloadFields = {\n room_id: room.roomId,\n type: eventType,\n content: content,\n };\n\n const encryptedContent: IEncryptedContent = {\n algorithm: olmlib.OLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key!,\n ciphertext: {},\n };\n\n const promises: Promise[] = [];\n\n for (const userId of users) {\n const devices = this.crypto.getStoredDevicesForUser(userId) || [];\n\n for (const deviceInfo of devices) {\n const key = deviceInfo.getIdentityKey();\n if (key == this.olmDevice.deviceCurve25519Key) {\n // don't bother sending to ourself\n continue;\n }\n if (deviceInfo.verified == DeviceVerification.BLOCKED) {\n // don't bother setting up sessions with blocked users\n continue;\n }\n\n promises.push(\n olmlib.encryptMessageForDevice(\n encryptedContent.ciphertext,\n this.userId,\n this.deviceId,\n this.olmDevice,\n userId,\n deviceInfo,\n payloadFields,\n ),\n );\n }\n }\n\n return Promise.all(promises).then(() => encryptedContent);\n }\n}\n\n/**\n * Olm decryption implementation\n *\n * @param params - parameters, as per {@link DecryptionAlgorithm}\n */\nclass OlmDecryption extends DecryptionAlgorithm {\n /**\n * returns a promise which resolves to a\n * {@link EventDecryptionResult} once we have finished\n * decrypting. Rejects with an `algorithms.DecryptionError` if there is a\n * problem decrypting the event.\n */\n public async decryptEvent(event: MatrixEvent): Promise {\n const content = event.getWireContent();\n const deviceKey = content.sender_key;\n const ciphertext = content.ciphertext;\n\n if (!ciphertext) {\n throw new DecryptionError(\"OLM_MISSING_CIPHERTEXT\", \"Missing ciphertext\");\n }\n\n if (!(this.olmDevice.deviceCurve25519Key! in ciphertext)) {\n throw new DecryptionError(\"OLM_NOT_INCLUDED_IN_RECIPIENTS\", \"Not included in recipients\");\n }\n const message = ciphertext[this.olmDevice.deviceCurve25519Key!];\n let payloadString: string;\n\n try {\n payloadString = await this.decryptMessage(deviceKey, message);\n } catch (e) {\n throw new DecryptionError(\"OLM_BAD_ENCRYPTED_MESSAGE\", \"Bad Encrypted Message\", {\n sender: deviceKey,\n err: e as Error,\n });\n }\n\n const payload = JSON.parse(payloadString);\n\n // check that we were the intended recipient, to avoid unknown-key attack\n // https://github.com/vector-im/vector-web/issues/2483\n if (payload.recipient != this.userId) {\n throw new DecryptionError(\"OLM_BAD_RECIPIENT\", \"Message was intented for \" + payload.recipient);\n }\n\n if (payload.recipient_keys.ed25519 != this.olmDevice.deviceEd25519Key) {\n throw new DecryptionError(\"OLM_BAD_RECIPIENT_KEY\", \"Message not intended for this device\", {\n intended: payload.recipient_keys.ed25519,\n our_key: this.olmDevice.deviceEd25519Key!,\n });\n }\n\n // check that the device that encrypted the event belongs to the user\n // that the event claims it's from. We need to make sure that our\n // device list is up-to-date. If the device is unknown, we can only\n // assume that the device logged out. Some event handlers, such as\n // secret sharing, may be more strict and reject events that come from\n // unknown devices.\n await this.crypto.deviceList.downloadKeys([event.getSender()!], false);\n const senderKeyUser = this.crypto.deviceList.getUserByIdentityKey(olmlib.OLM_ALGORITHM, deviceKey);\n if (senderKeyUser !== event.getSender() && senderKeyUser != undefined) {\n throw new DecryptionError(\"OLM_BAD_SENDER\", \"Message claimed to be from \" + event.getSender(), {\n real_sender: senderKeyUser,\n });\n }\n\n // check that the original sender matches what the homeserver told us, to\n // avoid people masquerading as others.\n // (this check is also provided via the sender's embedded ed25519 key,\n // which is checked elsewhere).\n if (payload.sender != event.getSender()) {\n throw new DecryptionError(\"OLM_FORWARDED_MESSAGE\", \"Message forwarded from \" + payload.sender, {\n reported_sender: event.getSender()!,\n });\n }\n\n // Olm events intended for a room have a room_id.\n if (payload.room_id !== event.getRoomId()) {\n throw new DecryptionError(\"OLM_BAD_ROOM\", \"Message intended for room \" + payload.room_id, {\n reported_room: event.getRoomId() || \"ROOM_ID_UNDEFINED\",\n });\n }\n\n const claimedKeys = payload.keys || {};\n\n return {\n clearEvent: payload,\n senderCurve25519Key: deviceKey,\n claimedEd25519Key: claimedKeys.ed25519 || null,\n };\n }\n\n /**\n * Attempt to decrypt an Olm message\n *\n * @param theirDeviceIdentityKey - Curve25519 identity key of the sender\n * @param message - message object, with 'type' and 'body' fields\n *\n * @returns payload, if decrypted successfully.\n */\n private decryptMessage(theirDeviceIdentityKey: string, message: IMessage): Promise {\n // This is a wrapper that serialises decryptions of prekey messages, because\n // otherwise we race between deciding we have no active sessions for the message\n // and creating a new one, which we can only do once because it removes the OTK.\n if (message.type !== 0) {\n // not a prekey message: we can safely just try & decrypt it\n return this.reallyDecryptMessage(theirDeviceIdentityKey, message);\n } else {\n const myPromise = this.olmDevice.olmPrekeyPromise.then(() => {\n return this.reallyDecryptMessage(theirDeviceIdentityKey, message);\n });\n // we want the error, but don't propagate it to the next decryption\n this.olmDevice.olmPrekeyPromise = myPromise.catch(() => {});\n return myPromise;\n }\n }\n\n private async reallyDecryptMessage(theirDeviceIdentityKey: string, message: IMessage): Promise {\n const sessionIds = await this.olmDevice.getSessionIdsForDevice(theirDeviceIdentityKey);\n\n // try each session in turn.\n const decryptionErrors: Record = {};\n for (const sessionId of sessionIds) {\n try {\n const payload = await this.olmDevice.decryptMessage(\n theirDeviceIdentityKey,\n sessionId,\n message.type,\n message.body,\n );\n logger.log(\"Decrypted Olm message from \" + theirDeviceIdentityKey + \" with session \" + sessionId);\n return payload;\n } catch (e) {\n const foundSession = await this.olmDevice.matchesSession(\n theirDeviceIdentityKey,\n sessionId,\n message.type,\n message.body,\n );\n\n if (foundSession) {\n // decryption failed, but it was a prekey message matching this\n // session, so it should have worked.\n throw new Error(\n \"Error decrypting prekey message with existing session id \" +\n sessionId +\n \": \" +\n (e).message,\n );\n }\n\n // otherwise it's probably a message for another session; carry on, but\n // keep a record of the error\n decryptionErrors[sessionId] = (e).message;\n }\n }\n\n if (message.type !== 0) {\n // not a prekey message, so it should have matched an existing session, but it\n // didn't work.\n\n if (sessionIds.length === 0) {\n throw new Error(\"No existing sessions\");\n }\n\n throw new Error(\n \"Error decrypting non-prekey message with existing sessions: \" + JSON.stringify(decryptionErrors),\n );\n }\n\n // prekey message which doesn't match any existing sessions: make a new\n // session.\n\n let res: IInboundSession;\n try {\n res = await this.olmDevice.createInboundSession(theirDeviceIdentityKey, message.type, message.body);\n } catch (e) {\n decryptionErrors[\"(new)\"] = (e).message;\n throw new Error(\"Error decrypting prekey message: \" + JSON.stringify(decryptionErrors));\n }\n\n logger.log(\"created new inbound Olm session ID \" + res.session_id + \" with \" + theirDeviceIdentityKey);\n return res.payload;\n }\n}\n\nregisterAlgorithm(olmlib.OLM_ALGORITHM, OlmEncryption, OlmDecryption);\n", - "/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { DeviceInfo } from \"./deviceinfo\";\nimport { IKeyBackupInfo } from \"./keybackup\";\nimport { PassphraseInfo } from \"../secret-storage\";\n\n/* re-exports for backwards compatibility. */\nexport {\n PassphraseInfo as IPassphraseInfo,\n SecretStorageKeyDescription as ISecretStorageKeyInfo,\n} from \"../secret-storage\";\n\n// TODO: Merge this with crypto.js once converted\n\nexport enum CrossSigningKey {\n Master = \"master\",\n SelfSigning = \"self_signing\",\n UserSigning = \"user_signing\",\n}\n\nexport interface IEncryptedEventInfo {\n /**\n * whether the event is encrypted (if not encrypted, some of the other properties may not be set)\n */\n encrypted: boolean;\n\n /**\n * the sender's key\n */\n senderKey: string;\n\n /**\n * the algorithm used to encrypt the event\n */\n algorithm: string;\n\n /**\n * whether we can be sure that the owner of the senderKey sent the event\n */\n authenticated: boolean;\n\n /**\n * the sender's device information, if available\n */\n sender?: DeviceInfo;\n\n /**\n * if the event's ed25519 and curve25519 keys don't match (only meaningful if `sender` is set)\n */\n mismatchedSender: boolean;\n}\n\nexport interface IRecoveryKey {\n keyInfo?: IAddSecretStorageKeyOpts;\n privateKey: Uint8Array;\n encodedPrivateKey?: string;\n}\n\nexport interface ICreateSecretStorageOpts {\n /**\n * Function called to await a secret storage key creation flow.\n * @returns Promise resolving to an object with public key metadata, encoded private\n * recovery key which should be disposed of after displaying to the user,\n * and raw private key to avoid round tripping if needed.\n */\n createSecretStorageKey?: () => Promise;\n\n /**\n * The current key backup object. If passed,\n * the passphrase and recovery key from this backup will be used.\n */\n keyBackupInfo?: IKeyBackupInfo;\n\n /**\n * If true, a new key backup version will be\n * created and the private key stored in the new SSSS store. Ignored if keyBackupInfo\n * is supplied.\n */\n setupNewKeyBackup?: boolean;\n\n /**\n * Reset even if keys already exist.\n */\n setupNewSecretStorage?: boolean;\n\n /**\n * Function called to get the user's\n * current key backup passphrase. Should return a promise that resolves with a Uint8Array\n * containing the key, or rejects if the key cannot be obtained.\n */\n getKeyBackupPassphrase?: () => Promise;\n}\n\nexport interface IAddSecretStorageKeyOpts {\n pubkey?: string;\n passphrase?: PassphraseInfo;\n name?: string;\n key?: Uint8Array;\n}\n\nexport interface IImportOpts {\n stage: string; // TODO: Enum\n successes: number;\n failures: number;\n total: number;\n}\n\nexport interface IImportRoomKeysOpts {\n /** called with an object that has a \"stage\" param */\n progressCallback?: (stage: IImportOpts) => void;\n untrusted?: boolean;\n source?: string; // TODO: Enum\n}\n", - "/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Classes for dealing with key backup.\n */\n\nimport type { IMegolmSessionData } from \"../@types/crypto\";\nimport { MatrixClient } from \"../client\";\nimport { logger } from \"../logger\";\nimport { MEGOLM_ALGORITHM, verifySignature } from \"./olmlib\";\nimport { DeviceInfo } from \"./deviceinfo\";\nimport { DeviceTrustLevel } from \"./CrossSigning\";\nimport { keyFromPassphrase } from \"./key_passphrase\";\nimport { safeSet, sleep } from \"../utils\";\nimport { IndexedDBCryptoStore } from \"./store/indexeddb-crypto-store\";\nimport { encodeRecoveryKey } from \"./recoverykey\";\nimport { calculateKeyCheck, decryptAES, encryptAES, IEncryptedPayload } from \"./aes\";\nimport {\n Curve25519SessionData,\n IAes256AuthData,\n ICurve25519AuthData,\n IKeyBackupInfo,\n IKeyBackupSession,\n} from \"./keybackup\";\nimport { UnstableValue } from \"../NamespacedValue\";\nimport { CryptoEvent } from \"./index\";\nimport { crypto } from \"./crypto\";\nimport { HTTPError, MatrixError } from \"../http-api\";\n\nconst KEY_BACKUP_KEYS_PER_REQUEST = 200;\nconst KEY_BACKUP_CHECK_RATE_LIMIT = 5000; // ms\n\ntype AuthData = IKeyBackupInfo[\"auth_data\"];\n\ntype SigInfo = {\n deviceId: string;\n valid?: boolean | null; // true: valid, false: invalid, null: cannot attempt validation\n device?: DeviceInfo | null;\n crossSigningId?: boolean;\n deviceTrust?: DeviceTrustLevel;\n};\n\nexport type TrustInfo = {\n usable: boolean; // is the backup trusted, true iff there is a sig that is valid & from a trusted device\n sigs: SigInfo[];\n // eslint-disable-next-line camelcase\n trusted_locally?: boolean;\n};\n\nexport interface IKeyBackupCheck {\n backupInfo?: IKeyBackupInfo;\n trustInfo: TrustInfo;\n}\n\n/* eslint-disable camelcase */\nexport interface IPreparedKeyBackupVersion {\n algorithm: string;\n auth_data: AuthData;\n recovery_key: string;\n privateKey: Uint8Array;\n}\n/* eslint-enable camelcase */\n\n/** A function used to get the secret key for a backup.\n */\ntype GetKey = () => Promise>;\n\ninterface BackupAlgorithmClass {\n algorithmName: string;\n // initialize from an existing backup\n init(authData: AuthData, getKey: GetKey): Promise;\n\n // prepare a brand new backup\n prepare(key?: string | Uint8Array | null): Promise<[Uint8Array, AuthData]>;\n\n checkBackupVersion(info: IKeyBackupInfo): void;\n}\n\ninterface BackupAlgorithm {\n untrusted: boolean;\n encryptSession(data: Record): Promise;\n decryptSessions(ciphertexts: Record): Promise;\n authData: AuthData;\n keyMatches(key: ArrayLike): Promise;\n free(): void;\n}\n\nexport interface IKeyBackup {\n rooms: {\n [roomId: string]: {\n sessions: {\n [sessionId: string]: IKeyBackupSession;\n };\n };\n };\n}\n\n/**\n * Manages the key backup.\n */\nexport class BackupManager {\n private algorithm: BackupAlgorithm | undefined;\n public backupInfo: IKeyBackupInfo | undefined; // The info dict from /room_keys/version\n public checkedForBackup: boolean; // Have we checked the server for a backup we can use?\n private sendingBackups: boolean; // Are we currently sending backups?\n private sessionLastCheckAttemptedTime: Record = {}; // When did we last try to check the server for a given session id?\n\n public constructor(private readonly baseApis: MatrixClient, public readonly getKey: GetKey) {\n this.checkedForBackup = false;\n this.sendingBackups = false;\n }\n\n public get version(): string | undefined {\n return this.backupInfo && this.backupInfo.version;\n }\n\n /**\n * Performs a quick check to ensure that the backup info looks sane.\n *\n * Throws an error if a problem is detected.\n *\n * @param info - the key backup info\n */\n public static checkBackupVersion(info: IKeyBackupInfo): void {\n const Algorithm = algorithmsByName[info.algorithm];\n if (!Algorithm) {\n throw new Error(\"Unknown backup algorithm: \" + info.algorithm);\n }\n if (typeof info.auth_data !== \"object\") {\n throw new Error(\"Invalid backup data returned\");\n }\n return Algorithm.checkBackupVersion(info);\n }\n\n public static makeAlgorithm(info: IKeyBackupInfo, getKey: GetKey): Promise {\n const Algorithm = algorithmsByName[info.algorithm];\n if (!Algorithm) {\n throw new Error(\"Unknown backup algorithm\");\n }\n return Algorithm.init(info.auth_data, getKey);\n }\n\n public async enableKeyBackup(info: IKeyBackupInfo): Promise {\n this.backupInfo = info;\n if (this.algorithm) {\n this.algorithm.free();\n }\n\n this.algorithm = await BackupManager.makeAlgorithm(info, this.getKey);\n\n this.baseApis.emit(CryptoEvent.KeyBackupStatus, true);\n\n // There may be keys left over from a partially completed backup, so\n // schedule a send to check.\n this.scheduleKeyBackupSend();\n }\n\n /**\n * Disable backing up of keys.\n */\n public disableKeyBackup(): void {\n if (this.algorithm) {\n this.algorithm.free();\n }\n this.algorithm = undefined;\n\n this.backupInfo = undefined;\n\n this.baseApis.emit(CryptoEvent.KeyBackupStatus, false);\n }\n\n public getKeyBackupEnabled(): boolean | null {\n if (!this.checkedForBackup) {\n return null;\n }\n return Boolean(this.algorithm);\n }\n\n public async prepareKeyBackupVersion(\n key?: string | Uint8Array | null,\n algorithm?: string | undefined,\n ): Promise {\n const Algorithm = algorithm ? algorithmsByName[algorithm] : DefaultAlgorithm;\n if (!Algorithm) {\n throw new Error(\"Unknown backup algorithm\");\n }\n\n const [privateKey, authData] = await Algorithm.prepare(key);\n const recoveryKey = encodeRecoveryKey(privateKey)!;\n return {\n algorithm: Algorithm.algorithmName,\n auth_data: authData,\n recovery_key: recoveryKey,\n privateKey,\n };\n }\n\n public async createKeyBackupVersion(info: IKeyBackupInfo): Promise {\n this.algorithm = await BackupManager.makeAlgorithm(info, this.getKey);\n }\n\n /**\n * Check the server for an active key backup and\n * if one is present and has a valid signature from\n * one of the user's verified devices, start backing up\n * to it.\n */\n public async checkAndStart(): Promise {\n logger.log(\"Checking key backup status...\");\n if (this.baseApis.isGuest()) {\n logger.log(\"Skipping key backup check since user is guest\");\n this.checkedForBackup = true;\n return null;\n }\n let backupInfo: IKeyBackupInfo | undefined;\n try {\n backupInfo = (await this.baseApis.getKeyBackupVersion()) ?? undefined;\n } catch (e) {\n logger.log(\"Error checking for active key backup\", e);\n if ((e).httpStatus === 404) {\n // 404 is returned when the key backup does not exist, so that\n // counts as successfully checking.\n this.checkedForBackup = true;\n }\n return null;\n }\n this.checkedForBackup = true;\n\n const trustInfo = await this.isKeyBackupTrusted(backupInfo);\n\n if (trustInfo.usable && !this.backupInfo) {\n logger.log(`Found usable key backup v${backupInfo!.version}: enabling key backups`);\n await this.enableKeyBackup(backupInfo!);\n } else if (!trustInfo.usable && this.backupInfo) {\n logger.log(\"No usable key backup: disabling key backup\");\n this.disableKeyBackup();\n } else if (!trustInfo.usable && !this.backupInfo) {\n logger.log(\"No usable key backup: not enabling key backup\");\n } else if (trustInfo.usable && this.backupInfo) {\n // may not be the same version: if not, we should switch\n if (backupInfo!.version !== this.backupInfo.version) {\n logger.log(\n `On backup version ${this.backupInfo.version} but ` +\n `found version ${backupInfo!.version}: switching.`,\n );\n this.disableKeyBackup();\n await this.enableKeyBackup(backupInfo!);\n // We're now using a new backup, so schedule all the keys we have to be\n // uploaded to the new backup. This is a bit of a workaround to upload\n // keys to a new backup in *most* cases, but it won't cover all cases\n // because we don't remember what backup version we uploaded keys to:\n // see https://github.com/vector-im/element-web/issues/14833\n await this.scheduleAllGroupSessionsForBackup();\n } else {\n logger.log(`Backup version ${backupInfo!.version} still current`);\n }\n }\n\n return { backupInfo, trustInfo };\n }\n\n /**\n * Forces a re-check of the key backup and enables/disables it\n * as appropriate.\n *\n * @returns Object with backup info (as returned by\n * getKeyBackupVersion) in backupInfo and\n * trust information (as returned by isKeyBackupTrusted)\n * in trustInfo.\n */\n public async checkKeyBackup(): Promise {\n this.checkedForBackup = false;\n return this.checkAndStart();\n }\n\n /**\n * Attempts to retrieve a session from a key backup, if enough time\n * has elapsed since the last check for this session id.\n */\n public async queryKeyBackupRateLimited(\n targetRoomId: string | undefined,\n targetSessionId: string | undefined,\n ): Promise {\n if (!this.backupInfo) {\n return;\n }\n\n const now = new Date().getTime();\n if (\n !this.sessionLastCheckAttemptedTime[targetSessionId!] ||\n now - this.sessionLastCheckAttemptedTime[targetSessionId!] > KEY_BACKUP_CHECK_RATE_LIMIT\n ) {\n this.sessionLastCheckAttemptedTime[targetSessionId!] = now;\n await this.baseApis.restoreKeyBackupWithCache(targetRoomId!, targetSessionId!, this.backupInfo, {});\n }\n }\n\n /**\n * Check if the given backup info is trusted.\n *\n * @param backupInfo - key backup info dict from /room_keys/version\n */\n public async isKeyBackupTrusted(backupInfo?: IKeyBackupInfo): Promise {\n const ret = {\n usable: false,\n trusted_locally: false,\n sigs: [] as SigInfo[],\n };\n\n if (!backupInfo || !backupInfo.algorithm || !backupInfo.auth_data || !backupInfo.auth_data.signatures) {\n logger.info(\"Key backup is absent or missing required data\");\n return ret;\n }\n\n const userId = this.baseApis.getUserId()!;\n const privKey = await this.baseApis.crypto!.getSessionBackupPrivateKey();\n if (privKey) {\n let algorithm: BackupAlgorithm | null = null;\n try {\n algorithm = await BackupManager.makeAlgorithm(backupInfo, async () => privKey);\n\n if (await algorithm.keyMatches(privKey)) {\n logger.info(\"Backup is trusted locally\");\n ret.trusted_locally = true;\n }\n } catch {\n // do nothing -- if we have an error, then we don't mark it as\n // locally trusted\n } finally {\n algorithm?.free();\n }\n }\n\n const mySigs = backupInfo.auth_data.signatures[userId] || {};\n\n for (const keyId of Object.keys(mySigs)) {\n const keyIdParts = keyId.split(\":\");\n if (keyIdParts[0] !== \"ed25519\") {\n logger.log(\"Ignoring unknown signature type: \" + keyIdParts[0]);\n continue;\n }\n // Could be a cross-signing master key, but just say this is the device\n // ID for backwards compat\n const sigInfo: SigInfo = { deviceId: keyIdParts[1] };\n\n // first check to see if it's from our cross-signing key\n const crossSigningId = this.baseApis.crypto!.crossSigningInfo.getId();\n if (crossSigningId === sigInfo.deviceId) {\n sigInfo.crossSigningId = true;\n try {\n await verifySignature(\n this.baseApis.crypto!.olmDevice,\n backupInfo.auth_data,\n userId,\n sigInfo.deviceId,\n crossSigningId,\n );\n sigInfo.valid = true;\n } catch (e) {\n logger.warn(\"Bad signature from cross signing key \" + crossSigningId, e);\n sigInfo.valid = false;\n }\n ret.sigs.push(sigInfo);\n continue;\n }\n\n // Now look for a sig from a device\n // At some point this can probably go away and we'll just support\n // it being signed by the cross-signing master key\n const device = this.baseApis.crypto!.deviceList.getStoredDevice(userId, sigInfo.deviceId);\n if (device) {\n sigInfo.device = device;\n sigInfo.deviceTrust = this.baseApis.checkDeviceTrust(userId, sigInfo.deviceId);\n try {\n await verifySignature(\n this.baseApis.crypto!.olmDevice,\n backupInfo.auth_data,\n userId,\n device.deviceId,\n device.getFingerprint(),\n );\n sigInfo.valid = true;\n } catch (e) {\n logger.info(\n \"Bad signature from key ID \" +\n keyId +\n \" userID \" +\n this.baseApis.getUserId() +\n \" device ID \" +\n device.deviceId +\n \" fingerprint: \" +\n device.getFingerprint(),\n backupInfo.auth_data,\n e,\n );\n sigInfo.valid = false;\n }\n } else {\n sigInfo.valid = null; // Can't determine validity because we don't have the signing device\n logger.info(\"Ignoring signature from unknown key \" + keyId);\n }\n ret.sigs.push(sigInfo);\n }\n\n ret.usable = ret.sigs.some((s) => {\n return s.valid && ((s.device && s.deviceTrust?.isVerified()) || s.crossSigningId);\n });\n return ret;\n }\n\n /**\n * Schedules sending all keys waiting to be sent to the backup, if not already\n * scheduled. Retries if necessary.\n *\n * @param maxDelay - Maximum delay to wait in ms. 0 means no delay.\n */\n public async scheduleKeyBackupSend(maxDelay = 10000): Promise {\n if (this.sendingBackups) return;\n\n this.sendingBackups = true;\n\n try {\n // wait between 0 and `maxDelay` seconds, to avoid backup\n // requests from different clients hitting the server all at\n // the same time when a new key is sent\n const delay = Math.random() * maxDelay;\n await sleep(delay);\n let numFailures = 0; // number of consecutive failures\n for (;;) {\n if (!this.algorithm) {\n return;\n }\n try {\n const numBackedUp = await this.backupPendingKeys(KEY_BACKUP_KEYS_PER_REQUEST);\n if (numBackedUp === 0) {\n // no sessions left needing backup: we're done\n return;\n }\n numFailures = 0;\n } catch (err) {\n numFailures++;\n logger.log(\"Key backup request failed\", err);\n if ((err).data) {\n if (\n (err).data.errcode == \"M_NOT_FOUND\" ||\n (err).data.errcode == \"M_WRONG_ROOM_KEYS_VERSION\"\n ) {\n // Re-check key backup status on error, so we can be\n // sure to present the current situation when asked.\n await this.checkKeyBackup();\n // Backup version has changed or this backup version\n // has been deleted\n this.baseApis.crypto!.emit(CryptoEvent.KeyBackupFailed, (err).data.errcode!);\n throw err;\n }\n }\n }\n if (numFailures) {\n // exponential backoff if we have failures\n await sleep(1000 * Math.pow(2, Math.min(numFailures - 1, 4)));\n }\n }\n } finally {\n this.sendingBackups = false;\n }\n }\n\n /**\n * Take some e2e keys waiting to be backed up and send them\n * to the backup.\n *\n * @param limit - Maximum number of keys to back up\n * @returns Number of sessions backed up\n */\n public async backupPendingKeys(limit: number): Promise {\n const sessions = await this.baseApis.crypto!.cryptoStore.getSessionsNeedingBackup(limit);\n if (!sessions.length) {\n return 0;\n }\n\n let remaining = await this.baseApis.crypto!.cryptoStore.countSessionsNeedingBackup();\n this.baseApis.crypto!.emit(CryptoEvent.KeyBackupSessionsRemaining, remaining);\n\n const rooms: IKeyBackup[\"rooms\"] = {};\n for (const session of sessions) {\n const roomId = session.sessionData!.room_id;\n safeSet(rooms, roomId, rooms[roomId] || { sessions: {} });\n\n const sessionData = this.baseApis.crypto!.olmDevice.exportInboundGroupSession(\n session.senderKey,\n session.sessionId,\n session.sessionData!,\n );\n sessionData.algorithm = MEGOLM_ALGORITHM;\n\n const forwardedCount = (sessionData.forwarding_curve25519_key_chain || []).length;\n\n const userId = this.baseApis.crypto!.deviceList.getUserByIdentityKey(MEGOLM_ALGORITHM, session.senderKey);\n const device =\n this.baseApis.crypto!.deviceList.getDeviceByIdentityKey(MEGOLM_ALGORITHM, session.senderKey) ??\n undefined;\n const verified = this.baseApis.crypto!.checkDeviceInfoTrust(userId!, device).isVerified();\n\n safeSet(rooms[roomId][\"sessions\"], session.sessionId, {\n first_message_index: sessionData.first_known_index,\n forwarded_count: forwardedCount,\n is_verified: verified,\n session_data: await this.algorithm!.encryptSession(sessionData),\n });\n }\n\n await this.baseApis.sendKeyBackup(undefined, undefined, this.backupInfo!.version, { rooms });\n\n await this.baseApis.crypto!.cryptoStore.unmarkSessionsNeedingBackup(sessions);\n remaining = await this.baseApis.crypto!.cryptoStore.countSessionsNeedingBackup();\n this.baseApis.crypto!.emit(CryptoEvent.KeyBackupSessionsRemaining, remaining);\n\n return sessions.length;\n }\n\n public async backupGroupSession(senderKey: string, sessionId: string): Promise {\n await this.baseApis.crypto!.cryptoStore.markSessionsNeedingBackup([\n {\n senderKey: senderKey,\n sessionId: sessionId,\n },\n ]);\n\n if (this.backupInfo) {\n // don't wait for this to complete: it will delay so\n // happens in the background\n this.scheduleKeyBackupSend();\n }\n // if this.backupInfo is not set, then the keys will be backed up when\n // this.enableKeyBackup is called\n }\n\n /**\n * Marks all group sessions as needing to be backed up and schedules them to\n * upload in the background as soon as possible.\n */\n public async scheduleAllGroupSessionsForBackup(): Promise {\n await this.flagAllGroupSessionsForBackup();\n\n // Schedule keys to upload in the background as soon as possible.\n this.scheduleKeyBackupSend(0 /* maxDelay */);\n }\n\n /**\n * Marks all group sessions as needing to be backed up without scheduling\n * them to upload in the background.\n * @returns Promise which resolves to the number of sessions now requiring a backup\n * (which will be equal to the number of sessions in the store).\n */\n public async flagAllGroupSessionsForBackup(): Promise {\n await this.baseApis.crypto!.cryptoStore.doTxn(\n \"readwrite\",\n [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS, IndexedDBCryptoStore.STORE_BACKUP],\n (txn) => {\n this.baseApis.crypto!.cryptoStore.getAllEndToEndInboundGroupSessions(txn, (session) => {\n if (session !== null) {\n this.baseApis.crypto!.cryptoStore.markSessionsNeedingBackup([session], txn);\n }\n });\n },\n );\n\n const remaining = await this.baseApis.crypto!.cryptoStore.countSessionsNeedingBackup();\n this.baseApis.emit(CryptoEvent.KeyBackupSessionsRemaining, remaining);\n return remaining;\n }\n\n /**\n * Counts the number of end to end session keys that are waiting to be backed up\n * @returns Promise which resolves to the number of sessions requiring backup\n */\n public countSessionsNeedingBackup(): Promise {\n return this.baseApis.crypto!.cryptoStore.countSessionsNeedingBackup();\n }\n}\n\nexport class Curve25519 implements BackupAlgorithm {\n public static algorithmName = \"m.megolm_backup.v1.curve25519-aes-sha2\";\n\n public constructor(\n public authData: ICurve25519AuthData,\n private publicKey: any, // FIXME: PkEncryption\n private getKey: () => Promise,\n ) {}\n\n public static async init(authData: AuthData, getKey: () => Promise): Promise {\n if (!authData || !(\"public_key\" in authData)) {\n throw new Error(\"auth_data missing required information\");\n }\n const publicKey = new global.Olm.PkEncryption();\n publicKey.set_recipient_key(authData.public_key);\n return new Curve25519(authData as ICurve25519AuthData, publicKey, getKey);\n }\n\n public static async prepare(key?: string | Uint8Array | null): Promise<[Uint8Array, AuthData]> {\n const decryption = new global.Olm.PkDecryption();\n try {\n const authData: Partial = {};\n if (!key) {\n authData.public_key = decryption.generate_key();\n } else if (key instanceof Uint8Array) {\n authData.public_key = decryption.init_with_private_key(key);\n } else {\n const derivation = await keyFromPassphrase(key);\n authData.private_key_salt = derivation.salt;\n authData.private_key_iterations = derivation.iterations;\n authData.public_key = decryption.init_with_private_key(derivation.key);\n }\n const publicKey = new global.Olm.PkEncryption();\n publicKey.set_recipient_key(authData.public_key);\n\n return [decryption.get_private_key(), authData as AuthData];\n } finally {\n decryption.free();\n }\n }\n\n public static checkBackupVersion(info: IKeyBackupInfo): void {\n if (!(\"public_key\" in info.auth_data)) {\n throw new Error(\"Invalid backup data returned\");\n }\n }\n\n public get untrusted(): boolean {\n return true;\n }\n\n public async encryptSession(data: Record): Promise {\n const plainText: Record = Object.assign({}, data);\n delete plainText.session_id;\n delete plainText.room_id;\n delete plainText.first_known_index;\n return this.publicKey.encrypt(JSON.stringify(plainText));\n }\n\n public async decryptSessions(\n sessions: Record>,\n ): Promise {\n const privKey = await this.getKey();\n const decryption = new global.Olm.PkDecryption();\n try {\n const backupPubKey = decryption.init_with_private_key(privKey);\n\n if (backupPubKey !== this.authData.public_key) {\n throw new MatrixError({ errcode: MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY });\n }\n\n const keys: IMegolmSessionData[] = [];\n\n for (const [sessionId, sessionData] of Object.entries(sessions)) {\n try {\n const decrypted = JSON.parse(\n decryption.decrypt(\n sessionData.session_data.ephemeral,\n sessionData.session_data.mac,\n sessionData.session_data.ciphertext,\n ),\n );\n decrypted.session_id = sessionId;\n keys.push(decrypted);\n } catch (e) {\n logger.log(\"Failed to decrypt megolm session from backup\", e, sessionData);\n }\n }\n return keys;\n } finally {\n decryption.free();\n }\n }\n\n public async keyMatches(key: Uint8Array): Promise {\n const decryption = new global.Olm.PkDecryption();\n let pubKey: string;\n try {\n pubKey = decryption.init_with_private_key(key);\n } finally {\n decryption.free();\n }\n\n return pubKey === this.authData.public_key;\n }\n\n public free(): void {\n this.publicKey.free();\n }\n}\n\nfunction randomBytes(size: number): Uint8Array {\n const buf = new Uint8Array(size);\n crypto.getRandomValues(buf);\n return buf;\n}\n\nconst UNSTABLE_MSC3270_NAME = new UnstableValue(\n \"m.megolm_backup.v1.aes-hmac-sha2\",\n \"org.matrix.msc3270.v1.aes-hmac-sha2\",\n);\n\nexport class Aes256 implements BackupAlgorithm {\n public static algorithmName = UNSTABLE_MSC3270_NAME.name;\n\n public constructor(public readonly authData: IAes256AuthData, private readonly key: Uint8Array) {}\n\n public static async init(authData: IAes256AuthData, getKey: () => Promise): Promise {\n if (!authData) {\n throw new Error(\"auth_data missing\");\n }\n const key = await getKey();\n if (authData.mac) {\n const { mac } = await calculateKeyCheck(key, authData.iv);\n if (authData.mac.replace(/=+$/g, \"\") !== mac.replace(/=+/g, \"\")) {\n throw new Error(\"Key does not match\");\n }\n }\n return new Aes256(authData, key);\n }\n\n public static async prepare(key?: string | Uint8Array | null): Promise<[Uint8Array, AuthData]> {\n let outKey: Uint8Array;\n const authData: Partial = {};\n if (!key) {\n outKey = randomBytes(32);\n } else if (key instanceof Uint8Array) {\n outKey = new Uint8Array(key);\n } else {\n const derivation = await keyFromPassphrase(key);\n authData.private_key_salt = derivation.salt;\n authData.private_key_iterations = derivation.iterations;\n outKey = derivation.key;\n }\n\n const { iv, mac } = await calculateKeyCheck(outKey);\n authData.iv = iv;\n authData.mac = mac;\n\n return [outKey, authData as AuthData];\n }\n\n public static checkBackupVersion(info: IKeyBackupInfo): void {\n if (!(\"iv\" in info.auth_data && \"mac\" in info.auth_data)) {\n throw new Error(\"Invalid backup data returned\");\n }\n }\n\n public get untrusted(): boolean {\n return false;\n }\n\n public encryptSession(data: Record): Promise {\n const plainText: Record = Object.assign({}, data);\n delete plainText.session_id;\n delete plainText.room_id;\n delete plainText.first_known_index;\n return encryptAES(JSON.stringify(plainText), this.key, data.session_id);\n }\n\n public async decryptSessions(\n sessions: Record>,\n ): Promise {\n const keys: IMegolmSessionData[] = [];\n\n for (const [sessionId, sessionData] of Object.entries(sessions)) {\n try {\n const decrypted = JSON.parse(await decryptAES(sessionData.session_data, this.key, sessionId));\n decrypted.session_id = sessionId;\n keys.push(decrypted);\n } catch (e) {\n logger.log(\"Failed to decrypt megolm session from backup\", e, sessionData);\n }\n }\n return keys;\n }\n\n public async keyMatches(key: Uint8Array): Promise {\n if (this.authData.mac) {\n const { mac } = await calculateKeyCheck(key, this.authData.iv);\n return this.authData.mac.replace(/=+$/g, \"\") === mac.replace(/=+/g, \"\");\n } else {\n // if we have no information, we have to assume the key is right\n return true;\n }\n }\n\n public free(): void {\n this.key.fill(0);\n }\n}\n\nexport const algorithmsByName: Record = {\n [Curve25519.algorithmName]: Curve25519,\n [Aes256.algorithmName]: Aes256,\n};\n\nexport const DefaultAlgorithm: BackupAlgorithmClass = Curve25519;\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from \"../logger\";\n\nexport let crypto = global.window?.crypto;\nexport let subtleCrypto = global.window?.crypto?.subtle ?? global.window?.crypto?.webkitSubtle;\nexport let TextEncoder = global.window?.TextEncoder;\n\n/* eslint-disable @typescript-eslint/no-var-requires */\nif (!crypto) {\n try {\n crypto = require(\"crypto\").webcrypto;\n } catch (e) {\n logger.error(\"Failed to load webcrypto\", e);\n }\n}\nif (!subtleCrypto) {\n subtleCrypto = crypto?.subtle;\n}\nif (!TextEncoder) {\n try {\n TextEncoder = require(\"util\").TextEncoder;\n } catch (e) {\n logger.error(\"Failed to load TextEncoder util\", e);\n }\n}\n/* eslint-enable @typescript-eslint/no-var-requires */\n\nexport function setCrypto(_crypto: Crypto): void {\n crypto = _crypto;\n subtleCrypto = _crypto.subtle ?? _crypto.webkitSubtle;\n}\n\nexport function setTextEncoder(_TextEncoder: typeof TextEncoder): void {\n TextEncoder = _TextEncoder;\n}\n", - "/*\nCopyright 2020-2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport anotherjson from \"another-json\";\n\nimport type { IDeviceKeys, IOneTimeKey } from \"../@types/crypto\";\nimport { decodeBase64, encodeBase64 } from \"./olmlib\";\nimport { IndexedDBCryptoStore } from \"../crypto/store/indexeddb-crypto-store\";\nimport { decryptAES, encryptAES } from \"./aes\";\nimport { logger } from \"../logger\";\nimport { Crypto } from \"./index\";\nimport { Method } from \"../http-api\";\nimport { SecretStorageKeyDescription } from \"../secret-storage\";\n\nexport interface IDehydratedDevice {\n device_id: string; // eslint-disable-line camelcase\n device_data: SecretStorageKeyDescription & {\n // eslint-disable-line camelcase\n algorithm: string;\n account: string; // pickle\n };\n}\n\nexport interface IDehydratedDeviceKeyInfo {\n passphrase?: string;\n}\n\nexport const DEHYDRATION_ALGORITHM = \"org.matrix.msc2697.v1.olm.libolm_pickle\";\n\nconst oneweek = 7 * 24 * 60 * 60 * 1000;\n\nexport class DehydrationManager {\n private inProgress = false;\n private timeoutId: any;\n private key?: Uint8Array;\n private keyInfo?: { [props: string]: any };\n private deviceDisplayName?: string;\n\n public constructor(private readonly crypto: Crypto) {\n this.getDehydrationKeyFromCache();\n }\n\n public getDehydrationKeyFromCache(): Promise {\n return this.crypto.cryptoStore.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n this.crypto.cryptoStore.getSecretStorePrivateKey(\n txn,\n async (result) => {\n if (result) {\n const { key, keyInfo, deviceDisplayName, time } = result;\n const pickleKey = Buffer.from(this.crypto.olmDevice.pickleKey);\n const decrypted = await decryptAES(key, pickleKey, DEHYDRATION_ALGORITHM);\n this.key = decodeBase64(decrypted);\n this.keyInfo = keyInfo;\n this.deviceDisplayName = deviceDisplayName;\n const now = Date.now();\n const delay = Math.max(1, time + oneweek - now);\n this.timeoutId = global.setTimeout(this.dehydrateDevice.bind(this), delay);\n }\n },\n \"dehydration\",\n );\n });\n }\n\n /** set the key, and queue periodic dehydration to the server in the background */\n public async setKeyAndQueueDehydration(\n key: Uint8Array,\n keyInfo: { [props: string]: any } = {},\n deviceDisplayName?: string,\n ): Promise {\n const matches = await this.setKey(key, keyInfo, deviceDisplayName);\n if (!matches) {\n // start dehydration in the background\n this.dehydrateDevice();\n }\n }\n\n public async setKey(\n key: Uint8Array,\n keyInfo: { [props: string]: any } = {},\n deviceDisplayName?: string,\n ): Promise {\n if (!key) {\n // unsetting the key -- cancel any pending dehydration task\n if (this.timeoutId) {\n global.clearTimeout(this.timeoutId);\n this.timeoutId = undefined;\n }\n // clear storage\n await this.crypto.cryptoStore.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n this.crypto.cryptoStore.storeSecretStorePrivateKey(txn, \"dehydration\", null);\n });\n this.key = undefined;\n this.keyInfo = undefined;\n return;\n }\n\n // Check to see if it's the same key as before. If it's different,\n // dehydrate a new device. If it's the same, we can keep the same\n // device. (Assume that keyInfo and deviceDisplayName will be the\n // same if the key is the same.)\n let matches: boolean = !!this.key && key.length == this.key.length;\n for (let i = 0; matches && i < key.length; i++) {\n if (key[i] != this.key![i]) {\n matches = false;\n }\n }\n if (!matches) {\n this.key = key;\n this.keyInfo = keyInfo;\n this.deviceDisplayName = deviceDisplayName;\n }\n return matches;\n }\n\n /** returns the device id of the newly created dehydrated device */\n public async dehydrateDevice(): Promise {\n if (this.inProgress) {\n logger.log(\"Dehydration already in progress -- not starting new dehydration\");\n return;\n }\n this.inProgress = true;\n if (this.timeoutId) {\n global.clearTimeout(this.timeoutId);\n this.timeoutId = undefined;\n }\n try {\n const pickleKey = Buffer.from(this.crypto.olmDevice.pickleKey);\n\n // update the crypto store with the timestamp\n const key = await encryptAES(encodeBase64(this.key!), pickleKey, DEHYDRATION_ALGORITHM);\n await this.crypto.cryptoStore.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n this.crypto.cryptoStore.storeSecretStorePrivateKey(txn, \"dehydration\", {\n keyInfo: this.keyInfo,\n key,\n deviceDisplayName: this.deviceDisplayName!,\n time: Date.now(),\n });\n });\n logger.log(\"Attempting to dehydrate device\");\n\n logger.log(\"Creating account\");\n // create the account and all the necessary keys\n const account = new global.Olm.Account();\n account.create();\n const e2eKeys = JSON.parse(account.identity_keys());\n\n const maxKeys = account.max_number_of_one_time_keys();\n // FIXME: generate in small batches?\n account.generate_one_time_keys(maxKeys / 2);\n account.generate_fallback_key();\n const otks: Record = JSON.parse(account.one_time_keys());\n const fallbacks: Record = JSON.parse(account.fallback_key());\n account.mark_keys_as_published();\n\n // dehydrate the account and store it on the server\n const pickledAccount = account.pickle(new Uint8Array(this.key!));\n\n const deviceData: { [props: string]: any } = {\n algorithm: DEHYDRATION_ALGORITHM,\n account: pickledAccount,\n };\n if (this.keyInfo!.passphrase) {\n deviceData.passphrase = this.keyInfo!.passphrase;\n }\n\n logger.log(\"Uploading account to server\");\n // eslint-disable-next-line camelcase\n const dehydrateResult = await this.crypto.baseApis.http.authedRequest<{ device_id: string }>(\n Method.Put,\n \"/dehydrated_device\",\n undefined,\n {\n device_data: deviceData,\n initial_device_display_name: this.deviceDisplayName,\n },\n {\n prefix: \"/_matrix/client/unstable/org.matrix.msc2697.v2\",\n },\n );\n\n // send the keys to the server\n const deviceId = dehydrateResult.device_id;\n logger.log(\"Preparing device keys\", deviceId);\n const deviceKeys: IDeviceKeys = {\n algorithms: this.crypto.supportedAlgorithms,\n device_id: deviceId,\n user_id: this.crypto.userId,\n keys: {\n [`ed25519:${deviceId}`]: e2eKeys.ed25519,\n [`curve25519:${deviceId}`]: e2eKeys.curve25519,\n },\n };\n const deviceSignature = account.sign(anotherjson.stringify(deviceKeys));\n deviceKeys.signatures = {\n [this.crypto.userId]: {\n [`ed25519:${deviceId}`]: deviceSignature,\n },\n };\n if (this.crypto.crossSigningInfo.getId(\"self_signing\")) {\n await this.crypto.crossSigningInfo.signObject(deviceKeys, \"self_signing\");\n }\n\n logger.log(\"Preparing one-time keys\");\n const oneTimeKeys: Record = {};\n for (const [keyId, key] of Object.entries(otks.curve25519)) {\n const k: IOneTimeKey = { key };\n const signature = account.sign(anotherjson.stringify(k));\n k.signatures = {\n [this.crypto.userId]: {\n [`ed25519:${deviceId}`]: signature,\n },\n };\n oneTimeKeys[`signed_curve25519:${keyId}`] = k;\n }\n\n logger.log(\"Preparing fallback keys\");\n const fallbackKeys: Record = {};\n for (const [keyId, key] of Object.entries(fallbacks.curve25519)) {\n const k: IOneTimeKey = { key, fallback: true };\n const signature = account.sign(anotherjson.stringify(k));\n k.signatures = {\n [this.crypto.userId]: {\n [`ed25519:${deviceId}`]: signature,\n },\n };\n fallbackKeys[`signed_curve25519:${keyId}`] = k;\n }\n\n logger.log(\"Uploading keys to server\");\n await this.crypto.baseApis.http.authedRequest(\n Method.Post,\n \"/keys/upload/\" + encodeURI(deviceId),\n undefined,\n {\n \"device_keys\": deviceKeys,\n \"one_time_keys\": oneTimeKeys,\n \"org.matrix.msc2732.fallback_keys\": fallbackKeys,\n },\n );\n logger.log(\"Done dehydrating\");\n\n // dehydrate again in a week\n this.timeoutId = global.setTimeout(this.dehydrateDevice.bind(this), oneweek);\n\n return deviceId;\n } finally {\n this.inProgress = false;\n }\n }\n\n public stop(): void {\n if (this.timeoutId) {\n global.clearTimeout(this.timeoutId);\n this.timeoutId = undefined;\n }\n }\n}\n", - "/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { ISignatures } from \"../@types/signed\";\n\nexport interface IDevice {\n keys: Record;\n algorithms: string[];\n verified: DeviceVerification;\n known: boolean;\n unsigned?: Record;\n signatures?: ISignatures;\n}\n\nenum DeviceVerification {\n Blocked = -1,\n Unverified = 0,\n Verified = 1,\n}\n\n/**\n * Information about a user's device\n */\nexport class DeviceInfo {\n /**\n * rehydrate a DeviceInfo from the session store\n *\n * @param obj - raw object from session store\n * @param deviceId - id of the device\n *\n * @returns new DeviceInfo\n */\n public static fromStorage(obj: Partial, deviceId: string): DeviceInfo {\n const res = new DeviceInfo(deviceId);\n for (const prop in obj) {\n if (obj.hasOwnProperty(prop)) {\n // @ts-ignore - this is messy and typescript doesn't like it\n res[prop as keyof IDevice] = obj[prop as keyof IDevice];\n }\n }\n return res;\n }\n\n public static DeviceVerification = {\n VERIFIED: DeviceVerification.Verified,\n UNVERIFIED: DeviceVerification.Unverified,\n BLOCKED: DeviceVerification.Blocked,\n };\n\n /** list of algorithms supported by this device */\n public algorithms: string[] = [];\n /** a map from `: -> ` */\n public keys: Record = {};\n /** whether the device has been verified/blocked by the user */\n public verified = DeviceVerification.Unverified;\n /**\n * whether the user knows of this device's existence\n * (useful when warning the user that a user has added new devices)\n */\n public known = false;\n /** additional data from the homeserver */\n public unsigned: Record = {};\n public signatures: ISignatures = {};\n\n /**\n * @param deviceId - id of the device\n */\n public constructor(public readonly deviceId: string) {}\n\n /**\n * Prepare a DeviceInfo for JSON serialisation in the session store\n *\n * @returns deviceinfo with non-serialised members removed\n */\n public toStorage(): IDevice {\n return {\n algorithms: this.algorithms,\n keys: this.keys,\n verified: this.verified,\n known: this.known,\n unsigned: this.unsigned,\n signatures: this.signatures,\n };\n }\n\n /**\n * Get the fingerprint for this device (ie, the Ed25519 key)\n *\n * @returns base64-encoded fingerprint of this device\n */\n public getFingerprint(): string {\n return this.keys[\"ed25519:\" + this.deviceId];\n }\n\n /**\n * Get the identity key for this device (ie, the Curve25519 key)\n *\n * @returns base64-encoded identity key of this device\n */\n public getIdentityKey(): string {\n return this.keys[\"curve25519:\" + this.deviceId];\n }\n\n /**\n * Get the configured display name for this device, if any\n *\n * @returns displayname\n */\n public getDisplayName(): string | null {\n return this.unsigned.device_display_name || null;\n }\n\n /**\n * Returns true if this device is blocked\n *\n * @returns true if blocked\n */\n public isBlocked(): boolean {\n return this.verified == DeviceVerification.Blocked;\n }\n\n /**\n * Returns true if this device is verified\n *\n * @returns true if verified\n */\n public isVerified(): boolean {\n return this.verified == DeviceVerification.Verified;\n }\n\n /**\n * Returns true if this device is unverified\n *\n * @returns true if unverified\n */\n public isUnverified(): boolean {\n return this.verified == DeviceVerification.Unverified;\n }\n\n /**\n * Returns true if the user knows about this device's existence\n *\n * @returns true if known\n */\n public isKnown(): boolean {\n return this.known === true;\n }\n}\n", - "/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations Ltd\nCopyright 2018-2019 New Vector Ltd\nCopyright 2019-2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport anotherjson from \"another-json\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport type { IDeviceKeys, IEventDecryptionResult, IMegolmSessionData, IOneTimeKey } from \"../@types/crypto\";\nimport type { PkDecryption, PkSigning } from \"@matrix-org/olm\";\nimport { EventType, ToDeviceMessageId } from \"../@types/event\";\nimport { TypedReEmitter } from \"../ReEmitter\";\nimport { logger } from \"../logger\";\nimport { IExportedDevice, OlmDevice } from \"./OlmDevice\";\nimport { IOlmDevice } from \"./algorithms/megolm\";\nimport * as olmlib from \"./olmlib\";\nimport { DeviceInfoMap, DeviceList } from \"./DeviceList\";\nimport { DeviceInfo, IDevice } from \"./deviceinfo\";\nimport type { DecryptionAlgorithm, EncryptionAlgorithm } from \"./algorithms\";\nimport * as algorithms from \"./algorithms\";\nimport { createCryptoStoreCacheCallbacks, CrossSigningInfo, DeviceTrustLevel, UserTrustLevel } from \"./CrossSigning\";\nimport { EncryptionSetupBuilder } from \"./EncryptionSetup\";\nimport {\n IAccountDataClient,\n ISecretRequest,\n SECRET_STORAGE_ALGORITHM_V1_AES,\n SecretStorage,\n SecretStorageKeyObject,\n SecretStorageKeyTuple,\n} from \"./SecretStorage\";\nimport {\n IAddSecretStorageKeyOpts,\n ICreateSecretStorageOpts,\n IEncryptedEventInfo,\n IImportRoomKeysOpts,\n IRecoveryKey,\n} from \"./api\";\nimport { OutgoingRoomKeyRequestManager } from \"./OutgoingRoomKeyRequestManager\";\nimport { IndexedDBCryptoStore } from \"./store/indexeddb-crypto-store\";\nimport { VerificationBase } from \"./verification/Base\";\nimport { ReciprocateQRCode, SCAN_QR_CODE_METHOD, SHOW_QR_CODE_METHOD } from \"./verification/QRCode\";\nimport { SAS as SASVerification } from \"./verification/SAS\";\nimport { keyFromPassphrase } from \"./key_passphrase\";\nimport { decodeRecoveryKey, encodeRecoveryKey } from \"./recoverykey\";\nimport { VerificationRequest } from \"./verification/request/VerificationRequest\";\nimport { InRoomChannel, InRoomRequests } from \"./verification/request/InRoomChannel\";\nimport { ToDeviceChannel, ToDeviceRequests, Request } from \"./verification/request/ToDeviceChannel\";\nimport { IllegalMethod } from \"./verification/IllegalMethod\";\nimport { KeySignatureUploadError } from \"../errors\";\nimport { calculateKeyCheck, decryptAES, encryptAES } from \"./aes\";\nimport { DehydrationManager } from \"./dehydration\";\nimport { BackupManager } from \"./backup\";\nimport { IStore } from \"../store\";\nimport { Room, RoomEvent } from \"../models/room\";\nimport { RoomMember, RoomMemberEvent } from \"../models/room-member\";\nimport { EventStatus, IEvent, MatrixEvent, MatrixEventEvent } from \"../models/event\";\nimport { ToDeviceBatch } from \"../models/ToDeviceMessage\";\nimport {\n ClientEvent,\n ICrossSigningKey,\n IKeysUploadResponse,\n ISignedKey,\n IUploadKeySignaturesResponse,\n MatrixClient,\n} from \"../client\";\nimport type { IRoomEncryption, RoomList } from \"./RoomList\";\nimport { IKeyBackupInfo } from \"./keybackup\";\nimport { ISyncStateData } from \"../sync\";\nimport { CryptoStore } from \"./store/base\";\nimport { IVerificationChannel } from \"./verification/request/Channel\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter\";\nimport { IContent } from \"../models/event\";\nimport { ISyncResponse, IToDeviceEvent } from \"../sync-accumulator\";\nimport { ISignatures } from \"../@types/signed\";\nimport { IMessage } from \"./algorithms/olm\";\nimport { CryptoBackend, OnSyncCompletedData } from \"../common-crypto/CryptoBackend\";\nimport { RoomState, RoomStateEvent } from \"../models/room-state\";\nimport { MapWithDefault, recursiveMapToObject } from \"../utils\";\nimport { SecretStorageKeyDescription } from \"../secret-storage\";\n\nconst DeviceVerification = DeviceInfo.DeviceVerification;\n\nconst defaultVerificationMethods = {\n [ReciprocateQRCode.NAME]: ReciprocateQRCode,\n [SASVerification.NAME]: SASVerification,\n\n // These two can't be used for actual verification, but we do\n // need to be able to define them here for the verification flows\n // to start.\n [SHOW_QR_CODE_METHOD]: IllegalMethod,\n [SCAN_QR_CODE_METHOD]: IllegalMethod,\n} as const;\n\n/**\n * verification method names\n */\n// legacy export identifier\nexport const verificationMethods = {\n RECIPROCATE_QR_CODE: ReciprocateQRCode.NAME,\n SAS: SASVerification.NAME,\n} as const;\n\nexport type VerificationMethod = keyof typeof verificationMethods | string;\n\nexport function isCryptoAvailable(): boolean {\n return Boolean(global.Olm);\n}\n\nconst MIN_FORCE_SESSION_INTERVAL_MS = 60 * 60 * 1000;\n\ninterface IInitOpts {\n exportedOlmDevice?: IExportedDevice;\n pickleKey?: string;\n}\n\nexport interface IBootstrapCrossSigningOpts {\n /** Optional. Reset even if keys already exist. */\n setupNewCrossSigning?: boolean;\n /**\n * A function that makes the request requiring auth. Receives the auth data as an object.\n * Can be called multiple times, first with an empty authDict, to obtain the flows.\n */\n authUploadDeviceSigningKeys?(makeRequest: (authData: any) => Promise<{}>): Promise;\n}\n\nexport interface ICryptoCallbacks {\n getCrossSigningKey?: (keyType: string, pubKey: string) => Promise;\n saveCrossSigningKeys?: (keys: Record) => void;\n shouldUpgradeDeviceVerifications?: (users: Record) => Promise;\n getSecretStorageKey?: (\n keys: { keys: Record },\n name: string,\n ) => Promise<[string, Uint8Array] | null>;\n cacheSecretStorageKey?: (keyId: string, keyInfo: SecretStorageKeyDescription, key: Uint8Array) => void;\n onSecretRequested?: (\n userId: string,\n deviceId: string,\n requestId: string,\n secretName: string,\n deviceTrust: DeviceTrustLevel,\n ) => Promise;\n getDehydrationKey?: (\n keyInfo: SecretStorageKeyDescription,\n checkFunc: (key: Uint8Array) => void,\n ) => Promise;\n getBackupKey?: () => Promise;\n}\n\n/* eslint-disable camelcase */\ninterface IRoomKey {\n room_id: string;\n algorithm: string;\n}\n\n/**\n * The parameters of a room key request. The details of the request may\n * vary with the crypto algorithm, but the management and storage layers for\n * outgoing requests expect it to have 'room_id' and 'session_id' properties.\n */\nexport interface IRoomKeyRequestBody extends IRoomKey {\n session_id: string;\n sender_key: string;\n}\n\n/* eslint-enable camelcase */\n\ninterface IDeviceVerificationUpgrade {\n devices: DeviceInfo[];\n crossSigningInfo: CrossSigningInfo;\n}\n\nexport interface ICheckOwnCrossSigningTrustOpts {\n allowPrivateKeyRequests?: boolean;\n}\n\ninterface IUserOlmSession {\n deviceIdKey: string;\n sessions: {\n sessionId: string;\n hasReceivedMessage: boolean;\n }[];\n}\n\nexport interface IRoomKeyRequestRecipient {\n userId: string;\n deviceId: string;\n}\n\ninterface ISignableObject {\n signatures?: ISignatures;\n unsigned?: object;\n}\n\nexport interface IRequestsMap {\n getRequest(event: MatrixEvent): VerificationRequest | undefined;\n getRequestByChannel(channel: IVerificationChannel): VerificationRequest | undefined;\n setRequest(event: MatrixEvent, request: VerificationRequest): void;\n setRequestByChannel(channel: IVerificationChannel, request: VerificationRequest): void;\n}\n\n/* eslint-disable camelcase */\nexport interface IOlmEncryptedContent {\n algorithm: typeof olmlib.OLM_ALGORITHM;\n sender_key: string;\n ciphertext: Record;\n [ToDeviceMessageId]?: string;\n}\n\nexport interface IMegolmEncryptedContent {\n algorithm: typeof olmlib.MEGOLM_ALGORITHM;\n sender_key: string;\n session_id: string;\n device_id: string;\n ciphertext: string;\n [ToDeviceMessageId]?: string;\n}\n/* eslint-enable camelcase */\n\nexport type IEncryptedContent = IOlmEncryptedContent | IMegolmEncryptedContent;\n\nexport enum CryptoEvent {\n DeviceVerificationChanged = \"deviceVerificationChanged\",\n UserTrustStatusChanged = \"userTrustStatusChanged\",\n UserCrossSigningUpdated = \"userCrossSigningUpdated\",\n RoomKeyRequest = \"crypto.roomKeyRequest\",\n RoomKeyRequestCancellation = \"crypto.roomKeyRequestCancellation\",\n KeyBackupStatus = \"crypto.keyBackupStatus\",\n KeyBackupFailed = \"crypto.keyBackupFailed\",\n KeyBackupSessionsRemaining = \"crypto.keyBackupSessionsRemaining\",\n KeySignatureUploadFailure = \"crypto.keySignatureUploadFailure\",\n VerificationRequest = \"crypto.verification.request\",\n Warning = \"crypto.warning\",\n WillUpdateDevices = \"crypto.willUpdateDevices\",\n DevicesUpdated = \"crypto.devicesUpdated\",\n KeysChanged = \"crossSigning.keysChanged\",\n}\n\nexport type CryptoEventHandlerMap = {\n /**\n * Fires when a device is marked as verified/unverified/blocked/unblocked by\n * {@link MatrixClient#setDeviceVerified|MatrixClient.setDeviceVerified} or\n * {@link MatrixClient#setDeviceBlocked|MatrixClient.setDeviceBlocked}.\n *\n * @param userId - the owner of the verified device\n * @param deviceId - the id of the verified device\n * @param deviceInfo - updated device information\n */\n [CryptoEvent.DeviceVerificationChanged]: (userId: string, deviceId: string, device: DeviceInfo) => void;\n /**\n * Fires when the trust status of a user changes\n * If userId is the userId of the logged-in user, this indicated a change\n * in the trust status of the cross-signing data on the account.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n * @experimental\n *\n * @param userId - the userId of the user in question\n * @param trustLevel - The new trust level of the user\n */\n [CryptoEvent.UserTrustStatusChanged]: (userId: string, trustLevel: UserTrustLevel) => void;\n /**\n * Fires when we receive a room key request\n *\n * @param req - request details\n */\n [CryptoEvent.RoomKeyRequest]: (request: IncomingRoomKeyRequest) => void;\n /**\n * Fires when we receive a room key request cancellation\n */\n [CryptoEvent.RoomKeyRequestCancellation]: (request: IncomingRoomKeyRequestCancellation) => void;\n /**\n * Fires whenever the status of e2e key backup changes, as returned by getKeyBackupEnabled()\n * @param enabled - true if key backup has been enabled, otherwise false\n * @example\n * ```\n * matrixClient.on(\"crypto.keyBackupStatus\", function(enabled){\n * if (enabled) {\n * [...]\n * }\n * });\n * ```\n */\n [CryptoEvent.KeyBackupStatus]: (enabled: boolean) => void;\n [CryptoEvent.KeyBackupFailed]: (errcode: string) => void;\n [CryptoEvent.KeyBackupSessionsRemaining]: (remaining: number) => void;\n [CryptoEvent.KeySignatureUploadFailure]: (\n failures: IUploadKeySignaturesResponse[\"failures\"],\n source: \"checkOwnCrossSigningTrust\" | \"afterCrossSigningLocalKeyChange\" | \"setDeviceVerification\",\n upload: (opts: { shouldEmit: boolean }) => Promise,\n ) => void;\n /**\n * Fires when a key verification is requested.\n */\n [CryptoEvent.VerificationRequest]: (request: VerificationRequest) => void;\n /**\n * Fires when the app may wish to warn the user about something related\n * the end-to-end crypto.\n *\n * @param type - One of the strings listed above\n */\n [CryptoEvent.Warning]: (type: string) => void;\n /**\n * Fires when the user's cross-signing keys have changed or cross-signing\n * has been enabled/disabled. The client can use getStoredCrossSigningForUser\n * with the user ID of the logged in user to check if cross-signing is\n * enabled on the account. If enabled, it can test whether the current key\n * is trusted using with checkUserTrust with the user ID of the logged\n * in user. The checkOwnCrossSigningTrust function may be used to reconcile\n * the trust in the account key.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n * @experimental\n */\n [CryptoEvent.KeysChanged]: (data: {}) => void;\n /**\n * Fires whenever the stored devices for a user will be updated\n * @param users - A list of user IDs that will be updated\n * @param initialFetch - If true, the store is empty (apart\n * from our own device) and is being seeded.\n */\n [CryptoEvent.WillUpdateDevices]: (users: string[], initialFetch: boolean) => void;\n /**\n * Fires whenever the stored devices for a user have changed\n * @param users - A list of user IDs that were updated\n * @param initialFetch - If true, the store was empty (apart\n * from our own device) and has been seeded.\n */\n [CryptoEvent.DevicesUpdated]: (users: string[], initialFetch: boolean) => void;\n [CryptoEvent.UserCrossSigningUpdated]: (userId: string) => void;\n};\n\nexport class Crypto extends TypedEventEmitter implements CryptoBackend {\n /**\n * @returns The version of Olm.\n */\n public static getOlmVersion(): [number, number, number] {\n return OlmDevice.getOlmVersion();\n }\n\n public readonly backupManager: BackupManager;\n public readonly crossSigningInfo: CrossSigningInfo;\n public readonly olmDevice: OlmDevice;\n public readonly deviceList: DeviceList;\n public readonly dehydrationManager: DehydrationManager;\n public readonly secretStorage: SecretStorage;\n\n private readonly reEmitter: TypedReEmitter;\n private readonly verificationMethods: Map;\n public readonly supportedAlgorithms: string[];\n private readonly outgoingRoomKeyRequestManager: OutgoingRoomKeyRequestManager;\n private readonly toDeviceVerificationRequests: ToDeviceRequests;\n public readonly inRoomVerificationRequests: InRoomRequests;\n\n private trustCrossSignedDevices = true;\n // the last time we did a check for the number of one-time-keys on the server.\n private lastOneTimeKeyCheck: number | null = null;\n private oneTimeKeyCheckInProgress = false;\n\n // EncryptionAlgorithm instance for each room\n private roomEncryptors = new Map();\n // map from algorithm to DecryptionAlgorithm instance, for each room\n private roomDecryptors = new Map>();\n\n private deviceKeys: Record = {}; // type: key\n\n public globalBlacklistUnverifiedDevices = false;\n public globalErrorOnUnknownDevices = true;\n\n // list of IncomingRoomKeyRequests/IncomingRoomKeyRequestCancellations\n // we received in the current sync.\n private receivedRoomKeyRequests: IncomingRoomKeyRequest[] = [];\n private receivedRoomKeyRequestCancellations: IncomingRoomKeyRequestCancellation[] = [];\n // true if we are currently processing received room key requests\n private processingRoomKeyRequests = false;\n // controls whether device tracking is delayed\n // until calling encryptEvent or trackRoomDevices,\n // or done immediately upon enabling room encryption.\n private lazyLoadMembers = false;\n // in case lazyLoadMembers is true,\n // track if an initial tracking of all the room members\n // has happened for a given room. This is delayed\n // to avoid loading room members as long as possible.\n private roomDeviceTrackingState: { [roomId: string]: Promise } = {};\n\n // The timestamp of the last time we forced establishment\n // of a new session for each device, in milliseconds.\n // {\n // userId: {\n // deviceId: 1234567890000,\n // },\n // }\n // Map: user Id → device Id → timestamp\n private lastNewSessionForced: MapWithDefault> = new MapWithDefault(\n () => new MapWithDefault(() => 0),\n );\n\n // This flag will be unset whilst the client processes a sync response\n // so that we don't start requesting keys until we've actually finished\n // processing the response.\n private sendKeyRequestsImmediately = false;\n\n private oneTimeKeyCount?: number;\n private needsNewFallback?: boolean;\n private fallbackCleanup?: ReturnType;\n\n /**\n * Cryptography bits\n *\n * This module is internal to the js-sdk; the public API is via MatrixClient.\n *\n * @internal\n *\n * @param baseApis - base matrix api interface\n *\n * @param userId - The user ID for the local user\n *\n * @param deviceId - The identifier for this device.\n *\n * @param clientStore - the MatrixClient data store.\n *\n * @param cryptoStore - storage for the crypto layer.\n *\n * @param roomList - An initialised RoomList object\n *\n * @param verificationMethods - Array of verification methods to use.\n * Each element can either be a string from MatrixClient.verificationMethods\n * or a class that implements a verification method.\n */\n public constructor(\n public readonly baseApis: MatrixClient,\n public readonly userId: string,\n private readonly deviceId: string,\n private readonly clientStore: IStore,\n public readonly cryptoStore: CryptoStore,\n private readonly roomList: RoomList,\n verificationMethods: Array,\n ) {\n super();\n this.reEmitter = new TypedReEmitter(this);\n\n if (verificationMethods) {\n this.verificationMethods = new Map();\n for (const method of verificationMethods) {\n if (typeof method === \"string\") {\n if (defaultVerificationMethods[method]) {\n this.verificationMethods.set(\n method,\n defaultVerificationMethods[method],\n );\n }\n } else if (method[\"NAME\"]) {\n this.verificationMethods.set(method[\"NAME\"], method as typeof VerificationBase);\n } else {\n logger.warn(`Excluding unknown verification method ${method}`);\n }\n }\n } else {\n this.verificationMethods = new Map(Object.entries(defaultVerificationMethods)) as Map<\n VerificationMethod,\n typeof VerificationBase\n >;\n }\n\n this.backupManager = new BackupManager(baseApis, async () => {\n // try to get key from cache\n const cachedKey = await this.getSessionBackupPrivateKey();\n if (cachedKey) {\n return cachedKey;\n }\n\n // try to get key from secret storage\n const storedKey = await this.getSecret(\"m.megolm_backup.v1\");\n\n if (storedKey) {\n // ensure that the key is in the right format. If not, fix the key and\n // store the fixed version\n const fixedKey = fixBackupKey(storedKey);\n if (fixedKey) {\n const keys = await this.getSecretStorageKey();\n await this.storeSecret(\"m.megolm_backup.v1\", fixedKey, [keys![0]]);\n }\n\n return olmlib.decodeBase64(fixedKey || storedKey);\n }\n\n // try to get key from app\n if (this.baseApis.cryptoCallbacks && this.baseApis.cryptoCallbacks.getBackupKey) {\n return this.baseApis.cryptoCallbacks.getBackupKey();\n }\n\n throw new Error(\"Unable to get private key\");\n });\n\n this.olmDevice = new OlmDevice(cryptoStore);\n this.deviceList = new DeviceList(baseApis, cryptoStore, this.olmDevice);\n\n // XXX: This isn't removed at any point, but then none of the event listeners\n // this class sets seem to be removed at any point... :/\n this.deviceList.on(CryptoEvent.UserCrossSigningUpdated, this.onDeviceListUserCrossSigningUpdated);\n this.reEmitter.reEmit(this.deviceList, [CryptoEvent.DevicesUpdated, CryptoEvent.WillUpdateDevices]);\n\n this.supportedAlgorithms = Array.from(algorithms.DECRYPTION_CLASSES.keys());\n\n this.outgoingRoomKeyRequestManager = new OutgoingRoomKeyRequestManager(\n baseApis,\n this.deviceId,\n this.cryptoStore,\n );\n\n this.toDeviceVerificationRequests = new ToDeviceRequests();\n this.inRoomVerificationRequests = new InRoomRequests();\n\n const cryptoCallbacks = this.baseApis.cryptoCallbacks || {};\n const cacheCallbacks = createCryptoStoreCacheCallbacks(cryptoStore, this.olmDevice);\n\n this.crossSigningInfo = new CrossSigningInfo(userId, cryptoCallbacks, cacheCallbacks);\n // Yes, we pass the client twice here: see SecretStorage\n this.secretStorage = new SecretStorage(baseApis as IAccountDataClient, cryptoCallbacks, baseApis);\n this.dehydrationManager = new DehydrationManager(this);\n\n // Assuming no app-supplied callback, default to getting from SSSS.\n if (!cryptoCallbacks.getCrossSigningKey && cryptoCallbacks.getSecretStorageKey) {\n cryptoCallbacks.getCrossSigningKey = async (type): Promise => {\n return CrossSigningInfo.getFromSecretStorage(type, this.secretStorage);\n };\n }\n }\n\n /**\n * Initialise the crypto module so that it is ready for use\n *\n * Returns a promise which resolves once the crypto module is ready for use.\n *\n * @param exportedOlmDevice - (Optional) data from exported device\n * that must be re-created.\n */\n public async init({ exportedOlmDevice, pickleKey }: IInitOpts = {}): Promise {\n logger.log(\"Crypto: initialising Olm...\");\n await global.Olm.init();\n logger.log(\n exportedOlmDevice\n ? \"Crypto: initialising Olm device from exported device...\"\n : \"Crypto: initialising Olm device...\",\n );\n await this.olmDevice.init({ fromExportedDevice: exportedOlmDevice, pickleKey });\n logger.log(\"Crypto: loading device list...\");\n await this.deviceList.load();\n\n // build our device keys: these will later be uploaded\n this.deviceKeys[\"ed25519:\" + this.deviceId] = this.olmDevice.deviceEd25519Key!;\n this.deviceKeys[\"curve25519:\" + this.deviceId] = this.olmDevice.deviceCurve25519Key!;\n\n logger.log(\"Crypto: fetching own devices...\");\n let myDevices = this.deviceList.getRawStoredDevicesForUser(this.userId);\n\n if (!myDevices) {\n myDevices = {};\n }\n\n if (!myDevices[this.deviceId]) {\n // add our own deviceinfo to the cryptoStore\n logger.log(\"Crypto: adding this device to the store...\");\n const deviceInfo = {\n keys: this.deviceKeys,\n algorithms: this.supportedAlgorithms,\n verified: DeviceVerification.VERIFIED,\n known: true,\n };\n\n myDevices[this.deviceId] = deviceInfo;\n this.deviceList.storeDevicesForUser(this.userId, myDevices);\n this.deviceList.saveIfDirty();\n }\n\n await this.cryptoStore.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n this.cryptoStore.getCrossSigningKeys(txn, (keys) => {\n // can be an empty object after resetting cross-signing keys, see storeTrustedSelfKeys\n if (keys && Object.keys(keys).length !== 0) {\n logger.log(\"Loaded cross-signing public keys from crypto store\");\n this.crossSigningInfo.setKeys(keys);\n }\n });\n });\n // make sure we are keeping track of our own devices\n // (this is important for key backups & things)\n this.deviceList.startTrackingDeviceList(this.userId);\n\n logger.log(\"Crypto: checking for key backup...\");\n this.backupManager.checkAndStart();\n }\n\n /**\n * Whether to trust a others users signatures of their devices.\n * If false, devices will only be considered 'verified' if we have\n * verified that device individually (effectively disabling cross-signing).\n *\n * Default: true\n *\n * @returns True if trusting cross-signed devices\n */\n public getCryptoTrustCrossSignedDevices(): boolean {\n return this.trustCrossSignedDevices;\n }\n\n /**\n * See getCryptoTrustCrossSignedDevices\n\n * This may be set before initCrypto() is called to ensure no races occur.\n *\n * @param val - True to trust cross-signed devices\n */\n public setCryptoTrustCrossSignedDevices(val: boolean): void {\n this.trustCrossSignedDevices = val;\n\n for (const userId of this.deviceList.getKnownUserIds()) {\n const devices = this.deviceList.getRawStoredDevicesForUser(userId);\n for (const deviceId of Object.keys(devices)) {\n const deviceTrust = this.checkDeviceTrust(userId, deviceId);\n // If the device is locally verified then isVerified() is always true,\n // so this will only have caused the value to change if the device is\n // cross-signing verified but not locally verified\n if (!deviceTrust.isLocallyVerified() && deviceTrust.isCrossSigningVerified()) {\n const deviceObj = this.deviceList.getStoredDevice(userId, deviceId)!;\n this.emit(CryptoEvent.DeviceVerificationChanged, userId, deviceId, deviceObj);\n }\n }\n }\n }\n\n /**\n * Create a recovery key from a user-supplied passphrase.\n *\n * @param password - Passphrase string that can be entered by the user\n * when restoring the backup as an alternative to entering the recovery key.\n * Optional.\n * @returns Object with public key metadata, encoded private\n * recovery key which should be disposed of after displaying to the user,\n * and raw private key to avoid round tripping if needed.\n */\n public async createRecoveryKeyFromPassphrase(password?: string): Promise {\n const decryption = new global.Olm.PkDecryption();\n try {\n const keyInfo: Partial = {};\n if (password) {\n const derivation = await keyFromPassphrase(password);\n keyInfo.passphrase = {\n algorithm: \"m.pbkdf2\",\n iterations: derivation.iterations,\n salt: derivation.salt,\n };\n keyInfo.pubkey = decryption.init_with_private_key(derivation.key);\n } else {\n keyInfo.pubkey = decryption.generate_key();\n }\n const privateKey = decryption.get_private_key();\n const encodedPrivateKey = encodeRecoveryKey(privateKey);\n return {\n keyInfo: keyInfo as IRecoveryKey[\"keyInfo\"],\n encodedPrivateKey,\n privateKey,\n };\n } finally {\n decryption?.free();\n }\n }\n\n /**\n * Checks if the user has previously published cross-signing keys\n *\n * This means downloading the devicelist for the user and checking if the list includes\n * the cross-signing pseudo-device.\n *\n * @internal\n */\n public async userHasCrossSigningKeys(): Promise {\n await this.downloadKeys([this.userId]);\n return this.deviceList.getStoredCrossSigningForUser(this.userId) !== null;\n }\n\n /**\n * Checks whether cross signing:\n * - is enabled on this account and trusted by this device\n * - has private keys either cached locally or stored in secret storage\n *\n * If this function returns false, bootstrapCrossSigning() can be used\n * to fix things such that it returns true. That is to say, after\n * bootstrapCrossSigning() completes successfully, this function should\n * return true.\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @returns True if cross-signing is ready to be used on this device\n */\n public async isCrossSigningReady(): Promise {\n const publicKeysOnDevice = this.crossSigningInfo.getId();\n const privateKeysExistSomewhere =\n (await this.crossSigningInfo.isStoredInKeyCache()) ||\n (await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage));\n\n return !!(publicKeysOnDevice && privateKeysExistSomewhere);\n }\n\n /**\n * Checks whether secret storage:\n * - is enabled on this account\n * - is storing cross-signing private keys\n * - is storing session backup key (if enabled)\n *\n * If this function returns false, bootstrapSecretStorage() can be used\n * to fix things such that it returns true. That is to say, after\n * bootstrapSecretStorage() completes successfully, this function should\n * return true.\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @returns True if secret storage is ready to be used on this device\n */\n public async isSecretStorageReady(): Promise {\n const secretStorageKeyInAccount = await this.secretStorage.hasKey();\n const privateKeysInStorage = await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage);\n const sessionBackupInStorage =\n !this.backupManager.getKeyBackupEnabled() || (await this.baseApis.isKeyBackupKeyStored());\n\n return !!(secretStorageKeyInAccount && privateKeysInStorage && sessionBackupInStorage);\n }\n\n /**\n * Bootstrap cross-signing by creating keys if needed. If everything is already\n * set up, then no changes are made, so this is safe to run to ensure\n * cross-signing is ready for use.\n *\n * This function:\n * - creates new cross-signing keys if they are not found locally cached nor in\n * secret storage (if it has been setup)\n *\n * The cross-signing API is currently UNSTABLE and may change without notice.\n *\n * @param authUploadDeviceSigningKeys - Function\n * called to await an interactive auth flow when uploading device signing keys.\n * @param setupNewCrossSigning - Optional. Reset even if keys\n * already exist.\n * Args:\n * A function that makes the request requiring auth. Receives the\n * auth data as an object. Can be called multiple times, first with an empty\n * authDict, to obtain the flows.\n */\n public async bootstrapCrossSigning({\n authUploadDeviceSigningKeys,\n setupNewCrossSigning,\n }: IBootstrapCrossSigningOpts = {}): Promise {\n logger.log(\"Bootstrapping cross-signing\");\n\n const delegateCryptoCallbacks = this.baseApis.cryptoCallbacks;\n const builder = new EncryptionSetupBuilder(this.baseApis.store.accountData, delegateCryptoCallbacks);\n const crossSigningInfo = new CrossSigningInfo(\n this.userId,\n builder.crossSigningCallbacks,\n builder.crossSigningCallbacks,\n );\n\n // Reset the cross-signing keys\n const resetCrossSigning = async (): Promise => {\n crossSigningInfo.resetKeys();\n // Sign master key with device key\n await this.signObject(crossSigningInfo.keys.master);\n\n // Store auth flow helper function, as we need to call it when uploading\n // to ensure we handle auth errors properly.\n builder.addCrossSigningKeys(authUploadDeviceSigningKeys, crossSigningInfo.keys);\n\n // Cross-sign own device\n const device = this.deviceList.getStoredDevice(this.userId, this.deviceId)!;\n const deviceSignature = await crossSigningInfo.signDevice(this.userId, device);\n builder.addKeySignature(this.userId, this.deviceId, deviceSignature!);\n\n // Sign message key backup with cross-signing master key\n if (this.backupManager.backupInfo) {\n await crossSigningInfo.signObject(this.backupManager.backupInfo.auth_data, \"master\");\n builder.addSessionBackup(this.backupManager.backupInfo);\n }\n };\n\n const publicKeysOnDevice = this.crossSigningInfo.getId();\n const privateKeysInCache = await this.crossSigningInfo.isStoredInKeyCache();\n const privateKeysInStorage = await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage);\n const privateKeysExistSomewhere = privateKeysInCache || privateKeysInStorage;\n\n // Log all relevant state for easier parsing of debug logs.\n logger.log({\n setupNewCrossSigning,\n publicKeysOnDevice,\n privateKeysInCache,\n privateKeysInStorage,\n privateKeysExistSomewhere,\n });\n\n if (!privateKeysExistSomewhere || setupNewCrossSigning) {\n logger.log(\"Cross-signing private keys not found locally or in secret storage, \" + \"creating new keys\");\n // If a user has multiple devices, it important to only call bootstrap\n // as part of some UI flow (and not silently during startup), as they\n // may have setup cross-signing on a platform which has not saved keys\n // to secret storage, and this would reset them. In such a case, you\n // should prompt the user to verify any existing devices first (and\n // request private keys from those devices) before calling bootstrap.\n await resetCrossSigning();\n } else if (publicKeysOnDevice && privateKeysInCache) {\n logger.log(\"Cross-signing public keys trusted and private keys found locally\");\n } else if (privateKeysInStorage) {\n logger.log(\n \"Cross-signing private keys not found locally, but they are available \" +\n \"in secret storage, reading storage and caching locally\",\n );\n await this.checkOwnCrossSigningTrust({\n allowPrivateKeyRequests: true,\n });\n }\n\n // Assuming no app-supplied callback, default to storing new private keys in\n // secret storage if it exists. If it does not, it is assumed this will be\n // done as part of setting up secret storage later.\n const crossSigningPrivateKeys = builder.crossSigningCallbacks.privateKeys;\n if (crossSigningPrivateKeys.size && !this.baseApis.cryptoCallbacks.saveCrossSigningKeys) {\n const secretStorage = new SecretStorage(\n builder.accountDataClientAdapter,\n builder.ssssCryptoCallbacks,\n undefined,\n );\n if (await secretStorage.hasKey()) {\n logger.log(\"Storing new cross-signing private keys in secret storage\");\n // This is writing to in-memory account data in\n // builder.accountDataClientAdapter so won't fail\n await CrossSigningInfo.storeInSecretStorage(crossSigningPrivateKeys, secretStorage);\n }\n }\n\n const operation = builder.buildOperation();\n await operation.apply(this);\n // This persists private keys and public keys as trusted,\n // only do this if apply succeeded for now as retry isn't in place yet\n await builder.persist(this);\n\n logger.log(\"Cross-signing ready\");\n }\n\n /**\n * Bootstrap Secure Secret Storage if needed by creating a default key. If everything is\n * already set up, then no changes are made, so this is safe to run to ensure secret\n * storage is ready for use.\n *\n * This function\n * - creates a new Secure Secret Storage key if no default key exists\n * - if a key backup exists, it is migrated to store the key in the Secret\n * Storage\n * - creates a backup if none exists, and one is requested\n * - migrates Secure Secret Storage to use the latest algorithm, if an outdated\n * algorithm is found\n *\n * The Secure Secret Storage API is currently UNSTABLE and may change without notice.\n *\n * @param createSecretStorageKey - Optional. Function\n * called to await a secret storage key creation flow.\n * Returns a Promise which resolves to an object with public key metadata, encoded private\n * recovery key which should be disposed of after displaying to the user,\n * and raw private key to avoid round tripping if needed.\n * @param keyBackupInfo - The current key backup object. If passed,\n * the passphrase and recovery key from this backup will be used.\n * @param setupNewKeyBackup - If true, a new key backup version will be\n * created and the private key stored in the new SSSS store. Ignored if keyBackupInfo\n * is supplied.\n * @param setupNewSecretStorage - Optional. Reset even if keys already exist.\n * @param getKeyBackupPassphrase - Optional. Function called to get the user's\n * current key backup passphrase. Should return a promise that resolves with a Buffer\n * containing the key, or rejects if the key cannot be obtained.\n * Returns:\n * A promise which resolves to key creation data for\n * SecretStorage#addKey: an object with `passphrase` etc fields.\n */\n // TODO this does not resolve with what it says it does\n public async bootstrapSecretStorage({\n createSecretStorageKey = async (): Promise => ({} as IRecoveryKey),\n keyBackupInfo,\n setupNewKeyBackup,\n setupNewSecretStorage,\n getKeyBackupPassphrase,\n }: ICreateSecretStorageOpts = {}): Promise {\n logger.log(\"Bootstrapping Secure Secret Storage\");\n const delegateCryptoCallbacks = this.baseApis.cryptoCallbacks;\n const builder = new EncryptionSetupBuilder(this.baseApis.store.accountData, delegateCryptoCallbacks);\n const secretStorage = new SecretStorage(\n builder.accountDataClientAdapter,\n builder.ssssCryptoCallbacks,\n undefined,\n );\n\n // the ID of the new SSSS key, if we create one\n let newKeyId: string | null = null;\n\n // create a new SSSS key and set it as default\n const createSSSS = async (opts: IAddSecretStorageKeyOpts, privateKey?: Uint8Array): Promise => {\n if (privateKey) {\n opts.key = privateKey;\n }\n\n const { keyId, keyInfo } = await secretStorage.addKey(SECRET_STORAGE_ALGORITHM_V1_AES, opts);\n\n if (privateKey) {\n // make the private key available to encrypt 4S secrets\n builder.ssssCryptoCallbacks.addPrivateKey(keyId, keyInfo, privateKey);\n }\n\n await secretStorage.setDefaultKeyId(keyId);\n return keyId;\n };\n\n const ensureCanCheckPassphrase = async (keyId: string, keyInfo: SecretStorageKeyDescription): Promise => {\n if (!keyInfo.mac) {\n const key = await this.baseApis.cryptoCallbacks.getSecretStorageKey?.(\n { keys: { [keyId]: keyInfo } },\n \"\",\n );\n if (key) {\n const privateKey = key[1];\n builder.ssssCryptoCallbacks.addPrivateKey(keyId, keyInfo, privateKey);\n const { iv, mac } = await calculateKeyCheck(privateKey);\n keyInfo.iv = iv;\n keyInfo.mac = mac;\n\n await builder.setAccountData(`m.secret_storage.key.${keyId}`, keyInfo);\n }\n }\n };\n\n const signKeyBackupWithCrossSigning = async (keyBackupAuthData: IKeyBackupInfo[\"auth_data\"]): Promise => {\n if (this.crossSigningInfo.getId() && (await this.crossSigningInfo.isStoredInKeyCache(\"master\"))) {\n try {\n logger.log(\"Adding cross-signing signature to key backup\");\n await this.crossSigningInfo.signObject(keyBackupAuthData, \"master\");\n } catch (e) {\n // This step is not critical (just helpful), so we catch here\n // and continue if it fails.\n logger.error(\"Signing key backup with cross-signing keys failed\", e);\n }\n } else {\n logger.warn(\"Cross-signing keys not available, skipping signature on key backup\");\n }\n };\n\n const oldSSSSKey = await this.getSecretStorageKey();\n const [oldKeyId, oldKeyInfo] = oldSSSSKey || [null, null];\n const storageExists =\n !setupNewSecretStorage && oldKeyInfo && oldKeyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES;\n\n // Log all relevant state for easier parsing of debug logs.\n logger.log({\n keyBackupInfo,\n setupNewKeyBackup,\n setupNewSecretStorage,\n storageExists,\n oldKeyInfo,\n });\n\n if (!storageExists && !keyBackupInfo) {\n // either we don't have anything, or we've been asked to restart\n // from scratch\n logger.log(\"Secret storage does not exist, creating new storage key\");\n\n // if we already have a usable default SSSS key and aren't resetting\n // SSSS just use it. otherwise, create a new one\n // Note: we leave the old SSSS key in place: there could be other\n // secrets using it, in theory. We could move them to the new key but a)\n // that would mean we'd need to prompt for the old passphrase, and b)\n // it's not clear that would be the right thing to do anyway.\n const { keyInfo = {} as IAddSecretStorageKeyOpts, privateKey } = await createSecretStorageKey();\n newKeyId = await createSSSS(keyInfo, privateKey);\n } else if (!storageExists && keyBackupInfo) {\n // we have an existing backup, but no SSSS\n logger.log(\"Secret storage does not exist, using key backup key\");\n\n // if we have the backup key already cached, use it; otherwise use the\n // callback to prompt for the key\n const backupKey = (await this.getSessionBackupPrivateKey()) || (await getKeyBackupPassphrase?.());\n\n // create a new SSSS key and use the backup key as the new SSSS key\n const opts = {} as IAddSecretStorageKeyOpts;\n\n if (keyBackupInfo.auth_data.private_key_salt && keyBackupInfo.auth_data.private_key_iterations) {\n // FIXME: ???\n opts.passphrase = {\n algorithm: \"m.pbkdf2\",\n iterations: keyBackupInfo.auth_data.private_key_iterations,\n salt: keyBackupInfo.auth_data.private_key_salt,\n bits: 256,\n };\n }\n\n newKeyId = await createSSSS(opts, backupKey);\n\n // store the backup key in secret storage\n await secretStorage.store(\"m.megolm_backup.v1\", olmlib.encodeBase64(backupKey!), [newKeyId]);\n\n // The backup is trusted because the user provided the private key.\n // Sign the backup with the cross-signing key so the key backup can\n // be trusted via cross-signing.\n await signKeyBackupWithCrossSigning(keyBackupInfo.auth_data);\n\n builder.addSessionBackup(keyBackupInfo);\n } else {\n // 4S is already set up\n logger.log(\"Secret storage exists\");\n\n if (oldKeyInfo && oldKeyInfo.algorithm === SECRET_STORAGE_ALGORITHM_V1_AES) {\n // make sure that the default key has the information needed to\n // check the passphrase\n await ensureCanCheckPassphrase(oldKeyId, oldKeyInfo);\n }\n }\n\n // If we have cross-signing private keys cached, store them in secret\n // storage if they are not there already.\n if (\n !this.baseApis.cryptoCallbacks.saveCrossSigningKeys &&\n (await this.isCrossSigningReady()) &&\n (newKeyId || !(await this.crossSigningInfo.isStoredInSecretStorage(secretStorage)))\n ) {\n logger.log(\"Copying cross-signing private keys from cache to secret storage\");\n const crossSigningPrivateKeys = await this.crossSigningInfo.getCrossSigningKeysFromCache();\n // This is writing to in-memory account data in\n // builder.accountDataClientAdapter so won't fail\n await CrossSigningInfo.storeInSecretStorage(crossSigningPrivateKeys, secretStorage);\n }\n\n if (setupNewKeyBackup && !keyBackupInfo) {\n logger.log(\"Creating new message key backup version\");\n const info = await this.baseApis.prepareKeyBackupVersion(\n null /* random key */,\n // don't write to secret storage, as it will write to this.secretStorage.\n // Here, we want to capture all the side-effects of bootstrapping,\n // and want to write to the local secretStorage object\n { secureSecretStorage: false },\n );\n // write the key ourselves to 4S\n const privateKey = decodeRecoveryKey(info.recovery_key);\n await secretStorage.store(\"m.megolm_backup.v1\", olmlib.encodeBase64(privateKey));\n\n // create keyBackupInfo object to add to builder\n const data: IKeyBackupInfo = {\n algorithm: info.algorithm,\n auth_data: info.auth_data,\n };\n\n // Sign with cross-signing master key\n await signKeyBackupWithCrossSigning(data.auth_data);\n\n // sign with the device fingerprint\n await this.signObject(data.auth_data);\n\n builder.addSessionBackup(data);\n }\n\n // Cache the session backup key\n const sessionBackupKey = await secretStorage.get(\"m.megolm_backup.v1\");\n if (sessionBackupKey) {\n logger.info(\"Got session backup key from secret storage: caching\");\n // fix up the backup key if it's in the wrong format, and replace\n // in secret storage\n const fixedBackupKey = fixBackupKey(sessionBackupKey);\n if (fixedBackupKey) {\n const keyId = newKeyId || oldKeyId;\n await secretStorage.store(\"m.megolm_backup.v1\", fixedBackupKey, keyId ? [keyId] : null);\n }\n const decodedBackupKey = new Uint8Array(olmlib.decodeBase64(fixedBackupKey || sessionBackupKey));\n builder.addSessionBackupPrivateKeyToCache(decodedBackupKey);\n } else if (this.backupManager.getKeyBackupEnabled()) {\n // key backup is enabled but we don't have a session backup key in SSSS: see if we have one in\n // the cache or the user can provide one, and if so, write it to SSSS\n const backupKey = (await this.getSessionBackupPrivateKey()) || (await getKeyBackupPassphrase?.());\n if (!backupKey) {\n // This will require user intervention to recover from since we don't have the key\n // backup key anywhere. The user should probably just set up a new key backup and\n // the key for the new backup will be stored. If we hit this scenario in the wild\n // with any frequency, we should do more than just log an error.\n logger.error(\"Key backup is enabled but couldn't get key backup key!\");\n return;\n }\n logger.info(\"Got session backup key from cache/user that wasn't in SSSS: saving to SSSS\");\n await secretStorage.store(\"m.megolm_backup.v1\", olmlib.encodeBase64(backupKey));\n }\n\n const operation = builder.buildOperation();\n await operation.apply(this);\n // this persists private keys and public keys as trusted,\n // only do this if apply succeeded for now as retry isn't in place yet\n await builder.persist(this);\n\n logger.log(\"Secure Secret Storage ready\");\n }\n\n public addSecretStorageKey(\n algorithm: string,\n opts: IAddSecretStorageKeyOpts,\n keyID?: string,\n ): Promise {\n return this.secretStorage.addKey(algorithm, opts, keyID);\n }\n\n public hasSecretStorageKey(keyID?: string): Promise {\n return this.secretStorage.hasKey(keyID);\n }\n\n public getSecretStorageKey(keyID?: string): Promise {\n return this.secretStorage.getKey(keyID);\n }\n\n public storeSecret(name: string, secret: string, keys?: string[]): Promise {\n return this.secretStorage.store(name, secret, keys);\n }\n\n public getSecret(name: string): Promise {\n return this.secretStorage.get(name);\n }\n\n public isSecretStored(name: string): Promise | null> {\n return this.secretStorage.isStored(name);\n }\n\n public requestSecret(name: string, devices: string[]): ISecretRequest {\n if (!devices) {\n devices = Object.keys(this.deviceList.getRawStoredDevicesForUser(this.userId));\n }\n return this.secretStorage.request(name, devices);\n }\n\n public getDefaultSecretStorageKeyId(): Promise {\n return this.secretStorage.getDefaultKeyId();\n }\n\n public setDefaultSecretStorageKeyId(k: string): Promise {\n return this.secretStorage.setDefaultKeyId(k);\n }\n\n public checkSecretStorageKey(key: Uint8Array, info: SecretStorageKeyDescription): Promise {\n return this.secretStorage.checkKey(key, info);\n }\n\n /**\n * Checks that a given secret storage private key matches a given public key.\n * This can be used by the getSecretStorageKey callback to verify that the\n * private key it is about to supply is the one that was requested.\n *\n * @param privateKey - The private key\n * @param expectedPublicKey - The public key\n * @returns true if the key matches, otherwise false\n */\n public checkSecretStoragePrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {\n let decryption: PkDecryption | null = null;\n try {\n decryption = new global.Olm.PkDecryption();\n const gotPubkey = decryption.init_with_private_key(privateKey);\n // make sure it agrees with the given pubkey\n return gotPubkey === expectedPublicKey;\n } finally {\n decryption?.free();\n }\n }\n\n /**\n * Fetches the backup private key, if cached\n * @returns the key, if any, or null\n */\n public async getSessionBackupPrivateKey(): Promise {\n let key = await new Promise((resolve) => {\n // TODO types\n this.cryptoStore.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n this.cryptoStore.getSecretStorePrivateKey(txn, resolve, \"m.megolm_backup.v1\");\n });\n });\n\n // make sure we have a Uint8Array, rather than a string\n if (key && typeof key === \"string\") {\n key = new Uint8Array(olmlib.decodeBase64(fixBackupKey(key) || key));\n await this.storeSessionBackupPrivateKey(key);\n }\n if (key && key.ciphertext) {\n const pickleKey = Buffer.from(this.olmDevice.pickleKey);\n const decrypted = await decryptAES(key, pickleKey, \"m.megolm_backup.v1\");\n key = olmlib.decodeBase64(decrypted);\n }\n return key;\n }\n\n /**\n * Stores the session backup key to the cache\n * @param key - the private key\n * @returns a promise so you can catch failures\n */\n public async storeSessionBackupPrivateKey(key: ArrayLike): Promise {\n if (!(key instanceof Uint8Array)) {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n throw new Error(`storeSessionBackupPrivateKey expects Uint8Array, got ${key}`);\n }\n const pickleKey = Buffer.from(this.olmDevice.pickleKey);\n const encryptedKey = await encryptAES(olmlib.encodeBase64(key), pickleKey, \"m.megolm_backup.v1\");\n return this.cryptoStore.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n this.cryptoStore.storeSecretStorePrivateKey(txn, \"m.megolm_backup.v1\", encryptedKey);\n });\n }\n\n /**\n * Checks that a given cross-signing private key matches a given public key.\n * This can be used by the getCrossSigningKey callback to verify that the\n * private key it is about to supply is the one that was requested.\n *\n * @param privateKey - The private key\n * @param expectedPublicKey - The public key\n * @returns true if the key matches, otherwise false\n */\n public checkCrossSigningPrivateKey(privateKey: Uint8Array, expectedPublicKey: string): boolean {\n let signing: PkSigning | null = null;\n try {\n signing = new global.Olm.PkSigning();\n const gotPubkey = signing.init_with_seed(privateKey);\n // make sure it agrees with the given pubkey\n return gotPubkey === expectedPublicKey;\n } finally {\n signing?.free();\n }\n }\n\n /**\n * Run various follow-up actions after cross-signing keys have changed locally\n * (either by resetting the keys for the account or by getting them from secret\n * storage), such as signing the current device, upgrading device\n * verifications, etc.\n */\n private async afterCrossSigningLocalKeyChange(): Promise {\n logger.info(\"Starting cross-signing key change post-processing\");\n\n // sign the current device with the new key, and upload to the server\n const device = this.deviceList.getStoredDevice(this.userId, this.deviceId)!;\n const signedDevice = await this.crossSigningInfo.signDevice(this.userId, device);\n logger.info(`Starting background key sig upload for ${this.deviceId}`);\n\n const upload = ({ shouldEmit = false }): Promise => {\n return this.baseApis\n .uploadKeySignatures({\n [this.userId]: {\n [this.deviceId]: signedDevice!,\n },\n })\n .then((response) => {\n const { failures } = response || {};\n if (Object.keys(failures || []).length > 0) {\n if (shouldEmit) {\n this.baseApis.emit(\n CryptoEvent.KeySignatureUploadFailure,\n failures,\n \"afterCrossSigningLocalKeyChange\",\n upload, // continuation\n );\n }\n throw new KeySignatureUploadError(\"Key upload failed\", { failures });\n }\n logger.info(`Finished background key sig upload for ${this.deviceId}`);\n })\n .catch((e) => {\n logger.error(`Error during background key sig upload for ${this.deviceId}`, e);\n });\n };\n upload({ shouldEmit: true });\n\n const shouldUpgradeCb = this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;\n if (shouldUpgradeCb) {\n logger.info(\"Starting device verification upgrade\");\n\n // Check all users for signatures if upgrade callback present\n // FIXME: do this in batches\n const users: Record = {};\n for (const [userId, crossSigningInfo] of Object.entries(this.deviceList.crossSigningInfo)) {\n const upgradeInfo = await this.checkForDeviceVerificationUpgrade(\n userId,\n CrossSigningInfo.fromStorage(crossSigningInfo, userId),\n );\n if (upgradeInfo) {\n users[userId] = upgradeInfo;\n }\n }\n\n if (Object.keys(users).length > 0) {\n logger.info(`Found ${Object.keys(users).length} verif users to upgrade`);\n try {\n const usersToUpgrade = await shouldUpgradeCb({ users: users });\n if (usersToUpgrade) {\n for (const userId of usersToUpgrade) {\n if (userId in users) {\n await this.baseApis.setDeviceVerified(userId, users[userId].crossSigningInfo.getId()!);\n }\n }\n }\n } catch (e) {\n logger.log(\"shouldUpgradeDeviceVerifications threw an error: not upgrading\", e);\n }\n }\n\n logger.info(\"Finished device verification upgrade\");\n }\n\n logger.info(\"Finished cross-signing key change post-processing\");\n }\n\n /**\n * Check if a user's cross-signing key is a candidate for upgrading from device\n * verification.\n *\n * @param userId - the user whose cross-signing information is to be checked\n * @param crossSigningInfo - the cross-signing information to check\n */\n private async checkForDeviceVerificationUpgrade(\n userId: string,\n crossSigningInfo: CrossSigningInfo,\n ): Promise {\n // only upgrade if this is the first cross-signing key that we've seen for\n // them, and if their cross-signing key isn't already verified\n const trustLevel = this.crossSigningInfo.checkUserTrust(crossSigningInfo);\n if (crossSigningInfo.firstUse && !trustLevel.isVerified()) {\n const devices = this.deviceList.getRawStoredDevicesForUser(userId);\n const deviceIds = await this.checkForValidDeviceSignature(userId, crossSigningInfo.keys.master, devices);\n if (deviceIds.length) {\n return {\n devices: deviceIds.map((deviceId) => DeviceInfo.fromStorage(devices[deviceId], deviceId)),\n crossSigningInfo,\n };\n }\n }\n }\n\n /**\n * Check if the cross-signing key is signed by a verified device.\n *\n * @param userId - the user ID whose key is being checked\n * @param key - the key that is being checked\n * @param devices - the user's devices. Should be a map from device ID\n * to device info\n */\n private async checkForValidDeviceSignature(\n userId: string,\n key: ICrossSigningKey,\n devices: Record,\n ): Promise {\n const deviceIds: string[] = [];\n if (devices && key.signatures && key.signatures[userId]) {\n for (const signame of Object.keys(key.signatures[userId])) {\n const [, deviceId] = signame.split(\":\", 2);\n if (deviceId in devices && devices[deviceId].verified === DeviceVerification.VERIFIED) {\n try {\n await olmlib.verifySignature(\n this.olmDevice,\n key,\n userId,\n deviceId,\n devices[deviceId].keys[signame],\n );\n deviceIds.push(deviceId);\n } catch (e) {}\n }\n }\n }\n return deviceIds;\n }\n\n /**\n * Get the user's cross-signing key ID.\n *\n * @param type - The type of key to get the ID of. One of\n * \"master\", \"self_signing\", or \"user_signing\". Defaults to \"master\".\n *\n * @returns the key ID\n */\n public getCrossSigningId(type: string): string | null {\n return this.crossSigningInfo.getId(type);\n }\n\n /**\n * Get the cross signing information for a given user.\n *\n * @param userId - the user ID to get the cross-signing info for.\n *\n * @returns the cross signing information for the user.\n */\n public getStoredCrossSigningForUser(userId: string): CrossSigningInfo | null {\n return this.deviceList.getStoredCrossSigningForUser(userId);\n }\n\n /**\n * Check whether a given user is trusted.\n *\n * @param userId - The ID of the user to check.\n *\n * @returns\n */\n public checkUserTrust(userId: string): UserTrustLevel {\n const userCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId);\n if (!userCrossSigning) {\n return new UserTrustLevel(false, false, false);\n }\n return this.crossSigningInfo.checkUserTrust(userCrossSigning);\n }\n\n /**\n * Check whether a given device is trusted.\n *\n * @param userId - The ID of the user whose devices is to be checked.\n * @param deviceId - The ID of the device to check\n *\n * @returns\n */\n public checkDeviceTrust(userId: string, deviceId: string): DeviceTrustLevel {\n const device = this.deviceList.getStoredDevice(userId, deviceId);\n return this.checkDeviceInfoTrust(userId, device);\n }\n\n /**\n * Check whether a given deviceinfo is trusted.\n *\n * @param userId - The ID of the user whose devices is to be checked.\n * @param device - The device info object to check\n *\n * @returns\n */\n public checkDeviceInfoTrust(userId: string, device?: DeviceInfo): DeviceTrustLevel {\n const trustedLocally = !!device?.isVerified();\n\n const userCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId);\n if (device && userCrossSigning) {\n // The trustCrossSignedDevices only affects trust of other people's cross-signing\n // signatures\n const trustCrossSig = this.trustCrossSignedDevices || userId === this.userId;\n return this.crossSigningInfo.checkDeviceTrust(userCrossSigning, device, trustedLocally, trustCrossSig);\n } else {\n return new DeviceTrustLevel(false, false, trustedLocally, false);\n }\n }\n\n /**\n * Check whether one of our own devices is cross-signed by our\n * user's stored keys, regardless of whether we trust those keys yet.\n *\n * @param deviceId - The ID of the device to check\n *\n * @returns true if the device is cross-signed\n */\n public checkIfOwnDeviceCrossSigned(deviceId: string): boolean {\n const device = this.deviceList.getStoredDevice(this.userId, deviceId);\n if (!device) return false;\n const userCrossSigning = this.deviceList.getStoredCrossSigningForUser(this.userId);\n return (\n userCrossSigning?.checkDeviceTrust(userCrossSigning, device, false, true).isCrossSigningVerified() ?? false\n );\n }\n\n /*\n * Event handler for DeviceList's userNewDevices event\n */\n private onDeviceListUserCrossSigningUpdated = async (userId: string): Promise => {\n if (userId === this.userId) {\n // An update to our own cross-signing key.\n // Get the new key first:\n const newCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId);\n const seenPubkey = newCrossSigning ? newCrossSigning.getId() : null;\n const currentPubkey = this.crossSigningInfo.getId();\n const changed = currentPubkey !== seenPubkey;\n\n if (currentPubkey && seenPubkey && !changed) {\n // If it's not changed, just make sure everything is up to date\n await this.checkOwnCrossSigningTrust();\n } else {\n // We'll now be in a state where cross-signing on the account is not trusted\n // because our locally stored cross-signing keys will not match the ones\n // on the server for our account. So we clear our own stored cross-signing keys,\n // effectively disabling cross-signing until the user gets verified by the device\n // that reset the keys\n this.storeTrustedSelfKeys(null);\n // emit cross-signing has been disabled\n this.emit(CryptoEvent.KeysChanged, {});\n // as the trust for our own user has changed,\n // also emit an event for this\n this.emit(CryptoEvent.UserTrustStatusChanged, this.userId, this.checkUserTrust(userId));\n }\n } else {\n await this.checkDeviceVerifications(userId);\n\n // Update verified before latch using the current state and save the new\n // latch value in the device list store.\n const crossSigning = this.deviceList.getStoredCrossSigningForUser(userId);\n if (crossSigning) {\n crossSigning.updateCrossSigningVerifiedBefore(this.checkUserTrust(userId).isCrossSigningVerified());\n this.deviceList.setRawStoredCrossSigningForUser(userId, crossSigning.toStorage());\n }\n\n this.emit(CryptoEvent.UserTrustStatusChanged, userId, this.checkUserTrust(userId));\n }\n };\n\n /**\n * Check the copy of our cross-signing key that we have in the device list and\n * see if we can get the private key. If so, mark it as trusted.\n */\n public async checkOwnCrossSigningTrust({\n allowPrivateKeyRequests = false,\n }: ICheckOwnCrossSigningTrustOpts = {}): Promise {\n const userId = this.userId;\n\n // Before proceeding, ensure our cross-signing public keys have been\n // downloaded via the device list.\n await this.downloadKeys([this.userId]);\n\n // Also check which private keys are locally cached.\n const crossSigningPrivateKeys = await this.crossSigningInfo.getCrossSigningKeysFromCache();\n\n // If we see an update to our own master key, check it against the master\n // key we have and, if it matches, mark it as verified\n\n // First, get the new cross-signing info\n const newCrossSigning = this.deviceList.getStoredCrossSigningForUser(userId);\n if (!newCrossSigning) {\n logger.error(\n \"Got cross-signing update event for user \" + userId + \" but no new cross-signing information found!\",\n );\n return;\n }\n\n const seenPubkey = newCrossSigning.getId()!;\n const masterChanged = this.crossSigningInfo.getId() !== seenPubkey;\n const masterExistsNotLocallyCached = newCrossSigning.getId() && !crossSigningPrivateKeys.has(\"master\");\n if (masterChanged) {\n logger.info(\"Got new master public key\", seenPubkey);\n }\n if (allowPrivateKeyRequests && (masterChanged || masterExistsNotLocallyCached)) {\n logger.info(\"Attempting to retrieve cross-signing master private key\");\n let signing: PkSigning | null = null;\n // It's important for control flow that we leave any errors alone for\n // higher levels to handle so that e.g. cancelling access properly\n // aborts any larger operation as well.\n try {\n const ret = await this.crossSigningInfo.getCrossSigningKey(\"master\", seenPubkey);\n signing = ret[1];\n logger.info(\"Got cross-signing master private key\");\n } finally {\n signing?.free();\n }\n }\n\n const oldSelfSigningId = this.crossSigningInfo.getId(\"self_signing\");\n const oldUserSigningId = this.crossSigningInfo.getId(\"user_signing\");\n\n // Update the version of our keys in our cross-signing object and the local store\n this.storeTrustedSelfKeys(newCrossSigning.keys);\n\n const selfSigningChanged = oldSelfSigningId !== newCrossSigning.getId(\"self_signing\");\n const userSigningChanged = oldUserSigningId !== newCrossSigning.getId(\"user_signing\");\n\n const selfSigningExistsNotLocallyCached =\n newCrossSigning.getId(\"self_signing\") && !crossSigningPrivateKeys.has(\"self_signing\");\n const userSigningExistsNotLocallyCached =\n newCrossSigning.getId(\"user_signing\") && !crossSigningPrivateKeys.has(\"user_signing\");\n\n const keySignatures: Record = {};\n\n if (selfSigningChanged) {\n logger.info(\"Got new self-signing key\", newCrossSigning.getId(\"self_signing\"));\n }\n if (allowPrivateKeyRequests && (selfSigningChanged || selfSigningExistsNotLocallyCached)) {\n logger.info(\"Attempting to retrieve cross-signing self-signing private key\");\n let signing: PkSigning | null = null;\n try {\n const ret = await this.crossSigningInfo.getCrossSigningKey(\n \"self_signing\",\n newCrossSigning.getId(\"self_signing\")!,\n );\n signing = ret[1];\n logger.info(\"Got cross-signing self-signing private key\");\n } finally {\n signing?.free();\n }\n\n const device = this.deviceList.getStoredDevice(this.userId, this.deviceId)!;\n const signedDevice = await this.crossSigningInfo.signDevice(this.userId, device);\n keySignatures[this.deviceId] = signedDevice!;\n }\n if (userSigningChanged) {\n logger.info(\"Got new user-signing key\", newCrossSigning.getId(\"user_signing\"));\n }\n if (allowPrivateKeyRequests && (userSigningChanged || userSigningExistsNotLocallyCached)) {\n logger.info(\"Attempting to retrieve cross-signing user-signing private key\");\n let signing: PkSigning | null = null;\n try {\n const ret = await this.crossSigningInfo.getCrossSigningKey(\n \"user_signing\",\n newCrossSigning.getId(\"user_signing\")!,\n );\n signing = ret[1];\n logger.info(\"Got cross-signing user-signing private key\");\n } finally {\n signing?.free();\n }\n }\n\n if (masterChanged) {\n const masterKey = this.crossSigningInfo.keys.master;\n await this.signObject(masterKey);\n const deviceSig = masterKey.signatures![this.userId][\"ed25519:\" + this.deviceId];\n // Include only the _new_ device signature in the upload.\n // We may have existing signatures from deleted devices, which will cause\n // the entire upload to fail.\n keySignatures[this.crossSigningInfo.getId()!] = Object.assign({} as ISignedKey, masterKey, {\n signatures: {\n [this.userId]: {\n [\"ed25519:\" + this.deviceId]: deviceSig,\n },\n },\n });\n }\n\n const keysToUpload = Object.keys(keySignatures);\n if (keysToUpload.length) {\n const upload = ({ shouldEmit = false }): Promise => {\n logger.info(`Starting background key sig upload for ${keysToUpload}`);\n return this.baseApis\n .uploadKeySignatures({ [this.userId]: keySignatures })\n .then((response) => {\n const { failures } = response || {};\n logger.info(`Finished background key sig upload for ${keysToUpload}`);\n if (Object.keys(failures || []).length > 0) {\n if (shouldEmit) {\n this.baseApis.emit(\n CryptoEvent.KeySignatureUploadFailure,\n failures,\n \"checkOwnCrossSigningTrust\",\n upload,\n );\n }\n throw new KeySignatureUploadError(\"Key upload failed\", { failures });\n }\n })\n .catch((e) => {\n logger.error(`Error during background key sig upload for ${keysToUpload}`, e);\n });\n };\n upload({ shouldEmit: true });\n }\n\n this.emit(CryptoEvent.UserTrustStatusChanged, userId, this.checkUserTrust(userId));\n\n if (masterChanged) {\n this.emit(CryptoEvent.KeysChanged, {});\n await this.afterCrossSigningLocalKeyChange();\n }\n\n // Now we may be able to trust our key backup\n await this.backupManager.checkKeyBackup();\n // FIXME: if we previously trusted the backup, should we automatically sign\n // the backup with the new key (if not already signed)?\n }\n\n /**\n * Store a set of keys as our own, trusted, cross-signing keys.\n *\n * @param keys - The new trusted set of keys\n */\n private async storeTrustedSelfKeys(keys: Record | null): Promise {\n if (keys) {\n this.crossSigningInfo.setKeys(keys);\n } else {\n this.crossSigningInfo.clearKeys();\n }\n await this.cryptoStore.doTxn(\"readwrite\", [IndexedDBCryptoStore.STORE_ACCOUNT], (txn) => {\n this.cryptoStore.storeCrossSigningKeys(txn, this.crossSigningInfo.keys);\n });\n }\n\n /**\n * Check if the master key is signed by a verified device, and if so, prompt\n * the application to mark it as verified.\n *\n * @param userId - the user ID whose key should be checked\n */\n private async checkDeviceVerifications(userId: string): Promise {\n const shouldUpgradeCb = this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;\n if (!shouldUpgradeCb) {\n // Upgrading skipped when callback is not present.\n return;\n }\n logger.info(`Starting device verification upgrade for ${userId}`);\n if (this.crossSigningInfo.keys.user_signing) {\n const crossSigningInfo = this.deviceList.getStoredCrossSigningForUser(userId);\n if (crossSigningInfo) {\n const upgradeInfo = await this.checkForDeviceVerificationUpgrade(userId, crossSigningInfo);\n if (upgradeInfo) {\n const usersToUpgrade = await shouldUpgradeCb({\n users: {\n [userId]: upgradeInfo,\n },\n });\n if (usersToUpgrade.includes(userId)) {\n await this.baseApis.setDeviceVerified(userId, crossSigningInfo.getId()!);\n }\n }\n }\n }\n logger.info(`Finished device verification upgrade for ${userId}`);\n }\n\n /**\n */\n public enableLazyLoading(): void {\n this.lazyLoadMembers = true;\n }\n\n /**\n * Tell the crypto module to register for MatrixClient events which it needs to\n * listen for\n *\n * @param eventEmitter - event source where we can register\n * for event notifications\n */\n public registerEventHandlers(\n eventEmitter: TypedEventEmitter<\n RoomMemberEvent.Membership | ClientEvent.ToDeviceEvent | RoomEvent.Timeline | MatrixEventEvent.Decrypted,\n any\n >,\n ): void {\n eventEmitter.on(RoomMemberEvent.Membership, this.onMembership);\n eventEmitter.on(ClientEvent.ToDeviceEvent, this.onToDeviceEvent);\n eventEmitter.on(RoomEvent.Timeline, this.onTimelineEvent);\n eventEmitter.on(MatrixEventEvent.Decrypted, this.onTimelineEvent);\n }\n\n /**\n * @deprecated this does nothing and will be removed in a future version\n */\n public start(): void {\n logger.warn(\"MatrixClient.crypto.start() is deprecated\");\n }\n\n /** Stop background processes related to crypto */\n public stop(): void {\n this.outgoingRoomKeyRequestManager.stop();\n this.deviceList.stop();\n this.dehydrationManager.stop();\n }\n\n /**\n * Get the Ed25519 key for this device\n *\n * @returns base64-encoded ed25519 key.\n */\n public getDeviceEd25519Key(): string | null {\n return this.olmDevice.deviceEd25519Key;\n }\n\n /**\n * Get the Curve25519 key for this device\n *\n * @returns base64-encoded curve25519 key.\n */\n public getDeviceCurve25519Key(): string | null {\n return this.olmDevice.deviceCurve25519Key;\n }\n\n /**\n * Set the global override for whether the client should ever send encrypted\n * messages to unverified devices. This provides the default for rooms which\n * do not specify a value.\n *\n * @param value - whether to blacklist all unverified devices by default\n *\n * @deprecated For external code, use {@link MatrixClient#setGlobalBlacklistUnverifiedDevices}. For\n * internal code, set {@link MatrixClient#globalBlacklistUnverifiedDevices} directly.\n */\n public setGlobalBlacklistUnverifiedDevices(value: boolean): void {\n this.globalBlacklistUnverifiedDevices = value;\n }\n\n /**\n * @returns whether to blacklist all unverified devices by default\n *\n * @deprecated For external code, use {@link MatrixClient#getGlobalBlacklistUnverifiedDevices}. For\n * internal code, reference {@link MatrixClient#globalBlacklistUnverifiedDevices} directly.\n */\n public getGlobalBlacklistUnverifiedDevices(): boolean {\n return this.globalBlacklistUnverifiedDevices;\n }\n\n /**\n * Upload the device keys to the homeserver.\n * @returns A promise that will resolve when the keys are uploaded.\n */\n public uploadDeviceKeys(): Promise {\n const deviceKeys = {\n algorithms: this.supportedAlgorithms,\n device_id: this.deviceId,\n keys: this.deviceKeys,\n user_id: this.userId,\n };\n\n return this.signObject(deviceKeys).then(() => {\n return this.baseApis.uploadKeysRequest({\n device_keys: deviceKeys as Required,\n });\n });\n }\n\n /**\n * Stores the current one_time_key count which will be handled later (in a call of\n * onSyncCompleted). The count is e.g. coming from a /sync response.\n *\n * @param currentCount - The current count of one_time_keys to be stored\n */\n public updateOneTimeKeyCount(currentCount: number): void {\n if (isFinite(currentCount)) {\n this.oneTimeKeyCount = currentCount;\n } else {\n throw new TypeError(\"Parameter for updateOneTimeKeyCount has to be a number\");\n }\n }\n\n public setNeedsNewFallback(needsNewFallback: boolean): void {\n this.needsNewFallback = needsNewFallback;\n }\n\n public getNeedsNewFallback(): boolean {\n return !!this.needsNewFallback;\n }\n\n // check if it's time to upload one-time keys, and do so if so.\n private maybeUploadOneTimeKeys(): void {\n // frequency with which to check & upload one-time keys\n const uploadPeriod = 1000 * 60; // one minute\n\n // max number of keys to upload at once\n // Creating keys can be an expensive operation so we limit the\n // number we generate in one go to avoid blocking the application\n // for too long.\n const maxKeysPerCycle = 5;\n\n if (this.oneTimeKeyCheckInProgress) {\n return;\n }\n\n const now = Date.now();\n if (this.lastOneTimeKeyCheck !== null && now - this.lastOneTimeKeyCheck < uploadPeriod) {\n // we've done a key upload recently.\n return;\n }\n\n this.lastOneTimeKeyCheck = now;\n\n // We need to keep a pool of one time public keys on the server so that\n // other devices can start conversations with us. But we can only store\n // a finite number of private keys in the olm Account object.\n // To complicate things further then can be a delay between a device\n // claiming a public one time key from the server and it sending us a\n // message. We need to keep the corresponding private key locally until\n // we receive the message.\n // But that message might never arrive leaving us stuck with duff\n // private keys clogging up our local storage.\n // So we need some kind of engineering compromise to balance all of\n // these factors.\n\n // Check how many keys we can store in the Account object.\n const maxOneTimeKeys = this.olmDevice.maxNumberOfOneTimeKeys();\n // Try to keep at most half that number on the server. This leaves the\n // rest of the slots free to hold keys that have been claimed from the\n // server but we haven't received a message for.\n // If we run out of slots when generating new keys then olm will\n // discard the oldest private keys first. This will eventually clean\n // out stale private keys that won't receive a message.\n const keyLimit = Math.floor(maxOneTimeKeys / 2);\n\n const uploadLoop = async (keyCount: number): Promise => {\n while (keyLimit > keyCount || this.getNeedsNewFallback()) {\n // Ask olm to generate new one time keys, then upload them to synapse.\n if (keyLimit > keyCount) {\n logger.info(\"generating oneTimeKeys\");\n const keysThisLoop = Math.min(keyLimit - keyCount, maxKeysPerCycle);\n await this.olmDevice.generateOneTimeKeys(keysThisLoop);\n }\n\n if (this.getNeedsNewFallback()) {\n const fallbackKeys = await this.olmDevice.getFallbackKey();\n // if fallbackKeys is non-empty, we've already generated a\n // fallback key, but it hasn't been published yet, so we\n // can use that instead of generating a new one\n if (!fallbackKeys.curve25519 || Object.keys(fallbackKeys.curve25519).length == 0) {\n logger.info(\"generating fallback key\");\n if (this.fallbackCleanup) {\n // cancel any pending fallback cleanup because generating\n // a new fallback key will already drop the old fallback\n // that would have been dropped, and we don't want to kill\n // the current key\n clearTimeout(this.fallbackCleanup);\n delete this.fallbackCleanup;\n }\n await this.olmDevice.generateFallbackKey();\n }\n }\n\n logger.info(\"calling uploadOneTimeKeys\");\n const res = await this.uploadOneTimeKeys();\n if (res.one_time_key_counts && res.one_time_key_counts.signed_curve25519) {\n // if the response contains a more up to date value use this\n // for the next loop\n keyCount = res.one_time_key_counts.signed_curve25519;\n } else {\n throw new Error(\n \"response for uploading keys does not contain \" + \"one_time_key_counts.signed_curve25519\",\n );\n }\n }\n };\n\n this.oneTimeKeyCheckInProgress = true;\n Promise.resolve()\n .then(() => {\n if (this.oneTimeKeyCount !== undefined) {\n // We already have the current one_time_key count from a /sync response.\n // Use this value instead of asking the server for the current key count.\n return Promise.resolve(this.oneTimeKeyCount);\n }\n // ask the server how many keys we have\n return this.baseApis.uploadKeysRequest({}).then((res) => {\n return res.one_time_key_counts.signed_curve25519 || 0;\n });\n })\n .then((keyCount) => {\n // Start the uploadLoop with the current keyCount. The function checks if\n // we need to upload new keys or not.\n // If there are too many keys on the server then we don't need to\n // create any more keys.\n return uploadLoop(keyCount);\n })\n .catch((e) => {\n logger.error(\"Error uploading one-time keys\", e.stack || e);\n })\n .finally(() => {\n // reset oneTimeKeyCount to prevent start uploading based on old data.\n // it will be set again on the next /sync-response\n this.oneTimeKeyCount = undefined;\n this.oneTimeKeyCheckInProgress = false;\n });\n }\n\n // returns a promise which resolves to the response\n private async uploadOneTimeKeys(): Promise {\n const promises: Promise[] = [];\n\n let fallbackJson: Record | undefined;\n if (this.getNeedsNewFallback()) {\n fallbackJson = {};\n const fallbackKeys = await this.olmDevice.getFallbackKey();\n for (const [keyId, key] of Object.entries(fallbackKeys.curve25519)) {\n const k = { key, fallback: true };\n fallbackJson[\"signed_curve25519:\" + keyId] = k;\n promises.push(this.signObject(k));\n }\n this.setNeedsNewFallback(false);\n }\n\n const oneTimeKeys = await this.olmDevice.getOneTimeKeys();\n const oneTimeJson: Record = {};\n\n for (const keyId in oneTimeKeys.curve25519) {\n if (oneTimeKeys.curve25519.hasOwnProperty(keyId)) {\n const k = {\n key: oneTimeKeys.curve25519[keyId],\n };\n oneTimeJson[\"signed_curve25519:\" + keyId] = k;\n promises.push(this.signObject(k));\n }\n }\n\n await Promise.all(promises);\n\n const requestBody: Record = {\n one_time_keys: oneTimeJson,\n };\n\n if (fallbackJson) {\n requestBody[\"org.matrix.msc2732.fallback_keys\"] = fallbackJson;\n requestBody[\"fallback_keys\"] = fallbackJson;\n }\n\n const res = await this.baseApis.uploadKeysRequest(requestBody);\n\n if (fallbackJson) {\n this.fallbackCleanup = setTimeout(() => {\n delete this.fallbackCleanup;\n this.olmDevice.forgetOldFallbackKey();\n }, 60 * 60 * 1000);\n }\n\n await this.olmDevice.markKeysAsPublished();\n return res;\n }\n\n /**\n * Download the keys for a list of users and stores the keys in the session\n * store.\n * @param userIds - The users to fetch.\n * @param forceDownload - Always download the keys even if cached.\n *\n * @returns A promise which resolves to a map `userId->deviceId->{@link DeviceInfo}`.\n */\n public downloadKeys(userIds: string[], forceDownload?: boolean): Promise {\n return this.deviceList.downloadKeys(userIds, !!forceDownload);\n }\n\n /**\n * Get the stored device keys for a user id\n *\n * @param userId - the user to list keys for.\n *\n * @returns list of devices, or null if we haven't\n * managed to get a list of devices for this user yet.\n */\n public getStoredDevicesForUser(userId: string): Array | null {\n return this.deviceList.getStoredDevicesForUser(userId);\n }\n\n /**\n * Get the stored keys for a single device\n *\n *\n * @returns device, or undefined\n * if we don't know about this device\n */\n public getStoredDevice(userId: string, deviceId: string): DeviceInfo | undefined {\n return this.deviceList.getStoredDevice(userId, deviceId);\n }\n\n /**\n * Save the device list, if necessary\n *\n * @param delay - Time in ms before which the save actually happens.\n * By default, the save is delayed for a short period in order to batch\n * multiple writes, but this behaviour can be disabled by passing 0.\n *\n * @returns true if the data was saved, false if\n * it was not (eg. because no changes were pending). The promise\n * will only resolve once the data is saved, so may take some time\n * to resolve.\n */\n public saveDeviceList(delay: number): Promise {\n return this.deviceList.saveIfDirty(delay);\n }\n\n /**\n * Update the blocked/verified state of the given device\n *\n * @param userId - owner of the device\n * @param deviceId - unique identifier for the device or user's\n * cross-signing public key ID.\n *\n * @param verified - whether to mark the device as verified. Null to\n * leave unchanged.\n *\n * @param blocked - whether to mark the device as blocked. Null to\n * leave unchanged.\n *\n * @param known - whether to mark that the user has been made aware of\n * the existence of this device. Null to leave unchanged\n *\n * @param keys - The list of keys that was present\n * during the device verification. This will be double checked with the list\n * of keys the given device has currently.\n *\n * @returns updated DeviceInfo\n */\n public async setDeviceVerification(\n userId: string,\n deviceId: string,\n verified: boolean | null = null,\n blocked: boolean | null = null,\n known: boolean | null = null,\n keys?: Record,\n ): Promise {\n // Check if the 'device' is actually a cross signing key\n // The js-sdk's verification treats cross-signing keys as devices\n // and so uses this method to mark them verified.\n const xsk = this.deviceList.getStoredCrossSigningForUser(userId);\n if (xsk && xsk.getId() === deviceId) {\n if (blocked !== null || known !== null) {\n throw new Error(\"Cannot set blocked or known for a cross-signing key\");\n }\n if (!verified) {\n throw new Error(\"Cannot set a cross-signing key as unverified\");\n }\n const gotKeyId = keys ? Object.values(keys)[0] : null;\n if (keys && (Object.values(keys).length !== 1 || gotKeyId !== xsk.getId())) {\n throw new Error(`Key did not match expected value: expected ${xsk.getId()}, got ${gotKeyId}`);\n }\n\n if (!this.crossSigningInfo.getId() && userId === this.crossSigningInfo.userId) {\n this.storeTrustedSelfKeys(xsk.keys);\n // This will cause our own user trust to change, so emit the event\n this.emit(CryptoEvent.UserTrustStatusChanged, this.userId, this.checkUserTrust(userId));\n }\n\n // Now sign the master key with our user signing key (unless it's ourself)\n if (userId !== this.userId) {\n logger.info(\"Master key \" + xsk.getId() + \" for \" + userId + \" marked verified. Signing...\");\n const device = await this.crossSigningInfo.signUser(xsk);\n if (device) {\n const upload = async ({ shouldEmit = false }): Promise => {\n logger.info(\"Uploading signature for \" + userId + \"...\");\n const response = await this.baseApis.uploadKeySignatures({\n [userId]: {\n [deviceId]: device,\n },\n });\n const { failures } = response || {};\n if (Object.keys(failures || []).length > 0) {\n if (shouldEmit) {\n this.baseApis.emit(\n CryptoEvent.KeySignatureUploadFailure,\n failures,\n \"setDeviceVerification\",\n upload,\n );\n }\n /* Throwing here causes the process to be cancelled and the other\n * user to be notified */\n throw new KeySignatureUploadError(\"Key upload failed\", { failures });\n }\n };\n await upload({ shouldEmit: true });\n\n // This will emit events when it comes back down the sync\n // (we could do local echo to speed things up)\n }\n return device as any; // TODO types\n } else {\n return xsk;\n }\n }\n\n const devices = this.deviceList.getRawStoredDevicesForUser(userId);\n if (!devices || !devices[deviceId]) {\n throw new Error(\"Unknown device \" + userId + \":\" + deviceId);\n }\n\n const dev = devices[deviceId];\n let verificationStatus = dev.verified;\n\n if (verified) {\n if (keys) {\n for (const [keyId, key] of Object.entries(keys)) {\n if (dev.keys[keyId] !== key) {\n throw new Error(`Key did not match expected value: expected ${key}, got ${dev.keys[keyId]}`);\n }\n }\n }\n verificationStatus = DeviceVerification.VERIFIED;\n } else if (verified !== null && verificationStatus == DeviceVerification.VERIFIED) {\n verificationStatus = DeviceVerification.UNVERIFIED;\n }\n\n if (blocked) {\n verificationStatus = DeviceVerification.BLOCKED;\n } else if (blocked !== null && verificationStatus == DeviceVerification.BLOCKED) {\n verificationStatus = DeviceVerification.UNVERIFIED;\n }\n\n let knownStatus = dev.known;\n if (known !== null) {\n knownStatus = known;\n }\n\n if (dev.verified !== verificationStatus || dev.known !== knownStatus) {\n dev.verified = verificationStatus;\n dev.known = knownStatus;\n this.deviceList.storeDevicesForUser(userId, devices);\n this.deviceList.saveIfDirty();\n }\n\n // do cross-signing\n if (verified && userId === this.userId) {\n logger.info(\"Own device \" + deviceId + \" marked verified: signing\");\n\n // Signing only needed if other device not already signed\n let device: ISignedKey | undefined;\n const deviceTrust = this.checkDeviceTrust(userId, deviceId);\n if (deviceTrust.isCrossSigningVerified()) {\n logger.log(`Own device ${deviceId} already cross-signing verified`);\n } else {\n device = (await this.crossSigningInfo.signDevice(userId, DeviceInfo.fromStorage(dev, deviceId)))!;\n }\n\n if (device) {\n const upload = async ({ shouldEmit = false }): Promise => {\n logger.info(\"Uploading signature for \" + deviceId);\n const response = await this.baseApis.uploadKeySignatures({\n [userId]: {\n [deviceId]: device!,\n },\n });\n const { failures } = response || {};\n if (Object.keys(failures || []).length > 0) {\n if (shouldEmit) {\n this.baseApis.emit(\n CryptoEvent.KeySignatureUploadFailure,\n failures,\n \"setDeviceVerification\",\n upload, // continuation\n );\n }\n throw new KeySignatureUploadError(\"Key upload failed\", { failures });\n }\n };\n await upload({ shouldEmit: true });\n // XXX: we'll need to wait for the device list to be updated\n }\n }\n\n const deviceObj = DeviceInfo.fromStorage(dev, deviceId);\n this.emit(CryptoEvent.DeviceVerificationChanged, userId, deviceId, deviceObj);\n return deviceObj;\n }\n\n public findVerificationRequestDMInProgress(roomId: string): VerificationRequest | undefined {\n return this.inRoomVerificationRequests.findRequestInProgress(roomId);\n }\n\n public getVerificationRequestsToDeviceInProgress(userId: string): VerificationRequest[] {\n return this.toDeviceVerificationRequests.getRequestsInProgress(userId);\n }\n\n public requestVerificationDM(userId: string, roomId: string): Promise {\n const existingRequest = this.inRoomVerificationRequests.findRequestInProgress(roomId);\n if (existingRequest) {\n return Promise.resolve(existingRequest);\n }\n const channel = new InRoomChannel(this.baseApis, roomId, userId);\n return this.requestVerificationWithChannel(userId, channel, this.inRoomVerificationRequests);\n }\n\n public requestVerification(userId: string, devices?: string[]): Promise {\n if (!devices) {\n devices = Object.keys(this.deviceList.getRawStoredDevicesForUser(userId));\n }\n const existingRequest = this.toDeviceVerificationRequests.findRequestInProgress(userId, devices);\n if (existingRequest) {\n return Promise.resolve(existingRequest);\n }\n const channel = new ToDeviceChannel(this.baseApis, userId, devices, ToDeviceChannel.makeTransactionId());\n return this.requestVerificationWithChannel(userId, channel, this.toDeviceVerificationRequests);\n }\n\n private async requestVerificationWithChannel(\n userId: string,\n channel: IVerificationChannel,\n requestsMap: IRequestsMap,\n ): Promise {\n let request = new VerificationRequest(channel, this.verificationMethods, this.baseApis);\n // if transaction id is already known, add request\n if (channel.transactionId) {\n requestsMap.setRequestByChannel(channel, request);\n }\n await request.sendRequest();\n // don't replace the request created by a racing remote echo\n const racingRequest = requestsMap.getRequestByChannel(channel);\n if (racingRequest) {\n request = racingRequest;\n } else {\n logger.log(\n `Crypto: adding new request to ` + `requestsByTxnId with id ${channel.transactionId} ${channel.roomId}`,\n );\n requestsMap.setRequestByChannel(channel, request);\n }\n return request;\n }\n\n public beginKeyVerification(\n method: string,\n userId: string,\n deviceId: string,\n transactionId: string | null = null,\n ): VerificationBase {\n let request: Request | undefined;\n if (transactionId) {\n request = this.toDeviceVerificationRequests.getRequestBySenderAndTxnId(userId, transactionId);\n if (!request) {\n throw new Error(`No request found for user ${userId} with ` + `transactionId ${transactionId}`);\n }\n } else {\n transactionId = ToDeviceChannel.makeTransactionId();\n const channel = new ToDeviceChannel(this.baseApis, userId, [deviceId], transactionId, deviceId);\n request = new VerificationRequest(channel, this.verificationMethods, this.baseApis);\n this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(userId, transactionId, request);\n }\n return request.beginKeyVerification(method, { userId, deviceId });\n }\n\n public async legacyDeviceVerification(\n userId: string,\n deviceId: string,\n method: VerificationMethod,\n ): Promise {\n const transactionId = ToDeviceChannel.makeTransactionId();\n const channel = new ToDeviceChannel(this.baseApis, userId, [deviceId], transactionId, deviceId);\n const request = new VerificationRequest(channel, this.verificationMethods, this.baseApis);\n this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(userId, transactionId, request);\n const verifier = request.beginKeyVerification(method, { userId, deviceId });\n // either reject by an error from verify() while sending .start\n // or resolve when the request receives the\n // local (fake remote) echo for sending the .start event\n await Promise.race([verifier.verify(), request.waitFor((r) => r.started)]);\n return request;\n }\n\n /**\n * Get information on the active olm sessions with a user\n *

\n * Returns a map from device id to an object with keys 'deviceIdKey' (the\n * device's curve25519 identity key) and 'sessions' (an array of objects in the\n * same format as that returned by\n * {@link OlmDevice#getSessionInfoForDevice}).\n *

\n * This method is provided for debugging purposes.\n *\n * @param userId - id of user to inspect\n */\n public async getOlmSessionsForUser(userId: string): Promise> {\n const devices = this.getStoredDevicesForUser(userId) || [];\n const result: { [deviceId: string]: IUserOlmSession } = {};\n for (const device of devices) {\n const deviceKey = device.getIdentityKey();\n const sessions = await this.olmDevice.getSessionInfoForDevice(deviceKey);\n\n result[device.deviceId] = {\n deviceIdKey: deviceKey,\n sessions: sessions,\n };\n }\n return result;\n }\n\n /**\n * Get the device which sent an event\n *\n * @param event - event to be checked\n */\n public getEventSenderDeviceInfo(event: MatrixEvent): DeviceInfo | null {\n const senderKey = event.getSenderKey();\n const algorithm = event.getWireContent().algorithm;\n\n if (!senderKey || !algorithm) {\n return null;\n }\n\n if (event.isKeySourceUntrusted()) {\n // we got the key for this event from a source that we consider untrusted\n return null;\n }\n\n // senderKey is the Curve25519 identity key of the device which the event\n // was sent from. In the case of Megolm, it's actually the Curve25519\n // identity key of the device which set up the Megolm session.\n\n const device = this.deviceList.getDeviceByIdentityKey(algorithm, senderKey);\n\n if (device === null) {\n // we haven't downloaded the details of this device yet.\n return null;\n }\n\n // so far so good, but now we need to check that the sender of this event\n // hadn't advertised someone else's Curve25519 key as their own. We do that\n // by checking the Ed25519 claimed by the event (or, in the case of megolm,\n // the event which set up the megolm session), to check that it matches the\n // fingerprint of the purported sending device.\n //\n // (see https://github.com/vector-im/vector-web/issues/2215)\n\n const claimedKey = event.getClaimedEd25519Key();\n if (!claimedKey) {\n logger.warn(\"Event \" + event.getId() + \" claims no ed25519 key: \" + \"cannot verify sending device\");\n return null;\n }\n\n if (claimedKey !== device.getFingerprint()) {\n logger.warn(\n \"Event \" +\n event.getId() +\n \" claims ed25519 key \" +\n claimedKey +\n \" but sender device has key \" +\n device.getFingerprint(),\n );\n return null;\n }\n\n return device;\n }\n\n /**\n * Get information about the encryption of an event\n *\n * @param event - event to be checked\n *\n * @returns An object with the fields:\n * - encrypted: whether the event is encrypted (if not encrypted, some of the\n * other properties may not be set)\n * - senderKey: the sender's key\n * - algorithm: the algorithm used to encrypt the event\n * - authenticated: whether we can be sure that the owner of the senderKey\n * sent the event\n * - sender: the sender's device information, if available\n * - mismatchedSender: if the event's ed25519 and curve25519 keys don't match\n * (only meaningful if `sender` is set)\n */\n public getEventEncryptionInfo(event: MatrixEvent): IEncryptedEventInfo {\n const ret: Partial = {};\n\n ret.senderKey = event.getSenderKey() ?? undefined;\n ret.algorithm = event.getWireContent().algorithm;\n\n if (!ret.senderKey || !ret.algorithm) {\n ret.encrypted = false;\n return ret as IEncryptedEventInfo;\n }\n ret.encrypted = true;\n\n if (event.isKeySourceUntrusted()) {\n // we got the key this event from somewhere else\n // TODO: check if we can trust the forwarders.\n ret.authenticated = false;\n } else {\n ret.authenticated = true;\n }\n\n // senderKey is the Curve25519 identity key of the device which the event\n // was sent from. In the case of Megolm, it's actually the Curve25519\n // identity key of the device which set up the Megolm session.\n\n ret.sender = this.deviceList.getDeviceByIdentityKey(ret.algorithm, ret.senderKey) ?? undefined;\n\n // so far so good, but now we need to check that the sender of this event\n // hadn't advertised someone else's Curve25519 key as their own. We do that\n // by checking the Ed25519 claimed by the event (or, in the case of megolm,\n // the event which set up the megolm session), to check that it matches the\n // fingerprint of the purported sending device.\n //\n // (see https://github.com/vector-im/vector-web/issues/2215)\n\n const claimedKey = event.getClaimedEd25519Key();\n if (!claimedKey) {\n logger.warn(\"Event \" + event.getId() + \" claims no ed25519 key: \" + \"cannot verify sending device\");\n ret.mismatchedSender = true;\n }\n\n if (ret.sender && claimedKey !== ret.sender.getFingerprint()) {\n logger.warn(\n \"Event \" +\n event.getId() +\n \" claims ed25519 key \" +\n claimedKey +\n \"but sender device has key \" +\n ret.sender.getFingerprint(),\n );\n ret.mismatchedSender = true;\n }\n\n return ret as IEncryptedEventInfo;\n }\n\n /**\n * Forces the current outbound group session to be discarded such\n * that another one will be created next time an event is sent.\n *\n * @param roomId - The ID of the room to discard the session for\n *\n * This should not normally be necessary.\n */\n public forceDiscardSession(roomId: string): Promise {\n const alg = this.roomEncryptors.get(roomId);\n if (alg === undefined) throw new Error(\"Room not encrypted\");\n if (alg.forceDiscardSession === undefined) {\n throw new Error(\"Room encryption algorithm doesn't support session discarding\");\n }\n alg.forceDiscardSession();\n return Promise.resolve();\n }\n\n /**\n * Configure a room to use encryption (ie, save a flag in the cryptoStore).\n *\n * @param roomId - The room ID to enable encryption in.\n *\n * @param config - The encryption config for the room.\n *\n * @param inhibitDeviceQuery - true to suppress device list query for\n * users in the room (for now). In case lazy loading is enabled,\n * the device query is always inhibited as the members are not tracked.\n *\n * @deprecated It is normally incorrect to call this method directly. Encryption\n * is enabled by receiving an `m.room.encryption` event (which we may have sent\n * previously).\n */\n public async setRoomEncryption(\n roomId: string,\n config: IRoomEncryption,\n inhibitDeviceQuery?: boolean,\n ): Promise {\n const room = this.clientStore.getRoom(roomId);\n if (!room) {\n throw new Error(`Unable to enable encryption tracking devices in unknown room ${roomId}`);\n }\n await this.setRoomEncryptionImpl(room, config);\n if (!this.lazyLoadMembers && !inhibitDeviceQuery) {\n this.deviceList.refreshOutdatedDeviceLists();\n }\n }\n\n /**\n * Set up encryption for a room.\n *\n * This is called when an m.room.encryption event is received. It saves a flag\n * for the room in the cryptoStore (if it wasn't already set), sets up an \"encryptor\" for\n * the room, and enables device-list tracking for the room.\n *\n * It does not initiate a device list query for the room. That is normally\n * done once we finish processing the sync, in onSyncCompleted.\n *\n * @param room - The room to enable encryption in.\n * @param config - The encryption config for the room.\n */\n private async setRoomEncryptionImpl(room: Room, config: IRoomEncryption): Promise {\n const roomId = room.roomId;\n\n // ignore crypto events with no algorithm defined\n // This will happen if a crypto event is redacted before we fetch the room state\n // It would otherwise just throw later as an unknown algorithm would, but we may\n // as well catch this here\n if (!config.algorithm) {\n logger.log(\"Ignoring setRoomEncryption with no algorithm\");\n return;\n }\n\n // if state is being replayed from storage, we might already have a configuration\n // for this room as they are persisted as well.\n // We just need to make sure the algorithm is initialized in this case.\n // However, if the new config is different,\n // we should bail out as room encryption can't be changed once set.\n const existingConfig = this.roomList.getRoomEncryption(roomId);\n if (existingConfig) {\n if (JSON.stringify(existingConfig) != JSON.stringify(config)) {\n logger.error(\"Ignoring m.room.encryption event which requests \" + \"a change of config in \" + roomId);\n return;\n }\n }\n // if we already have encryption in this room, we should ignore this event,\n // as it would reset the encryption algorithm.\n // This is at least expected to be called twice, as sync calls onCryptoEvent\n // for both the timeline and state sections in the /sync response,\n // the encryption event would appear in both.\n // If it's called more than twice though,\n // it signals a bug on client or server.\n const existingAlg = this.roomEncryptors.get(roomId);\n if (existingAlg) {\n return;\n }\n\n // _roomList.getRoomEncryption will not race with _roomList.setRoomEncryption\n // because it first stores in memory. We should await the promise only\n // after all the in-memory state (roomEncryptors and _roomList) has been updated\n // to avoid races when calling this method multiple times. Hence keep a hold of the promise.\n let storeConfigPromise: Promise | null = null;\n if (!existingConfig) {\n storeConfigPromise = this.roomList.setRoomEncryption(roomId, config);\n }\n\n const AlgClass = algorithms.ENCRYPTION_CLASSES.get(config.algorithm);\n if (!AlgClass) {\n throw new Error(\"Unable to encrypt with \" + config.algorithm);\n }\n\n const alg = new AlgClass({\n userId: this.userId,\n deviceId: this.deviceId,\n crypto: this,\n olmDevice: this.olmDevice,\n baseApis: this.baseApis,\n roomId,\n config,\n });\n this.roomEncryptors.set(roomId, alg);\n\n if (storeConfigPromise) {\n await storeConfigPromise;\n }\n\n logger.log(`Enabling encryption in ${roomId}`);\n\n // we don't want to force a download of the full membership list of this room, but as soon as we have that\n // list we can start tracking the device list.\n if (room.membersLoaded()) {\n await this.trackRoomDevicesImpl(room);\n } else {\n // wait for the membership list to be loaded\n const onState = (_state: RoomState): void => {\n room.off(RoomStateEvent.Update, onState);\n if (room.membersLoaded()) {\n this.trackRoomDevicesImpl(room).catch((e) => {\n logger.error(`Error enabling device tracking in ${roomId}`, e);\n });\n }\n };\n room.on(RoomStateEvent.Update, onState);\n }\n }\n\n /**\n * Make sure we are tracking the device lists for all users in this room.\n *\n * @param roomId - The room ID to start tracking devices in.\n * @returns when all devices for the room have been fetched and marked to track\n * @deprecated there's normally no need to call this function: device list tracking\n * will be enabled as soon as we have the full membership list.\n */\n public trackRoomDevices(roomId: string): Promise {\n const room = this.clientStore.getRoom(roomId);\n if (!room) {\n throw new Error(`Unable to start tracking devices in unknown room ${roomId}`);\n }\n return this.trackRoomDevicesImpl(room);\n }\n\n /**\n * Make sure we are tracking the device lists for all users in this room.\n *\n * This is normally called when we are about to send an encrypted event, to make sure\n * we have all the devices in the room; but it is also called when processing an\n * m.room.encryption state event (if lazy-loading is disabled), or when members are\n * loaded (if lazy-loading is enabled), to prepare the device list.\n *\n * @param room - Room to enable device-list tracking in\n */\n private trackRoomDevicesImpl(room: Room): Promise {\n const roomId = room.roomId;\n const trackMembers = async (): Promise => {\n // not an encrypted room\n if (!this.roomEncryptors.has(roomId)) {\n return;\n }\n logger.log(`Starting to track devices for room ${roomId} ...`);\n const members = await room.getEncryptionTargetMembers();\n members.forEach((m) => {\n this.deviceList.startTrackingDeviceList(m.userId);\n });\n };\n\n let promise = this.roomDeviceTrackingState[roomId];\n if (!promise) {\n promise = trackMembers();\n this.roomDeviceTrackingState[roomId] = promise.catch((err) => {\n delete this.roomDeviceTrackingState[roomId];\n throw err;\n });\n }\n return promise;\n }\n\n /**\n * Try to make sure we have established olm sessions for all known devices for\n * the given users.\n *\n * @param users - list of user ids\n * @param force - If true, force a new Olm session to be created. Default false.\n *\n * @returns resolves once the sessions are complete, to\n * an Object mapping from userId to deviceId to\n * {@link OlmSessionResult}\n */\n public ensureOlmSessionsForUsers(\n users: string[],\n force?: boolean,\n ): Promise>> {\n // map user Id → DeviceInfo[]\n const devicesByUser: Map = new Map();\n\n for (const userId of users) {\n const userDevices: DeviceInfo[] = [];\n devicesByUser.set(userId, userDevices);\n\n const devices = this.getStoredDevicesForUser(userId) || [];\n for (const deviceInfo of devices) {\n const key = deviceInfo.getIdentityKey();\n if (key == this.olmDevice.deviceCurve25519Key) {\n // don't bother setting up session to ourself\n continue;\n }\n if (deviceInfo.verified == DeviceVerification.BLOCKED) {\n // don't bother setting up sessions with blocked users\n continue;\n }\n\n userDevices.push(deviceInfo);\n }\n }\n\n return olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, devicesByUser, force);\n }\n\n /**\n * Get a list containing all of the room keys\n *\n * @returns a list of session export objects\n */\n public async exportRoomKeys(): Promise {\n const exportedSessions: IMegolmSessionData[] = [];\n await this.cryptoStore.doTxn(\"readonly\", [IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS], (txn) => {\n this.cryptoStore.getAllEndToEndInboundGroupSessions(txn, (s) => {\n if (s === null) return;\n\n const sess = this.olmDevice.exportInboundGroupSession(s.senderKey, s.sessionId, s.sessionData!);\n delete sess.first_known_index;\n sess.algorithm = olmlib.MEGOLM_ALGORITHM;\n exportedSessions.push(sess);\n });\n });\n\n return exportedSessions;\n }\n\n /**\n * Import a list of room keys previously exported by exportRoomKeys\n *\n * @param keys - a list of session export objects\n * @returns a promise which resolves once the keys have been imported\n */\n public importRoomKeys(keys: IMegolmSessionData[], opts: IImportRoomKeysOpts = {}): Promise {\n let successes = 0;\n let failures = 0;\n const total = keys.length;\n\n function updateProgress(): void {\n opts.progressCallback?.({\n stage: \"load_keys\",\n successes,\n failures,\n total,\n });\n }\n\n return Promise.all(\n keys.map((key) => {\n if (!key.room_id || !key.algorithm) {\n logger.warn(\"ignoring room key entry with missing fields\", key);\n failures++;\n if (opts.progressCallback) {\n updateProgress();\n }\n return null;\n }\n\n const alg = this.getRoomDecryptor(key.room_id, key.algorithm);\n return alg.importRoomKey(key, opts).finally(() => {\n successes++;\n if (opts.progressCallback) {\n updateProgress();\n }\n });\n }),\n ).then();\n }\n\n /**\n * Counts the number of end to end session keys that are waiting to be backed up\n * @returns Promise which resolves to the number of sessions requiring backup\n */\n public countSessionsNeedingBackup(): Promise {\n return this.backupManager.countSessionsNeedingBackup();\n }\n\n /**\n * Perform any background tasks that can be done before a message is ready to\n * send, in order to speed up sending of the message.\n *\n * @param room - the room the event is in\n */\n public prepareToEncrypt(room: Room): void {\n const alg = this.roomEncryptors.get(room.roomId);\n if (alg) {\n alg.prepareToEncrypt(room);\n }\n }\n\n /**\n * Encrypt an event according to the configuration of the room.\n *\n * @param event - event to be sent\n *\n * @param room - destination room.\n *\n * @returns Promise which resolves when the event has been\n * encrypted, or null if nothing was needed\n */\n public async encryptEvent(event: MatrixEvent, room: Room): Promise {\n const roomId = event.getRoomId()!;\n\n const alg = this.roomEncryptors.get(roomId);\n if (!alg) {\n // MatrixClient has already checked that this room should be encrypted,\n // so this is an unexpected situation.\n throw new Error(\n \"Room \" +\n roomId +\n \" was previously configured to use encryption, but is \" +\n \"no longer. Perhaps the homeserver is hiding the \" +\n \"configuration event.\",\n );\n }\n\n // wait for all the room devices to be loaded\n await this.trackRoomDevicesImpl(room);\n\n let content = event.getContent();\n // If event has an m.relates_to then we need\n // to put this on the wrapping event instead\n const mRelatesTo = content[\"m.relates_to\"];\n if (mRelatesTo) {\n // Clone content here so we don't remove `m.relates_to` from the local-echo\n content = Object.assign({}, content);\n delete content[\"m.relates_to\"];\n }\n\n // Treat element's performance metrics the same as `m.relates_to` (when present)\n const elementPerfMetrics = content[\"io.element.performance_metrics\"];\n if (elementPerfMetrics) {\n content = Object.assign({}, content);\n delete content[\"io.element.performance_metrics\"];\n }\n\n const encryptedContent = (await alg.encryptMessage(room, event.getType(), content)) as IContent;\n\n if (mRelatesTo) {\n encryptedContent[\"m.relates_to\"] = mRelatesTo;\n }\n if (elementPerfMetrics) {\n encryptedContent[\"io.element.performance_metrics\"] = elementPerfMetrics;\n }\n\n event.makeEncrypted(\n \"m.room.encrypted\",\n encryptedContent,\n this.olmDevice.deviceCurve25519Key!,\n this.olmDevice.deviceEd25519Key!,\n );\n }\n\n /**\n * Decrypt a received event\n *\n *\n * @returns resolves once we have\n * finished decrypting. Rejects with an `algorithms.DecryptionError` if there\n * is a problem decrypting the event.\n */\n public async decryptEvent(event: MatrixEvent): Promise {\n if (event.isRedacted()) {\n // Try to decrypt the redaction event, to support encrypted\n // redaction reasons. If we can't decrypt, just fall back to using\n // the original redacted_because.\n const redactionEvent = new MatrixEvent({\n room_id: event.getRoomId(),\n ...event.getUnsigned().redacted_because,\n });\n let redactedBecause: IEvent = event.getUnsigned().redacted_because!;\n if (redactionEvent.isEncrypted()) {\n try {\n const decryptedEvent = await this.decryptEvent(redactionEvent);\n redactedBecause = decryptedEvent.clearEvent as IEvent;\n } catch (e) {\n logger.warn(\"Decryption of redaction failed. Falling back to unencrypted event.\", e);\n }\n }\n\n return {\n clearEvent: {\n room_id: event.getRoomId(),\n type: \"m.room.message\",\n content: {},\n unsigned: {\n redacted_because: redactedBecause,\n },\n },\n };\n } else {\n const content = event.getWireContent();\n const alg = this.getRoomDecryptor(event.getRoomId()!, content.algorithm);\n return alg.decryptEvent(event);\n }\n }\n\n /**\n * Handle the notification from /sync or /keys/changes that device lists have\n * been changed.\n *\n * @param syncData - Object containing sync tokens associated with this sync\n * @param syncDeviceLists - device_lists field from /sync, or response from\n * /keys/changes\n */\n public async handleDeviceListChanges(\n syncData: ISyncStateData,\n syncDeviceLists: Required[\"device_lists\"],\n ): Promise {\n // Initial syncs don't have device change lists. We'll either get the complete list\n // of changes for the interval or will have invalidated everything in willProcessSync\n if (!syncData.oldSyncToken) return;\n\n // Here, we're relying on the fact that we only ever save the sync data after\n // sucessfully saving the device list data, so we're guaranteed that the device\n // list store is at least as fresh as the sync token from the sync store, ie.\n // any device changes received in sync tokens prior to the 'next' token here\n // have been processed and are reflected in the current device list.\n // If we didn't make this assumption, we'd have to use the /keys/changes API\n // to get key changes between the sync token in the device list and the 'old'\n // sync token used here to make sure we didn't miss any.\n await this.evalDeviceListChanges(syncDeviceLists);\n }\n\n /**\n * Send a request for some room keys, if we have not already done so\n *\n * @param resend - whether to resend the key request if there is\n * already one\n *\n * @returns a promise that resolves when the key request is queued\n */\n public requestRoomKey(\n requestBody: IRoomKeyRequestBody,\n recipients: IRoomKeyRequestRecipient[],\n resend = false,\n ): Promise {\n return this.outgoingRoomKeyRequestManager\n .queueRoomKeyRequest(requestBody, recipients, resend)\n .then(() => {\n if (this.sendKeyRequestsImmediately) {\n this.outgoingRoomKeyRequestManager.sendQueuedRequests();\n }\n })\n .catch((e) => {\n // this normally means we couldn't talk to the store\n logger.error(\"Error requesting key for event\", e);\n });\n }\n\n /**\n * Cancel any earlier room key request\n *\n * @param requestBody - parameters to match for cancellation\n */\n public cancelRoomKeyRequest(requestBody: IRoomKeyRequestBody): void {\n this.outgoingRoomKeyRequestManager.cancelRoomKeyRequest(requestBody).catch((e) => {\n logger.warn(\"Error clearing pending room key requests\", e);\n });\n }\n\n /**\n * Re-send any outgoing key requests, eg after verification\n * @returns\n */\n public async cancelAndResendAllOutgoingKeyRequests(): Promise {\n await this.outgoingRoomKeyRequestManager.cancelAndResendAllOutgoingRequests();\n }\n\n /**\n * handle an m.room.encryption event\n *\n * @param room - in which the event was received\n * @param event - encryption event to be processed\n */\n public async onCryptoEvent(room: Room, event: MatrixEvent): Promise {\n const content = event.getContent();\n await this.setRoomEncryptionImpl(room, content);\n }\n\n /**\n * Called before the result of a sync is processed\n *\n * @param syncData - the data from the 'MatrixClient.sync' event\n */\n public async onSyncWillProcess(syncData: ISyncStateData): Promise {\n if (!syncData.oldSyncToken) {\n // If there is no old sync token, we start all our tracking from\n // scratch, so mark everything as untracked. onCryptoEvent will\n // be called for all e2e rooms during the processing of the sync,\n // at which point we'll start tracking all the users of that room.\n logger.log(\"Initial sync performed - resetting device tracking state\");\n this.deviceList.stopTrackingAllDeviceLists();\n // we always track our own device list (for key backups etc)\n this.deviceList.startTrackingDeviceList(this.userId);\n this.roomDeviceTrackingState = {};\n }\n\n this.sendKeyRequestsImmediately = false;\n }\n\n /**\n * handle the completion of a /sync\n *\n * This is called after the processing of each successful /sync response.\n * It is an opportunity to do a batch process on the information received.\n *\n * @param syncData - the data from the 'MatrixClient.sync' event\n */\n public async onSyncCompleted(syncData: OnSyncCompletedData): Promise {\n this.deviceList.setSyncToken(syncData.nextSyncToken ?? null);\n this.deviceList.saveIfDirty();\n\n // we always track our own device list (for key backups etc)\n this.deviceList.startTrackingDeviceList(this.userId);\n\n this.deviceList.refreshOutdatedDeviceLists();\n\n // we don't start uploading one-time keys until we've caught up with\n // to-device messages, to help us avoid throwing away one-time-keys that we\n // are about to receive messages for\n // (https://github.com/vector-im/element-web/issues/2782).\n if (!syncData.catchingUp) {\n this.maybeUploadOneTimeKeys();\n this.processReceivedRoomKeyRequests();\n\n // likewise don't start requesting keys until we've caught up\n // on to_device messages, otherwise we'll request keys that we're\n // just about to get.\n this.outgoingRoomKeyRequestManager.sendQueuedRequests();\n\n // Sync has finished so send key requests straight away.\n this.sendKeyRequestsImmediately = true;\n }\n }\n\n /**\n * Trigger the appropriate invalidations and removes for a given\n * device list\n *\n * @param deviceLists - device_lists field from /sync, or response from\n * /keys/changes\n */\n private async evalDeviceListChanges(deviceLists: Required[\"device_lists\"]): Promise {\n if (Array.isArray(deviceLists?.changed)) {\n deviceLists.changed.forEach((u) => {\n this.deviceList.invalidateUserDeviceList(u);\n });\n }\n\n if (Array.isArray(deviceLists?.left) && deviceLists.left.length) {\n // Check we really don't share any rooms with these users\n // any more: the server isn't required to give us the\n // exact correct set.\n const e2eUserIds = new Set(await this.getTrackedE2eUsers());\n\n deviceLists.left.forEach((u) => {\n if (!e2eUserIds.has(u)) {\n this.deviceList.stopTrackingDeviceList(u);\n }\n });\n }\n }\n\n /**\n * Get a list of all the IDs of users we share an e2e room with\n * for which we are tracking devices already\n *\n * @returns List of user IDs\n */\n private async getTrackedE2eUsers(): Promise {\n const e2eUserIds: string[] = [];\n for (const room of this.getTrackedE2eRooms()) {\n const members = await room.getEncryptionTargetMembers();\n for (const member of members) {\n e2eUserIds.push(member.userId);\n }\n }\n return e2eUserIds;\n }\n\n /**\n * Get a list of the e2e-enabled rooms we are members of,\n * and for which we are already tracking the devices\n *\n * @returns\n */\n private getTrackedE2eRooms(): Room[] {\n return this.clientStore.getRooms().filter((room) => {\n // check for rooms with encryption enabled\n const alg = this.roomEncryptors.get(room.roomId);\n if (!alg) {\n return false;\n }\n if (!this.roomDeviceTrackingState[room.roomId]) {\n return false;\n }\n\n // ignore any rooms which we have left\n const myMembership = room.getMyMembership();\n return myMembership === \"join\" || myMembership === \"invite\";\n });\n }\n\n /**\n * Encrypts and sends a given object via Olm to-device messages to a given\n * set of devices.\n * @param userDeviceInfoArr - the devices to send to\n * @param payload - fields to include in the encrypted payload\n * @returns Promise which\n * resolves once the message has been encrypted and sent to the given\n * userDeviceMap, and returns the `{ contentMap, deviceInfoByDeviceId }`\n * of the successfully sent messages.\n */\n public async encryptAndSendToDevices(userDeviceInfoArr: IOlmDevice[], payload: object): Promise {\n const toDeviceBatch: ToDeviceBatch = {\n eventType: EventType.RoomMessageEncrypted,\n batch: [],\n };\n\n try {\n await Promise.all(\n userDeviceInfoArr.map(async ({ userId, deviceInfo }) => {\n const deviceId = deviceInfo.deviceId;\n const encryptedContent: IEncryptedContent = {\n algorithm: olmlib.OLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key!,\n ciphertext: {},\n [ToDeviceMessageId]: uuidv4(),\n };\n\n toDeviceBatch.batch.push({\n userId,\n deviceId,\n payload: encryptedContent,\n });\n\n await olmlib.ensureOlmSessionsForDevices(\n this.olmDevice,\n this.baseApis,\n new Map([[userId, [deviceInfo]]]),\n );\n await olmlib.encryptMessageForDevice(\n encryptedContent.ciphertext,\n this.userId,\n this.deviceId,\n this.olmDevice,\n userId,\n deviceInfo,\n payload,\n );\n }),\n );\n\n // prune out any devices that encryptMessageForDevice could not encrypt for,\n // in which case it will have just not added anything to the ciphertext object.\n // There's no point sending messages to devices if we couldn't encrypt to them,\n // since that's effectively a blank message.\n toDeviceBatch.batch = toDeviceBatch.batch.filter((msg) => {\n if (Object.keys(msg.payload.ciphertext).length > 0) {\n return true;\n } else {\n logger.log(`No ciphertext for device ${msg.userId}:${msg.deviceId}: pruning`);\n return false;\n }\n });\n\n try {\n await this.baseApis.queueToDevice(toDeviceBatch);\n } catch (e) {\n logger.error(\"sendToDevice failed\", e);\n throw e;\n }\n } catch (e) {\n logger.error(\"encryptAndSendToDevices promises failed\", e);\n throw e;\n }\n }\n\n private onMembership = (event: MatrixEvent, member: RoomMember, oldMembership?: string): void => {\n try {\n this.onRoomMembership(event, member, oldMembership);\n } catch (e) {\n logger.error(\"Error handling membership change:\", e);\n }\n };\n\n public async preprocessToDeviceMessages(events: IToDeviceEvent[]): Promise {\n // all we do here is filter out encrypted to-device messages with the wrong algorithm. Decryption\n // happens later in decryptEvent, via the EventMapper\n return events.filter((toDevice) => {\n if (\n toDevice.type === EventType.RoomMessageEncrypted &&\n ![\"m.olm.v1.curve25519-aes-sha2\"].includes(toDevice.content?.algorithm)\n ) {\n logger.log(\"Ignoring invalid encrypted to-device event from \" + toDevice.sender);\n return false;\n }\n return true;\n });\n }\n\n public preprocessOneTimeKeyCounts(oneTimeKeysCounts: Map): Promise {\n const currentCount = oneTimeKeysCounts.get(\"signed_curve25519\") || 0;\n this.updateOneTimeKeyCount(currentCount);\n return Promise.resolve();\n }\n\n public preprocessUnusedFallbackKeys(unusedFallbackKeys: Set): Promise {\n this.setNeedsNewFallback(!unusedFallbackKeys.has(\"signed_curve25519\"));\n return Promise.resolve();\n }\n\n private onToDeviceEvent = (event: MatrixEvent): void => {\n try {\n logger.log(\n `received to-device ${event.getType()} from: ` +\n `${event.getSender()} id: ${event.getContent()[ToDeviceMessageId]}`,\n );\n\n if (event.getType() == \"m.room_key\" || event.getType() == \"m.forwarded_room_key\") {\n this.onRoomKeyEvent(event);\n } else if (event.getType() == \"m.room_key_request\") {\n this.onRoomKeyRequestEvent(event);\n } else if (event.getType() === \"m.secret.request\") {\n this.secretStorage.onRequestReceived(event);\n } else if (event.getType() === \"m.secret.send\") {\n this.secretStorage.onSecretReceived(event);\n } else if (event.getType() === \"m.room_key.withheld\") {\n this.onRoomKeyWithheldEvent(event);\n } else if (event.getContent().transaction_id) {\n this.onKeyVerificationMessage(event);\n } else if (event.getContent().msgtype === \"m.bad.encrypted\") {\n this.onToDeviceBadEncrypted(event);\n } else if (event.isBeingDecrypted() || event.shouldAttemptDecryption()) {\n if (!event.isBeingDecrypted()) {\n event.attemptDecryption(this);\n }\n // once the event has been decrypted, try again\n event.once(MatrixEventEvent.Decrypted, (ev) => {\n this.onToDeviceEvent(ev);\n });\n }\n } catch (e) {\n logger.error(\"Error handling toDeviceEvent:\", e);\n }\n };\n\n /**\n * Handle a key event\n *\n * @internal\n * @param event - key event\n */\n private onRoomKeyEvent(event: MatrixEvent): void {\n const content = event.getContent();\n\n if (!content.room_id || !content.algorithm) {\n logger.error(\"key event is missing fields\");\n return;\n }\n\n if (!this.backupManager.checkedForBackup) {\n // don't bother awaiting on this - the important thing is that we retry if we\n // haven't managed to check before\n this.backupManager.checkAndStart();\n }\n\n const alg = this.getRoomDecryptor(content.room_id, content.algorithm);\n alg.onRoomKeyEvent(event);\n }\n\n /**\n * Handle a key withheld event\n *\n * @internal\n * @param event - key withheld event\n */\n private onRoomKeyWithheldEvent(event: MatrixEvent): void {\n const content = event.getContent();\n\n if (\n (content.code !== \"m.no_olm\" && (!content.room_id || !content.session_id)) ||\n !content.algorithm ||\n !content.sender_key\n ) {\n logger.error(\"key withheld event is missing fields\");\n return;\n }\n\n logger.info(\n `Got room key withheld event from ${event.getSender()} ` +\n `for ${content.algorithm} session ${content.sender_key}|${content.session_id} ` +\n `in room ${content.room_id} with code ${content.code} (${content.reason})`,\n );\n\n const alg = this.getRoomDecryptor(content.room_id, content.algorithm);\n if (alg.onRoomKeyWithheldEvent) {\n alg.onRoomKeyWithheldEvent(event);\n }\n if (!content.room_id) {\n // retry decryption for all events sent by the sender_key. This will\n // update the events to show a message indicating that the olm session was\n // wedged.\n const roomDecryptors = this.getRoomDecryptors(content.algorithm);\n for (const decryptor of roomDecryptors) {\n decryptor.retryDecryptionFromSender(content.sender_key);\n }\n }\n }\n\n /**\n * Handle a general key verification event.\n *\n * @internal\n * @param event - verification start event\n */\n private onKeyVerificationMessage(event: MatrixEvent): void {\n if (!ToDeviceChannel.validateEvent(event, this.baseApis)) {\n return;\n }\n const createRequest = (event: MatrixEvent): VerificationRequest | undefined => {\n if (!ToDeviceChannel.canCreateRequest(ToDeviceChannel.getEventType(event))) {\n return;\n }\n const content = event.getContent();\n const deviceId = content && content.from_device;\n if (!deviceId) {\n return;\n }\n const userId = event.getSender()!;\n const channel = new ToDeviceChannel(this.baseApis, userId, [deviceId]);\n return new VerificationRequest(channel, this.verificationMethods, this.baseApis);\n };\n this.handleVerificationEvent(event, this.toDeviceVerificationRequests, createRequest);\n }\n\n /**\n * Handle key verification requests sent as timeline events\n *\n * @internal\n * @param event - the timeline event\n * @param room - not used\n * @param atStart - not used\n * @param removed - not used\n * @param whether - this is a live event\n */\n private onTimelineEvent = (\n event: MatrixEvent,\n room: Room,\n atStart: boolean,\n removed: boolean,\n { liveEvent = true } = {},\n ): void => {\n if (!InRoomChannel.validateEvent(event, this.baseApis)) {\n return;\n }\n const createRequest = (event: MatrixEvent): VerificationRequest => {\n const channel = new InRoomChannel(this.baseApis, event.getRoomId()!);\n return new VerificationRequest(channel, this.verificationMethods, this.baseApis);\n };\n this.handleVerificationEvent(event, this.inRoomVerificationRequests, createRequest, liveEvent);\n };\n\n private async handleVerificationEvent(\n event: MatrixEvent,\n requestsMap: IRequestsMap,\n createRequest: (event: MatrixEvent) => VerificationRequest | undefined,\n isLiveEvent = true,\n ): Promise {\n // Wait for event to get its final ID with pendingEventOrdering: \"chronological\", since DM channels depend on it.\n if (event.isSending() && event.status != EventStatus.SENT) {\n let eventIdListener: () => void;\n let statusListener: () => void;\n try {\n await new Promise((resolve, reject) => {\n eventIdListener = resolve;\n statusListener = (): void => {\n if (event.status == EventStatus.CANCELLED) {\n reject(new Error(\"Event status set to CANCELLED.\"));\n }\n };\n event.once(MatrixEventEvent.LocalEventIdReplaced, eventIdListener);\n event.on(MatrixEventEvent.Status, statusListener);\n });\n } catch (err) {\n logger.error(\"error while waiting for the verification event to be sent: \", err);\n return;\n } finally {\n event.removeListener(MatrixEventEvent.LocalEventIdReplaced, eventIdListener!);\n event.removeListener(MatrixEventEvent.Status, statusListener!);\n }\n }\n let request: VerificationRequest | undefined = requestsMap.getRequest(event);\n let isNewRequest = false;\n if (!request) {\n request = createRequest(event);\n // a request could not be made from this event, so ignore event\n if (!request) {\n logger.log(\n `Crypto: could not find VerificationRequest for ` +\n `${event.getType()}, and could not create one, so ignoring.`,\n );\n return;\n }\n isNewRequest = true;\n requestsMap.setRequest(event, request);\n }\n event.setVerificationRequest(request);\n try {\n await request.channel.handleEvent(event, request, isLiveEvent);\n } catch (err) {\n logger.error(\"error while handling verification event\", err);\n }\n const shouldEmit =\n isNewRequest &&\n !request.initiatedByMe &&\n !request.invalid && // check it has enough events to pass the UNSENT stage\n !request.observeOnly;\n if (shouldEmit) {\n this.baseApis.emit(CryptoEvent.VerificationRequest, request);\n }\n }\n\n /**\n * Handle a toDevice event that couldn't be decrypted\n *\n * @internal\n * @param event - undecryptable event\n */\n private async onToDeviceBadEncrypted(event: MatrixEvent): Promise {\n const content = event.getWireContent();\n const sender = event.getSender();\n const algorithm = content.algorithm;\n const deviceKey = content.sender_key;\n\n this.baseApis.emit(ClientEvent.UndecryptableToDeviceEvent, event);\n\n // retry decryption for all events sent by the sender_key. This will\n // update the events to show a message indicating that the olm session was\n // wedged.\n const retryDecryption = (): void => {\n const roomDecryptors = this.getRoomDecryptors(olmlib.MEGOLM_ALGORITHM);\n for (const decryptor of roomDecryptors) {\n decryptor.retryDecryptionFromSender(deviceKey);\n }\n };\n\n if (sender === undefined || deviceKey === undefined || deviceKey === undefined) {\n return;\n }\n\n // check when we last forced a new session with this device: if we've already done so\n // recently, don't do it again.\n const lastNewSessionDevices = this.lastNewSessionForced.getOrCreate(sender);\n const lastNewSessionForced = lastNewSessionDevices.getOrCreate(deviceKey);\n if (lastNewSessionForced + MIN_FORCE_SESSION_INTERVAL_MS > Date.now()) {\n logger.debug(\n \"New session already forced with device \" +\n sender +\n \":\" +\n deviceKey +\n \" at \" +\n lastNewSessionForced +\n \": not forcing another\",\n );\n await this.olmDevice.recordSessionProblem(deviceKey, \"wedged\", true);\n retryDecryption();\n return;\n }\n\n // establish a new olm session with this device since we're failing to decrypt messages\n // on a current session.\n // Note that an undecryptable message from another device could easily be spoofed -\n // is there anything we can do to mitigate this?\n let device = this.deviceList.getDeviceByIdentityKey(algorithm, deviceKey);\n if (!device) {\n // if we don't know about the device, fetch the user's devices again\n // and retry before giving up\n await this.downloadKeys([sender], false);\n device = this.deviceList.getDeviceByIdentityKey(algorithm, deviceKey);\n if (!device) {\n logger.info(\"Couldn't find device for identity key \" + deviceKey + \": not re-establishing session\");\n await this.olmDevice.recordSessionProblem(deviceKey, \"wedged\", false);\n retryDecryption();\n return;\n }\n }\n const devicesByUser = new Map([[sender, [device]]]);\n await olmlib.ensureOlmSessionsForDevices(this.olmDevice, this.baseApis, devicesByUser, true);\n\n lastNewSessionDevices.set(deviceKey, Date.now());\n\n // Now send a blank message on that session so the other side knows about it.\n // (The keyshare request is sent in the clear so that won't do)\n // We send this first such that, as long as the toDevice messages arrive in the\n // same order we sent them, the other end will get this first, set up the new session,\n // then get the keyshare request and send the key over this new session (because it\n // is the session it has most recently received a message on).\n const encryptedContent: IEncryptedContent = {\n algorithm: olmlib.OLM_ALGORITHM,\n sender_key: this.olmDevice.deviceCurve25519Key!,\n ciphertext: {},\n [ToDeviceMessageId]: uuidv4(),\n };\n await olmlib.encryptMessageForDevice(\n encryptedContent.ciphertext,\n this.userId,\n this.deviceId,\n this.olmDevice,\n sender,\n device,\n { type: \"m.dummy\" },\n );\n\n await this.olmDevice.recordSessionProblem(deviceKey, \"wedged\", true);\n retryDecryption();\n\n await this.baseApis.sendToDevice(\n \"m.room.encrypted\",\n new Map([[sender, new Map([[device.deviceId, encryptedContent]])]]),\n );\n\n // Most of the time this probably won't be necessary since we'll have queued up a key request when\n // we failed to decrypt the message and will be waiting a bit for the key to arrive before sending\n // it. This won't always be the case though so we need to re-send any that have already been sent\n // to avoid races.\n const requestsToResend = await this.outgoingRoomKeyRequestManager.getOutgoingSentRoomKeyRequest(\n sender,\n device.deviceId,\n );\n for (const keyReq of requestsToResend) {\n this.requestRoomKey(keyReq.requestBody, keyReq.recipients, true);\n }\n }\n\n /**\n * Handle a change in the membership state of a member of a room\n *\n * @internal\n * @param event - event causing the change\n * @param member - user whose membership changed\n * @param oldMembership - previous membership\n */\n private onRoomMembership(event: MatrixEvent, member: RoomMember, oldMembership?: string): void {\n // this event handler is registered on the *client* (as opposed to the room\n // member itself), which means it is only called on changes to the *live*\n // membership state (ie, it is not called when we back-paginate, nor when\n // we load the state in the initialsync).\n //\n // Further, it is automatically registered and called when new members\n // arrive in the room.\n\n const roomId = member.roomId;\n\n const alg = this.roomEncryptors.get(roomId);\n if (!alg) {\n // not encrypting in this room\n return;\n }\n // only mark users in this room as tracked if we already started tracking in this room\n // this way we don't start device queries after sync on behalf of this room which we won't use\n // the result of anyway, as we'll need to do a query again once all the members are fetched\n // by calling _trackRoomDevices\n if (roomId in this.roomDeviceTrackingState) {\n if (member.membership == \"join\") {\n logger.log(\"Join event for \" + member.userId + \" in \" + roomId);\n // make sure we are tracking the deviceList for this user\n this.deviceList.startTrackingDeviceList(member.userId);\n } else if (\n member.membership == \"invite\" &&\n this.clientStore.getRoom(roomId)?.shouldEncryptForInvitedMembers()\n ) {\n logger.log(\"Invite event for \" + member.userId + \" in \" + roomId);\n this.deviceList.startTrackingDeviceList(member.userId);\n }\n }\n\n alg.onRoomMembership(event, member, oldMembership);\n }\n\n /**\n * Called when we get an m.room_key_request event.\n *\n * @internal\n * @param event - key request event\n */\n private onRoomKeyRequestEvent(event: MatrixEvent): void {\n const content = event.getContent();\n if (content.action === \"request\") {\n // Queue it up for now, because they tend to arrive before the room state\n // events at initial sync, and we want to see if we know anything about the\n // room before passing them on to the app.\n const req = new IncomingRoomKeyRequest(event);\n this.receivedRoomKeyRequests.push(req);\n } else if (content.action === \"request_cancellation\") {\n const req = new IncomingRoomKeyRequestCancellation(event);\n this.receivedRoomKeyRequestCancellations.push(req);\n }\n }\n\n /**\n * Process any m.room_key_request events which were queued up during the\n * current sync.\n *\n * @internal\n */\n private async processReceivedRoomKeyRequests(): Promise {\n if (this.processingRoomKeyRequests) {\n // we're still processing last time's requests; keep queuing new ones\n // up for now.\n return;\n }\n this.processingRoomKeyRequests = true;\n\n try {\n // we need to grab and clear the queues in the synchronous bit of this method,\n // so that we don't end up racing with the next /sync.\n const requests = this.receivedRoomKeyRequests;\n this.receivedRoomKeyRequests = [];\n const cancellations = this.receivedRoomKeyRequestCancellations;\n this.receivedRoomKeyRequestCancellations = [];\n\n // Process all of the requests, *then* all of the cancellations.\n //\n // This makes sure that if we get a request and its cancellation in the\n // same /sync result, then we process the request before the\n // cancellation (and end up with a cancelled request), rather than the\n // cancellation before the request (and end up with an outstanding\n // request which should have been cancelled.)\n await Promise.all(requests.map((req) => this.processReceivedRoomKeyRequest(req)));\n await Promise.all(\n cancellations.map((cancellation) => this.processReceivedRoomKeyRequestCancellation(cancellation)),\n );\n } catch (e) {\n logger.error(`Error processing room key requsts: ${e}`);\n } finally {\n this.processingRoomKeyRequests = false;\n }\n }\n\n /**\n * Helper for processReceivedRoomKeyRequests\n *\n */\n private async processReceivedRoomKeyRequest(req: IncomingRoomKeyRequest): Promise {\n const userId = req.userId;\n const deviceId = req.deviceId;\n\n const body = req.requestBody;\n const roomId = body.room_id;\n const alg = body.algorithm;\n\n logger.log(\n `m.room_key_request from ${userId}:${deviceId}` +\n ` for ${roomId} / ${body.session_id} (id ${req.requestId})`,\n );\n\n if (userId !== this.userId) {\n if (!this.roomEncryptors.get(roomId)) {\n logger.debug(`room key request for unencrypted room ${roomId}`);\n return;\n }\n const encryptor = this.roomEncryptors.get(roomId)!;\n const device = this.deviceList.getStoredDevice(userId, deviceId);\n if (!device) {\n logger.debug(`Ignoring keyshare for unknown device ${userId}:${deviceId}`);\n return;\n }\n\n try {\n await encryptor.reshareKeyWithDevice!(body.sender_key, body.session_id, userId, device);\n } catch (e) {\n logger.warn(\n \"Failed to re-share keys for session \" +\n body.session_id +\n \" with device \" +\n userId +\n \":\" +\n device.deviceId,\n e,\n );\n }\n return;\n }\n\n if (deviceId === this.deviceId) {\n // We'll always get these because we send room key requests to\n // '*' (ie. 'all devices') which includes the sending device,\n // so ignore requests from ourself because apart from it being\n // very silly, it won't work because an Olm session cannot send\n // messages to itself.\n // The log here is probably superfluous since we know this will\n // always happen, but let's log anyway for now just in case it\n // causes issues.\n logger.log(\"Ignoring room key request from ourselves\");\n return;\n }\n\n // todo: should we queue up requests we don't yet have keys for,\n // in case they turn up later?\n\n // if we don't have a decryptor for this room/alg, we don't have\n // the keys for the requested events, and can drop the requests.\n if (!this.roomDecryptors.has(roomId)) {\n logger.log(`room key request for unencrypted room ${roomId}`);\n return;\n }\n\n const decryptor = this.roomDecryptors.get(roomId)!.get(alg);\n if (!decryptor) {\n logger.log(`room key request for unknown alg ${alg} in room ${roomId}`);\n return;\n }\n\n if (!(await decryptor.hasKeysForKeyRequest(req))) {\n logger.log(`room key request for unknown session ${roomId} / ` + body.session_id);\n return;\n }\n\n req.share = (): void => {\n decryptor.shareKeysWithDevice(req);\n };\n\n // if the device is verified already, share the keys\n if (this.checkDeviceTrust(userId, deviceId).isVerified()) {\n logger.log(\"device is already verified: sharing keys\");\n req.share();\n return;\n }\n\n this.emit(CryptoEvent.RoomKeyRequest, req);\n }\n\n /**\n * Helper for processReceivedRoomKeyRequests\n *\n */\n private async processReceivedRoomKeyRequestCancellation(\n cancellation: IncomingRoomKeyRequestCancellation,\n ): Promise {\n logger.log(\n `m.room_key_request cancellation for ${cancellation.userId}:` +\n `${cancellation.deviceId} (id ${cancellation.requestId})`,\n );\n\n // we should probably only notify the app of cancellations we told it\n // about, but we don't currently have a record of that, so we just pass\n // everything through.\n this.emit(CryptoEvent.RoomKeyRequestCancellation, cancellation);\n }\n\n /**\n * Get a decryptor for a given room and algorithm.\n *\n * If we already have a decryptor for the given room and algorithm, return\n * it. Otherwise try to instantiate it.\n *\n * @internal\n *\n * @param roomId - room id for decryptor. If undefined, a temporary\n * decryptor is instantiated.\n *\n * @param algorithm - crypto algorithm\n *\n * @throws {@link DecryptionError} if the algorithm is unknown\n */\n public getRoomDecryptor(roomId: string | null, algorithm: string): DecryptionAlgorithm {\n let decryptors: Map | undefined;\n let alg: DecryptionAlgorithm | undefined;\n\n if (roomId) {\n decryptors = this.roomDecryptors.get(roomId);\n if (!decryptors) {\n decryptors = new Map();\n this.roomDecryptors.set(roomId, decryptors);\n }\n\n alg = decryptors.get(algorithm);\n if (alg) {\n return alg;\n }\n }\n\n const AlgClass = algorithms.DECRYPTION_CLASSES.get(algorithm);\n if (!AlgClass) {\n throw new algorithms.DecryptionError(\n \"UNKNOWN_ENCRYPTION_ALGORITHM\",\n 'Unknown encryption algorithm \"' + algorithm + '\".',\n );\n }\n alg = new AlgClass({\n userId: this.userId,\n crypto: this,\n olmDevice: this.olmDevice,\n baseApis: this.baseApis,\n roomId: roomId ?? undefined,\n });\n\n if (decryptors) {\n decryptors.set(algorithm, alg);\n }\n return alg;\n }\n\n /**\n * Get all the room decryptors for a given encryption algorithm.\n *\n * @param algorithm - The encryption algorithm\n *\n * @returns An array of room decryptors\n */\n private getRoomDecryptors(algorithm: string): DecryptionAlgorithm[] {\n const decryptors: DecryptionAlgorithm[] = [];\n for (const d of this.roomDecryptors.values()) {\n if (d.has(algorithm)) {\n decryptors.push(d.get(algorithm)!);\n }\n }\n return decryptors;\n }\n\n /**\n * sign the given object with our ed25519 key\n *\n * @param obj - Object to which we will add a 'signatures' property\n */\n public async signObject(obj: T): Promise {\n const sigs = new Map(Object.entries(obj.signatures || {}));\n const unsigned = obj.unsigned;\n\n delete obj.signatures;\n delete obj.unsigned;\n\n const userSignatures = sigs.get(this.userId) || {};\n sigs.set(this.userId, userSignatures);\n userSignatures[\"ed25519:\" + this.deviceId] = await this.olmDevice.sign(anotherjson.stringify(obj));\n obj.signatures = recursiveMapToObject(sigs);\n if (unsigned !== undefined) obj.unsigned = unsigned;\n }\n}\n\n/**\n * Fix up the backup key, that may be in the wrong format due to a bug in a\n * migration step. Some backup keys were stored as a comma-separated list of\n * integers, rather than a base64-encoded byte array. If this function is\n * passed a string that looks like a list of integers rather than a base64\n * string, it will attempt to convert it to the right format.\n *\n * @param key - the key to check\n * @returns If the key is in the wrong format, then the fixed\n * key will be returned. Otherwise null will be returned.\n *\n */\nexport function fixBackupKey(key?: string): string | null {\n if (typeof key !== \"string\" || key.indexOf(\",\") < 0) {\n return null;\n }\n const fixedKey = Uint8Array.from(key.split(\",\"), (x) => parseInt(x));\n return olmlib.encodeBase64(fixedKey);\n}\n\n/**\n * Represents a received m.room_key_request event\n */\nexport class IncomingRoomKeyRequest {\n /** user requesting the key */\n public readonly userId: string;\n /** device requesting the key */\n public readonly deviceId: string;\n /** unique id for the request */\n public readonly requestId: string;\n public readonly requestBody: IRoomKeyRequestBody;\n /**\n * callback which, when called, will ask\n * the relevant crypto algorithm implementation to share the keys for\n * this request.\n */\n public share: () => void;\n\n public constructor(event: MatrixEvent) {\n const content = event.getContent();\n\n this.userId = event.getSender()!;\n this.deviceId = content.requesting_device_id;\n this.requestId = content.request_id;\n this.requestBody = content.body || {};\n this.share = (): void => {\n throw new Error(\"don't know how to share keys for this request yet\");\n };\n }\n}\n\n/**\n * Represents a received m.room_key_request cancellation\n */\nclass IncomingRoomKeyRequestCancellation {\n /** user requesting the cancellation */\n public readonly userId: string;\n /** device requesting the cancellation */\n public readonly deviceId: string;\n /** unique id for the request to be cancelled */\n public readonly requestId: string;\n\n public constructor(event: MatrixEvent) {\n const content = event.getContent();\n\n this.userId = event.getSender()!;\n this.deviceId = content.requesting_device_id;\n this.requestId = content.request_id;\n }\n}\n\n// a number of types are re-exported for backwards compatibility, in case any applications are referencing it.\nexport type { IEventDecryptionResult, IMegolmSessionData } from \"../@types/crypto\";\n", - "/*\nCopyright 2018 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { randomString } from \"../randomstring\";\nimport { subtleCrypto, TextEncoder } from \"./crypto\";\n\nconst DEFAULT_ITERATIONS = 500000;\n\nconst DEFAULT_BITSIZE = 256;\n\n/* eslint-disable camelcase */\ninterface IAuthData {\n private_key_salt?: string;\n private_key_iterations?: number;\n private_key_bits?: number;\n}\n/* eslint-enable camelcase */\n\ninterface IKey {\n key: Uint8Array;\n salt: string;\n iterations: number;\n}\n\nexport function keyFromAuthData(authData: IAuthData, password: string): Promise {\n if (!global.Olm) {\n throw new Error(\"Olm is not available\");\n }\n\n if (!authData.private_key_salt || !authData.private_key_iterations) {\n throw new Error(\"Salt and/or iterations not found: \" + \"this backup cannot be restored with a passphrase\");\n }\n\n return deriveKey(\n password,\n authData.private_key_salt,\n authData.private_key_iterations,\n authData.private_key_bits || DEFAULT_BITSIZE,\n );\n}\n\nexport async function keyFromPassphrase(password: string): Promise {\n if (!global.Olm) {\n throw new Error(\"Olm is not available\");\n }\n\n const salt = randomString(32);\n\n const key = await deriveKey(password, salt, DEFAULT_ITERATIONS, DEFAULT_BITSIZE);\n\n return { key, salt, iterations: DEFAULT_ITERATIONS };\n}\n\nexport async function deriveKey(\n password: string,\n salt: string,\n iterations: number,\n numBits = DEFAULT_BITSIZE,\n): Promise {\n if (!subtleCrypto || !TextEncoder) {\n throw new Error(\"Password-based backup is not available on this platform\");\n }\n\n const key = await subtleCrypto.importKey(\"raw\", new TextEncoder().encode(password), { name: \"PBKDF2\" }, false, [\n \"deriveBits\",\n ]);\n\n const keybits = await subtleCrypto.deriveBits(\n {\n name: \"PBKDF2\",\n salt: new TextEncoder().encode(salt),\n iterations: iterations,\n hash: \"SHA-512\",\n },\n key,\n numBits,\n );\n\n return new Uint8Array(keybits);\n}\n", - "/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Utilities common to olm encryption algorithms\n */\n\nimport anotherjson from \"another-json\";\n\nimport type { PkSigning } from \"@matrix-org/olm\";\nimport type { IOneTimeKey } from \"../@types/crypto\";\nimport { OlmDevice } from \"./OlmDevice\";\nimport { DeviceInfo } from \"./deviceinfo\";\nimport { logger } from \"../logger\";\nimport { IClaimOTKsResult, MatrixClient } from \"../client\";\nimport { ISignatures } from \"../@types/signed\";\nimport { MatrixEvent } from \"../models/event\";\nimport { EventType } from \"../@types/event\";\nimport { IMessage } from \"./algorithms/olm\";\nimport { MapWithDefault } from \"../utils\";\n\nenum Algorithm {\n Olm = \"m.olm.v1.curve25519-aes-sha2\",\n Megolm = \"m.megolm.v1.aes-sha2\",\n MegolmBackup = \"m.megolm_backup.v1.curve25519-aes-sha2\",\n}\n\n/**\n * matrix algorithm tag for olm\n */\nexport const OLM_ALGORITHM = Algorithm.Olm;\n\n/**\n * matrix algorithm tag for megolm\n */\nexport const MEGOLM_ALGORITHM = Algorithm.Megolm;\n\n/**\n * matrix algorithm tag for megolm backups\n */\nexport const MEGOLM_BACKUP_ALGORITHM = Algorithm.MegolmBackup;\n\nexport interface IOlmSessionResult {\n /** device info */\n device: DeviceInfo;\n /** base64 olm session id; null if no session could be established */\n sessionId: string | null;\n}\n\n/**\n * Encrypt an event payload for an Olm device\n *\n * @param resultsObject - The `ciphertext` property\n * of the m.room.encrypted event to which to add our result\n *\n * @param olmDevice - olm.js wrapper\n * @param payloadFields - fields to include in the encrypted payload\n *\n * Returns a promise which resolves (to undefined) when the payload\n * has been encrypted into `resultsObject`\n */\nexport async function encryptMessageForDevice(\n resultsObject: Record,\n ourUserId: string,\n ourDeviceId: string | undefined,\n olmDevice: OlmDevice,\n recipientUserId: string,\n recipientDevice: DeviceInfo,\n payloadFields: Record,\n): Promise {\n const deviceKey = recipientDevice.getIdentityKey();\n const sessionId = await olmDevice.getSessionIdForDevice(deviceKey);\n if (sessionId === null) {\n // If we don't have a session for a device then\n // we can't encrypt a message for it.\n logger.log(\n `[olmlib.encryptMessageForDevice] Unable to find Olm session for device ` +\n `${recipientUserId}:${recipientDevice.deviceId}`,\n );\n return;\n }\n\n logger.log(\n `[olmlib.encryptMessageForDevice] Using Olm session ${sessionId} for device ` +\n `${recipientUserId}:${recipientDevice.deviceId}`,\n );\n\n const payload = {\n sender: ourUserId,\n // TODO this appears to no longer be used whatsoever\n sender_device: ourDeviceId,\n\n // Include the Ed25519 key so that the recipient knows what\n // device this message came from.\n // We don't need to include the curve25519 key since the\n // recipient will already know this from the olm headers.\n // When combined with the device keys retrieved from the\n // homeserver signed by the ed25519 key this proves that\n // the curve25519 key and the ed25519 key are owned by\n // the same device.\n keys: {\n ed25519: olmDevice.deviceEd25519Key,\n },\n\n // include the recipient device details in the payload,\n // to avoid unknown key attacks, per\n // https://github.com/vector-im/vector-web/issues/2483\n recipient: recipientUserId,\n recipient_keys: {\n ed25519: recipientDevice.getFingerprint(),\n },\n ...payloadFields,\n };\n\n // TODO: technically, a bunch of that stuff only needs to be included for\n // pre-key messages: after that, both sides know exactly which devices are\n // involved in the session. If we're looking to reduce data transfer in the\n // future, we could elide them for subsequent messages.\n\n resultsObject[deviceKey] = await olmDevice.encryptMessage(deviceKey, sessionId, JSON.stringify(payload));\n}\n\ninterface IExistingOlmSession {\n device: DeviceInfo;\n sessionId: string | null;\n}\n\n/**\n * Get the existing olm sessions for the given devices, and the devices that\n * don't have olm sessions.\n *\n *\n *\n * @param devicesByUser - map from userid to list of devices to ensure sessions for\n *\n * @returns resolves to an array. The first element of the array is a\n * a map of user IDs to arrays of deviceInfo, representing the devices that\n * don't have established olm sessions. The second element of the array is\n * a map from userId to deviceId to {@link OlmSessionResult}\n */\nexport async function getExistingOlmSessions(\n olmDevice: OlmDevice,\n baseApis: MatrixClient,\n devicesByUser: Record,\n): Promise<[Map, Map>]> {\n // map user Id → DeviceInfo[]\n const devicesWithoutSession: MapWithDefault = new MapWithDefault(() => []);\n // map user Id → device Id → IExistingOlmSession\n const sessions: MapWithDefault> = new MapWithDefault(() => new Map());\n\n const promises: Promise[] = [];\n\n for (const [userId, devices] of Object.entries(devicesByUser)) {\n for (const deviceInfo of devices) {\n const deviceId = deviceInfo.deviceId;\n const key = deviceInfo.getIdentityKey();\n promises.push(\n (async (): Promise => {\n const sessionId = await olmDevice.getSessionIdForDevice(key, true);\n if (sessionId === null) {\n devicesWithoutSession.getOrCreate(userId).push(deviceInfo);\n } else {\n sessions.getOrCreate(userId).set(deviceId, {\n device: deviceInfo,\n sessionId: sessionId,\n });\n }\n })(),\n );\n }\n }\n\n await Promise.all(promises);\n\n return [devicesWithoutSession, sessions];\n}\n\n/**\n * Try to make sure we have established olm sessions for the given devices.\n *\n * @param devicesByUser - map from userid to list of devices to ensure sessions for\n *\n * @param force - If true, establish a new session even if one\n * already exists.\n *\n * @param otkTimeout - The timeout in milliseconds when requesting\n * one-time keys for establishing new olm sessions.\n *\n * @param failedServers - An array to fill with remote servers that\n * failed to respond to one-time-key requests.\n *\n * @param log - A possibly customised log\n *\n * @returns resolves once the sessions are complete, to\n * an Object mapping from userId to deviceId to\n * {@link OlmSessionResult}\n */\nexport async function ensureOlmSessionsForDevices(\n olmDevice: OlmDevice,\n baseApis: MatrixClient,\n devicesByUser: Map,\n force = false,\n otkTimeout?: number,\n failedServers?: string[],\n log = logger,\n): Promise>> {\n const devicesWithoutSession: [string, string][] = [\n // [userId, deviceId], ...\n ];\n // map user Id → device Id → IExistingOlmSession\n const result: Map> = new Map();\n // map device key → resolve session fn\n const resolveSession: Map void> = new Map();\n\n // Mark all sessions this task intends to update as in progress. It is\n // important to do this for all devices this task cares about in a single\n // synchronous operation, as otherwise it is possible to have deadlocks\n // where multiple tasks wait indefinitely on another task to update some set\n // of common devices.\n for (const devices of devicesByUser.values()) {\n for (const deviceInfo of devices) {\n const key = deviceInfo.getIdentityKey();\n\n if (key === olmDevice.deviceCurve25519Key) {\n // We don't start sessions with ourself, so there's no need to\n // mark it in progress.\n continue;\n }\n\n if (!olmDevice.sessionsInProgress[key]) {\n // pre-emptively mark the session as in-progress to avoid race\n // conditions. If we find that we already have a session, then\n // we'll resolve\n olmDevice.sessionsInProgress[key] = new Promise((resolve) => {\n resolveSession.set(key, (v: any): void => {\n delete olmDevice.sessionsInProgress[key];\n resolve(v);\n });\n });\n }\n }\n }\n\n for (const [userId, devices] of devicesByUser) {\n const resultDevices = new Map();\n result.set(userId, resultDevices);\n\n for (const deviceInfo of devices) {\n const deviceId = deviceInfo.deviceId;\n const key = deviceInfo.getIdentityKey();\n\n if (key === olmDevice.deviceCurve25519Key) {\n // We should never be trying to start a session with ourself.\n // Apart from talking to yourself being the first sign of madness,\n // olm sessions can't do this because they get confused when\n // they get a message and see that the 'other side' has started a\n // new chain when this side has an active sender chain.\n // If you see this message being logged in the wild, we should find\n // the thing that is trying to send Olm messages to itself and fix it.\n log.info(\"Attempted to start session with ourself! Ignoring\");\n // We must fill in the section in the return value though, as callers\n // expect it to be there.\n resultDevices.set(deviceId, {\n device: deviceInfo,\n sessionId: null,\n });\n continue;\n }\n\n const forWhom = `for ${key} (${userId}:${deviceId})`;\n const sessionId = await olmDevice.getSessionIdForDevice(key, !!resolveSession.get(key), log);\n const resolveSessionFn = resolveSession.get(key);\n if (sessionId !== null && resolveSessionFn) {\n // we found a session, but we had marked the session as\n // in-progress, so resolve it now, which will unmark it and\n // unblock anything that was waiting\n resolveSessionFn();\n }\n if (sessionId === null || force) {\n if (force) {\n log.info(`Forcing new Olm session ${forWhom}`);\n } else {\n log.info(`Making new Olm session ${forWhom}`);\n }\n devicesWithoutSession.push([userId, deviceId]);\n }\n resultDevices.set(deviceId, {\n device: deviceInfo,\n sessionId: sessionId,\n });\n }\n }\n\n if (devicesWithoutSession.length === 0) {\n return result;\n }\n\n const oneTimeKeyAlgorithm = \"signed_curve25519\";\n let res: IClaimOTKsResult;\n let taskDetail = `one-time keys for ${devicesWithoutSession.length} devices`;\n try {\n log.debug(`Claiming ${taskDetail}`);\n res = await baseApis.claimOneTimeKeys(devicesWithoutSession, oneTimeKeyAlgorithm, otkTimeout);\n log.debug(`Claimed ${taskDetail}`);\n } catch (e) {\n for (const resolver of resolveSession.values()) {\n resolver();\n }\n log.log(`Failed to claim ${taskDetail}`, e, devicesWithoutSession);\n throw e;\n }\n\n if (failedServers && \"failures\" in res) {\n failedServers.push(...Object.keys(res.failures));\n }\n\n const otkResult = res.one_time_keys || ({} as IClaimOTKsResult[\"one_time_keys\"]);\n const promises: Promise[] = [];\n for (const [userId, devices] of devicesByUser) {\n const userRes = otkResult[userId] || {};\n for (const deviceInfo of devices) {\n const deviceId = deviceInfo.deviceId;\n const key = deviceInfo.getIdentityKey();\n\n if (key === olmDevice.deviceCurve25519Key) {\n // We've already logged about this above. Skip here too\n // otherwise we'll log saying there are no one-time keys\n // which will be confusing.\n continue;\n }\n\n if (result.get(userId)?.get(deviceId)?.sessionId && !force) {\n // we already have a result for this device\n continue;\n }\n\n const deviceRes = userRes[deviceId] || {};\n let oneTimeKey: IOneTimeKey | null = null;\n for (const keyId in deviceRes) {\n if (keyId.indexOf(oneTimeKeyAlgorithm + \":\") === 0) {\n oneTimeKey = deviceRes[keyId];\n }\n }\n\n if (!oneTimeKey) {\n log.warn(`No one-time keys (alg=${oneTimeKeyAlgorithm}) ` + `for device ${userId}:${deviceId}`);\n resolveSession.get(key)?.();\n continue;\n }\n\n promises.push(\n _verifyKeyAndStartSession(olmDevice, oneTimeKey, userId, deviceInfo).then(\n (sid) => {\n resolveSession.get(key)?.(sid ?? undefined);\n const deviceInfo = result.get(userId)?.get(deviceId);\n if (deviceInfo) deviceInfo.sessionId = sid;\n },\n (e) => {\n resolveSession.get(key)?.();\n throw e;\n },\n ),\n );\n }\n }\n\n taskDetail = `Olm sessions for ${promises.length} devices`;\n log.debug(`Starting ${taskDetail}`);\n await Promise.all(promises);\n log.debug(`Started ${taskDetail}`);\n return result;\n}\n\nasync function _verifyKeyAndStartSession(\n olmDevice: OlmDevice,\n oneTimeKey: IOneTimeKey,\n userId: string,\n deviceInfo: DeviceInfo,\n): Promise {\n const deviceId = deviceInfo.deviceId;\n try {\n await verifySignature(olmDevice, oneTimeKey, userId, deviceId, deviceInfo.getFingerprint());\n } catch (e) {\n logger.error(\"Unable to verify signature on one-time key for device \" + userId + \":\" + deviceId + \":\", e);\n return null;\n }\n\n let sid;\n try {\n sid = await olmDevice.createOutboundSession(deviceInfo.getIdentityKey(), oneTimeKey.key);\n } catch (e) {\n // possibly a bad key\n logger.error(\"Error starting olm session with device \" + userId + \":\" + deviceId + \": \" + e);\n return null;\n }\n\n logger.log(\"Started new olm sessionid \" + sid + \" for device \" + userId + \":\" + deviceId);\n return sid;\n}\n\nexport interface IObject {\n unsigned?: object;\n signatures?: ISignatures;\n}\n\n/**\n * Verify the signature on an object\n *\n * @param olmDevice - olm wrapper to use for verify op\n *\n * @param obj - object to check signature on.\n *\n * @param signingUserId - ID of the user whose signature should be checked\n *\n * @param signingDeviceId - ID of the device whose signature should be checked\n *\n * @param signingKey - base64-ed ed25519 public key\n *\n * Returns a promise which resolves (to undefined) if the the signature is good,\n * or rejects with an Error if it is bad.\n */\nexport async function verifySignature(\n olmDevice: OlmDevice,\n obj: IOneTimeKey | IObject,\n signingUserId: string,\n signingDeviceId: string,\n signingKey: string,\n): Promise {\n const signKeyId = \"ed25519:\" + signingDeviceId;\n const signatures = obj.signatures || {};\n const userSigs = signatures[signingUserId] || {};\n const signature = userSigs[signKeyId];\n if (!signature) {\n throw Error(\"No signature\");\n }\n\n // prepare the canonical json: remove unsigned and signatures, and stringify with anotherjson\n const mangledObj = Object.assign({}, obj);\n if (\"unsigned\" in mangledObj) {\n delete mangledObj.unsigned;\n }\n delete mangledObj.signatures;\n const json = anotherjson.stringify(mangledObj);\n\n olmDevice.verifySignature(signingKey, json, signature);\n}\n\n/**\n * Sign a JSON object using public key cryptography\n * @param obj - Object to sign. The object will be modified to include\n * the new signature\n * @param key - the signing object or the private key\n * seed\n * @param userId - The user ID who owns the signing key\n * @param pubKey - The public key (ignored if key is a seed)\n * @returns the signature for the object\n */\nexport function pkSign(obj: object & IObject, key: Uint8Array | PkSigning, userId: string, pubKey: string): string {\n let createdKey = false;\n if (key instanceof Uint8Array) {\n const keyObj = new global.Olm.PkSigning();\n pubKey = keyObj.init_with_seed(key);\n key = keyObj;\n createdKey = true;\n }\n const sigs = obj.signatures || {};\n delete obj.signatures;\n const unsigned = obj.unsigned;\n if (obj.unsigned) delete obj.unsigned;\n try {\n const mysigs = sigs[userId] || {};\n sigs[userId] = mysigs;\n\n return (mysigs[\"ed25519:\" + pubKey] = key.sign(anotherjson.stringify(obj)));\n } finally {\n obj.signatures = sigs;\n if (unsigned) obj.unsigned = unsigned;\n if (createdKey) {\n key.free();\n }\n }\n}\n\n/**\n * Verify a signed JSON object\n * @param obj - Object to verify\n * @param pubKey - The public key to use to verify\n * @param userId - The user ID who signed the object\n */\nexport function pkVerify(obj: IObject, pubKey: string, userId: string): void {\n const keyId = \"ed25519:\" + pubKey;\n if (!(obj.signatures && obj.signatures[userId] && obj.signatures[userId][keyId])) {\n throw new Error(\"No signature\");\n }\n const signature = obj.signatures[userId][keyId];\n const util = new global.Olm.Utility();\n const sigs = obj.signatures;\n delete obj.signatures;\n const unsigned = obj.unsigned;\n if (obj.unsigned) delete obj.unsigned;\n try {\n util.ed25519_verify(pubKey, anotherjson.stringify(obj), signature);\n } finally {\n obj.signatures = sigs;\n if (unsigned) obj.unsigned = unsigned;\n util.free();\n }\n}\n\n/**\n * Check that an event was encrypted using olm.\n */\nexport function isOlmEncrypted(event: MatrixEvent): boolean {\n if (!event.getSenderKey()) {\n logger.error(\"Event has no sender key (not encrypted?)\");\n return false;\n }\n if (\n event.getWireType() !== EventType.RoomMessageEncrypted ||\n ![\"m.olm.v1.curve25519-aes-sha2\"].includes(event.getWireContent().algorithm)\n ) {\n logger.error(\"Event was not encrypted using an appropriate algorithm\");\n return false;\n }\n return true;\n}\n\n/**\n * Encode a typed array of uint8 as base64.\n * @param uint8Array - The data to encode.\n * @returns The base64.\n */\nexport function encodeBase64(uint8Array: ArrayBuffer | Uint8Array): string {\n return Buffer.from(uint8Array).toString(\"base64\");\n}\n\n/**\n * Encode a typed array of uint8 as unpadded base64.\n * @param uint8Array - The data to encode.\n * @returns The unpadded base64.\n */\nexport function encodeUnpaddedBase64(uint8Array: ArrayBuffer | Uint8Array): string {\n return encodeBase64(uint8Array).replace(/=+$/g, \"\");\n}\n\n/**\n * Decode a base64 string to a typed array of uint8.\n * @param base64 - The base64 to decode.\n * @returns The decoded data.\n */\nexport function decodeBase64(base64: string): Uint8Array {\n return Buffer.from(base64, \"base64\");\n}\n", - "/*\nCopyright 2018 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport * as bs58 from \"bs58\";\n\n// picked arbitrarily but to try & avoid clashing with any bitcoin ones\n// (which are also base58 encoded, but bitcoin's involve a lot more hashing)\nconst OLM_RECOVERY_KEY_PREFIX = [0x8b, 0x01];\n\nexport function encodeRecoveryKey(key: ArrayLike): string | undefined {\n const buf = Buffer.alloc(OLM_RECOVERY_KEY_PREFIX.length + key.length + 1);\n buf.set(OLM_RECOVERY_KEY_PREFIX, 0);\n buf.set(key, OLM_RECOVERY_KEY_PREFIX.length);\n\n let parity = 0;\n for (let i = 0; i < buf.length - 1; ++i) {\n parity ^= buf[i];\n }\n buf[buf.length - 1] = parity;\n const base58key = bs58.encode(buf);\n\n return base58key.match(/.{1,4}/g)?.join(\" \");\n}\n\nexport function decodeRecoveryKey(recoveryKey: string): Uint8Array {\n const result = bs58.decode(recoveryKey.replace(/ /g, \"\"));\n\n let parity = 0;\n for (const b of result) {\n parity ^= b;\n }\n if (parity !== 0) {\n throw new Error(\"Incorrect parity\");\n }\n\n for (let i = 0; i < OLM_RECOVERY_KEY_PREFIX.length; ++i) {\n if (result[i] !== OLM_RECOVERY_KEY_PREFIX[i]) {\n throw new Error(\"Incorrect prefix\");\n }\n }\n\n if (result.length !== OLM_RECOVERY_KEY_PREFIX.length + global.Olm.PRIVATE_KEY_LENGTH + 1) {\n throw new Error(\"Incorrect length\");\n }\n\n return Uint8Array.from(\n result.slice(OLM_RECOVERY_KEY_PREFIX.length, OLM_RECOVERY_KEY_PREFIX.length + global.Olm.PRIVATE_KEY_LENGTH),\n );\n}\n", - "/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger, PrefixedLogger } from \"../../logger\";\nimport * as utils from \"../../utils\";\nimport {\n CryptoStore,\n IDeviceData,\n IProblem,\n ISession,\n ISessionInfo,\n IWithheld,\n Mode,\n OutgoingRoomKeyRequest,\n ParkedSharedHistory,\n SecretStorePrivateKeys,\n} from \"./base\";\nimport { IRoomKeyRequestBody, IRoomKeyRequestRecipient } from \"../index\";\nimport { ICrossSigningKey } from \"../../client\";\nimport { IOlmDevice } from \"../algorithms/megolm\";\nimport { IRoomEncryption } from \"../RoomList\";\nimport { InboundGroupSessionData } from \"../OlmDevice\";\n\nconst PROFILE_TRANSACTIONS = false;\n\n/**\n * Implementation of a CryptoStore which is backed by an existing\n * IndexedDB connection. Generally you want IndexedDBCryptoStore\n * which connects to the database and defers to one of these.\n */\nexport class Backend implements CryptoStore {\n private nextTxnId = 0;\n\n /**\n */\n public constructor(private db: IDBDatabase) {\n // make sure we close the db on `onversionchange` - otherwise\n // attempts to delete the database will block (and subsequent\n // attempts to re-create it will also block).\n db.onversionchange = (): void => {\n logger.log(`versionchange for indexeddb ${this.db.name}: closing`);\n db.close();\n };\n }\n\n public async startup(): Promise {\n // No work to do, as the startup is done by the caller (e.g IndexedDBCryptoStore)\n // by passing us a ready IDBDatabase instance\n return this;\n }\n public async deleteAllData(): Promise {\n throw Error(\"This is not implemented, call IDBFactory::deleteDatabase(dbName) instead.\");\n }\n\n /**\n * Look for an existing outgoing room key request, and if none is found,\n * add a new one\n *\n *\n * @returns resolves to\n * {@link OutgoingRoomKeyRequest}: either the\n * same instance as passed in, or the existing one.\n */\n public getOrAddOutgoingRoomKeyRequest(request: OutgoingRoomKeyRequest): Promise {\n const requestBody = request.requestBody;\n\n return new Promise((resolve, reject) => {\n const txn = this.db.transaction(\"outgoingRoomKeyRequests\", \"readwrite\");\n txn.onerror = reject;\n\n // first see if we already have an entry for this request.\n this._getOutgoingRoomKeyRequest(txn, requestBody, (existing) => {\n if (existing) {\n // this entry matches the request - return it.\n logger.log(\n `already have key request outstanding for ` +\n `${requestBody.room_id} / ${requestBody.session_id}: ` +\n `not sending another`,\n );\n resolve(existing);\n return;\n }\n\n // we got to the end of the list without finding a match\n // - add the new request.\n logger.log(`enqueueing key request for ${requestBody.room_id} / ` + requestBody.session_id);\n txn.oncomplete = (): void => {\n resolve(request);\n };\n const store = txn.objectStore(\"outgoingRoomKeyRequests\");\n store.add(request);\n });\n });\n }\n\n /**\n * Look for an existing room key request\n *\n * @param requestBody - existing request to look for\n *\n * @returns resolves to the matching\n * {@link OutgoingRoomKeyRequest}, or null if\n * not found\n */\n public getOutgoingRoomKeyRequest(requestBody: IRoomKeyRequestBody): Promise {\n return new Promise((resolve, reject) => {\n const txn = this.db.transaction(\"outgoingRoomKeyRequests\", \"readonly\");\n txn.onerror = reject;\n\n this._getOutgoingRoomKeyRequest(txn, requestBody, (existing) => {\n resolve(existing);\n });\n });\n }\n\n /**\n * look for an existing room key request in the db\n *\n * @internal\n * @param txn - database transaction\n * @param requestBody - existing request to look for\n * @param callback - function to call with the results of the\n * search. Either passed a matching\n * {@link OutgoingRoomKeyRequest}, or null if\n * not found.\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n private _getOutgoingRoomKeyRequest(\n txn: IDBTransaction,\n requestBody: IRoomKeyRequestBody,\n callback: (req: OutgoingRoomKeyRequest | null) => void,\n ): void {\n const store = txn.objectStore(\"outgoingRoomKeyRequests\");\n\n const idx = store.index(\"session\");\n const cursorReq = idx.openCursor([requestBody.room_id, requestBody.session_id]);\n\n cursorReq.onsuccess = (): void => {\n const cursor = cursorReq.result;\n if (!cursor) {\n // no match found\n callback(null);\n return;\n }\n\n const existing = cursor.value;\n\n if (utils.deepCompare(existing.requestBody, requestBody)) {\n // got a match\n callback(existing);\n return;\n }\n\n // look at the next entry in the index\n cursor.continue();\n };\n }\n\n /**\n * Look for room key requests by state\n *\n * @param wantedStates - list of acceptable states\n *\n * @returns resolves to the a\n * {@link OutgoingRoomKeyRequest}, or null if\n * there are no pending requests in those states. If there are multiple\n * requests in those states, an arbitrary one is chosen.\n */\n public getOutgoingRoomKeyRequestByState(wantedStates: number[]): Promise {\n if (wantedStates.length === 0) {\n return Promise.resolve(null);\n }\n\n // this is a bit tortuous because we need to make sure we do the lookup\n // in a single transaction, to avoid having a race with the insertion\n // code.\n\n // index into the wantedStates array\n let stateIndex = 0;\n let result: OutgoingRoomKeyRequest;\n\n function onsuccess(this: IDBRequest): void {\n const cursor = this.result;\n if (cursor) {\n // got a match\n result = cursor.value;\n return;\n }\n\n // try the next state in the list\n stateIndex++;\n if (stateIndex >= wantedStates.length) {\n // no matches\n return;\n }\n\n const wantedState = wantedStates[stateIndex];\n const cursorReq = (this.source as IDBIndex).openCursor(wantedState);\n cursorReq.onsuccess = onsuccess;\n }\n\n const txn = this.db.transaction(\"outgoingRoomKeyRequests\", \"readonly\");\n const store = txn.objectStore(\"outgoingRoomKeyRequests\");\n\n const wantedState = wantedStates[stateIndex];\n const cursorReq = store.index(\"state\").openCursor(wantedState);\n cursorReq.onsuccess = onsuccess;\n\n return promiseifyTxn(txn).then(() => result);\n }\n\n /**\n *\n * @returns All elements in a given state\n */\n public getAllOutgoingRoomKeyRequestsByState(wantedState: number): Promise {\n return new Promise((resolve, reject) => {\n const txn = this.db.transaction(\"outgoingRoomKeyRequests\", \"readonly\");\n const store = txn.objectStore(\"outgoingRoomKeyRequests\");\n const index = store.index(\"state\");\n const request = index.getAll(wantedState);\n\n request.onsuccess = (): void => resolve(request.result);\n request.onerror = (): void => reject(request.error);\n });\n }\n\n public getOutgoingRoomKeyRequestsByTarget(\n userId: string,\n deviceId: string,\n wantedStates: number[],\n ): Promise {\n let stateIndex = 0;\n const results: OutgoingRoomKeyRequest[] = [];\n\n function onsuccess(this: IDBRequest): void {\n const cursor = this.result;\n if (cursor) {\n const keyReq = cursor.value;\n if (\n keyReq.recipients.some(\n (recipient: IRoomKeyRequestRecipient) =>\n recipient.userId === userId && recipient.deviceId === deviceId,\n )\n ) {\n results.push(keyReq);\n }\n cursor.continue();\n } else {\n // try the next state in the list\n stateIndex++;\n if (stateIndex >= wantedStates.length) {\n // no matches\n return;\n }\n\n const wantedState = wantedStates[stateIndex];\n const cursorReq = (this.source as IDBIndex).openCursor(wantedState);\n cursorReq.onsuccess = onsuccess;\n }\n }\n\n const txn = this.db.transaction(\"outgoingRoomKeyRequests\", \"readonly\");\n const store = txn.objectStore(\"outgoingRoomKeyRequests\");\n\n const wantedState = wantedStates[stateIndex];\n const cursorReq = store.index(\"state\").openCursor(wantedState);\n cursorReq.onsuccess = onsuccess;\n\n return promiseifyTxn(txn).then(() => results);\n }\n\n /**\n * Look for an existing room key request by id and state, and update it if\n * found\n *\n * @param requestId - ID of request to update\n * @param expectedState - state we expect to find the request in\n * @param updates - name/value map of updates to apply\n *\n * @returns resolves to\n * {@link OutgoingRoomKeyRequest}\n * updated request, or null if no matching row was found\n */\n public updateOutgoingRoomKeyRequest(\n requestId: string,\n expectedState: number,\n updates: Partial,\n ): Promise {\n let result: OutgoingRoomKeyRequest | null = null;\n\n function onsuccess(this: IDBRequest): void {\n const cursor = this.result;\n if (!cursor) {\n return;\n }\n const data = cursor.value;\n if (data.state != expectedState) {\n logger.warn(\n `Cannot update room key request from ${expectedState} ` +\n `as it was already updated to ${data.state}`,\n );\n return;\n }\n Object.assign(data, updates);\n cursor.update(data);\n result = data;\n }\n\n const txn = this.db.transaction(\"outgoingRoomKeyRequests\", \"readwrite\");\n const cursorReq = txn.objectStore(\"outgoingRoomKeyRequests\").openCursor(requestId);\n cursorReq.onsuccess = onsuccess;\n return promiseifyTxn(txn).then(() => result);\n }\n\n /**\n * Look for an existing room key request by id and state, and delete it if\n * found\n *\n * @param requestId - ID of request to update\n * @param expectedState - state we expect to find the request in\n *\n * @returns resolves once the operation is completed\n */\n public deleteOutgoingRoomKeyRequest(\n requestId: string,\n expectedState: number,\n ): Promise {\n const txn = this.db.transaction(\"outgoingRoomKeyRequests\", \"readwrite\");\n const cursorReq = txn.objectStore(\"outgoingRoomKeyRequests\").openCursor(requestId);\n cursorReq.onsuccess = (): void => {\n const cursor = cursorReq.result;\n if (!cursor) {\n return;\n }\n const data = cursor.value;\n if (data.state != expectedState) {\n logger.warn(`Cannot delete room key request in state ${data.state} ` + `(expected ${expectedState})`);\n return;\n }\n cursor.delete();\n };\n return promiseifyTxn(txn);\n }\n\n // Olm Account\n\n public getAccount(txn: IDBTransaction, func: (accountPickle: string | null) => void): void {\n const objectStore = txn.objectStore(\"account\");\n const getReq = objectStore.get(\"-\");\n getReq.onsuccess = function (): void {\n try {\n func(getReq.result || null);\n } catch (e) {\n abortWithException(txn, e);\n }\n };\n }\n\n public storeAccount(txn: IDBTransaction, accountPickle: string): void {\n const objectStore = txn.objectStore(\"account\");\n objectStore.put(accountPickle, \"-\");\n }\n\n public getCrossSigningKeys(\n txn: IDBTransaction,\n func: (keys: Record | null) => void,\n ): void {\n const objectStore = txn.objectStore(\"account\");\n const getReq = objectStore.get(\"crossSigningKeys\");\n getReq.onsuccess = function (): void {\n try {\n func(getReq.result || null);\n } catch (e) {\n abortWithException(txn, e);\n }\n };\n }\n\n public getSecretStorePrivateKey(\n txn: IDBTransaction,\n func: (key: SecretStorePrivateKeys[K] | null) => void,\n type: K,\n ): void {\n const objectStore = txn.objectStore(\"account\");\n const getReq = objectStore.get(`ssss_cache:${type}`);\n getReq.onsuccess = function (): void {\n try {\n func(getReq.result || null);\n } catch (e) {\n abortWithException(txn, e);\n }\n };\n }\n\n public storeCrossSigningKeys(txn: IDBTransaction, keys: Record): void {\n const objectStore = txn.objectStore(\"account\");\n objectStore.put(keys, \"crossSigningKeys\");\n }\n\n public storeSecretStorePrivateKey(\n txn: IDBTransaction,\n type: K,\n key: SecretStorePrivateKeys[K],\n ): void {\n const objectStore = txn.objectStore(\"account\");\n objectStore.put(key, `ssss_cache:${type}`);\n }\n\n // Olm Sessions\n\n public countEndToEndSessions(txn: IDBTransaction, func: (count: number) => void): void {\n const objectStore = txn.objectStore(\"sessions\");\n const countReq = objectStore.count();\n countReq.onsuccess = function (): void {\n try {\n func(countReq.result);\n } catch (e) {\n abortWithException(txn, e);\n }\n };\n }\n\n public getEndToEndSessions(\n deviceKey: string,\n txn: IDBTransaction,\n func: (sessions: { [sessionId: string]: ISessionInfo }) => void,\n ): void {\n const objectStore = txn.objectStore(\"sessions\");\n const idx = objectStore.index(\"deviceKey\");\n const getReq = idx.openCursor(deviceKey);\n const results: Parameters[2]>[0] = {};\n getReq.onsuccess = function (): void {\n const cursor = getReq.result;\n if (cursor) {\n results[cursor.value.sessionId] = {\n session: cursor.value.session,\n lastReceivedMessageTs: cursor.value.lastReceivedMessageTs,\n };\n cursor.continue();\n } else {\n try {\n func(results);\n } catch (e) {\n abortWithException(txn, e);\n }\n }\n };\n }\n\n public getEndToEndSession(\n deviceKey: string,\n sessionId: string,\n txn: IDBTransaction,\n func: (session: ISessionInfo | null) => void,\n ): void {\n const objectStore = txn.objectStore(\"sessions\");\n const getReq = objectStore.get([deviceKey, sessionId]);\n getReq.onsuccess = function (): void {\n try {\n if (getReq.result) {\n func({\n session: getReq.result.session,\n lastReceivedMessageTs: getReq.result.lastReceivedMessageTs,\n });\n } else {\n func(null);\n }\n } catch (e) {\n abortWithException(txn, e);\n }\n };\n }\n\n public getAllEndToEndSessions(txn: IDBTransaction, func: (session: ISessionInfo | null) => void): void {\n const objectStore = txn.objectStore(\"sessions\");\n const getReq = objectStore.openCursor();\n getReq.onsuccess = function (): void {\n try {\n const cursor = getReq.result;\n if (cursor) {\n func(cursor.value);\n cursor.continue();\n } else {\n func(null);\n }\n } catch (e) {\n abortWithException(txn, e);\n }\n };\n }\n\n public storeEndToEndSession(\n deviceKey: string,\n sessionId: string,\n sessionInfo: ISessionInfo,\n txn: IDBTransaction,\n ): void {\n const objectStore = txn.objectStore(\"sessions\");\n objectStore.put({\n deviceKey,\n sessionId,\n session: sessionInfo.session,\n lastReceivedMessageTs: sessionInfo.lastReceivedMessageTs,\n });\n }\n\n public async storeEndToEndSessionProblem(deviceKey: string, type: string, fixed: boolean): Promise {\n const txn = this.db.transaction(\"session_problems\", \"readwrite\");\n const objectStore = txn.objectStore(\"session_problems\");\n objectStore.put({\n deviceKey,\n type,\n fixed,\n time: Date.now(),\n });\n await promiseifyTxn(txn);\n }\n\n public async getEndToEndSessionProblem(deviceKey: string, timestamp: number): Promise {\n let result: IProblem | null = null;\n const txn = this.db.transaction(\"session_problems\", \"readwrite\");\n const objectStore = txn.objectStore(\"session_problems\");\n const index = objectStore.index(\"deviceKey\");\n const req = index.getAll(deviceKey);\n req.onsuccess = (): void => {\n const problems = req.result;\n if (!problems.length) {\n result = null;\n return;\n }\n problems.sort((a, b) => {\n return a.time - b.time;\n });\n const lastProblem = problems[problems.length - 1];\n for (const problem of problems) {\n if (problem.time > timestamp) {\n result = Object.assign({}, problem, { fixed: lastProblem.fixed });\n return;\n }\n }\n if (lastProblem.fixed) {\n result = null;\n } else {\n result = lastProblem;\n }\n };\n await promiseifyTxn(txn);\n return result;\n }\n\n // FIXME: we should probably prune this when devices get deleted\n public async filterOutNotifiedErrorDevices(devices: IOlmDevice[]): Promise {\n const txn = this.db.transaction(\"notified_error_devices\", \"readwrite\");\n const objectStore = txn.objectStore(\"notified_error_devices\");\n\n const ret: IOlmDevice[] = [];\n\n await Promise.all(\n devices.map((device) => {\n return new Promise((resolve) => {\n const { userId, deviceInfo } = device;\n const getReq = objectStore.get([userId, deviceInfo.deviceId]);\n getReq.onsuccess = function (): void {\n if (!getReq.result) {\n objectStore.put({ userId, deviceId: deviceInfo.deviceId });\n ret.push(device);\n }\n resolve();\n };\n });\n }),\n );\n\n return ret;\n }\n\n // Inbound group sessions\n\n public getEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n txn: IDBTransaction,\n func: (groupSession: InboundGroupSessionData | null, groupSessionWithheld: IWithheld | null) => void,\n ): void {\n let session: InboundGroupSessionData | null | boolean = false;\n let withheld: IWithheld | null | boolean = false;\n const objectStore = txn.objectStore(\"inbound_group_sessions\");\n const getReq = objectStore.get([senderCurve25519Key, sessionId]);\n getReq.onsuccess = function (): void {\n try {\n if (getReq.result) {\n session = getReq.result.session;\n } else {\n session = null;\n }\n if (withheld !== false) {\n func(session as InboundGroupSessionData, withheld as IWithheld);\n }\n } catch (e) {\n abortWithException(txn, e);\n }\n };\n\n const withheldObjectStore = txn.objectStore(\"inbound_group_sessions_withheld\");\n const withheldGetReq = withheldObjectStore.get([senderCurve25519Key, sessionId]);\n withheldGetReq.onsuccess = function (): void {\n try {\n if (withheldGetReq.result) {\n withheld = withheldGetReq.result.session;\n } else {\n withheld = null;\n }\n if (session !== false) {\n func(session as InboundGroupSessionData, withheld as IWithheld);\n }\n } catch (e) {\n abortWithException(txn, e);\n }\n };\n }\n\n public getAllEndToEndInboundGroupSessions(txn: IDBTransaction, func: (session: ISession | null) => void): void {\n const objectStore = txn.objectStore(\"inbound_group_sessions\");\n const getReq = objectStore.openCursor();\n getReq.onsuccess = function (): void {\n const cursor = getReq.result;\n if (cursor) {\n try {\n func({\n senderKey: cursor.value.senderCurve25519Key,\n sessionId: cursor.value.sessionId,\n sessionData: cursor.value.session,\n });\n } catch (e) {\n abortWithException(txn, e);\n }\n cursor.continue();\n } else {\n try {\n func(null);\n } catch (e) {\n abortWithException(txn, e);\n }\n }\n };\n }\n\n public addEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n sessionData: InboundGroupSessionData,\n txn: IDBTransaction,\n ): void {\n const objectStore = txn.objectStore(\"inbound_group_sessions\");\n const addReq = objectStore.add({\n senderCurve25519Key,\n sessionId,\n session: sessionData,\n });\n addReq.onerror = (ev): void => {\n if (addReq.error?.name === \"ConstraintError\") {\n // This stops the error from triggering the txn's onerror\n ev.stopPropagation();\n // ...and this stops it from aborting the transaction\n ev.preventDefault();\n logger.log(\"Ignoring duplicate inbound group session: \" + senderCurve25519Key + \" / \" + sessionId);\n } else {\n abortWithException(txn, new Error(\"Failed to add inbound group session: \" + addReq.error));\n }\n };\n }\n\n public storeEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n sessionData: InboundGroupSessionData,\n txn: IDBTransaction,\n ): void {\n const objectStore = txn.objectStore(\"inbound_group_sessions\");\n objectStore.put({\n senderCurve25519Key,\n sessionId,\n session: sessionData,\n });\n }\n\n public storeEndToEndInboundGroupSessionWithheld(\n senderCurve25519Key: string,\n sessionId: string,\n sessionData: IWithheld,\n txn: IDBTransaction,\n ): void {\n const objectStore = txn.objectStore(\"inbound_group_sessions_withheld\");\n objectStore.put({\n senderCurve25519Key,\n sessionId,\n session: sessionData,\n });\n }\n\n public getEndToEndDeviceData(txn: IDBTransaction, func: (deviceData: IDeviceData | null) => void): void {\n const objectStore = txn.objectStore(\"device_data\");\n const getReq = objectStore.get(\"-\");\n getReq.onsuccess = function (): void {\n try {\n func(getReq.result || null);\n } catch (e) {\n abortWithException(txn, e);\n }\n };\n }\n\n public storeEndToEndDeviceData(deviceData: IDeviceData, txn: IDBTransaction): void {\n const objectStore = txn.objectStore(\"device_data\");\n objectStore.put(deviceData, \"-\");\n }\n\n public storeEndToEndRoom(roomId: string, roomInfo: IRoomEncryption, txn: IDBTransaction): void {\n const objectStore = txn.objectStore(\"rooms\");\n objectStore.put(roomInfo, roomId);\n }\n\n public getEndToEndRooms(txn: IDBTransaction, func: (rooms: Record) => void): void {\n const rooms: Parameters[1]>[0] = {};\n const objectStore = txn.objectStore(\"rooms\");\n const getReq = objectStore.openCursor();\n getReq.onsuccess = function (): void {\n const cursor = getReq.result;\n if (cursor) {\n rooms[cursor.key as string] = cursor.value;\n cursor.continue();\n } else {\n try {\n func(rooms);\n } catch (e) {\n abortWithException(txn, e);\n }\n }\n };\n }\n\n // session backups\n\n public getSessionsNeedingBackup(limit: number): Promise {\n return new Promise((resolve, reject) => {\n const sessions: ISession[] = [];\n\n const txn = this.db.transaction([\"sessions_needing_backup\", \"inbound_group_sessions\"], \"readonly\");\n txn.onerror = reject;\n txn.oncomplete = function (): void {\n resolve(sessions);\n };\n const objectStore = txn.objectStore(\"sessions_needing_backup\");\n const sessionStore = txn.objectStore(\"inbound_group_sessions\");\n const getReq = objectStore.openCursor();\n getReq.onsuccess = function (): void {\n const cursor = getReq.result;\n if (cursor) {\n const sessionGetReq = sessionStore.get(cursor.key);\n sessionGetReq.onsuccess = function (): void {\n sessions.push({\n senderKey: sessionGetReq.result.senderCurve25519Key,\n sessionId: sessionGetReq.result.sessionId,\n sessionData: sessionGetReq.result.session,\n });\n };\n if (!limit || sessions.length < limit) {\n cursor.continue();\n }\n }\n };\n });\n }\n\n public countSessionsNeedingBackup(txn?: IDBTransaction): Promise {\n if (!txn) {\n txn = this.db.transaction(\"sessions_needing_backup\", \"readonly\");\n }\n const objectStore = txn.objectStore(\"sessions_needing_backup\");\n return new Promise((resolve, reject) => {\n const req = objectStore.count();\n req.onerror = reject;\n req.onsuccess = (): void => resolve(req.result);\n });\n }\n\n public async unmarkSessionsNeedingBackup(sessions: ISession[], txn?: IDBTransaction): Promise {\n if (!txn) {\n txn = this.db.transaction(\"sessions_needing_backup\", \"readwrite\");\n }\n const objectStore = txn.objectStore(\"sessions_needing_backup\");\n await Promise.all(\n sessions.map((session) => {\n return new Promise((resolve, reject) => {\n const req = objectStore.delete([session.senderKey, session.sessionId]);\n req.onsuccess = resolve;\n req.onerror = reject;\n });\n }),\n );\n }\n\n public async markSessionsNeedingBackup(sessions: ISession[], txn?: IDBTransaction): Promise {\n if (!txn) {\n txn = this.db.transaction(\"sessions_needing_backup\", \"readwrite\");\n }\n const objectStore = txn.objectStore(\"sessions_needing_backup\");\n await Promise.all(\n sessions.map((session) => {\n return new Promise((resolve, reject) => {\n const req = objectStore.put({\n senderCurve25519Key: session.senderKey,\n sessionId: session.sessionId,\n });\n req.onsuccess = resolve;\n req.onerror = reject;\n });\n }),\n );\n }\n\n public addSharedHistoryInboundGroupSession(\n roomId: string,\n senderKey: string,\n sessionId: string,\n txn?: IDBTransaction,\n ): void {\n if (!txn) {\n txn = this.db.transaction(\"shared_history_inbound_group_sessions\", \"readwrite\");\n }\n const objectStore = txn.objectStore(\"shared_history_inbound_group_sessions\");\n const req = objectStore.get([roomId]);\n req.onsuccess = (): void => {\n const { sessions } = req.result || { sessions: [] };\n sessions.push([senderKey, sessionId]);\n objectStore.put({ roomId, sessions });\n };\n }\n\n public getSharedHistoryInboundGroupSessions(\n roomId: string,\n txn?: IDBTransaction,\n ): Promise<[senderKey: string, sessionId: string][]> {\n if (!txn) {\n txn = this.db.transaction(\"shared_history_inbound_group_sessions\", \"readonly\");\n }\n const objectStore = txn.objectStore(\"shared_history_inbound_group_sessions\");\n const req = objectStore.get([roomId]);\n return new Promise((resolve, reject) => {\n req.onsuccess = (): void => {\n const { sessions } = req.result || { sessions: [] };\n resolve(sessions);\n };\n req.onerror = reject;\n });\n }\n\n public addParkedSharedHistory(roomId: string, parkedData: ParkedSharedHistory, txn?: IDBTransaction): void {\n if (!txn) {\n txn = this.db.transaction(\"parked_shared_history\", \"readwrite\");\n }\n const objectStore = txn.objectStore(\"parked_shared_history\");\n const req = objectStore.get([roomId]);\n req.onsuccess = (): void => {\n const { parked } = req.result || { parked: [] };\n parked.push(parkedData);\n objectStore.put({ roomId, parked });\n };\n }\n\n public takeParkedSharedHistory(roomId: string, txn?: IDBTransaction): Promise {\n if (!txn) {\n txn = this.db.transaction(\"parked_shared_history\", \"readwrite\");\n }\n const cursorReq = txn.objectStore(\"parked_shared_history\").openCursor(roomId);\n return new Promise((resolve, reject) => {\n cursorReq.onsuccess = (): void => {\n const cursor = cursorReq.result;\n if (!cursor) {\n resolve([]);\n return;\n }\n const data = cursor.value;\n cursor.delete();\n resolve(data);\n };\n cursorReq.onerror = reject;\n });\n }\n\n public doTxn(\n mode: Mode,\n stores: string | string[],\n func: (txn: IDBTransaction) => T,\n log: PrefixedLogger = logger,\n ): Promise {\n let startTime: number;\n let description: string;\n if (PROFILE_TRANSACTIONS) {\n const txnId = this.nextTxnId++;\n startTime = Date.now();\n description = `${mode} crypto store transaction ${txnId} in ${stores}`;\n log.debug(`Starting ${description}`);\n }\n const txn = this.db.transaction(stores, mode);\n const promise = promiseifyTxn(txn);\n const result = func(txn);\n if (PROFILE_TRANSACTIONS) {\n promise.then(\n () => {\n const elapsedTime = Date.now() - startTime;\n log.debug(`Finished ${description}, took ${elapsedTime} ms`);\n },\n () => {\n const elapsedTime = Date.now() - startTime;\n log.error(`Failed ${description}, took ${elapsedTime} ms`);\n },\n );\n }\n return promise.then(() => {\n return result;\n });\n }\n}\n\ntype DbMigration = (db: IDBDatabase) => void;\nconst DB_MIGRATIONS: DbMigration[] = [\n (db): void => {\n createDatabase(db);\n },\n (db): void => {\n db.createObjectStore(\"account\");\n },\n (db): void => {\n const sessionsStore = db.createObjectStore(\"sessions\", {\n keyPath: [\"deviceKey\", \"sessionId\"],\n });\n sessionsStore.createIndex(\"deviceKey\", \"deviceKey\");\n },\n (db): void => {\n db.createObjectStore(\"inbound_group_sessions\", {\n keyPath: [\"senderCurve25519Key\", \"sessionId\"],\n });\n },\n (db): void => {\n db.createObjectStore(\"device_data\");\n },\n (db): void => {\n db.createObjectStore(\"rooms\");\n },\n (db): void => {\n db.createObjectStore(\"sessions_needing_backup\", {\n keyPath: [\"senderCurve25519Key\", \"sessionId\"],\n });\n },\n (db): void => {\n db.createObjectStore(\"inbound_group_sessions_withheld\", {\n keyPath: [\"senderCurve25519Key\", \"sessionId\"],\n });\n },\n (db): void => {\n const problemsStore = db.createObjectStore(\"session_problems\", {\n keyPath: [\"deviceKey\", \"time\"],\n });\n problemsStore.createIndex(\"deviceKey\", \"deviceKey\");\n\n db.createObjectStore(\"notified_error_devices\", {\n keyPath: [\"userId\", \"deviceId\"],\n });\n },\n (db): void => {\n db.createObjectStore(\"shared_history_inbound_group_sessions\", {\n keyPath: [\"roomId\"],\n });\n },\n (db): void => {\n db.createObjectStore(\"parked_shared_history\", {\n keyPath: [\"roomId\"],\n });\n },\n // Expand as needed.\n];\nexport const VERSION = DB_MIGRATIONS.length;\n\nexport function upgradeDatabase(db: IDBDatabase, oldVersion: number): void {\n logger.log(`Upgrading IndexedDBCryptoStore from version ${oldVersion}` + ` to ${VERSION}`);\n DB_MIGRATIONS.forEach((migration, index) => {\n if (oldVersion <= index) migration(db);\n });\n}\n\nfunction createDatabase(db: IDBDatabase): void {\n const outgoingRoomKeyRequestsStore = db.createObjectStore(\"outgoingRoomKeyRequests\", { keyPath: \"requestId\" });\n\n // we assume that the RoomKeyRequestBody will have room_id and session_id\n // properties, to make the index efficient.\n outgoingRoomKeyRequestsStore.createIndex(\"session\", [\"requestBody.room_id\", \"requestBody.session_id\"]);\n\n outgoingRoomKeyRequestsStore.createIndex(\"state\", \"state\");\n}\n\ninterface IWrappedIDBTransaction extends IDBTransaction {\n _mx_abortexception: Error; // eslint-disable-line camelcase\n}\n\n/*\n * Aborts a transaction with a given exception\n * The transaction promise will be rejected with this exception.\n */\nfunction abortWithException(txn: IDBTransaction, e: Error): void {\n // We cheekily stick our exception onto the transaction object here\n // We could alternatively make the thing we pass back to the app\n // an object containing the transaction and exception.\n (txn as IWrappedIDBTransaction)._mx_abortexception = e;\n try {\n txn.abort();\n } catch (e) {\n // sometimes we won't be able to abort the transaction\n // (ie. if it's aborted or completed)\n }\n}\n\nfunction promiseifyTxn(txn: IDBTransaction): Promise {\n return new Promise((resolve, reject) => {\n txn.oncomplete = (): void => {\n if ((txn as IWrappedIDBTransaction)._mx_abortexception !== undefined) {\n reject((txn as IWrappedIDBTransaction)._mx_abortexception);\n }\n resolve(null);\n };\n txn.onerror = (event): void => {\n if ((txn as IWrappedIDBTransaction)._mx_abortexception !== undefined) {\n reject((txn as IWrappedIDBTransaction)._mx_abortexception);\n } else {\n logger.log(\"Error performing indexeddb txn\", event);\n reject(txn.error);\n }\n };\n txn.onabort = (event): void => {\n if ((txn as IWrappedIDBTransaction)._mx_abortexception !== undefined) {\n reject((txn as IWrappedIDBTransaction)._mx_abortexception);\n } else {\n logger.log(\"Error performing indexeddb txn\", event);\n reject(txn.error);\n }\n };\n });\n}\n", - "/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger, PrefixedLogger } from \"../../logger\";\nimport { LocalStorageCryptoStore } from \"./localStorage-crypto-store\";\nimport { MemoryCryptoStore } from \"./memory-crypto-store\";\nimport * as IndexedDBCryptoStoreBackend from \"./indexeddb-crypto-store-backend\";\nimport { InvalidCryptoStoreError, InvalidCryptoStoreState } from \"../../errors\";\nimport * as IndexedDBHelpers from \"../../indexeddb-helpers\";\nimport {\n CryptoStore,\n IDeviceData,\n IProblem,\n ISession,\n ISessionInfo,\n IWithheld,\n Mode,\n OutgoingRoomKeyRequest,\n ParkedSharedHistory,\n SecretStorePrivateKeys,\n} from \"./base\";\nimport { IRoomKeyRequestBody } from \"../index\";\nimport { ICrossSigningKey } from \"../../client\";\nimport { IOlmDevice } from \"../algorithms/megolm\";\nimport { IRoomEncryption } from \"../RoomList\";\nimport { InboundGroupSessionData } from \"../OlmDevice\";\n\n/**\n * Internal module. indexeddb storage for e2e.\n */\n\n/**\n * An implementation of CryptoStore, which is normally backed by an indexeddb,\n * but with fallback to MemoryCryptoStore.\n */\nexport class IndexedDBCryptoStore implements CryptoStore {\n public static STORE_ACCOUNT = \"account\";\n public static STORE_SESSIONS = \"sessions\";\n public static STORE_INBOUND_GROUP_SESSIONS = \"inbound_group_sessions\";\n public static STORE_INBOUND_GROUP_SESSIONS_WITHHELD = \"inbound_group_sessions_withheld\";\n public static STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS = \"shared_history_inbound_group_sessions\";\n public static STORE_PARKED_SHARED_HISTORY = \"parked_shared_history\";\n public static STORE_DEVICE_DATA = \"device_data\";\n public static STORE_ROOMS = \"rooms\";\n public static STORE_BACKUP = \"sessions_needing_backup\";\n\n public static exists(indexedDB: IDBFactory, dbName: string): Promise {\n return IndexedDBHelpers.exists(indexedDB, dbName);\n }\n\n private backendPromise?: Promise;\n private backend?: CryptoStore;\n\n /**\n * Create a new IndexedDBCryptoStore\n *\n * @param indexedDB - global indexedDB instance\n * @param dbName - name of db to connect to\n */\n public constructor(private readonly indexedDB: IDBFactory, private readonly dbName: string) {}\n\n /**\n * Ensure the database exists and is up-to-date, or fall back to\n * a local storage or in-memory store.\n *\n * This must be called before the store can be used.\n *\n * @returns resolves to either an IndexedDBCryptoStoreBackend.Backend,\n * or a MemoryCryptoStore\n */\n public startup(): Promise {\n if (this.backendPromise) {\n return this.backendPromise;\n }\n\n this.backendPromise = new Promise((resolve, reject) => {\n if (!this.indexedDB) {\n reject(new Error(\"no indexeddb support available\"));\n return;\n }\n\n logger.log(`connecting to indexeddb ${this.dbName}`);\n\n const req = this.indexedDB.open(this.dbName, IndexedDBCryptoStoreBackend.VERSION);\n\n req.onupgradeneeded = (ev): void => {\n const db = req.result;\n const oldVersion = ev.oldVersion;\n IndexedDBCryptoStoreBackend.upgradeDatabase(db, oldVersion);\n };\n\n req.onblocked = (): void => {\n logger.log(`can't yet open IndexedDBCryptoStore because it is open elsewhere`);\n };\n\n req.onerror = (ev): void => {\n logger.log(\"Error connecting to indexeddb\", ev);\n reject(req.error);\n };\n\n req.onsuccess = (): void => {\n const db = req.result;\n\n logger.log(`connected to indexeddb ${this.dbName}`);\n resolve(new IndexedDBCryptoStoreBackend.Backend(db));\n };\n })\n .then((backend) => {\n // Edge has IndexedDB but doesn't support compund keys which we use fairly extensively.\n // Try a dummy query which will fail if the browser doesn't support compund keys, so\n // we can fall back to a different backend.\n return backend\n .doTxn(\n \"readonly\",\n [\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,\n IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD,\n ],\n (txn) => {\n backend.getEndToEndInboundGroupSession(\"\", \"\", txn, () => {});\n },\n )\n .then(() => backend);\n })\n .catch((e) => {\n if (e.name === \"VersionError\") {\n logger.warn(\"Crypto DB is too new for us to use!\", e);\n // don't fall back to a different store: the user has crypto data\n // in this db so we should use it or nothing at all.\n throw new InvalidCryptoStoreError(InvalidCryptoStoreState.TooNew);\n }\n logger.warn(\n `unable to connect to indexeddb ${this.dbName}` + `: falling back to localStorage store: ${e}`,\n );\n\n try {\n return new LocalStorageCryptoStore(global.localStorage);\n } catch (e) {\n logger.warn(`unable to open localStorage: falling back to in-memory store: ${e}`);\n return new MemoryCryptoStore();\n }\n })\n .then((backend) => {\n this.backend = backend;\n return backend;\n });\n\n return this.backendPromise;\n }\n\n /**\n * Delete all data from this store.\n *\n * @returns resolves when the store has been cleared.\n */\n public deleteAllData(): Promise {\n return new Promise((resolve, reject) => {\n if (!this.indexedDB) {\n reject(new Error(\"no indexeddb support available\"));\n return;\n }\n\n logger.log(`Removing indexeddb instance: ${this.dbName}`);\n const req = this.indexedDB.deleteDatabase(this.dbName);\n\n req.onblocked = (): void => {\n logger.log(`can't yet delete IndexedDBCryptoStore because it is open elsewhere`);\n };\n\n req.onerror = (ev): void => {\n logger.log(\"Error deleting data from indexeddb\", ev);\n reject(req.error);\n };\n\n req.onsuccess = (): void => {\n logger.log(`Removed indexeddb instance: ${this.dbName}`);\n resolve();\n };\n }).catch((e) => {\n // in firefox, with indexedDB disabled, this fails with a\n // DOMError. We treat this as non-fatal, so that people can\n // still use the app.\n logger.warn(`unable to delete IndexedDBCryptoStore: ${e}`);\n });\n }\n\n /**\n * Look for an existing outgoing room key request, and if none is found,\n * add a new one\n *\n *\n * @returns resolves to\n * {@link OutgoingRoomKeyRequest}: either the\n * same instance as passed in, or the existing one.\n */\n public getOrAddOutgoingRoomKeyRequest(request: OutgoingRoomKeyRequest): Promise {\n return this.backend!.getOrAddOutgoingRoomKeyRequest(request);\n }\n\n /**\n * Look for an existing room key request\n *\n * @param requestBody - existing request to look for\n *\n * @returns resolves to the matching\n * {@link OutgoingRoomKeyRequest}, or null if\n * not found\n */\n public getOutgoingRoomKeyRequest(requestBody: IRoomKeyRequestBody): Promise {\n return this.backend!.getOutgoingRoomKeyRequest(requestBody);\n }\n\n /**\n * Look for room key requests by state\n *\n * @param wantedStates - list of acceptable states\n *\n * @returns resolves to the a\n * {@link OutgoingRoomKeyRequest}, or null if\n * there are no pending requests in those states. If there are multiple\n * requests in those states, an arbitrary one is chosen.\n */\n public getOutgoingRoomKeyRequestByState(wantedStates: number[]): Promise {\n return this.backend!.getOutgoingRoomKeyRequestByState(wantedStates);\n }\n\n /**\n * Look for room key requests by state –\n * unlike above, return a list of all entries in one state.\n *\n * @returns Returns an array of requests in the given state\n */\n public getAllOutgoingRoomKeyRequestsByState(wantedState: number): Promise {\n return this.backend!.getAllOutgoingRoomKeyRequestsByState(wantedState);\n }\n\n /**\n * Look for room key requests by target device and state\n *\n * @param userId - Target user ID\n * @param deviceId - Target device ID\n * @param wantedStates - list of acceptable states\n *\n * @returns resolves to a list of all the\n * {@link OutgoingRoomKeyRequest}\n */\n public getOutgoingRoomKeyRequestsByTarget(\n userId: string,\n deviceId: string,\n wantedStates: number[],\n ): Promise {\n return this.backend!.getOutgoingRoomKeyRequestsByTarget(userId, deviceId, wantedStates);\n }\n\n /**\n * Look for an existing room key request by id and state, and update it if\n * found\n *\n * @param requestId - ID of request to update\n * @param expectedState - state we expect to find the request in\n * @param updates - name/value map of updates to apply\n *\n * @returns resolves to\n * {@link OutgoingRoomKeyRequest}\n * updated request, or null if no matching row was found\n */\n public updateOutgoingRoomKeyRequest(\n requestId: string,\n expectedState: number,\n updates: Partial,\n ): Promise {\n return this.backend!.updateOutgoingRoomKeyRequest(requestId, expectedState, updates);\n }\n\n /**\n * Look for an existing room key request by id and state, and delete it if\n * found\n *\n * @param requestId - ID of request to update\n * @param expectedState - state we expect to find the request in\n *\n * @returns resolves once the operation is completed\n */\n public deleteOutgoingRoomKeyRequest(\n requestId: string,\n expectedState: number,\n ): Promise {\n return this.backend!.deleteOutgoingRoomKeyRequest(requestId, expectedState);\n }\n\n // Olm Account\n\n /*\n * Get the account pickle from the store.\n * This requires an active transaction. See doTxn().\n *\n * @param txn - An active transaction. See doTxn().\n * @param func - Called with the account pickle\n */\n public getAccount(txn: IDBTransaction, func: (accountPickle: string | null) => void): void {\n this.backend!.getAccount(txn, func);\n }\n\n /**\n * Write the account pickle to the store.\n * This requires an active transaction. See doTxn().\n *\n * @param txn - An active transaction. See doTxn().\n * @param accountPickle - The new account pickle to store.\n */\n public storeAccount(txn: IDBTransaction, accountPickle: string): void {\n this.backend!.storeAccount(txn, accountPickle);\n }\n\n /**\n * Get the public part of the cross-signing keys (eg. self-signing key,\n * user signing key).\n *\n * @param txn - An active transaction. See doTxn().\n * @param func - Called with the account keys object:\n * `{ key_type: base64 encoded seed }` where key type = user_signing_key_seed or self_signing_key_seed\n */\n public getCrossSigningKeys(\n txn: IDBTransaction,\n func: (keys: Record | null) => void,\n ): void {\n this.backend!.getCrossSigningKeys(txn, func);\n }\n\n /**\n * @param txn - An active transaction. See doTxn().\n * @param func - Called with the private key\n * @param type - A key type\n */\n public getSecretStorePrivateKey(\n txn: IDBTransaction,\n func: (key: SecretStorePrivateKeys[K] | null) => void,\n type: K,\n ): void {\n this.backend!.getSecretStorePrivateKey(txn, func, type);\n }\n\n /**\n * Write the cross-signing keys back to the store\n *\n * @param txn - An active transaction. See doTxn().\n * @param keys - keys object as getCrossSigningKeys()\n */\n public storeCrossSigningKeys(txn: IDBTransaction, keys: Record): void {\n this.backend!.storeCrossSigningKeys(txn, keys);\n }\n\n /**\n * Write the cross-signing private keys back to the store\n *\n * @param txn - An active transaction. See doTxn().\n * @param type - The type of cross-signing private key to store\n * @param key - keys object as getCrossSigningKeys()\n */\n public storeSecretStorePrivateKey(\n txn: IDBTransaction,\n type: K,\n key: SecretStorePrivateKeys[K],\n ): void {\n this.backend!.storeSecretStorePrivateKey(txn, type, key);\n }\n\n // Olm sessions\n\n /**\n * Returns the number of end-to-end sessions in the store\n * @param txn - An active transaction. See doTxn().\n * @param func - Called with the count of sessions\n */\n public countEndToEndSessions(txn: IDBTransaction, func: (count: number) => void): void {\n this.backend!.countEndToEndSessions(txn, func);\n }\n\n /**\n * Retrieve a specific end-to-end session between the logged-in user\n * and another device.\n * @param deviceKey - The public key of the other device.\n * @param sessionId - The ID of the session to retrieve\n * @param txn - An active transaction. See doTxn().\n * @param func - Called with A map from sessionId\n * to session information object with 'session' key being the\n * Base64 end-to-end session and lastReceivedMessageTs being the\n * timestamp in milliseconds at which the session last received\n * a message.\n */\n public getEndToEndSession(\n deviceKey: string,\n sessionId: string,\n txn: IDBTransaction,\n func: (session: ISessionInfo | null) => void,\n ): void {\n this.backend!.getEndToEndSession(deviceKey, sessionId, txn, func);\n }\n\n /**\n * Retrieve the end-to-end sessions between the logged-in user and another\n * device.\n * @param deviceKey - The public key of the other device.\n * @param txn - An active transaction. See doTxn().\n * @param func - Called with A map from sessionId\n * to session information object with 'session' key being the\n * Base64 end-to-end session and lastReceivedMessageTs being the\n * timestamp in milliseconds at which the session last received\n * a message.\n */\n public getEndToEndSessions(\n deviceKey: string,\n txn: IDBTransaction,\n func: (sessions: { [sessionId: string]: ISessionInfo }) => void,\n ): void {\n this.backend!.getEndToEndSessions(deviceKey, txn, func);\n }\n\n /**\n * Retrieve all end-to-end sessions\n * @param txn - An active transaction. See doTxn().\n * @param func - Called one for each session with\n * an object with, deviceKey, lastReceivedMessageTs, sessionId\n * and session keys.\n */\n public getAllEndToEndSessions(txn: IDBTransaction, func: (session: ISessionInfo | null) => void): void {\n this.backend!.getAllEndToEndSessions(txn, func);\n }\n\n /**\n * Store a session between the logged-in user and another device\n * @param deviceKey - The public key of the other device.\n * @param sessionId - The ID for this end-to-end session.\n * @param sessionInfo - Session information object\n * @param txn - An active transaction. See doTxn().\n */\n public storeEndToEndSession(\n deviceKey: string,\n sessionId: string,\n sessionInfo: ISessionInfo,\n txn: IDBTransaction,\n ): void {\n this.backend!.storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn);\n }\n\n public storeEndToEndSessionProblem(deviceKey: string, type: string, fixed: boolean): Promise {\n return this.backend!.storeEndToEndSessionProblem(deviceKey, type, fixed);\n }\n\n public getEndToEndSessionProblem(deviceKey: string, timestamp: number): Promise {\n return this.backend!.getEndToEndSessionProblem(deviceKey, timestamp);\n }\n\n public filterOutNotifiedErrorDevices(devices: IOlmDevice[]): Promise {\n return this.backend!.filterOutNotifiedErrorDevices(devices);\n }\n\n // Inbound group sessions\n\n /**\n * Retrieve the end-to-end inbound group session for a given\n * server key and session ID\n * @param senderCurve25519Key - The sender's curve 25519 key\n * @param sessionId - The ID of the session\n * @param txn - An active transaction. See doTxn().\n * @param func - Called with A map from sessionId\n * to Base64 end-to-end session.\n */\n public getEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n txn: IDBTransaction,\n func: (groupSession: InboundGroupSessionData | null, groupSessionWithheld: IWithheld | null) => void,\n ): void {\n this.backend!.getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func);\n }\n\n /**\n * Fetches all inbound group sessions in the store\n * @param txn - An active transaction. See doTxn().\n * @param func - Called once for each group session\n * in the store with an object having keys `{senderKey, sessionId, sessionData}`,\n * then once with null to indicate the end of the list.\n */\n public getAllEndToEndInboundGroupSessions(txn: IDBTransaction, func: (session: ISession | null) => void): void {\n this.backend!.getAllEndToEndInboundGroupSessions(txn, func);\n }\n\n /**\n * Adds an end-to-end inbound group session to the store.\n * If there already exists an inbound group session with the same\n * senderCurve25519Key and sessionID, the session will not be added.\n * @param senderCurve25519Key - The sender's curve 25519 key\n * @param sessionId - The ID of the session\n * @param sessionData - The session data structure\n * @param txn - An active transaction. See doTxn().\n */\n public addEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n sessionData: InboundGroupSessionData,\n txn: IDBTransaction,\n ): void {\n this.backend!.addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn);\n }\n\n /**\n * Writes an end-to-end inbound group session to the store.\n * If there already exists an inbound group session with the same\n * senderCurve25519Key and sessionID, it will be overwritten.\n * @param senderCurve25519Key - The sender's curve 25519 key\n * @param sessionId - The ID of the session\n * @param sessionData - The session data structure\n * @param txn - An active transaction. See doTxn().\n */\n public storeEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n sessionData: InboundGroupSessionData,\n txn: IDBTransaction,\n ): void {\n this.backend!.storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn);\n }\n\n public storeEndToEndInboundGroupSessionWithheld(\n senderCurve25519Key: string,\n sessionId: string,\n sessionData: IWithheld,\n txn: IDBTransaction,\n ): void {\n this.backend!.storeEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId, sessionData, txn);\n }\n\n // End-to-end device tracking\n\n /**\n * Store the state of all tracked devices\n * This contains devices for each user, a tracking state for each user\n * and a sync token matching the point in time the snapshot represents.\n * These all need to be written out in full each time such that the snapshot\n * is always consistent, so they are stored in one object.\n *\n * @param txn - An active transaction. See doTxn().\n */\n public storeEndToEndDeviceData(deviceData: IDeviceData, txn: IDBTransaction): void {\n this.backend!.storeEndToEndDeviceData(deviceData, txn);\n }\n\n /**\n * Get the state of all tracked devices\n *\n * @param txn - An active transaction. See doTxn().\n * @param func - Function called with the\n * device data\n */\n public getEndToEndDeviceData(txn: IDBTransaction, func: (deviceData: IDeviceData | null) => void): void {\n this.backend!.getEndToEndDeviceData(txn, func);\n }\n\n // End to End Rooms\n\n /**\n * Store the end-to-end state for a room.\n * @param roomId - The room's ID.\n * @param roomInfo - The end-to-end info for the room.\n * @param txn - An active transaction. See doTxn().\n */\n public storeEndToEndRoom(roomId: string, roomInfo: IRoomEncryption, txn: IDBTransaction): void {\n this.backend!.storeEndToEndRoom(roomId, roomInfo, txn);\n }\n\n /**\n * Get an object of `roomId->roomInfo` for all e2e rooms in the store\n * @param txn - An active transaction. See doTxn().\n * @param func - Function called with the end-to-end encrypted rooms\n */\n public getEndToEndRooms(txn: IDBTransaction, func: (rooms: Record) => void): void {\n this.backend!.getEndToEndRooms(txn, func);\n }\n\n // session backups\n\n /**\n * Get the inbound group sessions that need to be backed up.\n * @param limit - The maximum number of sessions to retrieve. 0\n * for no limit.\n * @returns resolves to an array of inbound group sessions\n */\n public getSessionsNeedingBackup(limit: number): Promise {\n return this.backend!.getSessionsNeedingBackup(limit);\n }\n\n /**\n * Count the inbound group sessions that need to be backed up.\n * @param txn - An active transaction. See doTxn(). (optional)\n * @returns resolves to the number of sessions\n */\n public countSessionsNeedingBackup(txn?: IDBTransaction): Promise {\n return this.backend!.countSessionsNeedingBackup(txn);\n }\n\n /**\n * Unmark sessions as needing to be backed up.\n * @param sessions - The sessions that need to be backed up.\n * @param txn - An active transaction. See doTxn(). (optional)\n * @returns resolves when the sessions are unmarked\n */\n public unmarkSessionsNeedingBackup(sessions: ISession[], txn?: IDBTransaction): Promise {\n return this.backend!.unmarkSessionsNeedingBackup(sessions, txn);\n }\n\n /**\n * Mark sessions as needing to be backed up.\n * @param sessions - The sessions that need to be backed up.\n * @param txn - An active transaction. See doTxn(). (optional)\n * @returns resolves when the sessions are marked\n */\n public markSessionsNeedingBackup(sessions: ISession[], txn?: IDBTransaction): Promise {\n return this.backend!.markSessionsNeedingBackup(sessions, txn);\n }\n\n /**\n * Add a shared-history group session for a room.\n * @param roomId - The room that the key belongs to\n * @param senderKey - The sender's curve 25519 key\n * @param sessionId - The ID of the session\n * @param txn - An active transaction. See doTxn(). (optional)\n */\n public addSharedHistoryInboundGroupSession(\n roomId: string,\n senderKey: string,\n sessionId: string,\n txn?: IDBTransaction,\n ): void {\n this.backend!.addSharedHistoryInboundGroupSession(roomId, senderKey, sessionId, txn);\n }\n\n /**\n * Get the shared-history group session for a room.\n * @param roomId - The room that the key belongs to\n * @param txn - An active transaction. See doTxn(). (optional)\n * @returns Promise which resolves to an array of [senderKey, sessionId]\n */\n public getSharedHistoryInboundGroupSessions(\n roomId: string,\n txn?: IDBTransaction,\n ): Promise<[senderKey: string, sessionId: string][]> {\n return this.backend!.getSharedHistoryInboundGroupSessions(roomId, txn);\n }\n\n /**\n * Park a shared-history group session for a room we may be invited to later.\n */\n public addParkedSharedHistory(roomId: string, parkedData: ParkedSharedHistory, txn?: IDBTransaction): void {\n this.backend!.addParkedSharedHistory(roomId, parkedData, txn);\n }\n\n /**\n * Pop out all shared-history group sessions for a room.\n */\n public takeParkedSharedHistory(roomId: string, txn?: IDBTransaction): Promise {\n return this.backend!.takeParkedSharedHistory(roomId, txn);\n }\n\n /**\n * Perform a transaction on the crypto store. Any store methods\n * that require a transaction (txn) object to be passed in may\n * only be called within a callback of either this function or\n * one of the store functions operating on the same transaction.\n *\n * @param mode - 'readwrite' if you need to call setter\n * functions with this transaction. Otherwise, 'readonly'.\n * @param stores - List IndexedDBCryptoStore.STORE_*\n * options representing all types of object that will be\n * accessed or written to with this transaction.\n * @param func - Function called with the\n * transaction object: an opaque object that should be passed\n * to store functions.\n * @param log - A possibly customised log\n * @returns Promise that resolves with the result of the `func`\n * when the transaction is complete. If the backend is\n * async (ie. the indexeddb backend) any of the callback\n * functions throwing an exception will cause this promise to\n * reject with that exception. On synchronous backends, the\n * exception will propagate to the caller of the getFoo method.\n */\n public doTxn(\n mode: Mode,\n stores: Iterable,\n func: (txn: IDBTransaction) => T,\n log?: PrefixedLogger,\n ): Promise {\n return this.backend!.doTxn(mode, stores, func as (txn: unknown) => T, log);\n }\n}\n", - "/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from \"../../logger\";\nimport { MemoryCryptoStore } from \"./memory-crypto-store\";\nimport { IDeviceData, IProblem, ISession, ISessionInfo, IWithheld, Mode, SecretStorePrivateKeys } from \"./base\";\nimport { IOlmDevice } from \"../algorithms/megolm\";\nimport { IRoomEncryption } from \"../RoomList\";\nimport { ICrossSigningKey } from \"../../client\";\nimport { InboundGroupSessionData } from \"../OlmDevice\";\nimport { safeSet } from \"../../utils\";\n\n/**\n * Internal module. Partial localStorage backed storage for e2e.\n * This is not a full crypto store, just the in-memory store with\n * some things backed by localStorage. It exists because indexedDB\n * is broken in Firefox private mode or set to, \"will not remember\n * history\".\n */\n\nconst E2E_PREFIX = \"crypto.\";\nconst KEY_END_TO_END_ACCOUNT = E2E_PREFIX + \"account\";\nconst KEY_CROSS_SIGNING_KEYS = E2E_PREFIX + \"cross_signing_keys\";\nconst KEY_NOTIFIED_ERROR_DEVICES = E2E_PREFIX + \"notified_error_devices\";\nconst KEY_DEVICE_DATA = E2E_PREFIX + \"device_data\";\nconst KEY_INBOUND_SESSION_PREFIX = E2E_PREFIX + \"inboundgroupsessions/\";\nconst KEY_INBOUND_SESSION_WITHHELD_PREFIX = E2E_PREFIX + \"inboundgroupsessions.withheld/\";\nconst KEY_ROOMS_PREFIX = E2E_PREFIX + \"rooms/\";\nconst KEY_SESSIONS_NEEDING_BACKUP = E2E_PREFIX + \"sessionsneedingbackup\";\n\nfunction keyEndToEndSessions(deviceKey: string): string {\n return E2E_PREFIX + \"sessions/\" + deviceKey;\n}\n\nfunction keyEndToEndSessionProblems(deviceKey: string): string {\n return E2E_PREFIX + \"session.problems/\" + deviceKey;\n}\n\nfunction keyEndToEndInboundGroupSession(senderKey: string, sessionId: string): string {\n return KEY_INBOUND_SESSION_PREFIX + senderKey + \"/\" + sessionId;\n}\n\nfunction keyEndToEndInboundGroupSessionWithheld(senderKey: string, sessionId: string): string {\n return KEY_INBOUND_SESSION_WITHHELD_PREFIX + senderKey + \"/\" + sessionId;\n}\n\nfunction keyEndToEndRoomsPrefix(roomId: string): string {\n return KEY_ROOMS_PREFIX + roomId;\n}\n\nexport class LocalStorageCryptoStore extends MemoryCryptoStore {\n public static exists(store: Storage): boolean {\n const length = store.length;\n for (let i = 0; i < length; i++) {\n if (store.key(i)?.startsWith(E2E_PREFIX)) {\n return true;\n }\n }\n return false;\n }\n\n public constructor(private readonly store: Storage) {\n super();\n }\n\n // Olm Sessions\n\n public countEndToEndSessions(txn: unknown, func: (count: number) => void): void {\n let count = 0;\n for (let i = 0; i < this.store.length; ++i) {\n if (this.store.key(i)?.startsWith(keyEndToEndSessions(\"\"))) ++count;\n }\n func(count);\n }\n\n // eslint-disable-next-line @typescript-eslint/naming-convention\n private _getEndToEndSessions(deviceKey: string): Record {\n const sessions = getJsonItem(this.store, keyEndToEndSessions(deviceKey));\n const fixedSessions: Record = {};\n\n // fix up any old sessions to be objects rather than just the base64 pickle\n for (const [sid, val] of Object.entries(sessions || {})) {\n if (typeof val === \"string\") {\n fixedSessions[sid] = {\n session: val,\n };\n } else {\n fixedSessions[sid] = val;\n }\n }\n\n return fixedSessions;\n }\n\n public getEndToEndSession(\n deviceKey: string,\n sessionId: string,\n txn: unknown,\n func: (session: ISessionInfo) => void,\n ): void {\n const sessions = this._getEndToEndSessions(deviceKey);\n func(sessions[sessionId] || {});\n }\n\n public getEndToEndSessions(\n deviceKey: string,\n txn: unknown,\n func: (sessions: { [sessionId: string]: ISessionInfo }) => void,\n ): void {\n func(this._getEndToEndSessions(deviceKey) || {});\n }\n\n public getAllEndToEndSessions(txn: unknown, func: (session: ISessionInfo) => void): void {\n for (let i = 0; i < this.store.length; ++i) {\n if (this.store.key(i)?.startsWith(keyEndToEndSessions(\"\"))) {\n const deviceKey = this.store.key(i)!.split(\"/\")[1];\n for (const sess of Object.values(this._getEndToEndSessions(deviceKey))) {\n func(sess);\n }\n }\n }\n }\n\n public storeEndToEndSession(deviceKey: string, sessionId: string, sessionInfo: ISessionInfo, txn: unknown): void {\n const sessions = this._getEndToEndSessions(deviceKey) || {};\n sessions[sessionId] = sessionInfo;\n setJsonItem(this.store, keyEndToEndSessions(deviceKey), sessions);\n }\n\n public async storeEndToEndSessionProblem(deviceKey: string, type: string, fixed: boolean): Promise {\n const key = keyEndToEndSessionProblems(deviceKey);\n const problems = getJsonItem(this.store, key) || [];\n problems.push({ type, fixed, time: Date.now() });\n problems.sort((a, b) => {\n return a.time - b.time;\n });\n setJsonItem(this.store, key, problems);\n }\n\n public async getEndToEndSessionProblem(deviceKey: string, timestamp: number): Promise {\n const key = keyEndToEndSessionProblems(deviceKey);\n const problems = getJsonItem(this.store, key) || [];\n if (!problems.length) {\n return null;\n }\n const lastProblem = problems[problems.length - 1];\n for (const problem of problems) {\n if (problem.time > timestamp) {\n return Object.assign({}, problem, { fixed: lastProblem.fixed });\n }\n }\n if (lastProblem.fixed) {\n return null;\n } else {\n return lastProblem;\n }\n }\n\n public async filterOutNotifiedErrorDevices(devices: IOlmDevice[]): Promise {\n const notifiedErrorDevices =\n getJsonItem(this.store, KEY_NOTIFIED_ERROR_DEVICES) || {};\n const ret: IOlmDevice[] = [];\n\n for (const device of devices) {\n const { userId, deviceInfo } = device;\n if (userId in notifiedErrorDevices) {\n if (!(deviceInfo.deviceId in notifiedErrorDevices[userId])) {\n ret.push(device);\n safeSet(notifiedErrorDevices[userId], deviceInfo.deviceId, true);\n }\n } else {\n ret.push(device);\n safeSet(notifiedErrorDevices, userId, { [deviceInfo.deviceId]: true });\n }\n }\n\n setJsonItem(this.store, KEY_NOTIFIED_ERROR_DEVICES, notifiedErrorDevices);\n\n return ret;\n }\n\n // Inbound Group Sessions\n\n public getEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n txn: unknown,\n func: (groupSession: InboundGroupSessionData | null, groupSessionWithheld: IWithheld | null) => void,\n ): void {\n func(\n getJsonItem(this.store, keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId)),\n getJsonItem(this.store, keyEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId)),\n );\n }\n\n public getAllEndToEndInboundGroupSessions(txn: unknown, func: (session: ISession | null) => void): void {\n for (let i = 0; i < this.store.length; ++i) {\n const key = this.store.key(i);\n if (key?.startsWith(KEY_INBOUND_SESSION_PREFIX)) {\n // we can't use split, as the components we are trying to split out\n // might themselves contain '/' characters. We rely on the\n // senderKey being a (32-byte) curve25519 key, base64-encoded\n // (hence 43 characters long).\n\n func({\n senderKey: key.slice(KEY_INBOUND_SESSION_PREFIX.length, KEY_INBOUND_SESSION_PREFIX.length + 43),\n sessionId: key.slice(KEY_INBOUND_SESSION_PREFIX.length + 44),\n sessionData: getJsonItem(this.store, key)!,\n });\n }\n }\n func(null);\n }\n\n public addEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n sessionData: InboundGroupSessionData,\n txn: unknown,\n ): void {\n const existing = getJsonItem(this.store, keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId));\n if (!existing) {\n this.storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn);\n }\n }\n\n public storeEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n sessionData: InboundGroupSessionData,\n txn: unknown,\n ): void {\n setJsonItem(this.store, keyEndToEndInboundGroupSession(senderCurve25519Key, sessionId), sessionData);\n }\n\n public storeEndToEndInboundGroupSessionWithheld(\n senderCurve25519Key: string,\n sessionId: string,\n sessionData: IWithheld,\n txn: unknown,\n ): void {\n setJsonItem(this.store, keyEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId), sessionData);\n }\n\n public getEndToEndDeviceData(txn: unknown, func: (deviceData: IDeviceData | null) => void): void {\n func(getJsonItem(this.store, KEY_DEVICE_DATA));\n }\n\n public storeEndToEndDeviceData(deviceData: IDeviceData, txn: unknown): void {\n setJsonItem(this.store, KEY_DEVICE_DATA, deviceData);\n }\n\n public storeEndToEndRoom(roomId: string, roomInfo: IRoomEncryption, txn: unknown): void {\n setJsonItem(this.store, keyEndToEndRoomsPrefix(roomId), roomInfo);\n }\n\n public getEndToEndRooms(txn: unknown, func: (rooms: Record) => void): void {\n const result: Record = {};\n const prefix = keyEndToEndRoomsPrefix(\"\");\n\n for (let i = 0; i < this.store.length; ++i) {\n const key = this.store.key(i);\n if (key?.startsWith(prefix)) {\n const roomId = key.slice(prefix.length);\n result[roomId] = getJsonItem(this.store, key)!;\n }\n }\n func(result);\n }\n\n public getSessionsNeedingBackup(limit: number): Promise {\n const sessionsNeedingBackup = getJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {};\n const sessions: ISession[] = [];\n\n for (const session in sessionsNeedingBackup) {\n if (Object.prototype.hasOwnProperty.call(sessionsNeedingBackup, session)) {\n // see getAllEndToEndInboundGroupSessions for the magic number explanations\n const senderKey = session.slice(0, 43);\n const sessionId = session.slice(44);\n this.getEndToEndInboundGroupSession(senderKey, sessionId, null, (sessionData) => {\n sessions.push({\n senderKey: senderKey,\n sessionId: sessionId,\n sessionData: sessionData!,\n });\n });\n if (limit && sessions.length >= limit) {\n break;\n }\n }\n }\n return Promise.resolve(sessions);\n }\n\n public countSessionsNeedingBackup(): Promise {\n const sessionsNeedingBackup = getJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {};\n return Promise.resolve(Object.keys(sessionsNeedingBackup).length);\n }\n\n public unmarkSessionsNeedingBackup(sessions: ISession[]): Promise {\n const sessionsNeedingBackup =\n getJsonItem<{\n [senderKeySessionId: string]: string;\n }>(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {};\n for (const session of sessions) {\n delete sessionsNeedingBackup[session.senderKey + \"/\" + session.sessionId];\n }\n setJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP, sessionsNeedingBackup);\n return Promise.resolve();\n }\n\n public markSessionsNeedingBackup(sessions: ISession[]): Promise {\n const sessionsNeedingBackup =\n getJsonItem<{\n [senderKeySessionId: string]: boolean;\n }>(this.store, KEY_SESSIONS_NEEDING_BACKUP) || {};\n for (const session of sessions) {\n sessionsNeedingBackup[session.senderKey + \"/\" + session.sessionId] = true;\n }\n setJsonItem(this.store, KEY_SESSIONS_NEEDING_BACKUP, sessionsNeedingBackup);\n return Promise.resolve();\n }\n\n /**\n * Delete all data from this store.\n *\n * @returns Promise which resolves when the store has been cleared.\n */\n public deleteAllData(): Promise {\n this.store.removeItem(KEY_END_TO_END_ACCOUNT);\n return Promise.resolve();\n }\n\n // Olm account\n\n public getAccount(txn: unknown, func: (accountPickle: string | null) => void): void {\n const accountPickle = getJsonItem(this.store, KEY_END_TO_END_ACCOUNT);\n func(accountPickle);\n }\n\n public storeAccount(txn: unknown, accountPickle: string): void {\n setJsonItem(this.store, KEY_END_TO_END_ACCOUNT, accountPickle);\n }\n\n public getCrossSigningKeys(txn: unknown, func: (keys: Record | null) => void): void {\n const keys = getJsonItem>(this.store, KEY_CROSS_SIGNING_KEYS);\n func(keys);\n }\n\n public getSecretStorePrivateKey(\n txn: unknown,\n func: (key: SecretStorePrivateKeys[K] | null) => void,\n type: K,\n ): void {\n const key = getJsonItem(this.store, E2E_PREFIX + `ssss_cache.${type}`);\n func(key);\n }\n\n public storeCrossSigningKeys(txn: unknown, keys: Record): void {\n setJsonItem(this.store, KEY_CROSS_SIGNING_KEYS, keys);\n }\n\n public storeSecretStorePrivateKey(\n txn: unknown,\n type: K,\n key: SecretStorePrivateKeys[K],\n ): void {\n setJsonItem(this.store, E2E_PREFIX + `ssss_cache.${type}`, key);\n }\n\n public doTxn(mode: Mode, stores: Iterable, func: (txn: unknown) => T): Promise {\n return Promise.resolve(func(null));\n }\n}\n\nfunction getJsonItem(store: Storage, key: string): T | null {\n try {\n // if the key is absent, store.getItem() returns null, and\n // JSON.parse(null) === null, so this returns null.\n return JSON.parse(store.getItem(key)!);\n } catch (e) {\n logger.log(\"Error: Failed to get key %s: %s\", key, (e).message);\n logger.log((e).stack);\n }\n return null;\n}\n\nfunction setJsonItem(store: Storage, key: string, val: T): void {\n store.setItem(key, JSON.stringify(val));\n}\n", - "/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from \"../../logger\";\nimport * as utils from \"../../utils\";\nimport {\n CryptoStore,\n IDeviceData,\n IProblem,\n ISession,\n ISessionInfo,\n IWithheld,\n Mode,\n OutgoingRoomKeyRequest,\n ParkedSharedHistory,\n SecretStorePrivateKeys,\n} from \"./base\";\nimport { IRoomKeyRequestBody } from \"../index\";\nimport { ICrossSigningKey } from \"../../client\";\nimport { IOlmDevice } from \"../algorithms/megolm\";\nimport { IRoomEncryption } from \"../RoomList\";\nimport { InboundGroupSessionData } from \"../OlmDevice\";\nimport { safeSet } from \"../../utils\";\n\n/**\n * Internal module. in-memory storage for e2e.\n */\n\nexport class MemoryCryptoStore implements CryptoStore {\n private outgoingRoomKeyRequests: OutgoingRoomKeyRequest[] = [];\n private account: string | null = null;\n private crossSigningKeys: Record | null = null;\n private privateKeys: Partial = {};\n\n private sessions: { [deviceKey: string]: { [sessionId: string]: ISessionInfo } } = {};\n private sessionProblems: { [deviceKey: string]: IProblem[] } = {};\n private notifiedErrorDevices: { [userId: string]: { [deviceId: string]: boolean } } = {};\n private inboundGroupSessions: { [sessionKey: string]: InboundGroupSessionData } = {};\n private inboundGroupSessionsWithheld: Record = {};\n // Opaque device data object\n private deviceData: IDeviceData | null = null;\n private rooms: { [roomId: string]: IRoomEncryption } = {};\n private sessionsNeedingBackup: { [sessionKey: string]: boolean } = {};\n private sharedHistoryInboundGroupSessions: { [roomId: string]: [senderKey: string, sessionId: string][] } = {};\n private parkedSharedHistory = new Map(); // keyed by room ID\n\n /**\n * Ensure the database exists and is up-to-date.\n *\n * This must be called before the store can be used.\n *\n * @returns resolves to the store.\n */\n public async startup(): Promise {\n // No startup work to do for the memory store.\n return this;\n }\n\n /**\n * Delete all data from this store.\n *\n * @returns Promise which resolves when the store has been cleared.\n */\n public deleteAllData(): Promise {\n return Promise.resolve();\n }\n\n /**\n * Look for an existing outgoing room key request, and if none is found,\n * add a new one\n *\n *\n * @returns resolves to\n * {@link OutgoingRoomKeyRequest}: either the\n * same instance as passed in, or the existing one.\n */\n public getOrAddOutgoingRoomKeyRequest(request: OutgoingRoomKeyRequest): Promise {\n const requestBody = request.requestBody;\n\n return utils.promiseTry(() => {\n // first see if we already have an entry for this request.\n const existing = this._getOutgoingRoomKeyRequest(requestBody);\n\n if (existing) {\n // this entry matches the request - return it.\n logger.log(\n `already have key request outstanding for ` +\n `${requestBody.room_id} / ${requestBody.session_id}: ` +\n `not sending another`,\n );\n return existing;\n }\n\n // we got to the end of the list without finding a match\n // - add the new request.\n logger.log(`enqueueing key request for ${requestBody.room_id} / ` + requestBody.session_id);\n this.outgoingRoomKeyRequests.push(request);\n return request;\n });\n }\n\n /**\n * Look for an existing room key request\n *\n * @param requestBody - existing request to look for\n *\n * @returns resolves to the matching\n * {@link OutgoingRoomKeyRequest}, or null if\n * not found\n */\n public getOutgoingRoomKeyRequest(requestBody: IRoomKeyRequestBody): Promise {\n return Promise.resolve(this._getOutgoingRoomKeyRequest(requestBody));\n }\n\n /**\n * Looks for existing room key request, and returns the result synchronously.\n *\n * @internal\n *\n * @param requestBody - existing request to look for\n *\n * @returns\n * the matching request, or null if not found\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n private _getOutgoingRoomKeyRequest(requestBody: IRoomKeyRequestBody): OutgoingRoomKeyRequest | null {\n for (const existing of this.outgoingRoomKeyRequests) {\n if (utils.deepCompare(existing.requestBody, requestBody)) {\n return existing;\n }\n }\n return null;\n }\n\n /**\n * Look for room key requests by state\n *\n * @param wantedStates - list of acceptable states\n *\n * @returns resolves to the a\n * {@link OutgoingRoomKeyRequest}, or null if\n * there are no pending requests in those states\n */\n public getOutgoingRoomKeyRequestByState(wantedStates: number[]): Promise {\n for (const req of this.outgoingRoomKeyRequests) {\n for (const state of wantedStates) {\n if (req.state === state) {\n return Promise.resolve(req);\n }\n }\n }\n return Promise.resolve(null);\n }\n\n /**\n *\n * @returns All OutgoingRoomKeyRequests in state\n */\n public getAllOutgoingRoomKeyRequestsByState(wantedState: number): Promise {\n return Promise.resolve(this.outgoingRoomKeyRequests.filter((r) => r.state == wantedState));\n }\n\n public getOutgoingRoomKeyRequestsByTarget(\n userId: string,\n deviceId: string,\n wantedStates: number[],\n ): Promise {\n const results: OutgoingRoomKeyRequest[] = [];\n\n for (const req of this.outgoingRoomKeyRequests) {\n for (const state of wantedStates) {\n if (\n req.state === state &&\n req.recipients.some((recipient) => recipient.userId === userId && recipient.deviceId === deviceId)\n ) {\n results.push(req);\n }\n }\n }\n return Promise.resolve(results);\n }\n\n /**\n * Look for an existing room key request by id and state, and update it if\n * found\n *\n * @param requestId - ID of request to update\n * @param expectedState - state we expect to find the request in\n * @param updates - name/value map of updates to apply\n *\n * @returns resolves to\n * {@link OutgoingRoomKeyRequest}\n * updated request, or null if no matching row was found\n */\n public updateOutgoingRoomKeyRequest(\n requestId: string,\n expectedState: number,\n updates: Partial,\n ): Promise {\n for (const req of this.outgoingRoomKeyRequests) {\n if (req.requestId !== requestId) {\n continue;\n }\n\n if (req.state !== expectedState) {\n logger.warn(\n `Cannot update room key request from ${expectedState} ` +\n `as it was already updated to ${req.state}`,\n );\n return Promise.resolve(null);\n }\n Object.assign(req, updates);\n return Promise.resolve(req);\n }\n\n return Promise.resolve(null);\n }\n\n /**\n * Look for an existing room key request by id and state, and delete it if\n * found\n *\n * @param requestId - ID of request to update\n * @param expectedState - state we expect to find the request in\n *\n * @returns resolves once the operation is completed\n */\n public deleteOutgoingRoomKeyRequest(\n requestId: string,\n expectedState: number,\n ): Promise {\n for (let i = 0; i < this.outgoingRoomKeyRequests.length; i++) {\n const req = this.outgoingRoomKeyRequests[i];\n\n if (req.requestId !== requestId) {\n continue;\n }\n\n if (req.state != expectedState) {\n logger.warn(`Cannot delete room key request in state ${req.state} ` + `(expected ${expectedState})`);\n return Promise.resolve(null);\n }\n\n this.outgoingRoomKeyRequests.splice(i, 1);\n return Promise.resolve(req);\n }\n\n return Promise.resolve(null);\n }\n\n // Olm Account\n\n public getAccount(txn: unknown, func: (accountPickle: string | null) => void): void {\n func(this.account);\n }\n\n public storeAccount(txn: unknown, accountPickle: string): void {\n this.account = accountPickle;\n }\n\n public getCrossSigningKeys(txn: unknown, func: (keys: Record | null) => void): void {\n func(this.crossSigningKeys);\n }\n\n public getSecretStorePrivateKey(\n txn: unknown,\n func: (key: SecretStorePrivateKeys[K] | null) => void,\n type: K,\n ): void {\n const result = this.privateKeys[type] as SecretStorePrivateKeys[K] | undefined;\n func(result || null);\n }\n\n public storeCrossSigningKeys(txn: unknown, keys: Record): void {\n this.crossSigningKeys = keys;\n }\n\n public storeSecretStorePrivateKey(\n txn: unknown,\n type: K,\n key: SecretStorePrivateKeys[K],\n ): void {\n this.privateKeys[type] = key;\n }\n\n // Olm Sessions\n\n public countEndToEndSessions(txn: unknown, func: (count: number) => void): void {\n func(Object.keys(this.sessions).length);\n }\n\n public getEndToEndSession(\n deviceKey: string,\n sessionId: string,\n txn: unknown,\n func: (session: ISessionInfo) => void,\n ): void {\n const deviceSessions = this.sessions[deviceKey] || {};\n func(deviceSessions[sessionId] || null);\n }\n\n public getEndToEndSessions(\n deviceKey: string,\n txn: unknown,\n func: (sessions: { [sessionId: string]: ISessionInfo }) => void,\n ): void {\n func(this.sessions[deviceKey] || {});\n }\n\n public getAllEndToEndSessions(txn: unknown, func: (session: ISessionInfo) => void): void {\n Object.entries(this.sessions).forEach(([deviceKey, deviceSessions]) => {\n Object.entries(deviceSessions).forEach(([sessionId, session]) => {\n func({\n ...session,\n deviceKey,\n sessionId,\n });\n });\n });\n }\n\n public storeEndToEndSession(deviceKey: string, sessionId: string, sessionInfo: ISessionInfo, txn: unknown): void {\n let deviceSessions = this.sessions[deviceKey];\n if (deviceSessions === undefined) {\n deviceSessions = {};\n this.sessions[deviceKey] = deviceSessions;\n }\n deviceSessions[sessionId] = sessionInfo;\n }\n\n public async storeEndToEndSessionProblem(deviceKey: string, type: string, fixed: boolean): Promise {\n const problems = (this.sessionProblems[deviceKey] = this.sessionProblems[deviceKey] || []);\n problems.push({ type, fixed, time: Date.now() });\n problems.sort((a, b) => {\n return a.time - b.time;\n });\n }\n\n public async getEndToEndSessionProblem(deviceKey: string, timestamp: number): Promise {\n const problems = this.sessionProblems[deviceKey] || [];\n if (!problems.length) {\n return null;\n }\n const lastProblem = problems[problems.length - 1];\n for (const problem of problems) {\n if (problem.time > timestamp) {\n return Object.assign({}, problem, { fixed: lastProblem.fixed });\n }\n }\n if (lastProblem.fixed) {\n return null;\n } else {\n return lastProblem;\n }\n }\n\n public async filterOutNotifiedErrorDevices(devices: IOlmDevice[]): Promise {\n const notifiedErrorDevices = this.notifiedErrorDevices;\n const ret: IOlmDevice[] = [];\n\n for (const device of devices) {\n const { userId, deviceInfo } = device;\n if (userId in notifiedErrorDevices) {\n if (!(deviceInfo.deviceId in notifiedErrorDevices[userId])) {\n ret.push(device);\n safeSet(notifiedErrorDevices[userId], deviceInfo.deviceId, true);\n }\n } else {\n ret.push(device);\n safeSet(notifiedErrorDevices, userId, { [deviceInfo.deviceId]: true });\n }\n }\n\n return ret;\n }\n\n // Inbound Group Sessions\n\n public getEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n txn: unknown,\n func: (groupSession: InboundGroupSessionData | null, groupSessionWithheld: IWithheld | null) => void,\n ): void {\n const k = senderCurve25519Key + \"/\" + sessionId;\n func(this.inboundGroupSessions[k] || null, this.inboundGroupSessionsWithheld[k] || null);\n }\n\n public getAllEndToEndInboundGroupSessions(txn: unknown, func: (session: ISession | null) => void): void {\n for (const key of Object.keys(this.inboundGroupSessions)) {\n // we can't use split, as the components we are trying to split out\n // might themselves contain '/' characters. We rely on the\n // senderKey being a (32-byte) curve25519 key, base64-encoded\n // (hence 43 characters long).\n\n func({\n senderKey: key.slice(0, 43),\n sessionId: key.slice(44),\n sessionData: this.inboundGroupSessions[key],\n });\n }\n func(null);\n }\n\n public addEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n sessionData: InboundGroupSessionData,\n txn: unknown,\n ): void {\n const k = senderCurve25519Key + \"/\" + sessionId;\n if (this.inboundGroupSessions[k] === undefined) {\n this.inboundGroupSessions[k] = sessionData;\n }\n }\n\n public storeEndToEndInboundGroupSession(\n senderCurve25519Key: string,\n sessionId: string,\n sessionData: InboundGroupSessionData,\n txn: unknown,\n ): void {\n this.inboundGroupSessions[senderCurve25519Key + \"/\" + sessionId] = sessionData;\n }\n\n public storeEndToEndInboundGroupSessionWithheld(\n senderCurve25519Key: string,\n sessionId: string,\n sessionData: IWithheld,\n txn: unknown,\n ): void {\n const k = senderCurve25519Key + \"/\" + sessionId;\n this.inboundGroupSessionsWithheld[k] = sessionData;\n }\n\n // Device Data\n\n public getEndToEndDeviceData(txn: unknown, func: (deviceData: IDeviceData | null) => void): void {\n func(this.deviceData);\n }\n\n public storeEndToEndDeviceData(deviceData: IDeviceData, txn: unknown): void {\n this.deviceData = deviceData;\n }\n\n // E2E rooms\n\n public storeEndToEndRoom(roomId: string, roomInfo: IRoomEncryption, txn: unknown): void {\n this.rooms[roomId] = roomInfo;\n }\n\n public getEndToEndRooms(txn: unknown, func: (rooms: Record) => void): void {\n func(this.rooms);\n }\n\n public getSessionsNeedingBackup(limit: number): Promise {\n const sessions: ISession[] = [];\n for (const session in this.sessionsNeedingBackup) {\n if (this.inboundGroupSessions[session]) {\n sessions.push({\n senderKey: session.slice(0, 43),\n sessionId: session.slice(44),\n sessionData: this.inboundGroupSessions[session],\n });\n if (limit && session.length >= limit) {\n break;\n }\n }\n }\n return Promise.resolve(sessions);\n }\n\n public countSessionsNeedingBackup(): Promise {\n return Promise.resolve(Object.keys(this.sessionsNeedingBackup).length);\n }\n\n public unmarkSessionsNeedingBackup(sessions: ISession[]): Promise {\n for (const session of sessions) {\n const sessionKey = session.senderKey + \"/\" + session.sessionId;\n delete this.sessionsNeedingBackup[sessionKey];\n }\n return Promise.resolve();\n }\n\n public markSessionsNeedingBackup(sessions: ISession[]): Promise {\n for (const session of sessions) {\n const sessionKey = session.senderKey + \"/\" + session.sessionId;\n this.sessionsNeedingBackup[sessionKey] = true;\n }\n return Promise.resolve();\n }\n\n public addSharedHistoryInboundGroupSession(roomId: string, senderKey: string, sessionId: string): void {\n const sessions = this.sharedHistoryInboundGroupSessions[roomId] || [];\n sessions.push([senderKey, sessionId]);\n this.sharedHistoryInboundGroupSessions[roomId] = sessions;\n }\n\n public getSharedHistoryInboundGroupSessions(roomId: string): Promise<[senderKey: string, sessionId: string][]> {\n return Promise.resolve(this.sharedHistoryInboundGroupSessions[roomId] || []);\n }\n\n public addParkedSharedHistory(roomId: string, parkedData: ParkedSharedHistory): void {\n const parked = this.parkedSharedHistory.get(roomId) ?? [];\n parked.push(parkedData);\n this.parkedSharedHistory.set(roomId, parked);\n }\n\n public takeParkedSharedHistory(roomId: string): Promise {\n const parked = this.parkedSharedHistory.get(roomId) ?? [];\n this.parkedSharedHistory.delete(roomId);\n return Promise.resolve(parked);\n }\n\n // Session key backups\n\n public doTxn(mode: Mode, stores: Iterable, func: (txn?: unknown) => T): Promise {\n return Promise.resolve(func(null));\n }\n}\n", - "/*\nCopyright 2018 New Vector Ltd\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Base class for verification methods.\n */\n\nimport { MatrixEvent } from \"../../models/event\";\nimport { EventType } from \"../../@types/event\";\nimport { logger } from \"../../logger\";\nimport { DeviceInfo } from \"../deviceinfo\";\nimport { newTimeoutError } from \"./Error\";\nimport { KeysDuringVerification, requestKeysDuringVerification } from \"../CrossSigning\";\nimport { IVerificationChannel } from \"./request/Channel\";\nimport { MatrixClient } from \"../../client\";\nimport { VerificationRequest } from \"./request/VerificationRequest\";\nimport { ListenerMap, TypedEventEmitter } from \"../../models/typed-event-emitter\";\n\nconst timeoutException = new Error(\"Verification timed out\");\n\nexport class SwitchStartEventError extends Error {\n public constructor(public readonly startEvent: MatrixEvent | null) {\n super();\n }\n}\n\nexport type KeyVerifier = (keyId: string, device: DeviceInfo, keyInfo: string) => void;\n\nexport enum VerificationEvent {\n Cancel = \"cancel\",\n}\n\nexport type VerificationEventHandlerMap = {\n [VerificationEvent.Cancel]: (e: Error | MatrixEvent) => void;\n};\n\nexport class VerificationBase<\n Events extends string,\n Arguments extends ListenerMap,\n> extends TypedEventEmitter {\n private cancelled = false;\n private _done = false;\n private promise: Promise | null = null;\n private transactionTimeoutTimer: ReturnType | null = null;\n protected expectedEvent?: string;\n private resolve?: () => void;\n private reject?: (e: Error | MatrixEvent) => void;\n private resolveEvent?: (e: MatrixEvent) => void;\n private rejectEvent?: (e: Error) => void;\n private started?: boolean;\n\n /**\n * Base class for verification methods.\n *\n *

Once a verifier object is created, the verification can be started by\n * calling the verify() method, which will return a promise that will\n * resolve when the verification is completed, or reject if it could not\n * complete.

\n *\n *

Subclasses must have a NAME class property.

\n *\n * @param channel - the verification channel to send verification messages over.\n * TODO: Channel types\n *\n * @param baseApis - base matrix api interface\n *\n * @param userId - the user ID that is being verified\n *\n * @param deviceId - the device ID that is being verified\n *\n * @param startEvent - the m.key.verification.start event that\n * initiated this verification, if any\n *\n * @param request - the key verification request object related to\n * this verification, if any\n */\n public constructor(\n public readonly channel: IVerificationChannel,\n public readonly baseApis: MatrixClient,\n public readonly userId: string,\n public readonly deviceId: string,\n public startEvent: MatrixEvent | null,\n public readonly request: VerificationRequest,\n ) {\n super();\n }\n\n public get initiatedByMe(): boolean {\n // if there is no start event yet,\n // we probably want to send it,\n // which happens if we initiate\n if (!this.startEvent) {\n return true;\n }\n const sender = this.startEvent.getSender();\n const content = this.startEvent.getContent();\n return sender === this.baseApis.getUserId() && content.from_device === this.baseApis.getDeviceId();\n }\n\n public get hasBeenCancelled(): boolean {\n return this.cancelled;\n }\n\n private resetTimer(): void {\n logger.info(\"Refreshing/starting the verification transaction timeout timer\");\n if (this.transactionTimeoutTimer !== null) {\n clearTimeout(this.transactionTimeoutTimer);\n }\n this.transactionTimeoutTimer = setTimeout(() => {\n if (!this._done && !this.cancelled) {\n logger.info(\"Triggering verification timeout\");\n this.cancel(timeoutException);\n }\n }, 10 * 60 * 1000); // 10 minutes\n }\n\n private endTimer(): void {\n if (this.transactionTimeoutTimer !== null) {\n clearTimeout(this.transactionTimeoutTimer);\n this.transactionTimeoutTimer = null;\n }\n }\n\n protected send(type: string, uncompletedContent: Record): Promise {\n return this.channel.send(type, uncompletedContent);\n }\n\n protected waitForEvent(type: string): Promise {\n if (this._done) {\n return Promise.reject(new Error(\"Verification is already done\"));\n }\n const existingEvent = this.request.getEventFromOtherParty(type);\n if (existingEvent) {\n return Promise.resolve(existingEvent);\n }\n\n this.expectedEvent = type;\n return new Promise((resolve, reject) => {\n this.resolveEvent = resolve;\n this.rejectEvent = reject;\n });\n }\n\n public canSwitchStartEvent(event: MatrixEvent): boolean {\n return false;\n }\n\n public switchStartEvent(event: MatrixEvent): void {\n if (this.canSwitchStartEvent(event)) {\n logger.log(\"Verification Base: switching verification start event\", { restartingFlow: !!this.rejectEvent });\n if (this.rejectEvent) {\n const reject = this.rejectEvent;\n this.rejectEvent = undefined;\n reject(new SwitchStartEventError(event));\n } else {\n this.startEvent = event;\n }\n }\n }\n\n public handleEvent(e: MatrixEvent): void {\n if (this._done) {\n return;\n } else if (e.getType() === this.expectedEvent) {\n // if we receive an expected m.key.verification.done, then just\n // ignore it, since we don't need to do anything about it\n if (this.expectedEvent !== EventType.KeyVerificationDone) {\n this.expectedEvent = undefined;\n this.rejectEvent = undefined;\n this.resetTimer();\n this.resolveEvent?.(e);\n }\n } else if (e.getType() === EventType.KeyVerificationCancel) {\n const reject = this.reject;\n this.reject = undefined;\n // there is only promise to reject if verify has been called\n if (reject) {\n const content = e.getContent();\n const { reason, code } = content;\n reject(new Error(`Other side cancelled verification ` + `because ${reason} (${code})`));\n }\n } else if (this.expectedEvent) {\n // only cancel if there is an event expected.\n // if there is no event expected, it means verify() wasn't called\n // and we're just replaying the timeline events when syncing\n // after a refresh when the events haven't been stored in the cache yet.\n const exception = new Error(\n \"Unexpected message: expecting \" + this.expectedEvent + \" but got \" + e.getType(),\n );\n this.expectedEvent = undefined;\n if (this.rejectEvent) {\n const reject = this.rejectEvent;\n this.rejectEvent = undefined;\n reject(exception);\n }\n this.cancel(exception);\n }\n }\n\n public async done(): Promise {\n this.endTimer(); // always kill the activity timer\n if (!this._done) {\n this.request.onVerifierFinished();\n this.resolve?.();\n return requestKeysDuringVerification(this.baseApis, this.userId, this.deviceId);\n }\n }\n\n public cancel(e: Error | MatrixEvent): void {\n this.endTimer(); // always kill the activity timer\n if (!this._done) {\n this.cancelled = true;\n this.request.onVerifierCancelled();\n if (this.userId && this.deviceId) {\n // send a cancellation to the other user (if it wasn't\n // cancelled by the other user)\n if (e === timeoutException) {\n const timeoutEvent = newTimeoutError();\n this.send(timeoutEvent.getType(), timeoutEvent.getContent());\n } else if (e instanceof MatrixEvent) {\n const sender = e.getSender();\n if (sender !== this.userId) {\n const content = e.getContent();\n if (e.getType() === EventType.KeyVerificationCancel) {\n content.code = content.code || \"m.unknown\";\n content.reason = content.reason || content.body || \"Unknown reason\";\n this.send(EventType.KeyVerificationCancel, content);\n } else {\n this.send(EventType.KeyVerificationCancel, {\n code: \"m.unknown\",\n reason: content.body || \"Unknown reason\",\n });\n }\n }\n } else {\n this.send(EventType.KeyVerificationCancel, {\n code: \"m.unknown\",\n reason: e.toString(),\n });\n }\n }\n if (this.promise !== null) {\n // when we cancel without a promise, we end up with a promise\n // but no reject function. If cancel is called again, we'd error.\n if (this.reject) this.reject(e);\n } else {\n // FIXME: this causes an \"Uncaught promise\" console message\n // if nothing ends up chaining this promise.\n this.promise = Promise.reject(e);\n }\n // Also emit a 'cancel' event that the app can listen for to detect cancellation\n // before calling verify()\n this.emit(VerificationEvent.Cancel, e);\n }\n }\n\n /**\n * Begin the key verification\n *\n * @returns Promise which resolves when the verification has\n * completed.\n */\n public verify(): Promise {\n if (this.promise) return this.promise;\n\n this.promise = new Promise((resolve, reject) => {\n this.resolve = (...args): void => {\n this._done = true;\n this.endTimer();\n resolve(...args);\n };\n this.reject = (e: Error | MatrixEvent): void => {\n this._done = true;\n this.endTimer();\n reject(e);\n };\n });\n if (this.doVerification && !this.started) {\n this.started = true;\n this.resetTimer(); // restart the timeout\n new Promise((resolve, reject) => {\n const crossSignId = this.baseApis.crypto!.deviceList.getStoredCrossSigningForUser(this.userId)?.getId();\n if (crossSignId === this.deviceId) {\n reject(new Error(\"Device ID is the same as the cross-signing ID\"));\n }\n resolve();\n })\n .then(() => this.doVerification!())\n .then(this.done.bind(this), this.cancel.bind(this));\n }\n return this.promise;\n }\n\n protected doVerification?: () => Promise;\n\n protected async verifyKeys(userId: string, keys: Record, verifier: KeyVerifier): Promise {\n // we try to verify all the keys that we're told about, but we might\n // not know about all of them, so keep track of the keys that we know\n // about, and ignore the rest\n const verifiedDevices: [string, string, string][] = [];\n\n for (const [keyId, keyInfo] of Object.entries(keys)) {\n const deviceId = keyId.split(\":\", 2)[1];\n const device = this.baseApis.getStoredDevice(userId, deviceId);\n if (device) {\n verifier(keyId, device, keyInfo);\n verifiedDevices.push([deviceId, keyId, device.keys[keyId]]);\n } else {\n const crossSigningInfo = this.baseApis.crypto!.deviceList.getStoredCrossSigningForUser(userId);\n if (crossSigningInfo && crossSigningInfo.getId() === deviceId) {\n verifier(\n keyId,\n DeviceInfo.fromStorage(\n {\n keys: {\n [keyId]: deviceId,\n },\n },\n deviceId,\n ),\n keyInfo,\n );\n verifiedDevices.push([deviceId, keyId, deviceId]);\n } else {\n logger.warn(`verification: Could not find device ${deviceId} to verify`);\n }\n }\n }\n\n // if none of the keys could be verified, then error because the app\n // should be informed about that\n if (!verifiedDevices.length) {\n throw new Error(\"No devices could be verified\");\n }\n\n logger.info(\"Verification completed! Marking devices verified: \", verifiedDevices);\n // TODO: There should probably be a batch version of this, otherwise it's going\n // to upload each signature in a separate API call which is silly because the\n // API supports as many signatures as you like.\n for (const [deviceId, keyId, key] of verifiedDevices) {\n await this.baseApis.crypto!.setDeviceVerification(userId, deviceId, true, null, null, { [keyId]: key });\n }\n\n // if one of the user's own devices is being marked as verified / unverified,\n // check the key backup status, since whether or not we use this depends on\n // whether it has a signature from a verified device\n if (userId == this.baseApis.credentials.userId) {\n await this.baseApis.checkKeyBackup();\n }\n }\n\n public get events(): string[] | undefined {\n return undefined;\n }\n}\n", - "/*\nCopyright 2018 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Error messages.\n */\n\nimport { MatrixEvent } from \"../../models/event\";\nimport { EventType } from \"../../@types/event\";\n\nexport function newVerificationError(code: string, reason: string, extraData?: Record): MatrixEvent {\n const content = Object.assign({}, { code, reason }, extraData);\n return new MatrixEvent({\n type: EventType.KeyVerificationCancel,\n content,\n });\n}\n\nexport function errorFactory(code: string, reason: string): (extraData?: Record) => MatrixEvent {\n return function (extraData?: Record) {\n return newVerificationError(code, reason, extraData);\n };\n}\n\n/**\n * The verification was cancelled by the user.\n */\nexport const newUserCancelledError = errorFactory(\"m.user\", \"Cancelled by user\");\n\n/**\n * The verification timed out.\n */\nexport const newTimeoutError = errorFactory(\"m.timeout\", \"Timed out\");\n\n/**\n * An unknown method was selected.\n */\nexport const newUnknownMethodError = errorFactory(\"m.unknown_method\", \"Unknown method\");\n\n/**\n * An unexpected message was sent.\n */\nexport const newUnexpectedMessageError = errorFactory(\"m.unexpected_message\", \"Unexpected message\");\n\n/**\n * The key does not match.\n */\nexport const newKeyMismatchError = errorFactory(\"m.key_mismatch\", \"Key mismatch\");\n\n/**\n * An invalid message was sent.\n */\nexport const newInvalidMessageError = errorFactory(\"m.invalid_message\", \"Invalid message\");\n\nexport function errorFromEvent(event: MatrixEvent): { code: string; reason: string } {\n const content = event.getContent();\n if (content) {\n const { code, reason } = content;\n return { code, reason };\n } else {\n return { code: \"Unknown error\", reason: \"m.unknown\" };\n }\n}\n", - "/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Verification method that is illegal to have (cannot possibly\n * do verification with this method).\n */\n\nimport { VerificationBase as Base, VerificationEvent, VerificationEventHandlerMap } from \"./Base\";\nimport { IVerificationChannel } from \"./request/Channel\";\nimport { MatrixClient } from \"../../client\";\nimport { MatrixEvent } from \"../../models/event\";\nimport { VerificationRequest } from \"./request/VerificationRequest\";\n\nexport class IllegalMethod extends Base {\n public static factory(\n channel: IVerificationChannel,\n baseApis: MatrixClient,\n userId: string,\n deviceId: string,\n startEvent: MatrixEvent,\n request: VerificationRequest,\n ): IllegalMethod {\n return new IllegalMethod(channel, baseApis, userId, deviceId, startEvent, request);\n }\n\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public static get NAME(): string {\n // Typically the name will be something else, but to complete\n // the contract we offer a default one here.\n return \"org.matrix.illegal_method\";\n }\n\n protected doVerification = async (): Promise => {\n throw new Error(\"Verification is not possible with this method\");\n };\n}\n", - "/*\nCopyright 2018 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * QR code key verification.\n */\n\nimport { VerificationBase as Base, VerificationEventHandlerMap } from \"./Base\";\nimport { newKeyMismatchError, newUserCancelledError } from \"./Error\";\nimport { decodeBase64, encodeUnpaddedBase64 } from \"../olmlib\";\nimport { logger } from \"../../logger\";\nimport { VerificationRequest } from \"./request/VerificationRequest\";\nimport { MatrixClient } from \"../../client\";\nimport { IVerificationChannel } from \"./request/Channel\";\nimport { MatrixEvent } from \"../../models/event\";\n\nexport const SHOW_QR_CODE_METHOD = \"m.qr_code.show.v1\";\nexport const SCAN_QR_CODE_METHOD = \"m.qr_code.scan.v1\";\n\ninterface IReciprocateQr {\n confirm(): void;\n cancel(): void;\n}\n\nexport enum QrCodeEvent {\n ShowReciprocateQr = \"show_reciprocate_qr\",\n}\n\ntype EventHandlerMap = {\n [QrCodeEvent.ShowReciprocateQr]: (qr: IReciprocateQr) => void;\n} & VerificationEventHandlerMap;\n\nexport class ReciprocateQRCode extends Base {\n public reciprocateQREvent?: IReciprocateQr;\n\n public static factory(\n channel: IVerificationChannel,\n baseApis: MatrixClient,\n userId: string,\n deviceId: string,\n startEvent: MatrixEvent,\n request: VerificationRequest,\n ): ReciprocateQRCode {\n return new ReciprocateQRCode(channel, baseApis, userId, deviceId, startEvent, request);\n }\n\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public static get NAME(): string {\n return \"m.reciprocate.v1\";\n }\n\n protected doVerification = async (): Promise => {\n if (!this.startEvent) {\n // TODO: Support scanning QR codes\n throw new Error(\"It is not currently possible to start verification\" + \"with this method yet.\");\n }\n\n const { qrCodeData } = this.request;\n // 1. check the secret\n if (this.startEvent.getContent()[\"secret\"] !== qrCodeData?.encodedSharedSecret) {\n throw newKeyMismatchError();\n }\n\n // 2. ask if other user shows shield as well\n await new Promise((resolve, reject) => {\n this.reciprocateQREvent = {\n confirm: resolve,\n cancel: () => reject(newUserCancelledError()),\n };\n this.emit(QrCodeEvent.ShowReciprocateQr, this.reciprocateQREvent);\n });\n\n // 3. determine key to sign / mark as trusted\n const keys: Record = {};\n\n switch (qrCodeData?.mode) {\n case Mode.VerifyOtherUser: {\n // add master key to keys to be signed, only if we're not doing self-verification\n const masterKey = qrCodeData.otherUserMasterKey;\n keys[`ed25519:${masterKey}`] = masterKey!;\n break;\n }\n case Mode.VerifySelfTrusted: {\n const deviceId = this.request.targetDevice.deviceId;\n keys[`ed25519:${deviceId}`] = qrCodeData.otherDeviceKey!;\n break;\n }\n case Mode.VerifySelfUntrusted: {\n const masterKey = qrCodeData.myMasterKey;\n keys[`ed25519:${masterKey}`] = masterKey!;\n break;\n }\n }\n\n // 4. sign the key (or mark own MSK as verified in case of MODE_VERIFY_SELF_TRUSTED)\n await this.verifyKeys(this.userId, keys, (keyId, device, keyInfo) => {\n // make sure the device has the expected keys\n const targetKey = keys[keyId];\n if (!targetKey) throw newKeyMismatchError();\n\n if (keyInfo !== targetKey) {\n logger.error(\"key ID from key info does not match\");\n throw newKeyMismatchError();\n }\n for (const deviceKeyId in device.keys) {\n if (!deviceKeyId.startsWith(\"ed25519\")) continue;\n const deviceTargetKey = keys[deviceKeyId];\n if (!deviceTargetKey) throw newKeyMismatchError();\n if (device.keys[deviceKeyId] !== deviceTargetKey) {\n logger.error(\"master key does not match\");\n throw newKeyMismatchError();\n }\n }\n });\n };\n}\n\nconst CODE_VERSION = 0x02; // the version of binary QR codes we support\nconst BINARY_PREFIX = \"MATRIX\"; // ASCII, used to prefix the binary format\n\nenum Mode {\n VerifyOtherUser = 0x00, // Verifying someone who isn't us\n VerifySelfTrusted = 0x01, // We trust the master key\n VerifySelfUntrusted = 0x02, // We do not trust the master key\n}\n\ninterface IQrData {\n prefix: string;\n version: number;\n mode: Mode;\n transactionId?: string;\n firstKeyB64: string;\n secondKeyB64: string;\n secretB64: string;\n}\n\nexport class QRCodeData {\n public constructor(\n public readonly mode: Mode,\n private readonly sharedSecret: string,\n // only set when mode is MODE_VERIFY_OTHER_USER, master key of other party at time of generating QR code\n public readonly otherUserMasterKey: string | null,\n // only set when mode is MODE_VERIFY_SELF_TRUSTED, device key of other party at time of generating QR code\n public readonly otherDeviceKey: string | null,\n // only set when mode is MODE_VERIFY_SELF_UNTRUSTED, own master key at time of generating QR code\n public readonly myMasterKey: string | null,\n private readonly buffer: Buffer,\n ) {}\n\n public static async create(request: VerificationRequest, client: MatrixClient): Promise {\n const sharedSecret = QRCodeData.generateSharedSecret();\n const mode = QRCodeData.determineMode(request, client);\n let otherUserMasterKey: string | null = null;\n let otherDeviceKey: string | null = null;\n let myMasterKey: string | null = null;\n if (mode === Mode.VerifyOtherUser) {\n const otherUserCrossSigningInfo = client.getStoredCrossSigningForUser(request.otherUserId);\n otherUserMasterKey = otherUserCrossSigningInfo!.getId(\"master\");\n } else if (mode === Mode.VerifySelfTrusted) {\n otherDeviceKey = await QRCodeData.getOtherDeviceKey(request, client);\n } else if (mode === Mode.VerifySelfUntrusted) {\n const myUserId = client.getUserId()!;\n const myCrossSigningInfo = client.getStoredCrossSigningForUser(myUserId);\n myMasterKey = myCrossSigningInfo!.getId(\"master\");\n }\n const qrData = QRCodeData.generateQrData(\n request,\n client,\n mode,\n sharedSecret,\n otherUserMasterKey!,\n otherDeviceKey!,\n myMasterKey!,\n );\n const buffer = QRCodeData.generateBuffer(qrData);\n return new QRCodeData(mode, sharedSecret, otherUserMasterKey, otherDeviceKey, myMasterKey, buffer);\n }\n\n /**\n * The unpadded base64 encoded shared secret.\n */\n public get encodedSharedSecret(): string {\n return this.sharedSecret;\n }\n\n public getBuffer(): Buffer {\n return this.buffer;\n }\n\n private static generateSharedSecret(): string {\n const secretBytes = new Uint8Array(11);\n global.crypto.getRandomValues(secretBytes);\n return encodeUnpaddedBase64(secretBytes);\n }\n\n private static async getOtherDeviceKey(request: VerificationRequest, client: MatrixClient): Promise {\n const myUserId = client.getUserId()!;\n const otherDevice = request.targetDevice;\n const device = otherDevice.deviceId ? client.getStoredDevice(myUserId, otherDevice.deviceId) : undefined;\n if (!device) {\n throw new Error(\"could not find device \" + otherDevice?.deviceId);\n }\n return device.getFingerprint();\n }\n\n private static determineMode(request: VerificationRequest, client: MatrixClient): Mode {\n const myUserId = client.getUserId();\n const otherUserId = request.otherUserId;\n\n let mode = Mode.VerifyOtherUser;\n if (myUserId === otherUserId) {\n // Mode changes depending on whether or not we trust the master cross signing key\n const myTrust = client.checkUserTrust(myUserId);\n if (myTrust.isCrossSigningVerified()) {\n mode = Mode.VerifySelfTrusted;\n } else {\n mode = Mode.VerifySelfUntrusted;\n }\n }\n return mode;\n }\n\n private static generateQrData(\n request: VerificationRequest,\n client: MatrixClient,\n mode: Mode,\n encodedSharedSecret: string,\n otherUserMasterKey?: string,\n otherDeviceKey?: string,\n myMasterKey?: string,\n ): IQrData {\n const myUserId = client.getUserId()!;\n const transactionId = request.channel.transactionId;\n const qrData: IQrData = {\n prefix: BINARY_PREFIX,\n version: CODE_VERSION,\n mode,\n transactionId,\n firstKeyB64: \"\", // worked out shortly\n secondKeyB64: \"\", // worked out shortly\n secretB64: encodedSharedSecret,\n };\n\n const myCrossSigningInfo = client.getStoredCrossSigningForUser(myUserId);\n\n if (mode === Mode.VerifyOtherUser) {\n // First key is our master cross signing key\n qrData.firstKeyB64 = myCrossSigningInfo!.getId(\"master\")!;\n // Second key is the other user's master cross signing key\n qrData.secondKeyB64 = otherUserMasterKey!;\n } else if (mode === Mode.VerifySelfTrusted) {\n // First key is our master cross signing key\n qrData.firstKeyB64 = myCrossSigningInfo!.getId(\"master\")!;\n qrData.secondKeyB64 = otherDeviceKey!;\n } else if (mode === Mode.VerifySelfUntrusted) {\n // First key is our device's key\n qrData.firstKeyB64 = client.getDeviceEd25519Key()!;\n // Second key is what we think our master cross signing key is\n qrData.secondKeyB64 = myMasterKey!;\n }\n return qrData;\n }\n\n private static generateBuffer(qrData: IQrData): Buffer {\n let buf = Buffer.alloc(0); // we'll concat our way through life\n\n const appendByte = (b: number): void => {\n const tmpBuf = Buffer.from([b]);\n buf = Buffer.concat([buf, tmpBuf]);\n };\n const appendInt = (i: number): void => {\n const tmpBuf = Buffer.alloc(2);\n tmpBuf.writeInt16BE(i, 0);\n buf = Buffer.concat([buf, tmpBuf]);\n };\n const appendStr = (s: string, enc: BufferEncoding, withLengthPrefix = true): void => {\n const tmpBuf = Buffer.from(s, enc);\n if (withLengthPrefix) appendInt(tmpBuf.byteLength);\n buf = Buffer.concat([buf, tmpBuf]);\n };\n const appendEncBase64 = (b64: string): void => {\n const b = decodeBase64(b64);\n const tmpBuf = Buffer.from(b);\n buf = Buffer.concat([buf, tmpBuf]);\n };\n\n // Actually build the buffer for the QR code\n appendStr(qrData.prefix, \"ascii\", false);\n appendByte(qrData.version);\n appendByte(qrData.mode);\n appendStr(qrData.transactionId!, \"utf-8\");\n appendEncBase64(qrData.firstKeyB64);\n appendEncBase64(qrData.secondKeyB64);\n appendEncBase64(qrData.secretB64);\n\n return buf;\n }\n}\n", - "/*\nCopyright 2018 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Short Authentication String (SAS) verification.\n */\n\nimport anotherjson from \"another-json\";\nimport { Utility, SAS as OlmSAS } from \"@matrix-org/olm\";\n\nimport { VerificationBase as Base, SwitchStartEventError, VerificationEventHandlerMap } from \"./Base\";\nimport {\n errorFactory,\n newInvalidMessageError,\n newKeyMismatchError,\n newUnknownMethodError,\n newUserCancelledError,\n} from \"./Error\";\nimport { logger } from \"../../logger\";\nimport { IContent, MatrixEvent } from \"../../models/event\";\nimport { generateDecimalSas } from \"./SASDecimal\";\nimport { EventType } from \"../../@types/event\";\n\nconst START_TYPE = EventType.KeyVerificationStart;\n\nconst EVENTS = [EventType.KeyVerificationAccept, EventType.KeyVerificationKey, EventType.KeyVerificationMac];\n\nlet olmutil: Utility;\n\nconst newMismatchedSASError = errorFactory(\"m.mismatched_sas\", \"Mismatched short authentication string\");\n\nconst newMismatchedCommitmentError = errorFactory(\"m.mismatched_commitment\", \"Mismatched commitment\");\n\ntype EmojiMapping = [emoji: string, name: string];\n\nconst emojiMapping: EmojiMapping[] = [\n [\"🐶\", \"dog\"], // 0\n [\"🐱\", \"cat\"], // 1\n [\"🦁\", \"lion\"], // 2\n [\"🐎\", \"horse\"], // 3\n [\"🦄\", \"unicorn\"], // 4\n [\"🐷\", \"pig\"], // 5\n [\"🐘\", \"elephant\"], // 6\n [\"🐰\", \"rabbit\"], // 7\n [\"🐼\", \"panda\"], // 8\n [\"🐓\", \"rooster\"], // 9\n [\"🐧\", \"penguin\"], // 10\n [\"🐢\", \"turtle\"], // 11\n [\"🐟\", \"fish\"], // 12\n [\"🐙\", \"octopus\"], // 13\n [\"🦋\", \"butterfly\"], // 14\n [\"🌷\", \"flower\"], // 15\n [\"🌳\", \"tree\"], // 16\n [\"🌵\", \"cactus\"], // 17\n [\"🍄\", \"mushroom\"], // 18\n [\"🌏\", \"globe\"], // 19\n [\"🌙\", \"moon\"], // 20\n [\"☁️\", \"cloud\"], // 21\n [\"🔥\", \"fire\"], // 22\n [\"🍌\", \"banana\"], // 23\n [\"🍎\", \"apple\"], // 24\n [\"🍓\", \"strawberry\"], // 25\n [\"🌽\", \"corn\"], // 26\n [\"🍕\", \"pizza\"], // 27\n [\"🎂\", \"cake\"], // 28\n [\"❤️\", \"heart\"], // 29\n [\"🙂\", \"smiley\"], // 30\n [\"🤖\", \"robot\"], // 31\n [\"🎩\", \"hat\"], // 32\n [\"👓\", \"glasses\"], // 33\n [\"🔧\", \"spanner\"], // 34\n [\"🎅\", \"santa\"], // 35\n [\"👍\", \"thumbs up\"], // 36\n [\"☂️\", \"umbrella\"], // 37\n [\"⌛\", \"hourglass\"], // 38\n [\"⏰\", \"clock\"], // 39\n [\"🎁\", \"gift\"], // 40\n [\"💡\", \"light bulb\"], // 41\n [\"📕\", \"book\"], // 42\n [\"✏️\", \"pencil\"], // 43\n [\"📎\", \"paperclip\"], // 44\n [\"✂️\", \"scissors\"], // 45\n [\"🔒\", \"lock\"], // 46\n [\"🔑\", \"key\"], // 47\n [\"🔨\", \"hammer\"], // 48\n [\"☎️\", \"telephone\"], // 49\n [\"🏁\", \"flag\"], // 50\n [\"🚂\", \"train\"], // 51\n [\"🚲\", \"bicycle\"], // 52\n [\"✈️\", \"aeroplane\"], // 53\n [\"🚀\", \"rocket\"], // 54\n [\"🏆\", \"trophy\"], // 55\n [\"⚽\", \"ball\"], // 56\n [\"🎸\", \"guitar\"], // 57\n [\"🎺\", \"trumpet\"], // 58\n [\"🔔\", \"bell\"], // 59\n [\"⚓️\", \"anchor\"], // 60\n [\"🎧\", \"headphones\"], // 61\n [\"📁\", \"folder\"], // 62\n [\"📌\", \"pin\"], // 63\n];\n\nfunction generateEmojiSas(sasBytes: number[]): EmojiMapping[] {\n const emojis = [\n // just like base64 encoding\n sasBytes[0] >> 2,\n ((sasBytes[0] & 0x3) << 4) | (sasBytes[1] >> 4),\n ((sasBytes[1] & 0xf) << 2) | (sasBytes[2] >> 6),\n sasBytes[2] & 0x3f,\n sasBytes[3] >> 2,\n ((sasBytes[3] & 0x3) << 4) | (sasBytes[4] >> 4),\n ((sasBytes[4] & 0xf) << 2) | (sasBytes[5] >> 6),\n ];\n\n return emojis.map((num) => emojiMapping[num]);\n}\n\nconst sasGenerators = {\n decimal: generateDecimalSas,\n emoji: generateEmojiSas,\n} as const;\n\nexport interface IGeneratedSas {\n decimal?: [number, number, number];\n emoji?: EmojiMapping[];\n}\n\nexport interface ISasEvent {\n sas: IGeneratedSas;\n confirm(): Promise;\n cancel(): void;\n mismatch(): void;\n}\n\nfunction generateSas(sasBytes: Uint8Array, methods: string[]): IGeneratedSas {\n const sas: IGeneratedSas = {};\n for (const method of methods) {\n if (method in sasGenerators) {\n // @ts-ignore - ts doesn't like us mixing types like this\n sas[method] = sasGenerators[method](Array.from(sasBytes));\n }\n }\n return sas;\n}\n\nconst macMethods = {\n \"hkdf-hmac-sha256\": \"calculate_mac\",\n \"org.matrix.msc3783.hkdf-hmac-sha256\": \"calculate_mac_fixed_base64\",\n \"hkdf-hmac-sha256.v2\": \"calculate_mac_fixed_base64\",\n \"hmac-sha256\": \"calculate_mac_long_kdf\",\n} as const;\n\ntype MacMethod = keyof typeof macMethods;\n\nfunction calculateMAC(olmSAS: OlmSAS, method: MacMethod) {\n return function (input: string, info: string): string {\n const mac = olmSAS[macMethods[method]](input, info);\n logger.log(\"SAS calculateMAC:\", method, [input, info], mac);\n return mac;\n };\n}\n\nconst calculateKeyAgreement = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n \"curve25519-hkdf-sha256\": function (sas: SAS, olmSAS: OlmSAS, bytes: number): Uint8Array {\n const ourInfo = `${sas.baseApis.getUserId()}|${sas.baseApis.deviceId}|` + `${sas.ourSASPubKey}|`;\n const theirInfo = `${sas.userId}|${sas.deviceId}|${sas.theirSASPubKey}|`;\n const sasInfo =\n \"MATRIX_KEY_VERIFICATION_SAS|\" +\n (sas.initiatedByMe ? ourInfo + theirInfo : theirInfo + ourInfo) +\n sas.channel.transactionId;\n return olmSAS.generate_bytes(sasInfo, bytes);\n },\n \"curve25519\": function (sas: SAS, olmSAS: OlmSAS, bytes: number): Uint8Array {\n const ourInfo = `${sas.baseApis.getUserId()}${sas.baseApis.deviceId}`;\n const theirInfo = `${sas.userId}${sas.deviceId}`;\n const sasInfo =\n \"MATRIX_KEY_VERIFICATION_SAS\" +\n (sas.initiatedByMe ? ourInfo + theirInfo : theirInfo + ourInfo) +\n sas.channel.transactionId;\n return olmSAS.generate_bytes(sasInfo, bytes);\n },\n} as const;\n\ntype KeyAgreement = keyof typeof calculateKeyAgreement;\n\n/* lists of algorithms/methods that are supported. The key agreement, hashes,\n * and MAC lists should be sorted in order of preference (most preferred\n * first).\n */\nconst KEY_AGREEMENT_LIST: KeyAgreement[] = [\"curve25519-hkdf-sha256\", \"curve25519\"];\nconst HASHES_LIST = [\"sha256\"];\nconst MAC_LIST: MacMethod[] = [\n \"hkdf-hmac-sha256.v2\",\n \"org.matrix.msc3783.hkdf-hmac-sha256\",\n \"hkdf-hmac-sha256\",\n \"hmac-sha256\",\n];\nconst SAS_LIST = Object.keys(sasGenerators);\n\nconst KEY_AGREEMENT_SET = new Set(KEY_AGREEMENT_LIST);\nconst HASHES_SET = new Set(HASHES_LIST);\nconst MAC_SET = new Set(MAC_LIST);\nconst SAS_SET = new Set(SAS_LIST);\n\nfunction intersection(anArray: T[], aSet: Set): T[] {\n return Array.isArray(anArray) ? anArray.filter((x) => aSet.has(x)) : [];\n}\n\nexport enum SasEvent {\n ShowSas = \"show_sas\",\n}\n\ntype EventHandlerMap = {\n [SasEvent.ShowSas]: (sas: ISasEvent) => void;\n} & VerificationEventHandlerMap;\n\nexport class SAS extends Base {\n private waitingForAccept?: boolean;\n public ourSASPubKey?: string;\n public theirSASPubKey?: string;\n public sasEvent?: ISasEvent;\n\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public static get NAME(): string {\n return \"m.sas.v1\";\n }\n\n public get events(): string[] {\n return EVENTS;\n }\n\n protected doVerification = async (): Promise => {\n await global.Olm.init();\n olmutil = olmutil || new global.Olm.Utility();\n\n // make sure user's keys are downloaded\n await this.baseApis.downloadKeys([this.userId]);\n\n let retry = false;\n do {\n try {\n if (this.initiatedByMe) {\n return await this.doSendVerification();\n } else {\n return await this.doRespondVerification();\n }\n } catch (err) {\n if (err instanceof SwitchStartEventError) {\n // this changes what initiatedByMe returns\n this.startEvent = err.startEvent;\n retry = true;\n } else {\n throw err;\n }\n }\n } while (retry);\n };\n\n public canSwitchStartEvent(event: MatrixEvent): boolean {\n if (event.getType() !== START_TYPE) {\n return false;\n }\n const content = event.getContent();\n return content?.method === SAS.NAME && !!this.waitingForAccept;\n }\n\n private async sendStart(): Promise> {\n const startContent = this.channel.completeContent(START_TYPE, {\n method: SAS.NAME,\n from_device: this.baseApis.deviceId,\n key_agreement_protocols: KEY_AGREEMENT_LIST,\n hashes: HASHES_LIST,\n message_authentication_codes: MAC_LIST,\n // FIXME: allow app to specify what SAS methods can be used\n short_authentication_string: SAS_LIST,\n });\n await this.channel.sendCompleted(START_TYPE, startContent);\n return startContent;\n }\n\n private async verifyAndCheckMAC(\n keyAgreement: KeyAgreement,\n sasMethods: string[],\n olmSAS: OlmSAS,\n macMethod: MacMethod,\n ): Promise {\n const sasBytes = calculateKeyAgreement[keyAgreement](this, olmSAS, 6);\n const verifySAS = new Promise((resolve, reject) => {\n this.sasEvent = {\n sas: generateSas(sasBytes, sasMethods),\n confirm: async (): Promise => {\n try {\n await this.sendMAC(olmSAS, macMethod);\n resolve();\n } catch (err) {\n reject(err);\n }\n },\n cancel: () => reject(newUserCancelledError()),\n mismatch: () => reject(newMismatchedSASError()),\n };\n this.emit(SasEvent.ShowSas, this.sasEvent);\n });\n\n const [e] = await Promise.all([\n this.waitForEvent(EventType.KeyVerificationMac).then((e) => {\n // we don't expect any more messages from the other\n // party, and they may send a m.key.verification.done\n // when they're done on their end\n this.expectedEvent = EventType.KeyVerificationDone;\n return e;\n }),\n verifySAS,\n ]);\n const content = e.getContent();\n await this.checkMAC(olmSAS, content, macMethod);\n }\n\n private async doSendVerification(): Promise {\n this.waitingForAccept = true;\n let startContent;\n if (this.startEvent) {\n startContent = this.channel.completedContentFromEvent(this.startEvent);\n } else {\n startContent = await this.sendStart();\n }\n\n // we might have switched to a different start event,\n // but was we didn't call _waitForEvent there was no\n // call that could throw yet. So check manually that\n // we're still on the initiator side\n if (!this.initiatedByMe) {\n throw new SwitchStartEventError(this.startEvent);\n }\n\n let e: MatrixEvent;\n try {\n e = await this.waitForEvent(EventType.KeyVerificationAccept);\n } finally {\n this.waitingForAccept = false;\n }\n let content = e.getContent();\n const sasMethods = intersection(content.short_authentication_string, SAS_SET);\n if (\n !(\n KEY_AGREEMENT_SET.has(content.key_agreement_protocol) &&\n HASHES_SET.has(content.hash) &&\n MAC_SET.has(content.message_authentication_code) &&\n sasMethods.length\n )\n ) {\n throw newUnknownMethodError();\n }\n if (typeof content.commitment !== \"string\") {\n throw newInvalidMessageError();\n }\n const keyAgreement = content.key_agreement_protocol;\n const macMethod = content.message_authentication_code;\n const hashCommitment = content.commitment;\n const olmSAS = new global.Olm.SAS();\n try {\n this.ourSASPubKey = olmSAS.get_pubkey();\n await this.send(EventType.KeyVerificationKey, {\n key: this.ourSASPubKey,\n });\n\n e = await this.waitForEvent(EventType.KeyVerificationKey);\n // FIXME: make sure event is properly formed\n content = e.getContent();\n const commitmentStr = content.key + anotherjson.stringify(startContent);\n // TODO: use selected hash function (when we support multiple)\n if (olmutil.sha256(commitmentStr) !== hashCommitment) {\n throw newMismatchedCommitmentError();\n }\n this.theirSASPubKey = content.key;\n olmSAS.set_their_key(content.key);\n\n await this.verifyAndCheckMAC(keyAgreement, sasMethods, olmSAS, macMethod);\n } finally {\n olmSAS.free();\n }\n }\n\n private async doRespondVerification(): Promise {\n // as m.related_to is not included in the encrypted content in e2e rooms,\n // we need to make sure it is added\n let content = this.channel.completedContentFromEvent(this.startEvent!);\n\n // Note: we intersect using our pre-made lists, rather than the sets,\n // so that the result will be in our order of preference. Then\n // fetching the first element from the array will give our preferred\n // method out of the ones offered by the other party.\n const keyAgreement = intersection(KEY_AGREEMENT_LIST, new Set(content.key_agreement_protocols))[0];\n const hashMethod = intersection(HASHES_LIST, new Set(content.hashes))[0];\n const macMethod = intersection(MAC_LIST, new Set(content.message_authentication_codes))[0];\n // FIXME: allow app to specify what SAS methods can be used\n const sasMethods = intersection(content.short_authentication_string, SAS_SET);\n if (!(keyAgreement !== undefined && hashMethod !== undefined && macMethod !== undefined && sasMethods.length)) {\n throw newUnknownMethodError();\n }\n\n const olmSAS = new global.Olm.SAS();\n try {\n const commitmentStr = olmSAS.get_pubkey() + anotherjson.stringify(content);\n await this.send(EventType.KeyVerificationAccept, {\n key_agreement_protocol: keyAgreement,\n hash: hashMethod,\n message_authentication_code: macMethod,\n short_authentication_string: sasMethods,\n // TODO: use selected hash function (when we support multiple)\n commitment: olmutil.sha256(commitmentStr),\n });\n\n const e = await this.waitForEvent(EventType.KeyVerificationKey);\n // FIXME: make sure event is properly formed\n content = e.getContent();\n this.theirSASPubKey = content.key;\n olmSAS.set_their_key(content.key);\n this.ourSASPubKey = olmSAS.get_pubkey();\n await this.send(EventType.KeyVerificationKey, {\n key: this.ourSASPubKey,\n });\n\n await this.verifyAndCheckMAC(keyAgreement, sasMethods, olmSAS, macMethod);\n } finally {\n olmSAS.free();\n }\n }\n\n private sendMAC(olmSAS: OlmSAS, method: MacMethod): Promise {\n const mac: Record = {};\n const keyList: string[] = [];\n const baseInfo =\n \"MATRIX_KEY_VERIFICATION_MAC\" +\n this.baseApis.getUserId() +\n this.baseApis.deviceId +\n this.userId +\n this.deviceId +\n this.channel.transactionId;\n\n const deviceKeyId = `ed25519:${this.baseApis.deviceId}`;\n mac[deviceKeyId] = calculateMAC(olmSAS, method)(this.baseApis.getDeviceEd25519Key()!, baseInfo + deviceKeyId);\n keyList.push(deviceKeyId);\n\n const crossSigningId = this.baseApis.getCrossSigningId();\n if (crossSigningId) {\n const crossSigningKeyId = `ed25519:${crossSigningId}`;\n mac[crossSigningKeyId] = calculateMAC(olmSAS, method)(crossSigningId, baseInfo + crossSigningKeyId);\n keyList.push(crossSigningKeyId);\n }\n\n const keys = calculateMAC(olmSAS, method)(keyList.sort().join(\",\"), baseInfo + \"KEY_IDS\");\n return this.send(EventType.KeyVerificationMac, { mac, keys });\n }\n\n private async checkMAC(olmSAS: OlmSAS, content: IContent, method: MacMethod): Promise {\n const baseInfo =\n \"MATRIX_KEY_VERIFICATION_MAC\" +\n this.userId +\n this.deviceId +\n this.baseApis.getUserId() +\n this.baseApis.deviceId +\n this.channel.transactionId;\n\n if (\n content.keys !==\n calculateMAC(olmSAS, method)(Object.keys(content.mac).sort().join(\",\"), baseInfo + \"KEY_IDS\")\n ) {\n throw newKeyMismatchError();\n }\n\n await this.verifyKeys(this.userId, content.mac, (keyId, device, keyInfo) => {\n if (keyInfo !== calculateMAC(olmSAS, method)(device.keys[keyId], baseInfo + keyId)) {\n throw newKeyMismatchError();\n }\n });\n }\n}\n", - "/*\nCopyright 2018 - 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Implementation of decimal encoding of SAS as per:\n * https://spec.matrix.org/v1.4/client-server-api/#sas-method-decimal\n * @param sasBytes - the five bytes generated by HKDF\n * @returns the derived three numbers between 1000 and 9191 inclusive\n */\nexport function generateDecimalSas(sasBytes: number[]): [number, number, number] {\n /*\n * +--------+--------+--------+--------+--------+\n * | Byte 0 | Byte 1 | Byte 2 | Byte 3 | Byte 4 |\n * +--------+--------+--------+--------+--------+\n * bits: 87654321 87654321 87654321 87654321 87654321\n * \\____________/\\_____________/\\____________/\n * 1st number 2nd number 3rd number\n */\n return [\n ((sasBytes[0] << 5) | (sasBytes[1] >> 3)) + 1000,\n (((sasBytes[1] & 0x7) << 10) | (sasBytes[2] << 2) | (sasBytes[3] >> 6)) + 1000,\n (((sasBytes[3] & 0x3f) << 7) | (sasBytes[4] >> 1)) + 1000,\n ];\n}\n", - "/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { VerificationRequest, REQUEST_TYPE, READY_TYPE, START_TYPE } from \"./VerificationRequest\";\nimport { logger } from \"../../../logger\";\nimport { IVerificationChannel } from \"./Channel\";\nimport { EventType } from \"../../../@types/event\";\nimport { MatrixClient } from \"../../../client\";\nimport { MatrixEvent } from \"../../../models/event\";\nimport { IRequestsMap } from \"../..\";\n\nconst MESSAGE_TYPE = EventType.RoomMessage;\nconst M_REFERENCE = \"m.reference\";\nconst M_RELATES_TO = \"m.relates_to\";\n\n/**\n * A key verification channel that sends verification events in the timeline of a room.\n * Uses the event id of the initial m.key.verification.request event as a transaction id.\n */\nexport class InRoomChannel implements IVerificationChannel {\n private requestEventId?: string;\n\n /**\n * @param client - the matrix client, to send messages with and get current user & device from.\n * @param roomId - id of the room where verification events should be posted in, should be a DM with the given user.\n * @param userId - id of user that the verification request is directed at, should be present in the room.\n */\n public constructor(private readonly client: MatrixClient, public readonly roomId: string, public userId?: string) {}\n\n public get receiveStartFromOtherDevices(): boolean {\n return true;\n }\n\n /** The transaction id generated/used by this verification channel */\n public get transactionId(): string | undefined {\n return this.requestEventId;\n }\n\n public static getOtherPartyUserId(event: MatrixEvent, client: MatrixClient): string | undefined {\n const type = InRoomChannel.getEventType(event);\n if (type !== REQUEST_TYPE) {\n return;\n }\n const ownUserId = client.getUserId();\n const sender = event.getSender();\n const content = event.getContent();\n const receiver = content.to;\n\n if (sender === ownUserId) {\n return receiver;\n } else if (receiver === ownUserId) {\n return sender;\n }\n }\n\n /**\n * @param event - the event to get the timestamp of\n * @returns the timestamp when the event was sent\n */\n public getTimestamp(event: MatrixEvent): number {\n return event.getTs();\n }\n\n /**\n * Checks whether the given event type should be allowed to initiate a new VerificationRequest over this channel\n * @param type - the event type to check\n * @returns boolean flag\n */\n public static canCreateRequest(type: string): boolean {\n return type === REQUEST_TYPE;\n }\n\n public canCreateRequest(type: string): boolean {\n return InRoomChannel.canCreateRequest(type);\n }\n\n /**\n * Extract the transaction id used by a given key verification event, if any\n * @param event - the event\n * @returns the transaction id\n */\n public static getTransactionId(event: MatrixEvent): string | undefined {\n if (InRoomChannel.getEventType(event) === REQUEST_TYPE) {\n return event.getId();\n } else {\n const relation = event.getRelation();\n if (relation?.rel_type === M_REFERENCE) {\n return relation.event_id;\n }\n }\n }\n\n /**\n * Checks whether this event is a well-formed key verification event.\n * This only does checks that don't rely on the current state of a potentially already channel\n * so we can prevent channels being created by invalid events.\n * `handleEvent` can do more checks and choose to ignore invalid events.\n * @param event - the event to validate\n * @param client - the client to get the current user and device id from\n * @returns whether the event is valid and should be passed to handleEvent\n */\n public static validateEvent(event: MatrixEvent, client: MatrixClient): boolean {\n const txnId = InRoomChannel.getTransactionId(event);\n if (typeof txnId !== \"string\" || txnId.length === 0) {\n return false;\n }\n const type = InRoomChannel.getEventType(event);\n const content = event.getContent();\n\n // from here on we're fairly sure that this is supposed to be\n // part of a verification request, so be noisy when rejecting something\n if (type === REQUEST_TYPE) {\n if (!content || typeof content.to !== \"string\" || !content.to.length) {\n logger.log(\"InRoomChannel: validateEvent: \" + \"no valid to \" + (content && content.to));\n return false;\n }\n\n // ignore requests that are not direct to or sent by the syncing user\n if (!InRoomChannel.getOtherPartyUserId(event, client)) {\n logger.log(\n \"InRoomChannel: validateEvent: \" +\n `not directed to or sent by me: ${event.getSender()}` +\n `, ${content && content.to}`,\n );\n return false;\n }\n }\n\n return VerificationRequest.validateEvent(type, event, client);\n }\n\n /**\n * As m.key.verification.request events are as m.room.message events with the InRoomChannel\n * to have a fallback message in non-supporting clients, we map the real event type\n * to the symbolic one to keep things in unison with ToDeviceChannel\n * @param event - the event to get the type of\n * @returns the \"symbolic\" event type\n */\n public static getEventType(event: MatrixEvent): string {\n const type = event.getType();\n if (type === MESSAGE_TYPE) {\n const content = event.getContent();\n if (content) {\n const { msgtype } = content;\n if (msgtype === REQUEST_TYPE) {\n return REQUEST_TYPE;\n }\n }\n }\n if (type && type !== REQUEST_TYPE) {\n return type;\n } else {\n return \"\";\n }\n }\n\n /**\n * Changes the state of the channel, request, and verifier in response to a key verification event.\n * @param event - to handle\n * @param request - the request to forward handling to\n * @param isLiveEvent - whether this is an even received through sync or not\n * @returns a promise that resolves when any requests as an answer to the passed-in event are sent.\n */\n public async handleEvent(event: MatrixEvent, request: VerificationRequest, isLiveEvent = false): Promise {\n // prevent processing the same event multiple times, as under\n // some circumstances Room.timeline can get emitted twice for the same event\n if (request.hasEventId(event.getId()!)) {\n return;\n }\n const type = InRoomChannel.getEventType(event);\n // do validations that need state (roomId, userId),\n // ignore if invalid\n\n if (event.getRoomId() !== this.roomId) {\n return;\n }\n // set userId if not set already\n if (!this.userId) {\n const userId = InRoomChannel.getOtherPartyUserId(event, this.client);\n if (userId) {\n this.userId = userId;\n }\n }\n // ignore events not sent by us or the other party\n const ownUserId = this.client.getUserId();\n const sender = event.getSender();\n if (this.userId) {\n if (sender !== ownUserId && sender !== this.userId) {\n logger.log(`InRoomChannel: ignoring verification event from non-participating sender ${sender}`);\n return;\n }\n }\n if (!this.requestEventId) {\n this.requestEventId = InRoomChannel.getTransactionId(event);\n }\n\n const isRemoteEcho = !!event.getUnsigned().transaction_id;\n const isSentByUs = event.getSender() === this.client.getUserId();\n\n return request.handleEvent(type, event, isLiveEvent, isRemoteEcho, isSentByUs);\n }\n\n /**\n * Adds the transaction id (relation) back to a received event\n * so it has the same format as returned by `completeContent` before sending.\n * The relation can not appear on the event content because of encryption,\n * relations are excluded from encryption.\n * @param event - the received event\n * @returns the content object with the relation added again\n */\n public completedContentFromEvent(event: MatrixEvent): Record {\n // ensure m.related_to is included in e2ee rooms\n // as the field is excluded from encryption\n const content = Object.assign({}, event.getContent());\n content[M_RELATES_TO] = event.getRelation()!;\n return content;\n }\n\n /**\n * Add all the fields to content needed for sending it over this channel.\n * This is public so verification methods (SAS uses this) can get the exact\n * content that will be sent independent of the used channel,\n * as they need to calculate the hash of it.\n * @param type - the event type\n * @param content - the (incomplete) content\n * @returns the complete content, as it will be sent.\n */\n public completeContent(type: string, content: Record): Record {\n content = Object.assign({}, content);\n if (type === REQUEST_TYPE || type === READY_TYPE || type === START_TYPE) {\n content.from_device = this.client.getDeviceId();\n }\n if (type === REQUEST_TYPE) {\n // type is mapped to m.room.message in the send method\n content = {\n body:\n this.client.getUserId() +\n \" is requesting to verify \" +\n \"your key, but your client does not support in-chat key \" +\n \"verification. You will need to use legacy key \" +\n \"verification to verify keys.\",\n msgtype: REQUEST_TYPE,\n to: this.userId,\n from_device: content.from_device,\n methods: content.methods,\n };\n } else {\n content[M_RELATES_TO] = {\n rel_type: M_REFERENCE,\n event_id: this.transactionId,\n };\n }\n return content;\n }\n\n /**\n * Send an event over the channel with the content not having gone through `completeContent`.\n * @param type - the event type\n * @param uncompletedContent - the (incomplete) content\n * @returns the promise of the request\n */\n public send(type: string, uncompletedContent: Record): Promise {\n const content = this.completeContent(type, uncompletedContent);\n return this.sendCompleted(type, content);\n }\n\n /**\n * Send an event over the channel with the content having gone through `completeContent` already.\n * @param type - the event type\n * @returns the promise of the request\n */\n public async sendCompleted(type: string, content: Record): Promise {\n let sendType = type;\n if (type === REQUEST_TYPE) {\n sendType = MESSAGE_TYPE;\n }\n const response = await this.client.sendEvent(this.roomId, sendType, content);\n if (type === REQUEST_TYPE) {\n this.requestEventId = response.event_id;\n }\n }\n}\n\nexport class InRoomRequests implements IRequestsMap {\n private requestsByRoomId = new Map>();\n\n public getRequest(event: MatrixEvent): VerificationRequest | undefined {\n const roomId = event.getRoomId()!;\n const txnId = InRoomChannel.getTransactionId(event)!;\n return this.getRequestByTxnId(roomId, txnId);\n }\n\n public getRequestByChannel(channel: InRoomChannel): VerificationRequest | undefined {\n return this.getRequestByTxnId(channel.roomId, channel.transactionId!);\n }\n\n private getRequestByTxnId(roomId: string, txnId: string): VerificationRequest | undefined {\n const requestsByTxnId = this.requestsByRoomId.get(roomId);\n if (requestsByTxnId) {\n return requestsByTxnId.get(txnId);\n }\n }\n\n public setRequest(event: MatrixEvent, request: VerificationRequest): void {\n this.doSetRequest(event.getRoomId()!, InRoomChannel.getTransactionId(event)!, request);\n }\n\n public setRequestByChannel(channel: IVerificationChannel, request: VerificationRequest): void {\n this.doSetRequest(channel.roomId!, channel.transactionId!, request);\n }\n\n private doSetRequest(roomId: string, txnId: string, request: VerificationRequest): void {\n let requestsByTxnId = this.requestsByRoomId.get(roomId);\n if (!requestsByTxnId) {\n requestsByTxnId = new Map();\n this.requestsByRoomId.set(roomId, requestsByTxnId);\n }\n requestsByTxnId.set(txnId, request);\n }\n\n public removeRequest(event: MatrixEvent): void {\n const roomId = event.getRoomId()!;\n const requestsByTxnId = this.requestsByRoomId.get(roomId);\n if (requestsByTxnId) {\n requestsByTxnId.delete(InRoomChannel.getTransactionId(event)!);\n if (requestsByTxnId.size === 0) {\n this.requestsByRoomId.delete(roomId);\n }\n }\n }\n\n public findRequestInProgress(roomId: string): VerificationRequest | undefined {\n const requestsByTxnId = this.requestsByRoomId.get(roomId);\n if (requestsByTxnId) {\n for (const request of requestsByTxnId.values()) {\n if (request.pending) {\n return request;\n }\n }\n }\n }\n}\n", - "/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { randomString } from \"../../../randomstring\";\nimport { logger } from \"../../../logger\";\nimport {\n CANCEL_TYPE,\n PHASE_STARTED,\n PHASE_READY,\n REQUEST_TYPE,\n READY_TYPE,\n START_TYPE,\n VerificationRequest,\n} from \"./VerificationRequest\";\nimport { errorFromEvent, newUnexpectedMessageError } from \"../Error\";\nimport { MatrixEvent } from \"../../../models/event\";\nimport { IVerificationChannel } from \"./Channel\";\nimport { MatrixClient } from \"../../../client\";\nimport { IRequestsMap } from \"../..\";\n\nexport type Request = VerificationRequest;\n\n/**\n * A key verification channel that sends verification events over to_device messages.\n * Generates its own transaction ids.\n */\nexport class ToDeviceChannel implements IVerificationChannel {\n public request?: VerificationRequest;\n\n // userId and devices of user we're about to verify\n public constructor(\n private readonly client: MatrixClient,\n public readonly userId: string,\n private readonly devices: string[],\n public transactionId?: string,\n public deviceId?: string,\n ) {}\n\n public isToDevices(devices: string[]): boolean {\n if (devices.length === this.devices.length) {\n for (const device of devices) {\n if (!this.devices.includes(device)) {\n return false;\n }\n }\n return true;\n } else {\n return false;\n }\n }\n\n public static getEventType(event: MatrixEvent): string {\n return event.getType();\n }\n\n /**\n * Extract the transaction id used by a given key verification event, if any\n * @param event - the event\n * @returns the transaction id\n */\n public static getTransactionId(event: MatrixEvent): string {\n const content = event.getContent();\n return content && content.transaction_id;\n }\n\n /**\n * Checks whether the given event type should be allowed to initiate a new VerificationRequest over this channel\n * @param type - the event type to check\n * @returns boolean flag\n */\n public static canCreateRequest(type: string): boolean {\n return type === REQUEST_TYPE || type === START_TYPE;\n }\n\n public canCreateRequest(type: string): boolean {\n return ToDeviceChannel.canCreateRequest(type);\n }\n\n /**\n * Checks whether this event is a well-formed key verification event.\n * This only does checks that don't rely on the current state of a potentially already channel\n * so we can prevent channels being created by invalid events.\n * `handleEvent` can do more checks and choose to ignore invalid events.\n * @param event - the event to validate\n * @param client - the client to get the current user and device id from\n * @returns whether the event is valid and should be passed to handleEvent\n */\n public static validateEvent(event: MatrixEvent, client: MatrixClient): boolean {\n if (event.isCancelled()) {\n logger.warn(\"Ignoring flagged verification request from \" + event.getSender());\n return false;\n }\n const content = event.getContent();\n if (!content) {\n logger.warn(\"ToDeviceChannel.validateEvent: invalid: no content\");\n return false;\n }\n\n if (!content.transaction_id) {\n logger.warn(\"ToDeviceChannel.validateEvent: invalid: no transaction_id\");\n return false;\n }\n\n const type = event.getType();\n\n if (type === REQUEST_TYPE) {\n if (!Number.isFinite(content.timestamp)) {\n logger.warn(\"ToDeviceChannel.validateEvent: invalid: no timestamp\");\n return false;\n }\n if (event.getSender() === client.getUserId() && content.from_device == client.getDeviceId()) {\n // ignore requests from ourselves, because it doesn't make sense for a\n // device to verify itself\n logger.warn(\"ToDeviceChannel.validateEvent: invalid: from own device\");\n return false;\n }\n }\n\n return VerificationRequest.validateEvent(type, event, client);\n }\n\n /**\n * @param event - the event to get the timestamp of\n * @returns the timestamp when the event was sent\n */\n public getTimestamp(event: MatrixEvent): number {\n const content = event.getContent();\n return content && content.timestamp;\n }\n\n /**\n * Changes the state of the channel, request, and verifier in response to a key verification event.\n * @param event - to handle\n * @param request - the request to forward handling to\n * @param isLiveEvent - whether this is an even received through sync or not\n * @returns a promise that resolves when any requests as an answer to the passed-in event are sent.\n */\n public async handleEvent(event: MatrixEvent, request: Request, isLiveEvent = false): Promise {\n const type = event.getType();\n const content = event.getContent();\n if (type === REQUEST_TYPE || type === READY_TYPE || type === START_TYPE) {\n if (!this.transactionId) {\n this.transactionId = content.transaction_id;\n }\n const deviceId = content.from_device;\n // adopt deviceId if not set before and valid\n if (!this.deviceId && this.devices.includes(deviceId)) {\n this.deviceId = deviceId;\n }\n // if no device id or different from adopted one, cancel with sender\n if (!this.deviceId || this.deviceId !== deviceId) {\n // also check that message came from the device we sent the request to earlier on\n // and do send a cancel message to that device\n // (but don't cancel the request for the device we should be talking to)\n const cancelContent = this.completeContent(CANCEL_TYPE, errorFromEvent(newUnexpectedMessageError()));\n return this.sendToDevices(CANCEL_TYPE, cancelContent, [deviceId]);\n }\n }\n const wasStarted = request.phase === PHASE_STARTED || request.phase === PHASE_READY;\n\n await request.handleEvent(event.getType(), event, isLiveEvent, false, false);\n\n const isStarted = request.phase === PHASE_STARTED || request.phase === PHASE_READY;\n\n const isAcceptingEvent = type === START_TYPE || type === READY_TYPE;\n // the request has picked a ready or start event, tell the other devices about it\n if (isAcceptingEvent && !wasStarted && isStarted && this.deviceId) {\n const nonChosenDevices = this.devices.filter((d) => d !== this.deviceId && d !== this.client.getDeviceId());\n if (nonChosenDevices.length) {\n const message = this.completeContent(CANCEL_TYPE, {\n code: \"m.accepted\",\n reason: \"Verification request accepted by another device\",\n });\n await this.sendToDevices(CANCEL_TYPE, message, nonChosenDevices);\n }\n }\n }\n\n /**\n * See {@link InRoomChannel#completedContentFromEvent} for why this is needed.\n * @param event - the received event\n * @returns the content object\n */\n public completedContentFromEvent(event: MatrixEvent): Record {\n return event.getContent();\n }\n\n /**\n * Add all the fields to content needed for sending it over this channel.\n * This is public so verification methods (SAS uses this) can get the exact\n * content that will be sent independent of the used channel,\n * as they need to calculate the hash of it.\n * @param type - the event type\n * @param content - the (incomplete) content\n * @returns the complete content, as it will be sent.\n */\n public completeContent(type: string, content: Record): Record {\n // make a copy\n content = Object.assign({}, content);\n if (this.transactionId) {\n content.transaction_id = this.transactionId;\n }\n if (type === REQUEST_TYPE || type === READY_TYPE || type === START_TYPE) {\n content.from_device = this.client.getDeviceId();\n }\n if (type === REQUEST_TYPE) {\n content.timestamp = Date.now();\n }\n return content;\n }\n\n /**\n * Send an event over the channel with the content not having gone through `completeContent`.\n * @param type - the event type\n * @param uncompletedContent - the (incomplete) content\n * @returns the promise of the request\n */\n public send(type: string, uncompletedContent: Record = {}): Promise {\n // create transaction id when sending request\n if ((type === REQUEST_TYPE || type === START_TYPE) && !this.transactionId) {\n this.transactionId = ToDeviceChannel.makeTransactionId();\n }\n const content = this.completeContent(type, uncompletedContent);\n return this.sendCompleted(type, content);\n }\n\n /**\n * Send an event over the channel with the content having gone through `completeContent` already.\n * @param type - the event type\n * @returns the promise of the request\n */\n public async sendCompleted(type: string, content: Record): Promise {\n let result;\n if (type === REQUEST_TYPE || (type === CANCEL_TYPE && !this.deviceId)) {\n result = await this.sendToDevices(type, content, this.devices);\n } else {\n result = await this.sendToDevices(type, content, [this.deviceId!]);\n }\n // the VerificationRequest state machine requires remote echos of the event\n // the client sends itself, so we fake this for to_device messages\n const remoteEchoEvent = new MatrixEvent({\n sender: this.client.getUserId()!,\n content,\n type,\n });\n await this.request!.handleEvent(\n type,\n remoteEchoEvent,\n /*isLiveEvent=*/ true,\n /*isRemoteEcho=*/ true,\n /*isSentByUs=*/ true,\n );\n return result;\n }\n\n private async sendToDevices(type: string, content: Record, devices: string[]): Promise {\n if (devices.length) {\n const deviceMessages: Map> = new Map();\n for (const deviceId of devices) {\n deviceMessages.set(deviceId, content);\n }\n\n await this.client.sendToDevice(type, new Map([[this.userId, deviceMessages]]));\n }\n }\n\n /**\n * Allow Crypto module to create and know the transaction id before the .start event gets sent.\n * @returns the transaction id\n */\n public static makeTransactionId(): string {\n return randomString(32);\n }\n}\n\nexport class ToDeviceRequests implements IRequestsMap {\n private requestsByUserId = new Map>();\n\n public getRequest(event: MatrixEvent): Request | undefined {\n return this.getRequestBySenderAndTxnId(event.getSender()!, ToDeviceChannel.getTransactionId(event));\n }\n\n public getRequestByChannel(channel: ToDeviceChannel): Request | undefined {\n return this.getRequestBySenderAndTxnId(channel.userId, channel.transactionId!);\n }\n\n public getRequestBySenderAndTxnId(sender: string, txnId: string): Request | undefined {\n const requestsByTxnId = this.requestsByUserId.get(sender);\n if (requestsByTxnId) {\n return requestsByTxnId.get(txnId);\n }\n }\n\n public setRequest(event: MatrixEvent, request: Request): void {\n this.setRequestBySenderAndTxnId(event.getSender()!, ToDeviceChannel.getTransactionId(event), request);\n }\n\n public setRequestByChannel(channel: ToDeviceChannel, request: Request): void {\n this.setRequestBySenderAndTxnId(channel.userId, channel.transactionId!, request);\n }\n\n public setRequestBySenderAndTxnId(sender: string, txnId: string, request: Request): void {\n let requestsByTxnId = this.requestsByUserId.get(sender);\n if (!requestsByTxnId) {\n requestsByTxnId = new Map();\n this.requestsByUserId.set(sender, requestsByTxnId);\n }\n requestsByTxnId.set(txnId, request);\n }\n\n public removeRequest(event: MatrixEvent): void {\n const userId = event.getSender()!;\n const requestsByTxnId = this.requestsByUserId.get(userId);\n if (requestsByTxnId) {\n requestsByTxnId.delete(ToDeviceChannel.getTransactionId(event));\n if (requestsByTxnId.size === 0) {\n this.requestsByUserId.delete(userId);\n }\n }\n }\n\n public findRequestInProgress(userId: string, devices: string[]): Request | undefined {\n const requestsByTxnId = this.requestsByUserId.get(userId);\n if (requestsByTxnId) {\n for (const request of requestsByTxnId.values()) {\n if (request.pending && request.channel.isToDevices(devices)) {\n return request;\n }\n }\n }\n }\n\n public getRequestsInProgress(userId: string): Request[] {\n const requestsByTxnId = this.requestsByUserId.get(userId);\n if (requestsByTxnId) {\n return Array.from(requestsByTxnId.values()).filter((r) => r.pending);\n }\n return [];\n }\n}\n", - "/*\nCopyright 2018 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from \"../../../logger\";\nimport { errorFactory, errorFromEvent, newUnexpectedMessageError, newUnknownMethodError } from \"../Error\";\nimport { QRCodeData, SCAN_QR_CODE_METHOD } from \"../QRCode\";\nimport { IVerificationChannel } from \"./Channel\";\nimport { MatrixClient } from \"../../../client\";\nimport { MatrixEvent } from \"../../../models/event\";\nimport { EventType } from \"../../../@types/event\";\nimport { VerificationBase } from \"../Base\";\nimport { VerificationMethod } from \"../../index\";\nimport { TypedEventEmitter } from \"../../../models/typed-event-emitter\";\n\n// How long after the event's timestamp that the request times out\nconst TIMEOUT_FROM_EVENT_TS = 10 * 60 * 1000; // 10 minutes\n\n// How long after we receive the event that the request times out\nconst TIMEOUT_FROM_EVENT_RECEIPT = 2 * 60 * 1000; // 2 minutes\n\n// to avoid almost expired verification notifications\n// from showing a notification and almost immediately\n// disappearing, also ignore verification requests that\n// are this amount of time away from expiring.\nconst VERIFICATION_REQUEST_MARGIN = 3 * 1000; // 3 seconds\n\nexport const EVENT_PREFIX = \"m.key.verification.\";\nexport const REQUEST_TYPE = EVENT_PREFIX + \"request\";\nexport const START_TYPE = EVENT_PREFIX + \"start\";\nexport const CANCEL_TYPE = EVENT_PREFIX + \"cancel\";\nexport const DONE_TYPE = EVENT_PREFIX + \"done\";\nexport const READY_TYPE = EVENT_PREFIX + \"ready\";\n\nexport enum Phase {\n Unsent = 1,\n Requested,\n Ready,\n Started,\n Cancelled,\n Done,\n}\n\n// Legacy export fields\nexport const PHASE_UNSENT = Phase.Unsent;\nexport const PHASE_REQUESTED = Phase.Requested;\nexport const PHASE_READY = Phase.Ready;\nexport const PHASE_STARTED = Phase.Started;\nexport const PHASE_CANCELLED = Phase.Cancelled;\nexport const PHASE_DONE = Phase.Done;\n\ninterface ITargetDevice {\n userId?: string;\n deviceId?: string;\n}\n\ninterface ITransition {\n phase: Phase;\n event?: MatrixEvent;\n}\n\nexport enum VerificationRequestEvent {\n Change = \"change\",\n}\n\ntype EventHandlerMap = {\n /**\n * Fires whenever the state of the request object has changed.\n */\n [VerificationRequestEvent.Change]: () => void;\n};\n\n/**\n * State machine for verification requests.\n * Things that differ based on what channel is used to\n * send and receive verification events are put in `InRoomChannel` or `ToDeviceChannel`.\n */\nexport class VerificationRequest extends TypedEventEmitter<\n VerificationRequestEvent,\n EventHandlerMap\n> {\n private eventsByUs = new Map();\n private eventsByThem = new Map();\n private _observeOnly = false;\n private timeoutTimer: ReturnType | null = null;\n private _accepting = false;\n private _declining = false;\n private verifierHasFinished = false;\n private _cancelled = false;\n private _chosenMethod: VerificationMethod | null = null;\n // we keep a copy of the QR Code data (including other user master key) around\n // for QR reciprocate verification, to protect against\n // cross-signing identity reset between the .ready and .start event\n // and signing the wrong key after .start\n private _qrCodeData: QRCodeData | null = null;\n\n // The timestamp when we received the request event from the other side\n private requestReceivedAt: number | null = null;\n\n private commonMethods: VerificationMethod[] = [];\n private _phase!: Phase;\n public _cancellingUserId?: string; // Used in tests only\n private _verifier?: VerificationBase;\n\n public constructor(\n public readonly channel: C,\n private readonly verificationMethods: Map,\n private readonly client: MatrixClient,\n ) {\n super();\n this.channel.request = this;\n this.setPhase(PHASE_UNSENT, false);\n }\n\n /**\n * Stateless validation logic not specific to the channel.\n * Invoked by the same static method in either channel.\n * @param type - the \"symbolic\" event type, as returned by the `getEventType` function on the channel.\n * @param event - the event to validate. Don't call getType() on it but use the `type` parameter instead.\n * @param client - the client to get the current user and device id from\n * @returns whether the event is valid and should be passed to handleEvent\n */\n public static validateEvent(type: string, event: MatrixEvent, client: MatrixClient): boolean {\n const content = event.getContent();\n\n if (!type || !type.startsWith(EVENT_PREFIX)) {\n return false;\n }\n\n // from here on we're fairly sure that this is supposed to be\n // part of a verification request, so be noisy when rejecting something\n if (!content) {\n logger.log(\"VerificationRequest: validateEvent: no content\");\n return false;\n }\n\n if (type === REQUEST_TYPE || type === READY_TYPE) {\n if (!Array.isArray(content.methods)) {\n logger.log(\"VerificationRequest: validateEvent: \" + \"fail because methods\");\n return false;\n }\n }\n\n if (type === REQUEST_TYPE || type === READY_TYPE || type === START_TYPE) {\n if (typeof content.from_device !== \"string\" || content.from_device.length === 0) {\n logger.log(\"VerificationRequest: validateEvent: \" + \"fail because from_device\");\n return false;\n }\n }\n\n return true;\n }\n\n public get invalid(): boolean {\n return this.phase === PHASE_UNSENT;\n }\n\n /** returns whether the phase is PHASE_REQUESTED */\n public get requested(): boolean {\n return this.phase === PHASE_REQUESTED;\n }\n\n /** returns whether the phase is PHASE_CANCELLED */\n public get cancelled(): boolean {\n return this.phase === PHASE_CANCELLED;\n }\n\n /** returns whether the phase is PHASE_READY */\n public get ready(): boolean {\n return this.phase === PHASE_READY;\n }\n\n /** returns whether the phase is PHASE_STARTED */\n public get started(): boolean {\n return this.phase === PHASE_STARTED;\n }\n\n /** returns whether the phase is PHASE_DONE */\n public get done(): boolean {\n return this.phase === PHASE_DONE;\n }\n\n /** once the phase is PHASE_STARTED (and !initiatedByMe) or PHASE_READY: common methods supported by both sides */\n public get methods(): VerificationMethod[] {\n return this.commonMethods;\n }\n\n /** the method picked in the .start event */\n public get chosenMethod(): VerificationMethod | null {\n return this._chosenMethod;\n }\n\n public calculateEventTimeout(event: MatrixEvent): number {\n let effectiveExpiresAt = this.channel.getTimestamp(event) + TIMEOUT_FROM_EVENT_TS;\n\n if (this.requestReceivedAt && !this.initiatedByMe && this.phase <= PHASE_REQUESTED) {\n const expiresAtByReceipt = this.requestReceivedAt + TIMEOUT_FROM_EVENT_RECEIPT;\n effectiveExpiresAt = Math.min(effectiveExpiresAt, expiresAtByReceipt);\n }\n\n return Math.max(0, effectiveExpiresAt - Date.now());\n }\n\n /** The current remaining amount of ms before the request should be automatically cancelled */\n public get timeout(): number {\n const requestEvent = this.getEventByEither(REQUEST_TYPE);\n if (requestEvent) {\n return this.calculateEventTimeout(requestEvent);\n }\n return 0;\n }\n\n /**\n * The key verification request event.\n * @returns The request event, or falsey if not found.\n */\n public get requestEvent(): MatrixEvent | undefined {\n return this.getEventByEither(REQUEST_TYPE);\n }\n\n /** current phase of the request. Some properties might only be defined in a current phase. */\n public get phase(): Phase {\n return this._phase;\n }\n\n /** The verifier to do the actual verification, once the method has been established. Only defined when the `phase` is PHASE_STARTED. */\n public get verifier(): VerificationBase | undefined {\n return this._verifier;\n }\n\n public get canAccept(): boolean {\n return this.phase < PHASE_READY && !this._accepting && !this._declining;\n }\n\n public get accepting(): boolean {\n return this._accepting;\n }\n\n public get declining(): boolean {\n return this._declining;\n }\n\n /** whether this request has sent it's initial event and needs more events to complete */\n public get pending(): boolean {\n return !this.observeOnly && this._phase !== PHASE_DONE && this._phase !== PHASE_CANCELLED;\n }\n\n /** Only set after a .ready if the other party can scan a QR code */\n public get qrCodeData(): QRCodeData | null {\n return this._qrCodeData;\n }\n\n /** Checks whether the other party supports a given verification method.\n * This is useful when setting up the QR code UI, as it is somewhat asymmetrical:\n * if the other party supports SCAN_QR, we should show a QR code in the UI, and vice versa.\n * For methods that need to be supported by both ends, use the `methods` property.\n * @param method - the method to check\n * @param force - to check even if the phase is not ready or started yet, internal usage\n * @returns whether or not the other party said the supported the method */\n public otherPartySupportsMethod(method: string, force = false): boolean {\n if (!force && !this.ready && !this.started) {\n return false;\n }\n const theirMethodEvent = this.eventsByThem.get(REQUEST_TYPE) || this.eventsByThem.get(READY_TYPE);\n if (!theirMethodEvent) {\n // if we started straight away with .start event,\n // we are assuming that the other side will support the\n // chosen method, so return true for that.\n if (this.started && this.initiatedByMe) {\n const myStartEvent = this.eventsByUs.get(START_TYPE);\n const content = myStartEvent && myStartEvent.getContent();\n const myStartMethod = content && content.method;\n return method == myStartMethod;\n }\n return false;\n }\n const content = theirMethodEvent.getContent();\n if (!content) {\n return false;\n }\n const { methods } = content;\n if (!Array.isArray(methods)) {\n return false;\n }\n\n return methods.includes(method);\n }\n\n /** Whether this request was initiated by the syncing user.\n * For InRoomChannel, this is who sent the .request event.\n * For ToDeviceChannel, this is who sent the .start event\n */\n public get initiatedByMe(): boolean {\n // event created by us but no remote echo has been received yet\n const noEventsYet = this.eventsByUs.size + this.eventsByThem.size === 0;\n if (this._phase === PHASE_UNSENT && noEventsYet) {\n return true;\n }\n const hasMyRequest = this.eventsByUs.has(REQUEST_TYPE);\n const hasTheirRequest = this.eventsByThem.has(REQUEST_TYPE);\n if (hasMyRequest && !hasTheirRequest) {\n return true;\n }\n if (!hasMyRequest && hasTheirRequest) {\n return false;\n }\n const hasMyStart = this.eventsByUs.has(START_TYPE);\n const hasTheirStart = this.eventsByThem.has(START_TYPE);\n if (hasMyStart && !hasTheirStart) {\n return true;\n }\n return false;\n }\n\n /** The id of the user that initiated the request */\n public get requestingUserId(): string {\n if (this.initiatedByMe) {\n return this.client.getUserId()!;\n } else {\n return this.otherUserId;\n }\n }\n\n /** The id of the user that (will) receive(d) the request */\n public get receivingUserId(): string {\n if (this.initiatedByMe) {\n return this.otherUserId;\n } else {\n return this.client.getUserId()!;\n }\n }\n\n /** The user id of the other party in this request */\n public get otherUserId(): string {\n return this.channel.userId!;\n }\n\n public get isSelfVerification(): boolean {\n return this.client.getUserId() === this.otherUserId;\n }\n\n /**\n * The id of the user that cancelled the request,\n * only defined when phase is PHASE_CANCELLED\n */\n public get cancellingUserId(): string | undefined {\n const myCancel = this.eventsByUs.get(CANCEL_TYPE);\n const theirCancel = this.eventsByThem.get(CANCEL_TYPE);\n\n if (myCancel && (!theirCancel || myCancel.getId()! < theirCancel.getId()!)) {\n return myCancel.getSender();\n }\n if (theirCancel) {\n return theirCancel.getSender();\n }\n return undefined;\n }\n\n /**\n * The cancellation code e.g m.user which is responsible for cancelling this verification\n */\n public get cancellationCode(): string {\n const ev = this.getEventByEither(CANCEL_TYPE);\n return ev ? ev.getContent().code : null;\n }\n\n public get observeOnly(): boolean {\n return this._observeOnly;\n }\n\n /**\n * Gets which device the verification should be started with\n * given the events sent so far in the verification. This is the\n * same algorithm used to determine which device to send the\n * verification to when no specific device is specified.\n * @returns The device information\n */\n public get targetDevice(): ITargetDevice {\n const theirFirstEvent =\n this.eventsByThem.get(REQUEST_TYPE) ||\n this.eventsByThem.get(READY_TYPE) ||\n this.eventsByThem.get(START_TYPE);\n const theirFirstContent = theirFirstEvent?.getContent();\n const fromDevice = theirFirstContent?.from_device;\n return {\n userId: this.otherUserId,\n deviceId: fromDevice,\n };\n }\n\n /* Start the key verification, creating a verifier and sending a .start event.\n * If no previous events have been sent, pass in `targetDevice` to set who to direct this request to.\n * @param method - the name of the verification method to use.\n * @param targetDevice.userId the id of the user to direct this request to\n * @param targetDevice.deviceId the id of the device to direct this request to\n * @returns the verifier of the given method\n */\n public beginKeyVerification(\n method: VerificationMethod,\n targetDevice: ITargetDevice | null = null,\n ): VerificationBase {\n // need to allow also when unsent in case of to_device\n if (!this.observeOnly && !this._verifier) {\n const validStartPhase =\n this.phase === PHASE_REQUESTED ||\n this.phase === PHASE_READY ||\n (this.phase === PHASE_UNSENT && this.channel.canCreateRequest(START_TYPE));\n if (validStartPhase) {\n // when called on a request that was initiated with .request event\n // check the method is supported by both sides\n if (this.commonMethods.length && !this.commonMethods.includes(method)) {\n throw newUnknownMethodError();\n }\n this._verifier = this.createVerifier(method, null, targetDevice);\n if (!this._verifier) {\n throw newUnknownMethodError();\n }\n this._chosenMethod = method;\n }\n }\n return this._verifier!;\n }\n\n /**\n * sends the initial .request event.\n * @returns resolves when the event has been sent.\n */\n public async sendRequest(): Promise {\n if (!this.observeOnly && this._phase === PHASE_UNSENT) {\n const methods = [...this.verificationMethods.keys()];\n await this.channel.send(REQUEST_TYPE, { methods });\n }\n }\n\n /**\n * Cancels the request, sending a cancellation to the other party\n * @param reason - the error reason to send the cancellation with\n * @param code - the error code to send the cancellation with\n * @returns resolves when the event has been sent.\n */\n public async cancel({ reason = \"User declined\", code = \"m.user\" } = {}): Promise {\n if (!this.observeOnly && this._phase !== PHASE_CANCELLED) {\n this._declining = true;\n this.emit(VerificationRequestEvent.Change);\n if (this._verifier) {\n return this._verifier.cancel(errorFactory(code, reason)());\n } else {\n this._cancellingUserId = this.client.getUserId()!;\n await this.channel.send(CANCEL_TYPE, { code, reason });\n }\n }\n }\n\n /**\n * Accepts the request, sending a .ready event to the other party\n * @returns resolves when the event has been sent.\n */\n public async accept(): Promise {\n if (!this.observeOnly && this.phase === PHASE_REQUESTED && !this.initiatedByMe) {\n const methods = [...this.verificationMethods.keys()];\n this._accepting = true;\n this.emit(VerificationRequestEvent.Change);\n await this.channel.send(READY_TYPE, { methods });\n }\n }\n\n /**\n * Can be used to listen for state changes until the callback returns true.\n * @param fn - callback to evaluate whether the request is in the desired state.\n * Takes the request as an argument.\n * @returns that resolves once the callback returns true\n * @throws Error when the request is cancelled\n */\n public waitFor(fn: (request: VerificationRequest) => boolean): Promise {\n return new Promise((resolve, reject) => {\n const check = (): boolean => {\n let handled = false;\n if (fn(this)) {\n resolve(this);\n handled = true;\n } else if (this.cancelled) {\n reject(new Error(\"cancelled\"));\n handled = true;\n }\n if (handled) {\n this.off(VerificationRequestEvent.Change, check);\n }\n return handled;\n };\n if (!check()) {\n this.on(VerificationRequestEvent.Change, check);\n }\n });\n }\n\n private setPhase(phase: Phase, notify = true): void {\n this._phase = phase;\n if (notify) {\n this.emit(VerificationRequestEvent.Change);\n }\n }\n\n private getEventByEither(type: string): MatrixEvent | undefined {\n return this.eventsByThem.get(type) || this.eventsByUs.get(type);\n }\n\n private getEventBy(type: string, byThem = false): MatrixEvent | undefined {\n if (byThem) {\n return this.eventsByThem.get(type);\n } else {\n return this.eventsByUs.get(type);\n }\n }\n\n private calculatePhaseTransitions(): ITransition[] {\n const transitions: ITransition[] = [{ phase: PHASE_UNSENT }];\n const phase = (): Phase => transitions[transitions.length - 1].phase;\n\n // always pass by .request first to be sure channel.userId has been set\n const hasRequestByThem = this.eventsByThem.has(REQUEST_TYPE);\n const requestEvent = this.getEventBy(REQUEST_TYPE, hasRequestByThem);\n if (requestEvent) {\n transitions.push({ phase: PHASE_REQUESTED, event: requestEvent });\n }\n\n const readyEvent = requestEvent && this.getEventBy(READY_TYPE, !hasRequestByThem);\n if (readyEvent && phase() === PHASE_REQUESTED) {\n transitions.push({ phase: PHASE_READY, event: readyEvent });\n }\n\n let startEvent: MatrixEvent | undefined;\n if (readyEvent || !requestEvent) {\n const theirStartEvent = this.eventsByThem.get(START_TYPE);\n const ourStartEvent = this.eventsByUs.get(START_TYPE);\n // any party can send .start after a .ready or unsent\n if (theirStartEvent && ourStartEvent) {\n startEvent =\n theirStartEvent.getSender()! < ourStartEvent.getSender()! ? theirStartEvent : ourStartEvent;\n } else {\n startEvent = theirStartEvent ? theirStartEvent : ourStartEvent;\n }\n } else {\n startEvent = this.getEventBy(START_TYPE, !hasRequestByThem);\n }\n if (startEvent) {\n const fromRequestPhase =\n phase() === PHASE_REQUESTED && requestEvent?.getSender() !== startEvent.getSender();\n const fromUnsentPhase = phase() === PHASE_UNSENT && this.channel.canCreateRequest(START_TYPE);\n if (fromRequestPhase || phase() === PHASE_READY || fromUnsentPhase) {\n transitions.push({ phase: PHASE_STARTED, event: startEvent });\n }\n }\n\n const ourDoneEvent = this.eventsByUs.get(DONE_TYPE);\n if (this.verifierHasFinished || (ourDoneEvent && phase() === PHASE_STARTED)) {\n transitions.push({ phase: PHASE_DONE });\n }\n\n const cancelEvent = this.getEventByEither(CANCEL_TYPE);\n if ((this._cancelled || cancelEvent) && phase() !== PHASE_DONE) {\n transitions.push({ phase: PHASE_CANCELLED, event: cancelEvent });\n return transitions;\n }\n\n return transitions;\n }\n\n private transitionToPhase(transition: ITransition): void {\n const { phase, event } = transition;\n // get common methods\n if (phase === PHASE_REQUESTED || phase === PHASE_READY) {\n if (!this.wasSentByOwnDevice(event)) {\n const content = event!.getContent<{\n methods: string[];\n }>();\n this.commonMethods = content.methods.filter((m) => this.verificationMethods.has(m));\n }\n }\n // detect if we're not a party in the request, and we should just observe\n if (!this.observeOnly) {\n // if requested or accepted by one of my other devices\n if (phase === PHASE_REQUESTED || phase === PHASE_STARTED || phase === PHASE_READY) {\n if (\n this.channel.receiveStartFromOtherDevices &&\n this.wasSentByOwnUser(event) &&\n !this.wasSentByOwnDevice(event)\n ) {\n this._observeOnly = true;\n }\n }\n }\n // create verifier\n if (phase === PHASE_STARTED) {\n const { method } = event!.getContent();\n if (!this._verifier && !this.observeOnly) {\n this._verifier = this.createVerifier(method, event);\n if (!this._verifier) {\n this.cancel({\n code: \"m.unknown_method\",\n reason: `Unknown method: ${method}`,\n });\n } else {\n this._chosenMethod = method;\n }\n }\n }\n }\n\n private applyPhaseTransitions(): ITransition[] {\n const transitions = this.calculatePhaseTransitions();\n const existingIdx = transitions.findIndex((t) => t.phase === this.phase);\n // trim off phases we already went through, if any\n const newTransitions = transitions.slice(existingIdx + 1);\n // transition to all new phases\n for (const transition of newTransitions) {\n this.transitionToPhase(transition);\n }\n return newTransitions;\n }\n\n private isWinningStartRace(newEvent: MatrixEvent): boolean {\n if (newEvent.getType() !== START_TYPE) {\n return false;\n }\n const oldEvent = this._verifier!.startEvent;\n\n let oldRaceIdentifier;\n if (this.isSelfVerification) {\n // if the verifier does not have a startEvent,\n // it is because it's still sending and we are on the initator side\n // we know we are sending a .start event because we already\n // have a verifier (checked in calling method)\n if (oldEvent) {\n const oldContent = oldEvent.getContent();\n oldRaceIdentifier = oldContent && oldContent.from_device;\n } else {\n oldRaceIdentifier = this.client.getDeviceId();\n }\n } else {\n if (oldEvent) {\n oldRaceIdentifier = oldEvent.getSender();\n } else {\n oldRaceIdentifier = this.client.getUserId();\n }\n }\n\n let newRaceIdentifier;\n if (this.isSelfVerification) {\n const newContent = newEvent.getContent();\n newRaceIdentifier = newContent && newContent.from_device;\n } else {\n newRaceIdentifier = newEvent.getSender();\n }\n return newRaceIdentifier < oldRaceIdentifier;\n }\n\n public hasEventId(eventId: string): boolean {\n for (const event of this.eventsByUs.values()) {\n if (event.getId() === eventId) {\n return true;\n }\n }\n for (const event of this.eventsByThem.values()) {\n if (event.getId() === eventId) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Changes the state of the request and verifier in response to a key verification event.\n * @param type - the \"symbolic\" event type, as returned by the `getEventType` function on the channel.\n * @param event - the event to handle. Don't call getType() on it but use the `type` parameter instead.\n * @param isLiveEvent - whether this is an even received through sync or not\n * @param isRemoteEcho - whether this is the remote echo of an event sent by the same device\n * @param isSentByUs - whether this event is sent by a party that can accept and/or observe the request like one of our peers.\n * For InRoomChannel this means any device for the syncing user. For ToDeviceChannel, just the syncing device.\n * @returns a promise that resolves when any requests as an answer to the passed-in event are sent.\n */\n public async handleEvent(\n type: string,\n event: MatrixEvent,\n isLiveEvent: boolean,\n isRemoteEcho: boolean,\n isSentByUs: boolean,\n ): Promise {\n // if reached phase cancelled or done, ignore anything else that comes\n if (this.done || this.cancelled) {\n return;\n }\n const wasObserveOnly = this._observeOnly;\n\n this.adjustObserveOnly(event, isLiveEvent);\n\n if (!this.observeOnly && !isRemoteEcho) {\n if (await this.cancelOnError(type, event)) {\n return;\n }\n }\n\n // This assumes verification won't need to send an event with\n // the same type for the same party twice.\n // This is true for QR and SAS verification, and was\n // added here to prevent verification getting cancelled\n // when the server duplicates an event (https://github.com/matrix-org/synapse/issues/3365)\n const isDuplicateEvent = isSentByUs ? this.eventsByUs.has(type) : this.eventsByThem.has(type);\n if (isDuplicateEvent) {\n return;\n }\n\n const oldPhase = this.phase;\n this.addEvent(type, event, isSentByUs);\n\n // this will create if needed the verifier so needs to happen before calling it\n const newTransitions = this.applyPhaseTransitions();\n try {\n // only pass events from the other side to the verifier,\n // no remote echos of our own events\n if (this._verifier && !this.observeOnly) {\n const newEventWinsRace = this.isWinningStartRace(event);\n if (this._verifier.canSwitchStartEvent(event) && newEventWinsRace) {\n this._verifier.switchStartEvent(event);\n } else if (!isRemoteEcho) {\n if (type === CANCEL_TYPE || this._verifier.events?.includes(type)) {\n this._verifier.handleEvent(event);\n }\n }\n }\n\n if (newTransitions.length) {\n // create QRCodeData if the other side can scan\n // important this happens before emitting a phase change,\n // so listeners can rely on it being there already\n // We only do this for live events because it is important that\n // we sign the keys that were in the QR code, and not the keys\n // we happen to have at some later point in time.\n if (isLiveEvent && newTransitions.some((t) => t.phase === PHASE_READY)) {\n const shouldGenerateQrCode = this.otherPartySupportsMethod(SCAN_QR_CODE_METHOD, true);\n if (shouldGenerateQrCode) {\n this._qrCodeData = await QRCodeData.create(this, this.client);\n }\n }\n\n const lastTransition = newTransitions[newTransitions.length - 1];\n const { phase } = lastTransition;\n\n this.setupTimeout(phase);\n // set phase as last thing as this emits the \"change\" event\n this.setPhase(phase);\n } else if (this._observeOnly !== wasObserveOnly) {\n this.emit(VerificationRequestEvent.Change);\n }\n } finally {\n // log events we processed so we can see from rageshakes what events were added to a request\n logger.log(\n `Verification request ${this.channel.transactionId}: ` +\n `${type} event with id:${event.getId()}, ` +\n `content:${JSON.stringify(event.getContent())} ` +\n `deviceId:${this.channel.deviceId}, ` +\n `sender:${event.getSender()}, isSentByUs:${isSentByUs}, ` +\n `isLiveEvent:${isLiveEvent}, isRemoteEcho:${isRemoteEcho}, ` +\n `phase:${oldPhase}=>${this.phase}, ` +\n `observeOnly:${wasObserveOnly}=>${this._observeOnly}`,\n );\n }\n }\n\n private setupTimeout(phase: Phase): void {\n const shouldTimeout = !this.timeoutTimer && !this.observeOnly && phase === PHASE_REQUESTED;\n\n if (shouldTimeout) {\n this.timeoutTimer = setTimeout(this.cancelOnTimeout, this.timeout);\n }\n if (this.timeoutTimer) {\n const shouldClear =\n phase === PHASE_STARTED || phase === PHASE_READY || phase === PHASE_DONE || phase === PHASE_CANCELLED;\n if (shouldClear) {\n clearTimeout(this.timeoutTimer);\n this.timeoutTimer = null;\n }\n }\n }\n\n private cancelOnTimeout = async (): Promise => {\n try {\n if (this.initiatedByMe) {\n await this.cancel({\n reason: \"Other party didn't accept in time\",\n code: \"m.timeout\",\n });\n } else {\n await this.cancel({\n reason: \"User didn't accept in time\",\n code: \"m.timeout\",\n });\n }\n } catch (err) {\n logger.error(\"Error while cancelling verification request\", err);\n }\n };\n\n private async cancelOnError(type: string, event: MatrixEvent): Promise {\n if (type === START_TYPE) {\n const method = event.getContent().method;\n if (!this.verificationMethods.has(method)) {\n await this.cancel(errorFromEvent(newUnknownMethodError()));\n return true;\n }\n }\n\n const isUnexpectedRequest = type === REQUEST_TYPE && this.phase !== PHASE_UNSENT;\n const isUnexpectedReady = type === READY_TYPE && this.phase !== PHASE_REQUESTED && this.phase !== PHASE_STARTED;\n // only if phase has passed from PHASE_UNSENT should we cancel, because events\n // are allowed to come in in any order (at least with InRoomChannel). So we only know\n // we're dealing with a valid request we should participate in once we've moved to PHASE_REQUESTED.\n // Before that, we could be looking at somebody else's verification request and we just\n // happen to be in the room\n if (this.phase !== PHASE_UNSENT && (isUnexpectedRequest || isUnexpectedReady)) {\n logger.warn(`Cancelling, unexpected ${type} verification ` + `event from ${event.getSender()}`);\n const reason = `Unexpected ${type} event in phase ${this.phase}`;\n await this.cancel(errorFromEvent(newUnexpectedMessageError({ reason })));\n return true;\n }\n return false;\n }\n\n private adjustObserveOnly(event: MatrixEvent, isLiveEvent = false): void {\n // don't send out events for historical requests\n if (!isLiveEvent) {\n this._observeOnly = true;\n }\n if (this.calculateEventTimeout(event) < VERIFICATION_REQUEST_MARGIN) {\n this._observeOnly = true;\n }\n }\n\n private addEvent(type: string, event: MatrixEvent, isSentByUs = false): void {\n if (isSentByUs) {\n this.eventsByUs.set(type, event);\n } else {\n this.eventsByThem.set(type, event);\n }\n\n // once we know the userId of the other party (from the .request event)\n // see if any event by anyone else crept into this.eventsByThem\n if (type === REQUEST_TYPE) {\n for (const [type, event] of this.eventsByThem.entries()) {\n if (event.getSender() !== this.otherUserId) {\n this.eventsByThem.delete(type);\n }\n }\n // also remember when we received the request event\n this.requestReceivedAt = Date.now();\n }\n }\n\n private createVerifier(\n method: VerificationMethod,\n startEvent: MatrixEvent | null = null,\n targetDevice: ITargetDevice | null = null,\n ): VerificationBase | undefined {\n if (!targetDevice) {\n targetDevice = this.targetDevice;\n }\n const { userId, deviceId } = targetDevice;\n\n const VerifierCtor = this.verificationMethods.get(method);\n if (!VerifierCtor) {\n logger.warn(\"could not find verifier constructor for method\", method);\n return;\n }\n return new VerifierCtor(this.channel, this.client, userId!, deviceId!, startEvent, this);\n }\n\n private wasSentByOwnUser(event?: MatrixEvent): boolean {\n return event?.getSender() === this.client.getUserId();\n }\n\n // only for .request, .ready or .start\n private wasSentByOwnDevice(event?: MatrixEvent): boolean {\n if (!this.wasSentByOwnUser(event)) {\n return false;\n }\n const content = event!.getContent();\n if (!content || content.from_device !== this.client.getDeviceId()) {\n return false;\n }\n return true;\n }\n\n public onVerifierCancelled(): void {\n this._cancelled = true;\n // move to cancelled phase\n const newTransitions = this.applyPhaseTransitions();\n if (newTransitions.length) {\n this.setPhase(newTransitions[newTransitions.length - 1].phase);\n }\n }\n\n public onVerifierFinished(): void {\n this.channel.send(EventType.KeyVerificationDone, {});\n this.verifierHasFinished = true;\n // move to .done phase\n const newTransitions = this.applyPhaseTransitions();\n if (newTransitions.length) {\n this.setPhase(newTransitions[newTransitions.length - 1].phase);\n }\n }\n\n public getEventFromOtherParty(type: string): MatrixEvent | undefined {\n return this.eventsByThem.get(type);\n }\n}\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {\n WidgetApi,\n WidgetApiToWidgetAction,\n MatrixCapabilities,\n IWidgetApiRequest,\n IWidgetApiAcknowledgeResponseData,\n ISendEventToWidgetActionRequest,\n ISendToDeviceToWidgetActionRequest,\n ISendEventFromWidgetResponseData,\n} from \"matrix-widget-api\";\n\nimport { IEvent, IContent, EventStatus } from \"./models/event\";\nimport { ISendEventResponse } from \"./@types/requests\";\nimport { EventType } from \"./@types/event\";\nimport { logger } from \"./logger\";\nimport { MatrixClient, ClientEvent, IMatrixClientCreateOpts, IStartClientOpts, SendToDeviceContentMap } from \"./client\";\nimport { SyncApi, SyncState } from \"./sync\";\nimport { SlidingSyncSdk } from \"./sliding-sync-sdk\";\nimport { MatrixEvent } from \"./models/event\";\nimport { User } from \"./models/user\";\nimport { Room } from \"./models/room\";\nimport { ToDeviceBatch, ToDevicePayload } from \"./models/ToDeviceMessage\";\nimport { DeviceInfo } from \"./crypto/deviceinfo\";\nimport { IOlmDevice } from \"./crypto/algorithms/megolm\";\nimport { MapWithDefault, recursiveMapToObject } from \"./utils\";\n\ninterface IStateEventRequest {\n eventType: string;\n stateKey?: string;\n}\n\nexport interface ICapabilities {\n /**\n * Event types that this client expects to send.\n */\n sendEvent?: string[];\n /**\n * Event types that this client expects to receive.\n */\n receiveEvent?: string[];\n\n /**\n * Message types that this client expects to send, or true for all message\n * types.\n */\n sendMessage?: string[] | true;\n /**\n * Message types that this client expects to receive, or true for all\n * message types.\n */\n receiveMessage?: string[] | true;\n\n /**\n * Types of state events that this client expects to send.\n */\n sendState?: IStateEventRequest[];\n /**\n * Types of state events that this client expects to receive.\n */\n receiveState?: IStateEventRequest[];\n\n /**\n * To-device event types that this client expects to send.\n */\n sendToDevice?: string[];\n /**\n * To-device event types that this client expects to receive.\n */\n receiveToDevice?: string[];\n\n /**\n * Whether this client needs access to TURN servers.\n * @defaultValue false\n */\n turnServers?: boolean;\n}\n\n/**\n * A MatrixClient that routes its requests through the widget API instead of the\n * real CS API.\n * @experimental This class is considered unstable!\n */\nexport class RoomWidgetClient extends MatrixClient {\n private room?: Room;\n private widgetApiReady = new Promise((resolve) => this.widgetApi.once(\"ready\", resolve));\n private lifecycle?: AbortController;\n private syncState: SyncState | null = null;\n\n public constructor(\n private readonly widgetApi: WidgetApi,\n private readonly capabilities: ICapabilities,\n private readonly roomId: string,\n opts: IMatrixClientCreateOpts,\n ) {\n super(opts);\n\n // Request capabilities for the functionality this client needs to support\n if (\n capabilities.sendEvent?.length ||\n capabilities.receiveEvent?.length ||\n capabilities.sendMessage === true ||\n (Array.isArray(capabilities.sendMessage) && capabilities.sendMessage.length) ||\n capabilities.receiveMessage === true ||\n (Array.isArray(capabilities.receiveMessage) && capabilities.receiveMessage.length) ||\n capabilities.sendState?.length ||\n capabilities.receiveState?.length\n ) {\n widgetApi.requestCapabilityForRoomTimeline(roomId);\n }\n capabilities.sendEvent?.forEach((eventType) => widgetApi.requestCapabilityToSendEvent(eventType));\n capabilities.receiveEvent?.forEach((eventType) => widgetApi.requestCapabilityToReceiveEvent(eventType));\n if (capabilities.sendMessage === true) {\n widgetApi.requestCapabilityToSendMessage();\n } else if (Array.isArray(capabilities.sendMessage)) {\n capabilities.sendMessage.forEach((msgType) => widgetApi.requestCapabilityToSendMessage(msgType));\n }\n if (capabilities.receiveMessage === true) {\n widgetApi.requestCapabilityToReceiveMessage();\n } else if (Array.isArray(capabilities.receiveMessage)) {\n capabilities.receiveMessage.forEach((msgType) => widgetApi.requestCapabilityToReceiveMessage(msgType));\n }\n capabilities.sendState?.forEach(({ eventType, stateKey }) =>\n widgetApi.requestCapabilityToSendState(eventType, stateKey),\n );\n capabilities.receiveState?.forEach(({ eventType, stateKey }) =>\n widgetApi.requestCapabilityToReceiveState(eventType, stateKey),\n );\n capabilities.sendToDevice?.forEach((eventType) => widgetApi.requestCapabilityToSendToDevice(eventType));\n capabilities.receiveToDevice?.forEach((eventType) => widgetApi.requestCapabilityToReceiveToDevice(eventType));\n if (capabilities.turnServers) {\n widgetApi.requestCapability(MatrixCapabilities.MSC3846TurnServers);\n }\n\n widgetApi.on(`action:${WidgetApiToWidgetAction.SendEvent}`, this.onEvent);\n widgetApi.on(`action:${WidgetApiToWidgetAction.SendToDevice}`, this.onToDevice);\n\n // Open communication with the host\n widgetApi.start();\n }\n\n public async startClient(opts: IStartClientOpts = {}): Promise {\n this.lifecycle = new AbortController();\n\n // Create our own user object artificially (instead of waiting for sync)\n // so it's always available, even if the user is not in any rooms etc.\n const userId = this.getUserId();\n if (userId) {\n this.store.storeUser(new User(userId));\n }\n\n // Even though we have no access token and cannot sync, the sync class\n // still has some valuable helper methods that we make use of, so we\n // instantiate it anyways\n if (opts.slidingSync) {\n this.syncApi = new SlidingSyncSdk(opts.slidingSync, this, opts, this.buildSyncApiOptions());\n } else {\n this.syncApi = new SyncApi(this, opts, this.buildSyncApiOptions());\n }\n\n this.room = this.syncApi.createRoom(this.roomId);\n this.store.storeRoom(this.room);\n\n await this.widgetApiReady;\n\n // Backfill the requested events\n // We only get the most recent event for every type + state key combo,\n // so it doesn't really matter what order we inject them in\n await Promise.all(\n this.capabilities.receiveState?.map(async ({ eventType, stateKey }) => {\n const rawEvents = await this.widgetApi.readStateEvents(eventType, undefined, stateKey, [this.roomId]);\n const events = rawEvents.map((rawEvent) => new MatrixEvent(rawEvent as Partial));\n\n await this.syncApi!.injectRoomEvents(this.room!, [], events);\n events.forEach((event) => {\n this.emit(ClientEvent.Event, event);\n logger.info(`Backfilled event ${event.getId()} ${event.getType()} ${event.getStateKey()}`);\n });\n }) ?? [],\n );\n this.setSyncState(SyncState.Syncing);\n logger.info(\"Finished backfilling events\");\n\n // Watch for TURN servers, if requested\n if (this.capabilities.turnServers) this.watchTurnServers();\n }\n\n public stopClient(): void {\n this.widgetApi.off(`action:${WidgetApiToWidgetAction.SendEvent}`, this.onEvent);\n this.widgetApi.off(`action:${WidgetApiToWidgetAction.SendToDevice}`, this.onToDevice);\n\n super.stopClient();\n this.lifecycle!.abort(); // Signal to other async tasks that the client has stopped\n }\n\n public async joinRoom(roomIdOrAlias: string): Promise {\n if (roomIdOrAlias === this.roomId) return this.room!;\n throw new Error(`Unknown room: ${roomIdOrAlias}`);\n }\n\n protected async encryptAndSendEvent(room: Room, event: MatrixEvent): Promise {\n let response: ISendEventFromWidgetResponseData;\n try {\n response = await this.widgetApi.sendRoomEvent(event.getType(), event.getContent(), room.roomId);\n } catch (e) {\n this.updatePendingEventStatus(room, event, EventStatus.NOT_SENT);\n throw e;\n }\n\n room.updatePendingEvent(event, EventStatus.SENT, response.event_id);\n return { event_id: response.event_id };\n }\n\n public async sendStateEvent(\n roomId: string,\n eventType: string,\n content: any,\n stateKey = \"\",\n ): Promise {\n return await this.widgetApi.sendStateEvent(eventType, stateKey, content, roomId);\n }\n\n public async sendToDevice(eventType: string, contentMap: SendToDeviceContentMap): Promise<{}> {\n await this.widgetApi.sendToDevice(eventType, false, recursiveMapToObject(contentMap));\n return {};\n }\n\n public async queueToDevice({ eventType, batch }: ToDeviceBatch): Promise {\n // map: user Id → device Id → payload\n const contentMap: MapWithDefault> = new MapWithDefault(() => new Map());\n for (const { userId, deviceId, payload } of batch) {\n contentMap.getOrCreate(userId).set(deviceId, payload);\n }\n\n await this.widgetApi.sendToDevice(eventType, false, recursiveMapToObject(contentMap));\n }\n\n public async encryptAndSendToDevices(userDeviceInfoArr: IOlmDevice[], payload: object): Promise {\n // map: user Id → device Id → payload\n const contentMap: MapWithDefault> = new MapWithDefault(() => new Map());\n for (const {\n userId,\n deviceInfo: { deviceId },\n } of userDeviceInfoArr) {\n contentMap.getOrCreate(userId).set(deviceId, payload);\n }\n\n await this.widgetApi.sendToDevice((payload as { type: string }).type, true, recursiveMapToObject(contentMap));\n }\n\n // Overridden since we get TURN servers automatically over the widget API,\n // and this method would otherwise complain about missing an access token\n public async checkTurnServers(): Promise {\n return this.turnServers.length > 0;\n }\n\n // Overridden since we 'sync' manually without the sync API\n public getSyncState(): SyncState | null {\n return this.syncState;\n }\n\n private setSyncState(state: SyncState): void {\n const oldState = this.syncState;\n this.syncState = state;\n this.emit(ClientEvent.Sync, state, oldState);\n }\n\n private async ack(ev: CustomEvent): Promise {\n await this.widgetApi.transport.reply(ev.detail, {});\n }\n\n private onEvent = async (ev: CustomEvent): Promise => {\n ev.preventDefault();\n\n // Verify the room ID matches, since it's possible for the client to\n // send us events from other rooms if this widget is always on screen\n if (ev.detail.data.room_id === this.roomId) {\n const event = new MatrixEvent(ev.detail.data as Partial);\n await this.syncApi!.injectRoomEvents(this.room!, [], [event]);\n this.emit(ClientEvent.Event, event);\n this.setSyncState(SyncState.Syncing);\n logger.info(`Received event ${event.getId()} ${event.getType()} ${event.getStateKey()}`);\n } else {\n const { event_id: eventId, room_id: roomId } = ev.detail.data;\n logger.info(`Received event ${eventId} for a different room ${roomId}; discarding`);\n }\n\n await this.ack(ev);\n };\n\n private onToDevice = async (ev: CustomEvent): Promise => {\n ev.preventDefault();\n\n const event = new MatrixEvent({\n type: ev.detail.data.type,\n sender: ev.detail.data.sender,\n content: ev.detail.data.content as IContent,\n });\n // Mark the event as encrypted if it was, using fake contents and keys since those are unknown to us\n if (ev.detail.data.encrypted) event.makeEncrypted(EventType.RoomMessageEncrypted, {}, \"\", \"\");\n\n this.emit(ClientEvent.ToDeviceEvent, event);\n this.setSyncState(SyncState.Syncing);\n await this.ack(ev);\n };\n\n private async watchTurnServers(): Promise {\n const servers = this.widgetApi.getTurnServers();\n const onClientStopped = (): void => {\n servers.return(undefined);\n };\n this.lifecycle!.signal.addEventListener(\"abort\", onClientStopped);\n\n try {\n for await (const server of servers) {\n this.turnServers = [\n {\n urls: server.uris,\n username: server.username,\n credential: server.password,\n },\n ];\n this.emit(ClientEvent.TurnServers, this.turnServers);\n logger.log(`Received TURN server: ${server.uris}`);\n }\n } catch (e) {\n logger.warn(\"Error watching TURN servers\", e);\n } finally {\n this.lifecycle!.signal.removeEventListener(\"abort\", onClientStopped);\n }\n }\n}\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport enum InvalidStoreState {\n ToggledLazyLoading,\n}\n\nexport class InvalidStoreError extends Error {\n public static TOGGLED_LAZY_LOADING = InvalidStoreState.ToggledLazyLoading;\n\n public constructor(public readonly reason: InvalidStoreState, public readonly value: any) {\n const message =\n `Store is invalid because ${reason}, ` +\n `please stop the client, delete all data and start the client again`;\n super(message);\n this.name = \"InvalidStoreError\";\n }\n}\n\nexport enum InvalidCryptoStoreState {\n TooNew = \"TOO_NEW\",\n}\n\nexport class InvalidCryptoStoreError extends Error {\n public static TOO_NEW = InvalidCryptoStoreState.TooNew;\n\n public constructor(public readonly reason: InvalidCryptoStoreState) {\n const message =\n `Crypto store is invalid because ${reason}, ` +\n `please stop the client, delete all data and start the client again`;\n super(message);\n this.name = \"InvalidCryptoStoreError\";\n }\n}\n\nexport class KeySignatureUploadError extends Error {\n public constructor(message: string, public readonly value: any) {\n super(message);\n }\n}\n", - "/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixClient } from \"./client\";\nimport { IEvent, MatrixEvent, MatrixEventEvent } from \"./models/event\";\nimport { RelationType } from \"./@types/event\";\n\nexport type EventMapper = (obj: Partial) => MatrixEvent;\n\nexport interface MapperOpts {\n // don't re-emit events emitted on an event mapped by this mapper on the client\n preventReEmit?: boolean;\n // decrypt event proactively\n decrypt?: boolean;\n // the event is a to_device event\n toDevice?: boolean;\n}\n\nexport function eventMapperFor(client: MatrixClient, options: MapperOpts): EventMapper {\n let preventReEmit = Boolean(options.preventReEmit);\n const decrypt = options.decrypt !== false;\n\n function mapper(plainOldJsObject: Partial): MatrixEvent {\n if (options.toDevice) {\n delete plainOldJsObject.room_id;\n }\n\n const room = client.getRoom(plainOldJsObject.room_id);\n\n let event: MatrixEvent | undefined;\n // If the event is already known to the room, let's re-use the model rather than duplicating.\n // We avoid doing this to state events as they may be forward or backwards looking which tweaks behaviour.\n if (room && plainOldJsObject.state_key === undefined) {\n event = room.findEventById(plainOldJsObject.event_id!);\n }\n\n if (!event || event.status) {\n event = new MatrixEvent(plainOldJsObject);\n } else {\n // merge the latest unsigned data from the server\n event.setUnsigned({ ...event.getUnsigned(), ...plainOldJsObject.unsigned });\n // prevent doubling up re-emitters\n preventReEmit = true;\n }\n\n // if there is a complete edit bundled alongside the event, perform the replacement.\n // (prior to MSC3925, events were automatically replaced on the server-side. MSC3925 proposes that that doesn't\n // happen automatically but the server does provide us with the whole content of the edit event.)\n const bundledEdit = event.getServerAggregatedRelation>(RelationType.Replace);\n if (bundledEdit?.content) {\n const replacement = mapper(bundledEdit);\n // XXX: it's worth noting that the spec says we should only respect encrypted edits if, once decrypted, the\n // replacement has a `m.new_content` property. The problem is that we haven't yet decrypted the replacement\n // (it should be happening in the background), so we can't enforce this. Possibly we should for decryption\n // to complete, but that sounds a bit racy. For now, we just assume it's ok.\n event.makeReplaced(replacement);\n }\n\n const thread = room?.findThreadForEvent(event);\n if (thread) {\n event.setThread(thread);\n }\n\n // TODO: once we get rid of the old libolm-backed crypto, we can restrict this to room events (rather than\n // to-device events), because the rust implementation decrypts to-device messages at a higher level.\n // Generally we probably want to use a different eventMapper implementation for to-device events because\n if (event.isEncrypted()) {\n if (!preventReEmit) {\n client.reEmitter.reEmit(event, [MatrixEventEvent.Decrypted]);\n }\n if (decrypt) {\n client.decryptEventIfNeeded(event);\n }\n }\n\n if (!preventReEmit) {\n client.reEmitter.reEmit(event, [MatrixEventEvent.Replaced, MatrixEventEvent.VisibilityChange]);\n room?.reEmitter.reEmit(event, [MatrixEventEvent.BeforeRedaction]);\n }\n return event;\n }\n\n return mapper;\n}\n", - "/*\nCopyright 2021 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { Optional } from \"matrix-events-sdk\";\n\n/**\n * Determines if the given optional was provided a value.\n * @param s - The optional to test.\n * @returns True if the value is defined.\n */\nexport function isProvided(s: Optional): boolean {\n return s !== null && s !== undefined;\n}\n\n/**\n * Determines if the given optional string is a defined string.\n * @param s - The input string.\n * @returns True if the input is a defined string.\n */\nexport function isOptionalAString(s: Optional): s is string {\n return isProvided(s) && typeof s === \"string\";\n}\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { IServerVersions } from \"./client\";\n\nexport enum ServerSupport {\n Stable,\n Unstable,\n Unsupported,\n}\n\nexport enum Feature {\n Thread = \"Thread\",\n ThreadUnreadNotifications = \"ThreadUnreadNotifications\",\n LoginTokenRequest = \"LoginTokenRequest\",\n RelationBasedRedactions = \"RelationBasedRedactions\",\n AccountDataDeletion = \"AccountDataDeletion\",\n}\n\ntype FeatureSupportCondition = {\n unstablePrefixes?: string[];\n matrixVersion?: string;\n};\n\nconst featureSupportResolver: Record = {\n [Feature.Thread]: {\n unstablePrefixes: [\"org.matrix.msc3440\"],\n matrixVersion: \"v1.3\",\n },\n [Feature.ThreadUnreadNotifications]: {\n unstablePrefixes: [\"org.matrix.msc3771\", \"org.matrix.msc3773\"],\n matrixVersion: \"v1.4\",\n },\n [Feature.LoginTokenRequest]: {\n unstablePrefixes: [\"org.matrix.msc3882\"],\n },\n [Feature.RelationBasedRedactions]: {\n unstablePrefixes: [\"org.matrix.msc3912\"],\n },\n [Feature.AccountDataDeletion]: {\n unstablePrefixes: [\"org.matrix.msc3391\"],\n },\n};\n\nexport async function buildFeatureSupportMap(versions: IServerVersions): Promise> {\n const supportMap = new Map();\n for (const [feature, supportCondition] of Object.entries(featureSupportResolver)) {\n const supportMatrixVersion = versions.versions?.includes(supportCondition.matrixVersion || \"\") ?? false;\n const supportUnstablePrefixes =\n supportCondition.unstablePrefixes?.every((unstablePrefix) => {\n return versions.unstable_features?.[unstablePrefix] === true;\n }) ?? false;\n if (supportMatrixVersion) {\n supportMap.set(feature as Feature, ServerSupport.Stable);\n } else if (supportUnstablePrefixes) {\n supportMap.set(feature as Feature, ServerSupport.Unstable);\n } else {\n supportMap.set(feature as Feature, ServerSupport.Unsupported);\n }\n }\n return supportMap;\n}\n", - "/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { RelationType } from \"./@types/event\";\nimport { MatrixEvent } from \"./models/event\";\nimport { FILTER_RELATED_BY_REL_TYPES, FILTER_RELATED_BY_SENDERS, THREAD_RELATION_TYPE } from \"./models/thread\";\n\n/**\n * Checks if a value matches a given field value, which may be a * terminated\n * wildcard pattern.\n * @param actualValue - The value to be compared\n * @param filterValue - The filter pattern to be compared\n * @returns true if the actualValue matches the filterValue\n */\nfunction matchesWildcard(actualValue: string, filterValue: string): boolean {\n if (filterValue.endsWith(\"*\")) {\n const typePrefix = filterValue.slice(0, -1);\n return actualValue.slice(0, typePrefix.length) === typePrefix;\n } else {\n return actualValue === filterValue;\n }\n}\n\n/* eslint-disable camelcase */\nexport interface IFilterComponent {\n \"types\"?: string[];\n \"not_types\"?: string[];\n \"rooms\"?: string[];\n \"not_rooms\"?: string[];\n \"senders\"?: string[];\n \"not_senders\"?: string[];\n \"contains_url\"?: boolean;\n \"limit\"?: number;\n \"related_by_senders\"?: Array;\n \"related_by_rel_types\"?: string[];\n\n // Unstable values\n \"io.element.relation_senders\"?: Array;\n \"io.element.relation_types\"?: string[];\n}\n/* eslint-enable camelcase */\n\n/**\n * FilterComponent is a section of a Filter definition which defines the\n * types, rooms, senders filters etc to be applied to a particular type of resource.\n * This is all ported over from synapse's Filter object.\n *\n * N.B. that synapse refers to these as 'Filters', and what js-sdk refers to as\n * 'Filters' are referred to as 'FilterCollections'.\n */\nexport class FilterComponent {\n public constructor(private filterJson: IFilterComponent, public readonly userId?: string | undefined | null) {}\n\n /**\n * Checks with the filter component matches the given event\n * @param event - event to be checked against the filter\n * @returns true if the event matches the filter\n */\n public check(event: MatrixEvent): boolean {\n const bundledRelationships = event.getUnsigned()?.[\"m.relations\"] || {};\n const relations: Array = Object.keys(bundledRelationships);\n // Relation senders allows in theory a look-up of any senders\n // however clients can only know about the current user participation status\n // as sending a whole list of participants could be proven problematic in terms\n // of performance\n // This should be improved when bundled relationships solve that problem\n const relationSenders: string[] = [];\n if (this.userId && bundledRelationships?.[THREAD_RELATION_TYPE.name]?.current_user_participated) {\n relationSenders.push(this.userId);\n }\n\n return this.checkFields(\n event.getRoomId(),\n event.getSender(),\n event.getType(),\n event.getContent() ? event.getContent().url !== undefined : false,\n relations,\n relationSenders,\n );\n }\n\n /**\n * Converts the filter component into the form expected over the wire\n */\n public toJSON(): object {\n return {\n types: this.filterJson.types || null,\n not_types: this.filterJson.not_types || [],\n rooms: this.filterJson.rooms || null,\n not_rooms: this.filterJson.not_rooms || [],\n senders: this.filterJson.senders || null,\n not_senders: this.filterJson.not_senders || [],\n contains_url: this.filterJson.contains_url || null,\n [FILTER_RELATED_BY_SENDERS.name]: this.filterJson[FILTER_RELATED_BY_SENDERS.name] || [],\n [FILTER_RELATED_BY_REL_TYPES.name]: this.filterJson[FILTER_RELATED_BY_REL_TYPES.name] || [],\n };\n }\n\n /**\n * Checks whether the filter component matches the given event fields.\n * @param roomId - the roomId for the event being checked\n * @param sender - the sender of the event being checked\n * @param eventType - the type of the event being checked\n * @param containsUrl - whether the event contains a content.url field\n * @param relationTypes - whether has aggregated relation of the given type\n * @param relationSenders - whether one of the relation is sent by the user listed\n * @returns true if the event fields match the filter\n */\n private checkFields(\n roomId: string | undefined,\n sender: string | undefined,\n eventType: string,\n containsUrl: boolean,\n relationTypes: Array,\n relationSenders: string[],\n ): boolean {\n const literalKeys = {\n rooms: function (v: string): boolean {\n return roomId === v;\n },\n senders: function (v: string): boolean {\n return sender === v;\n },\n types: function (v: string): boolean {\n return matchesWildcard(eventType, v);\n },\n } as const;\n\n for (const name in literalKeys) {\n const matchFunc = literalKeys[name];\n const notName = \"not_\" + name;\n const disallowedValues = this.filterJson[<`not_${keyof typeof literalKeys}`>notName];\n if (disallowedValues?.some(matchFunc)) {\n return false;\n }\n\n const allowedValues = this.filterJson[name as keyof typeof literalKeys];\n if (allowedValues && !allowedValues.some(matchFunc)) {\n return false;\n }\n }\n\n const containsUrlFilter = this.filterJson.contains_url;\n if (containsUrlFilter !== undefined && containsUrlFilter !== containsUrl) {\n return false;\n }\n\n const relationTypesFilter = this.filterJson[FILTER_RELATED_BY_REL_TYPES.name];\n if (relationTypesFilter !== undefined) {\n if (!this.arrayMatchesFilter(relationTypesFilter, relationTypes)) {\n return false;\n }\n }\n\n const relationSendersFilter = this.filterJson[FILTER_RELATED_BY_SENDERS.name];\n if (relationSendersFilter !== undefined) {\n if (!this.arrayMatchesFilter(relationSendersFilter, relationSenders)) {\n return false;\n }\n }\n\n return true;\n }\n\n private arrayMatchesFilter(filter: any[], values: any[]): boolean {\n return (\n values.length > 0 &&\n filter.every((value) => {\n return values.includes(value);\n })\n );\n }\n\n /**\n * Filters a list of events down to those which match this filter component\n * @param events - Events to be checked against the filter component\n * @returns events which matched the filter component\n */\n public filter(events: MatrixEvent[]): MatrixEvent[] {\n return events.filter(this.check, this);\n }\n\n /**\n * Returns the limit field for a given filter component, providing a default of\n * 10 if none is otherwise specified. Cargo-culted from Synapse.\n * @returns the limit for this filter component.\n */\n public limit(): number {\n return this.filterJson.limit !== undefined ? this.filterJson.limit : 10;\n }\n}\n", - "/*\nCopyright 2015 - 2021 Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventType, RelationType } from \"./@types/event\";\nimport { UNREAD_THREAD_NOTIFICATIONS } from \"./@types/sync\";\nimport { FilterComponent, IFilterComponent } from \"./filter-component\";\nimport { MatrixEvent } from \"./models/event\";\n\n/**\n */\nfunction setProp(obj: Record, keyNesting: string, val: any): void {\n const nestedKeys = keyNesting.split(\".\") as [keyof typeof obj];\n let currentObj = obj;\n for (let i = 0; i < nestedKeys.length - 1; i++) {\n if (!currentObj[nestedKeys[i]]) {\n currentObj[nestedKeys[i]] = {};\n }\n currentObj = currentObj[nestedKeys[i]];\n }\n currentObj[nestedKeys[nestedKeys.length - 1]] = val;\n}\n\n/* eslint-disable camelcase */\nexport interface IFilterDefinition {\n event_fields?: string[];\n event_format?: \"client\" | \"federation\";\n presence?: IFilterComponent;\n account_data?: IFilterComponent;\n room?: IRoomFilter;\n}\n\nexport interface IRoomEventFilter extends IFilterComponent {\n \"lazy_load_members\"?: boolean;\n \"include_redundant_members\"?: boolean;\n \"types\"?: Array;\n \"related_by_senders\"?: Array;\n \"related_by_rel_types\"?: string[];\n \"unread_thread_notifications\"?: boolean;\n \"org.matrix.msc3773.unread_thread_notifications\"?: boolean;\n\n // Unstable values\n \"io.element.relation_senders\"?: Array;\n \"io.element.relation_types\"?: string[];\n}\n\ninterface IStateFilter extends IRoomEventFilter {}\n\ninterface IRoomFilter {\n not_rooms?: string[];\n rooms?: string[];\n ephemeral?: IRoomEventFilter;\n include_leave?: boolean;\n state?: IStateFilter;\n timeline?: IRoomEventFilter;\n account_data?: IRoomEventFilter;\n}\n/* eslint-enable camelcase */\n\nexport class Filter {\n public static LAZY_LOADING_MESSAGES_FILTER = {\n lazy_load_members: true,\n };\n\n /**\n * Create a filter from existing data.\n */\n public static fromJson(userId: string | undefined | null, filterId: string, jsonObj: IFilterDefinition): Filter {\n const filter = new Filter(userId, filterId);\n filter.setDefinition(jsonObj);\n return filter;\n }\n\n private definition: IFilterDefinition = {};\n private roomFilter?: FilterComponent;\n private roomTimelineFilter?: FilterComponent;\n\n /**\n * Construct a new Filter.\n * @param userId - The user ID for this filter.\n * @param filterId - The filter ID if known.\n */\n public constructor(public readonly userId: string | undefined | null, public filterId?: string) {}\n\n /**\n * Get the ID of this filter on your homeserver (if known)\n * @returns The filter ID\n */\n public getFilterId(): string | undefined {\n return this.filterId;\n }\n\n /**\n * Get the JSON body of the filter.\n * @returns The filter definition\n */\n public getDefinition(): IFilterDefinition {\n return this.definition;\n }\n\n /**\n * Set the JSON body of the filter\n * @param definition - The filter definition\n */\n public setDefinition(definition: IFilterDefinition): void {\n this.definition = definition;\n\n // This is all ported from synapse's FilterCollection()\n\n // definitions look something like:\n // {\n // \"room\": {\n // \"rooms\": [\"!abcde:example.com\"],\n // \"not_rooms\": [\"!123456:example.com\"],\n // \"state\": {\n // \"types\": [\"m.room.*\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"lazy_load_members\": true,\n // },\n // \"timeline\": {\n // \"limit\": 10,\n // \"types\": [\"m.room.message\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"not_senders\": [\"@spam:example.com\"]\n // \"contains_url\": true\n // },\n // \"ephemeral\": {\n // \"types\": [\"m.receipt\", \"m.typing\"],\n // \"not_rooms\": [\"!726s6s6q:example.com\"],\n // \"not_senders\": [\"@spam:example.com\"]\n // }\n // },\n // \"presence\": {\n // \"types\": [\"m.presence\"],\n // \"not_senders\": [\"@alice:example.com\"]\n // },\n // \"event_format\": \"client\",\n // \"event_fields\": [\"type\", \"content\", \"sender\"]\n // }\n\n const roomFilterJson = definition.room;\n\n // consider the top level rooms/not_rooms filter\n const roomFilterFields: IRoomFilter = {};\n if (roomFilterJson) {\n if (roomFilterJson.rooms) {\n roomFilterFields.rooms = roomFilterJson.rooms;\n }\n if (roomFilterJson.rooms) {\n roomFilterFields.not_rooms = roomFilterJson.not_rooms;\n }\n }\n\n this.roomFilter = new FilterComponent(roomFilterFields, this.userId);\n this.roomTimelineFilter = new FilterComponent(roomFilterJson?.timeline || {}, this.userId);\n\n // don't bother porting this from synapse yet:\n // this._room_state_filter =\n // new FilterComponent(roomFilterJson.state || {});\n // this._room_ephemeral_filter =\n // new FilterComponent(roomFilterJson.ephemeral || {});\n // this._room_account_data_filter =\n // new FilterComponent(roomFilterJson.account_data || {});\n // this._presence_filter =\n // new FilterComponent(definition.presence || {});\n // this._account_data_filter =\n // new FilterComponent(definition.account_data || {});\n }\n\n /**\n * Get the room.timeline filter component of the filter\n * @returns room timeline filter component\n */\n public getRoomTimelineFilterComponent(): FilterComponent | undefined {\n return this.roomTimelineFilter;\n }\n\n /**\n * Filter the list of events based on whether they are allowed in a timeline\n * based on this filter\n * @param events - the list of events being filtered\n * @returns the list of events which match the filter\n */\n public filterRoomTimeline(events: MatrixEvent[]): MatrixEvent[] {\n if (this.roomFilter) {\n events = this.roomFilter.filter(events);\n }\n if (this.roomTimelineFilter) {\n events = this.roomTimelineFilter.filter(events);\n }\n return events;\n }\n\n /**\n * Set the max number of events to return for each room's timeline.\n * @param limit - The max number of events to return for each room.\n */\n public setTimelineLimit(limit: number): void {\n setProp(this.definition, \"room.timeline.limit\", limit);\n }\n\n /**\n * Enable threads unread notification\n */\n public setUnreadThreadNotifications(enabled: boolean): void {\n this.definition = {\n ...this.definition,\n room: {\n ...this.definition?.room,\n timeline: {\n ...this.definition?.room?.timeline,\n [UNREAD_THREAD_NOTIFICATIONS.name]: enabled,\n },\n },\n };\n }\n\n public setLazyLoadMembers(enabled: boolean): void {\n setProp(this.definition, \"room.state.lazy_load_members\", enabled);\n }\n\n /**\n * Control whether left rooms should be included in responses.\n * @param includeLeave - True to make rooms the user has left appear\n * in responses.\n */\n public setIncludeLeaveRooms(includeLeave: boolean): void {\n setProp(this.definition, \"room.include_leave\", includeLeave);\n }\n}\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { IUsageLimit } from \"../@types/partials\";\nimport { MatrixEvent } from \"../models/event\";\n\ninterface IErrorJson extends Partial {\n [key: string]: any; // extensible\n errcode?: string;\n error?: string;\n}\n\n/**\n * Construct a generic HTTP error. This is a JavaScript Error with additional information\n * specific to HTTP responses.\n * @param msg - The error message to include.\n * @param httpStatus - The HTTP response status code.\n */\nexport class HTTPError extends Error {\n public constructor(msg: string, public readonly httpStatus?: number) {\n super(msg);\n }\n}\n\nexport class MatrixError extends HTTPError {\n // The Matrix 'errcode' value, e.g. \"M_FORBIDDEN\".\n public readonly errcode?: string;\n // The raw Matrix error JSON used to construct this object.\n public data: IErrorJson;\n\n /**\n * Construct a Matrix error. This is a JavaScript Error with additional\n * information specific to the standard Matrix error response.\n * @param errorJson - The Matrix error JSON returned from the homeserver.\n * @param httpStatus - The numeric HTTP status code given\n */\n public constructor(\n errorJson: IErrorJson = {},\n public readonly httpStatus?: number,\n public url?: string,\n public event?: MatrixEvent,\n ) {\n let message = errorJson.error || \"Unknown message\";\n if (httpStatus) {\n message = `[${httpStatus}] ${message}`;\n }\n if (url) {\n message = `${message} (${url})`;\n }\n super(`MatrixError: ${message}`, httpStatus);\n this.errcode = errorJson.errcode;\n this.name = errorJson.errcode || \"Unknown error code\";\n this.data = errorJson;\n }\n}\n\n/**\n * Construct a ConnectionError. This is a JavaScript Error indicating\n * that a request failed because of some error with the connection, either\n * CORS was not correctly configured on the server, the server didn't response,\n * the request timed out, or the internet connection on the client side went down.\n */\nexport class ConnectionError extends Error {\n public constructor(message: string, cause?: Error) {\n super(message + (cause ? `: ${cause.message}` : \"\"));\n }\n\n public get name(): string {\n return \"ConnectionError\";\n }\n}\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixHttpApi} for the public class.\n */\n\nimport * as utils from \"../utils\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter\";\nimport { Method } from \"./method\";\nimport { ConnectionError, MatrixError } from \"./errors\";\nimport { HttpApiEvent, HttpApiEventHandlerMap, IHttpOpts, IRequestOpts } from \"./interface\";\nimport { anySignal, parseErrorResponse, timeoutSignal } from \"./utils\";\nimport { QueryDict } from \"../utils\";\n\ntype Body = Record | BodyInit;\n\ninterface TypedResponse extends Response {\n json(): Promise;\n}\n\nexport type ResponseType = O extends undefined\n ? T\n : O extends { onlyData: true }\n ? T\n : TypedResponse;\n\nexport class FetchHttpApi {\n private abortController = new AbortController();\n\n public constructor(\n private eventEmitter: TypedEventEmitter,\n public readonly opts: O,\n ) {\n utils.checkObjectHasKeys(opts, [\"baseUrl\", \"prefix\"]);\n opts.onlyData = !!opts.onlyData;\n opts.useAuthorizationHeader = opts.useAuthorizationHeader ?? true;\n }\n\n public abort(): void {\n this.abortController.abort();\n this.abortController = new AbortController();\n }\n\n public fetch(resource: URL | string, options?: RequestInit): ReturnType {\n if (this.opts.fetchFn) {\n return this.opts.fetchFn(resource, options);\n }\n return global.fetch(resource, options);\n }\n\n /**\n * Sets the base URL for the identity server\n * @param url - The new base url\n */\n public setIdBaseUrl(url: string): void {\n this.opts.idBaseUrl = url;\n }\n\n public idServerRequest>(\n method: Method,\n path: string,\n params: Record | undefined,\n prefix: string,\n accessToken?: string,\n ): Promise> {\n if (!this.opts.idBaseUrl) {\n throw new Error(\"No identity server base URL set\");\n }\n\n let queryParams: QueryDict | undefined = undefined;\n let body: Record | undefined = undefined;\n if (method === Method.Get) {\n queryParams = params;\n } else {\n body = params;\n }\n\n const fullUri = this.getUrl(path, queryParams, prefix, this.opts.idBaseUrl);\n\n const opts: IRequestOpts = {\n json: true,\n headers: {},\n };\n if (accessToken) {\n opts.headers!.Authorization = `Bearer ${accessToken}`;\n }\n\n return this.requestOtherUrl(method, fullUri, body, opts);\n }\n\n /**\n * Perform an authorised request to the homeserver.\n * @param method - The HTTP method e.g. \"GET\".\n * @param path - The HTTP path after the supplied prefix e.g.\n * \"/createRoom\".\n *\n * @param queryParams - A dict of query params (these will NOT be\n * urlencoded). If unspecified, there will be no query params.\n *\n * @param body - The HTTP JSON body.\n *\n * @param opts - additional options. If a number is specified,\n * this is treated as `opts.localTimeoutMs`.\n *\n * @returns Promise which resolves to\n * ```\n * {\n * data: {Object},\n * headers: {Object},\n * code: {Number},\n * }\n * ```\n * If `onlyData` is set, this will resolve to the `data` object only.\n * @returns Rejects with an error if a problem occurred.\n * This includes network problems and Matrix-specific error JSON.\n */\n public authedRequest(\n method: Method,\n path: string,\n queryParams?: QueryDict,\n body?: Body,\n opts: IRequestOpts = {},\n ): Promise> {\n if (!queryParams) queryParams = {};\n\n if (this.opts.accessToken) {\n if (this.opts.useAuthorizationHeader) {\n if (!opts.headers) {\n opts.headers = {};\n }\n if (!opts.headers.Authorization) {\n opts.headers.Authorization = \"Bearer \" + this.opts.accessToken;\n }\n if (queryParams.access_token) {\n delete queryParams.access_token;\n }\n } else if (!queryParams.access_token) {\n queryParams.access_token = this.opts.accessToken;\n }\n }\n\n const requestPromise = this.request(method, path, queryParams, body, opts);\n\n requestPromise.catch((err: MatrixError) => {\n if (err.errcode == \"M_UNKNOWN_TOKEN\" && !opts?.inhibitLogoutEmit) {\n this.eventEmitter.emit(HttpApiEvent.SessionLoggedOut, err);\n } else if (err.errcode == \"M_CONSENT_NOT_GIVEN\") {\n this.eventEmitter.emit(HttpApiEvent.NoConsent, err.message, err.data.consent_uri);\n }\n });\n\n // return the original promise, otherwise tests break due to it having to\n // go around the event loop one more time to process the result of the request\n return requestPromise;\n }\n\n /**\n * Perform a request to the homeserver without any credentials.\n * @param method - The HTTP method e.g. \"GET\".\n * @param path - The HTTP path after the supplied prefix e.g.\n * \"/createRoom\".\n *\n * @param queryParams - A dict of query params (these will NOT be\n * urlencoded). If unspecified, there will be no query params.\n *\n * @param body - The HTTP JSON body.\n *\n * @param opts - additional options\n *\n * @returns Promise which resolves to\n * ```\n * {\n * data: {Object},\n * headers: {Object},\n * code: {Number},\n * }\n * ```\n * If `onlyData
is set, this will resolve to the data`\n * object only.\n * @returns Rejects with an error if a problem\n * occurred. This includes network problems and Matrix-specific error JSON.\n */\n public request(\n method: Method,\n path: string,\n queryParams?: QueryDict,\n body?: Body,\n opts?: IRequestOpts,\n ): Promise> {\n const fullUri = this.getUrl(path, queryParams, opts?.prefix, opts?.baseUrl);\n return this.requestOtherUrl(method, fullUri, body, opts);\n }\n\n /**\n * Perform a request to an arbitrary URL.\n * @param method - The HTTP method e.g. \"GET\".\n * @param url - The HTTP URL object.\n *\n * @param body - The HTTP JSON body.\n *\n * @param opts - additional options\n *\n * @returns Promise which resolves to data unless `onlyData` is specified as false,\n * where the resolved value will be a fetch Response object.\n * @returns Rejects with an error if a problem\n * occurred. This includes network problems and Matrix-specific error JSON.\n */\n public async requestOtherUrl(\n method: Method,\n url: URL | string,\n body?: Body,\n opts: Pick = {},\n ): Promise> {\n const headers = Object.assign({}, opts.headers || {});\n const json = opts.json ?? true;\n // We can't use getPrototypeOf here as objects made in other contexts e.g. over postMessage won't have same ref\n const jsonBody = json && body?.constructor?.name === Object.name;\n\n if (json) {\n if (jsonBody && !headers[\"Content-Type\"]) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n\n if (!headers[\"Accept\"]) {\n headers[\"Accept\"] = \"application/json\";\n }\n }\n\n const timeout = opts.localTimeoutMs ?? this.opts.localTimeoutMs;\n const keepAlive = opts.keepAlive ?? false;\n const signals = [this.abortController.signal];\n if (timeout !== undefined) {\n signals.push(timeoutSignal(timeout));\n }\n if (opts.abortSignal) {\n signals.push(opts.abortSignal);\n }\n\n let data: BodyInit;\n if (jsonBody) {\n data = JSON.stringify(body);\n } else {\n data = body as BodyInit;\n }\n\n const { signal, cleanup } = anySignal(signals);\n\n let res: Response;\n try {\n res = await this.fetch(url, {\n signal,\n method,\n body: data,\n headers,\n mode: \"cors\",\n redirect: \"follow\",\n referrer: \"\",\n referrerPolicy: \"no-referrer\",\n cache: \"no-cache\",\n credentials: \"omit\", // we send credentials via headers\n keepalive: keepAlive,\n });\n } catch (e) {\n if ((e).name === \"AbortError\") {\n throw e;\n }\n throw new ConnectionError(\"fetch failed\", e);\n } finally {\n cleanup();\n }\n\n if (!res.ok) {\n throw parseErrorResponse(res, await res.text());\n }\n\n if (this.opts.onlyData) {\n return json ? res.json() : res.text();\n }\n return res as ResponseType;\n }\n\n /**\n * Form and return a homeserver request URL based on the given path params and prefix.\n * @param path - The HTTP path after the supplied prefix e.g. \"/createRoom\".\n * @param queryParams - A dict of query params (these will NOT be urlencoded).\n * @param prefix - The full prefix to use e.g. \"/_matrix/client/v2_alpha\", defaulting to this.opts.prefix.\n * @param baseUrl - The baseUrl to use e.g. \"https://matrix.org/\", defaulting to this.opts.baseUrl.\n * @returns URL\n */\n public getUrl(path: string, queryParams?: QueryDict, prefix?: string, baseUrl?: string): URL {\n const url = new URL((baseUrl ?? this.opts.baseUrl) + (prefix ?? this.opts.prefix) + path);\n if (queryParams) {\n utils.encodeParams(queryParams, url.searchParams);\n }\n return url;\n }\n}\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { FetchHttpApi } from \"./fetch\";\nimport { FileType, IContentUri, IHttpOpts, Upload, UploadOpts, UploadResponse } from \"./interface\";\nimport { MediaPrefix } from \"./prefix\";\nimport * as utils from \"../utils\";\nimport * as callbacks from \"../realtime-callbacks\";\nimport { Method } from \"./method\";\nimport { ConnectionError } from \"./errors\";\nimport { parseErrorResponse } from \"./utils\";\n\nexport * from \"./interface\";\nexport * from \"./prefix\";\nexport * from \"./errors\";\nexport * from \"./method\";\nexport * from \"./utils\";\n\nexport class MatrixHttpApi extends FetchHttpApi {\n private uploads: Upload[] = [];\n\n /**\n * Upload content to the homeserver\n *\n * @param file - The object to upload. On a browser, something that\n * can be sent to XMLHttpRequest.send (typically a File). Under node.js,\n * a Buffer, String or ReadStream.\n *\n * @param opts - options object\n *\n * @returns Promise which resolves to response object, as\n * determined by this.opts.onlyData, opts.rawResponse, and\n * opts.onlyContentUri. Rejects with an error (usually a MatrixError).\n */\n public uploadContent(file: FileType, opts: UploadOpts = {}): Promise {\n const includeFilename = opts.includeFilename ?? true;\n const abortController = opts.abortController ?? new AbortController();\n\n // If the file doesn't have a mime type, use a default since the HS errors if we don't supply one.\n const contentType = opts.type ?? (file as File).type ?? \"application/octet-stream\";\n const fileName = opts.name ?? (file as File).name;\n\n const upload = {\n loaded: 0,\n total: 0,\n abortController,\n } as Upload;\n const defer = utils.defer();\n\n if (global.XMLHttpRequest) {\n const xhr = new global.XMLHttpRequest();\n\n const timeoutFn = function (): void {\n xhr.abort();\n defer.reject(new Error(\"Timeout\"));\n };\n\n // set an initial timeout of 30s; we'll advance it each time we get a progress notification\n let timeoutTimer = callbacks.setTimeout(timeoutFn, 30000);\n\n xhr.onreadystatechange = function (): void {\n switch (xhr.readyState) {\n case global.XMLHttpRequest.DONE:\n callbacks.clearTimeout(timeoutTimer);\n try {\n if (xhr.status === 0) {\n throw new DOMException(xhr.statusText, \"AbortError\"); // mimic fetch API\n }\n if (!xhr.responseText) {\n throw new Error(\"No response body.\");\n }\n\n if (xhr.status >= 400) {\n defer.reject(parseErrorResponse(xhr, xhr.responseText));\n } else {\n defer.resolve(JSON.parse(xhr.responseText));\n }\n } catch (err) {\n if ((err).name === \"AbortError\") {\n defer.reject(err);\n return;\n }\n defer.reject(new ConnectionError(\"request failed\", err));\n }\n break;\n }\n };\n\n xhr.upload.onprogress = (ev: ProgressEvent): void => {\n callbacks.clearTimeout(timeoutTimer);\n upload.loaded = ev.loaded;\n upload.total = ev.total;\n timeoutTimer = callbacks.setTimeout(timeoutFn, 30000);\n opts.progressHandler?.({\n loaded: ev.loaded,\n total: ev.total,\n });\n };\n\n const url = this.getUrl(\"/upload\", undefined, MediaPrefix.R0);\n\n if (includeFilename && fileName) {\n url.searchParams.set(\"filename\", encodeURIComponent(fileName));\n }\n\n if (!this.opts.useAuthorizationHeader && this.opts.accessToken) {\n url.searchParams.set(\"access_token\", encodeURIComponent(this.opts.accessToken));\n }\n\n xhr.open(Method.Post, url.href);\n if (this.opts.useAuthorizationHeader && this.opts.accessToken) {\n xhr.setRequestHeader(\"Authorization\", \"Bearer \" + this.opts.accessToken);\n }\n xhr.setRequestHeader(\"Content-Type\", contentType);\n xhr.send(file);\n\n abortController.signal.addEventListener(\"abort\", () => {\n xhr.abort();\n });\n } else {\n const queryParams: utils.QueryDict = {};\n if (includeFilename && fileName) {\n queryParams.filename = fileName;\n }\n\n const headers: Record = { \"Content-Type\": contentType };\n\n this.authedRequest(Method.Post, \"/upload\", queryParams, file, {\n prefix: MediaPrefix.R0,\n headers,\n abortSignal: abortController.signal,\n })\n .then((response) => {\n return this.opts.onlyData ? response : response.json();\n })\n .then(defer.resolve, defer.reject);\n }\n\n // remove the upload from the list on completion\n upload.promise = defer.promise.finally(() => {\n utils.removeElement(this.uploads, (elem) => elem === upload);\n });\n abortController.signal.addEventListener(\"abort\", () => {\n utils.removeElement(this.uploads, (elem) => elem === upload);\n defer.reject(new DOMException(\"Aborted\", \"AbortError\"));\n });\n this.uploads.push(upload);\n return upload.promise;\n }\n\n public cancelUpload(promise: Promise): boolean {\n const upload = this.uploads.find((u) => u.promise === promise);\n if (upload) {\n upload.abortController.abort();\n return true;\n }\n return false;\n }\n\n public getCurrentUploads(): Upload[] {\n return this.uploads;\n }\n\n /**\n * Get the content repository url with query parameters.\n * @returns An object with a 'base', 'path' and 'params' for base URL,\n * path and query parameters respectively.\n */\n public getContentUri(): IContentUri {\n return {\n base: this.opts.baseUrl,\n path: MediaPrefix.R0 + \"/upload\",\n params: {\n access_token: this.opts.accessToken!,\n },\n };\n }\n}\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixError } from \"./errors\";\n\nexport interface IHttpOpts {\n fetchFn?: typeof global.fetch;\n\n baseUrl: string;\n idBaseUrl?: string;\n prefix: string;\n extraParams?: Record;\n\n accessToken?: string;\n useAuthorizationHeader?: boolean; // defaults to true\n\n onlyData?: boolean;\n localTimeoutMs?: number;\n}\n\nexport interface IRequestOpts {\n /**\n * The alternative base url to use.\n * If not specified, uses this.opts.baseUrl\n */\n baseUrl?: string;\n /**\n * The full prefix to use e.g.\n * \"/_matrix/client/v2_alpha\". If not specified, uses this.opts.prefix.\n */\n prefix?: string;\n /**\n * map of additional request headers\n */\n headers?: Record;\n abortSignal?: AbortSignal;\n /**\n * The maximum amount of time to wait before\n * timing out the request. If not specified, there is no timeout.\n */\n localTimeoutMs?: number;\n keepAlive?: boolean; // defaults to false\n json?: boolean; // defaults to true\n\n // Set to true to prevent the request function from emitting a Session.logged_out event.\n // This is intended for use on endpoints where M_UNKNOWN_TOKEN is a valid/notable error response,\n // such as with token refreshes.\n inhibitLogoutEmit?: boolean;\n}\n\nexport interface IContentUri {\n base: string;\n path: string;\n params: {\n // eslint-disable-next-line camelcase\n access_token: string;\n };\n}\n\nexport enum HttpApiEvent {\n SessionLoggedOut = \"Session.logged_out\",\n NoConsent = \"no_consent\",\n}\n\nexport type HttpApiEventHandlerMap = {\n /**\n * Fires whenever the login session the JS SDK is using is no\n * longer valid and the user must log in again.\n * NB. This only fires when action is required from the user, not\n * when then login session can be renewed by using a refresh token.\n * @example\n * ```\n * matrixClient.on(\"Session.logged_out\", function(errorObj){\n * // show the login screen\n * });\n * ```\n */\n [HttpApiEvent.SessionLoggedOut]: (err: MatrixError) => void;\n /**\n * Fires when the JS SDK receives a M_CONSENT_NOT_GIVEN error in response\n * to a HTTP request.\n * @example\n * ```\n * matrixClient.on(\"no_consent\", function(message, contentUri) {\n * console.info(message + ' Go to ' + contentUri);\n * });\n * ```\n */\n [HttpApiEvent.NoConsent]: (message: string, consentUri: string) => void;\n};\n\nexport interface UploadProgress {\n loaded: number;\n total: number;\n}\n\nexport interface UploadOpts {\n /**\n * Name to give the file on the server. Defaults to file.name.\n */\n name?: string;\n /**\n * Content-type for the upload. Defaults to\n * file.type, or applicaton/octet-stream.\n */\n type?: string;\n /**\n * if false will not send the filename,\n * e.g for encrypted file uploads where filename leaks are undesirable.\n * Defaults to true.\n */\n includeFilename?: boolean;\n /**\n * Optional. Called when a chunk of\n * data has been uploaded, with an object containing the fields `loaded`\n * (number of bytes transferred) and `total` (total size, if known).\n */\n progressHandler?(progress: UploadProgress): void;\n abortController?: AbortController;\n}\n\nexport interface Upload {\n loaded: number;\n total: number;\n promise: Promise;\n abortController: AbortController;\n}\n\nexport interface UploadResponse {\n // eslint-disable-next-line camelcase\n content_uri: string;\n}\n\nexport type FileType = XMLHttpRequestBodyInit;\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport enum Method {\n Get = \"GET\",\n Put = \"PUT\",\n Post = \"POST\",\n Delete = \"DELETE\",\n}\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport enum ClientPrefix {\n /**\n * A constant representing the URI path for release 0 of the Client-Server HTTP API.\n */\n R0 = \"/_matrix/client/r0\",\n /**\n * A constant representing the URI path for the legacy release v1 of the Client-Server HTTP API.\n */\n V1 = \"/_matrix/client/v1\",\n /**\n * A constant representing the URI path for Client-Server API endpoints versioned at v3.\n */\n V3 = \"/_matrix/client/v3\",\n /**\n * A constant representing the URI path for as-yet unspecified Client-Server HTTP APIs.\n */\n Unstable = \"/_matrix/client/unstable\",\n}\n\nexport enum IdentityPrefix {\n /**\n * URI path for the v2 identity API\n */\n V2 = \"/_matrix/identity/v2\",\n}\n\nexport enum MediaPrefix {\n /**\n * URI path for the media repo API\n */\n R0 = \"/_matrix/media/r0\",\n}\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { parse as parseContentType, ParsedMediaType } from \"content-type\";\n\nimport { logger } from \"../logger\";\nimport { sleep } from \"../utils\";\nimport { ConnectionError, HTTPError, MatrixError } from \"./errors\";\n\n// Ponyfill for https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout\nexport function timeoutSignal(ms: number): AbortSignal {\n const controller = new AbortController();\n setTimeout(() => {\n controller.abort();\n }, ms);\n\n return controller.signal;\n}\n\nexport function anySignal(signals: AbortSignal[]): {\n signal: AbortSignal;\n cleanup(): void;\n} {\n const controller = new AbortController();\n\n function cleanup(): void {\n for (const signal of signals) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n }\n\n function onAbort(): void {\n controller.abort();\n cleanup();\n }\n\n for (const signal of signals) {\n if (signal.aborted) {\n onAbort();\n break;\n }\n signal.addEventListener(\"abort\", onAbort);\n }\n\n return {\n signal: controller.signal,\n cleanup,\n };\n}\n\n/**\n * Attempt to turn an HTTP error response into a Javascript Error.\n *\n * If it is a JSON response, we will parse it into a MatrixError. Otherwise\n * we return a generic Error.\n *\n * @param response - response object\n * @param body - raw body of the response\n * @returns\n */\nexport function parseErrorResponse(response: XMLHttpRequest | Response, body?: string): Error {\n let contentType: ParsedMediaType | null;\n try {\n contentType = getResponseContentType(response);\n } catch (e) {\n return e;\n }\n\n if (contentType?.type === \"application/json\" && body) {\n return new MatrixError(\n JSON.parse(body),\n response.status,\n isXhr(response) ? response.responseURL : response.url,\n );\n }\n if (contentType?.type === \"text/plain\") {\n return new HTTPError(`Server returned ${response.status} error: ${body}`, response.status);\n }\n return new HTTPError(`Server returned ${response.status} error`, response.status);\n}\n\nfunction isXhr(response: XMLHttpRequest | Response): response is XMLHttpRequest {\n return \"getResponseHeader\" in response;\n}\n\n/**\n * extract the Content-Type header from the response object, and\n * parse it to a `{type, parameters}` object.\n *\n * returns null if no content-type header could be found.\n *\n * @param response - response object\n * @returns parsed content-type header, or null if not found\n */\nfunction getResponseContentType(response: XMLHttpRequest | Response): ParsedMediaType | null {\n let contentType: string | null;\n if (isXhr(response)) {\n contentType = response.getResponseHeader(\"Content-Type\");\n } else {\n contentType = response.headers.get(\"Content-Type\");\n }\n\n if (!contentType) return null;\n\n try {\n return parseContentType(contentType);\n } catch (e) {\n throw new Error(`Error parsing Content-Type '${contentType}': ${e}`);\n }\n}\n\n/**\n * Retries a network operation run in a callback.\n * @param maxAttempts - maximum attempts to try\n * @param callback - callback that returns a promise of the network operation. If rejected with ConnectionError, it will be retried by calling the callback again.\n * @returns the result of the network operation\n * @throws {@link ConnectionError} If after maxAttempts the callback still throws ConnectionError\n */\nexport async function retryNetworkOperation(maxAttempts: number, callback: () => Promise): Promise {\n let attempts = 0;\n let lastConnectionError: ConnectionError | null = null;\n while (attempts < maxAttempts) {\n try {\n if (attempts > 0) {\n const timeout = 1000 * Math.pow(2, attempts);\n logger.log(`network operation failed ${attempts} times, retrying in ${timeout}ms...`);\n await sleep(timeout);\n }\n return await callback();\n } catch (err) {\n if (err instanceof ConnectionError) {\n attempts += 1;\n lastConnectionError = err;\n } else {\n throw err;\n }\n }\n }\n throw lastConnectionError;\n}\n", - "/*\nCopyright 2019 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Check if an IndexedDB database exists. The only way to do so is to try opening it, so\n * we do that and then delete it did not exist before.\n *\n * @param indexedDB - The `indexedDB` interface\n * @param dbName - The database name to test for\n * @returns Whether the database exists\n */\nexport function exists(indexedDB: IDBFactory, dbName: string): Promise {\n return new Promise((resolve, reject) => {\n let exists = true;\n const req = indexedDB.open(dbName);\n req.onupgradeneeded = (): void => {\n // Since we did not provide an explicit version when opening, this event\n // should only fire if the DB did not exist before at any version.\n exists = false;\n };\n req.onblocked = (): void => reject(req.error);\n req.onsuccess = (): void => {\n const db = req.result;\n db.close();\n if (!exists) {\n // The DB did not exist before, but has been created as part of this\n // existence check. Delete it now to restore previous state. Delete can\n // actually take a while to complete in some browsers, so don't wait for\n // it. This won't block future open calls that a store might issue next to\n // properly set up the DB.\n indexedDB.deleteDatabase(dbName);\n }\n resolve(exists);\n };\n req.onerror = (): void => reject(req.error);\n });\n}\n", - "/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from \"./logger\";\nimport { MatrixClient } from \"./client\";\nimport { defer, IDeferred } from \"./utils\";\nimport { MatrixError } from \"./http-api\";\n\nconst EMAIL_STAGE_TYPE = \"m.login.email.identity\";\nconst MSISDN_STAGE_TYPE = \"m.login.msisdn\";\n\nexport interface UIAFlow {\n stages: AuthType[];\n}\n\nexport interface IInputs {\n // An email address. If supplied, a flow using email verification will be chosen.\n emailAddress?: string;\n // An ISO two letter country code. Gives the country that opts.phoneNumber should be resolved relative to.\n phoneCountry?: string;\n // A phone number. If supplied, a flow using phone number validation will be chosen.\n phoneNumber?: string;\n registrationToken?: string;\n}\n\nexport interface IStageStatus {\n emailSid?: string;\n errcode?: string;\n error?: string;\n}\n\nexport interface IAuthData {\n session?: string;\n type?: string;\n completed?: string[];\n flows?: UIAFlow[];\n available_flows?: UIAFlow[];\n stages?: string[];\n required_stages?: AuthType[];\n params?: Record>;\n data?: Record;\n errcode?: string;\n error?: string;\n user_id?: string;\n device_id?: string;\n access_token?: string;\n}\n\nexport enum AuthType {\n Password = \"m.login.password\",\n Recaptcha = \"m.login.recaptcha\",\n Terms = \"m.login.terms\",\n Email = \"m.login.email.identity\",\n Msisdn = \"m.login.msisdn\",\n Sso = \"m.login.sso\",\n SsoUnstable = \"org.matrix.login.sso\",\n Dummy = \"m.login.dummy\",\n RegistrationToken = \"m.login.registration_token\",\n // For backwards compatability with servers that have not yet updated to\n // use the stable \"m.login.registration_token\" type.\n // The authentication flow is the same in both cases.\n UnstableRegistrationToken = \"org.matrix.msc3231.login.registration_token\",\n}\n\nexport interface IAuthDict {\n // [key: string]: any;\n type?: string;\n session?: string;\n // TODO: Remove `user` once servers support proper UIA\n // See https://github.com/vector-im/element-web/issues/10312\n user?: string;\n identifier?: any;\n password?: string;\n response?: string;\n // TODO: Remove `threepid_creds` once servers support proper UIA\n // See https://github.com/vector-im/element-web/issues/10312\n // See https://github.com/matrix-org/matrix-doc/issues/2220\n // eslint-disable-next-line camelcase\n threepid_creds?: any;\n threepidCreds?: any;\n // For m.login.registration_token type\n token?: string;\n}\n\nclass NoAuthFlowFoundError extends Error {\n public name = \"NoAuthFlowFoundError\";\n\n // eslint-disable-next-line @typescript-eslint/naming-convention, camelcase\n public constructor(m: string, public readonly required_stages: string[], public readonly flows: UIAFlow[]) {\n super(m);\n }\n}\n\ninterface IOpts {\n /**\n * A matrix client to use for the auth process\n */\n matrixClient: MatrixClient;\n /**\n * Error response from the last request. If null, a request will be made with no auth before starting.\n */\n authData?: IAuthData;\n /**\n * Inputs provided by the user and used by different stages of the auto process.\n * The inputs provided will affect what flow is chosen.\n */\n inputs?: IInputs;\n /**\n * If resuming an existing interactive auth session, the sessionId of that session.\n */\n sessionId?: string;\n /**\n * If resuming an existing interactive auth session, the client secret for that session\n */\n clientSecret?: string;\n /**\n * If returning from having completed m.login.email.identity auth, the sid for the email verification session.\n */\n emailSid?: string;\n\n /**\n * Called with the new auth dict to submit the request.\n * Also passes a second deprecated arg which is a flag set to true if this request is a background request.\n * The busyChanged callback should be used instead of the background flag.\n * Should return a promise which resolves to the successful response or rejects with a MatrixError.\n */\n doRequest(auth: IAuthData | null, background: boolean): Promise;\n /**\n * Called when the status of the UI auth changes,\n * ie. when the state of an auth stage changes of when the auth flow moves to a new stage.\n * The arguments are: the login type (eg m.login.password); and an object which is either an error or an\n * informational object specific to the login type.\n * If the 'errcode' key is defined, the object is an error, and has keys:\n * errcode: string, the textual error code, eg. M_UNKNOWN\n * error: string, human readable string describing the error\n *\n * The login type specific objects are as follows:\n * m.login.email.identity:\n * * emailSid: string, the sid of the active email auth session\n */\n stateUpdated(nextStage: AuthType, status: IStageStatus): void;\n\n /**\n * A function that takes the email address (string), clientSecret (string), attempt number (int) and\n * sessionId (string) and calls the relevant requestToken function and returns the promise returned by that\n * function.\n * If the resulting promise rejects, the rejection will propagate through to the attemptAuth promise.\n */\n requestEmailToken(email: string, secret: string, attempt: number, session: string): Promise<{ sid: string }>;\n /**\n * Called whenever the interactive auth logic becomes busy submitting information provided by the user or finishes.\n * After this has been called with true the UI should indicate that a request is in progress\n * until it is called again with false.\n */\n busyChanged?(busy: boolean): void;\n startAuthStage?(nextStage: string): Promise; // LEGACY\n}\n\n/**\n * Abstracts the logic used to drive the interactive auth process.\n *\n *

Components implementing an interactive auth flow should instantiate one of\n * these, passing in the necessary callbacks to the constructor. They should\n * then call attemptAuth, which will return a promise which will resolve or\n * reject when the interactive-auth process completes.\n *\n *

Meanwhile, calls will be made to the startAuthStage and doRequest\n * callbacks, and information gathered from the user can be submitted with\n * submitAuthDict.\n *\n * @param opts - options object\n */\nexport class InteractiveAuth {\n private readonly matrixClient: MatrixClient;\n private readonly inputs: IInputs;\n private readonly clientSecret: string;\n private readonly requestCallback: IOpts[\"doRequest\"];\n private readonly busyChangedCallback?: IOpts[\"busyChanged\"];\n private readonly stateUpdatedCallback: IOpts[\"stateUpdated\"];\n private readonly requestEmailTokenCallback: IOpts[\"requestEmailToken\"];\n\n private data: IAuthData;\n private emailSid?: string;\n private requestingEmailToken = false;\n private attemptAuthDeferred: IDeferred | null = null;\n private chosenFlow: UIAFlow | null = null;\n private currentStage: string | null = null;\n\n private emailAttempt = 1;\n\n // if we are currently trying to submit an auth dict (which includes polling)\n // the promise the will resolve/reject when it completes\n private submitPromise: Promise | null = null;\n\n public constructor(opts: IOpts) {\n this.matrixClient = opts.matrixClient;\n this.data = opts.authData || {};\n this.requestCallback = opts.doRequest;\n this.busyChangedCallback = opts.busyChanged;\n // startAuthStage included for backwards compat\n this.stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage;\n this.requestEmailTokenCallback = opts.requestEmailToken;\n this.inputs = opts.inputs || {};\n\n if (opts.sessionId) this.data.session = opts.sessionId;\n this.clientSecret = opts.clientSecret || this.matrixClient.generateClientSecret();\n this.emailSid = opts.emailSid;\n }\n\n /**\n * begin the authentication process.\n *\n * @returns which resolves to the response on success,\n * or rejects with the error on failure. Rejects with NoAuthFlowFoundError if\n * no suitable authentication flow can be found\n */\n public attemptAuth(): Promise {\n // This promise will be quite long-lived and will resolve when the\n // request is authenticated and completes successfully.\n this.attemptAuthDeferred = defer();\n // pluck the promise out now, as doRequest may clear before we return\n const promise = this.attemptAuthDeferred.promise;\n\n // if we have no flows, try a request to acquire the flows\n if (!this.data?.flows) {\n this.busyChangedCallback?.(true);\n // use the existing sessionId, if one is present.\n const auth = this.data.session ? { session: this.data.session } : null;\n this.doRequest(auth).finally(() => {\n this.busyChangedCallback?.(false);\n });\n } else {\n this.startNextAuthStage();\n }\n\n return promise;\n }\n\n /**\n * Poll to check if the auth session or current stage has been\n * completed out-of-band. If so, the attemptAuth promise will\n * be resolved.\n */\n public async poll(): Promise {\n if (!this.data.session) return;\n // likewise don't poll if there is no auth session in progress\n if (!this.attemptAuthDeferred) return;\n // if we currently have a request in flight, there's no point making\n // another just to check what the status is\n if (this.submitPromise) return;\n\n let authDict: IAuthDict = {};\n if (this.currentStage == EMAIL_STAGE_TYPE) {\n // The email can be validated out-of-band, but we need to provide the\n // creds so the HS can go & check it.\n if (this.emailSid) {\n const creds: Record = {\n sid: this.emailSid,\n client_secret: this.clientSecret,\n };\n if (await this.matrixClient.doesServerRequireIdServerParam()) {\n const idServerParsedUrl = new URL(this.matrixClient.getIdentityServerUrl()!);\n creds.id_server = idServerParsedUrl.host;\n }\n authDict = {\n type: EMAIL_STAGE_TYPE,\n // TODO: Remove `threepid_creds` once servers support proper UIA\n // See https://github.com/matrix-org/synapse/issues/5665\n // See https://github.com/matrix-org/matrix-doc/issues/2220\n threepid_creds: creds,\n threepidCreds: creds,\n };\n }\n }\n\n this.submitAuthDict(authDict, true);\n }\n\n /**\n * get the auth session ID\n *\n * @returns session id\n */\n public getSessionId(): string | undefined {\n return this.data?.session;\n }\n\n /**\n * get the client secret used for validation sessions\n * with the identity server.\n *\n * @returns client secret\n */\n public getClientSecret(): string {\n return this.clientSecret;\n }\n\n /**\n * get the server params for a given stage\n *\n * @param loginType - login type for the stage\n * @returns any parameters from the server for this stage\n */\n public getStageParams(loginType: string): Record | undefined {\n return this.data.params?.[loginType];\n }\n\n public getChosenFlow(): UIAFlow | null {\n return this.chosenFlow;\n }\n\n /**\n * submit a new auth dict and fire off the request. This will either\n * make attemptAuth resolve/reject, or cause the startAuthStage callback\n * to be called for a new stage.\n *\n * @param authData - new auth dict to send to the server. Should\n * include a `type` property denoting the login type, as well as any\n * other params for that stage.\n * @param background - If true, this request failing will not result\n * in the attemptAuth promise being rejected. This can be set to true\n * for requests that just poll to see if auth has been completed elsewhere.\n */\n public async submitAuthDict(authData: IAuthDict, background = false): Promise {\n if (!this.attemptAuthDeferred) {\n throw new Error(\"submitAuthDict() called before attemptAuth()\");\n }\n\n if (!background) {\n this.busyChangedCallback?.(true);\n }\n\n // if we're currently trying a request, wait for it to finish\n // as otherwise we can get multiple 200 responses which can mean\n // things like multiple logins for register requests.\n // (but discard any exceptions as we only care when its done,\n // not whether it worked or not)\n while (this.submitPromise) {\n try {\n await this.submitPromise;\n } catch (e) {}\n }\n\n // use the sessionid from the last request, if one is present.\n let auth: IAuthDict;\n if (this.data.session) {\n auth = {\n session: this.data.session,\n };\n Object.assign(auth, authData);\n } else {\n auth = authData;\n }\n\n try {\n // NB. the 'background' flag is deprecated by the busyChanged\n // callback and is here for backwards compat\n this.submitPromise = this.doRequest(auth, background);\n await this.submitPromise;\n } finally {\n this.submitPromise = null;\n if (!background) {\n this.busyChangedCallback?.(false);\n }\n }\n }\n\n /**\n * Gets the sid for the email validation session\n * Specific to m.login.email.identity\n *\n * @returns The sid of the email auth session\n */\n public getEmailSid(): string | undefined {\n return this.emailSid;\n }\n\n /**\n * Sets the sid for the email validation session\n * This must be set in order to successfully poll for completion\n * of the email validation.\n * Specific to m.login.email.identity\n *\n * @param sid - The sid for the email validation session\n */\n public setEmailSid(sid: string): void {\n this.emailSid = sid;\n }\n\n /**\n * Requests a new email token and sets the email sid for the validation session\n */\n public requestEmailToken = async (): Promise => {\n if (!this.requestingEmailToken) {\n logger.trace(\"Requesting email token. Attempt: \" + this.emailAttempt);\n // If we've picked a flow with email auth, we send the email\n // now because we want the request to fail as soon as possible\n // if the email address is not valid (ie. already taken or not\n // registered, depending on what the operation is).\n this.requestingEmailToken = true;\n try {\n const requestTokenResult = await this.requestEmailTokenCallback(\n this.inputs.emailAddress!,\n this.clientSecret,\n this.emailAttempt++,\n this.data.session!,\n );\n this.emailSid = requestTokenResult.sid;\n logger.trace(\"Email token request succeeded\");\n } finally {\n this.requestingEmailToken = false;\n }\n } else {\n logger.warn(\"Could not request email token: Already requesting\");\n }\n };\n\n /**\n * Fire off a request, and either resolve the promise, or call\n * startAuthStage.\n *\n * @internal\n * @param auth - new auth dict, including session id\n * @param background - If true, this request is a background poll, so it\n * failing will not result in the attemptAuth promise being rejected.\n * This can be set to true for requests that just poll to see if auth has\n * been completed elsewhere.\n */\n private async doRequest(auth: IAuthData | null, background = false): Promise {\n try {\n const result = await this.requestCallback(auth, background);\n this.attemptAuthDeferred!.resolve(result);\n this.attemptAuthDeferred = null;\n } catch (error) {\n // sometimes UI auth errors don't come with flows\n const errorFlows = (error).data?.flows ?? null;\n const haveFlows = this.data.flows || Boolean(errorFlows);\n if ((error).httpStatus !== 401 || !(error).data || !haveFlows) {\n // doesn't look like an interactive-auth failure.\n if (!background) {\n this.attemptAuthDeferred?.reject(error);\n } else {\n // We ignore all failures here (even non-UI auth related ones)\n // since we don't want to suddenly fail if the internet connection\n // had a blip whilst we were polling\n logger.log(\"Background poll request failed doing UI auth: ignoring\", error);\n }\n }\n if (!(error).data) {\n (error).data = {};\n }\n // if the error didn't come with flows, completed flows or session ID,\n // copy over the ones we have. Synapse sometimes sends responses without\n // any UI auth data (eg. when polling for email validation, if the email\n // has not yet been validated). This appears to be a Synapse bug, which\n // we workaround here.\n if (\n !(error).data.flows &&\n !(error).data.completed &&\n !(error).data.session\n ) {\n (error).data.flows = this.data.flows;\n (error).data.completed = this.data.completed;\n (error).data.session = this.data.session;\n }\n this.data = (error).data;\n try {\n this.startNextAuthStage();\n } catch (e) {\n this.attemptAuthDeferred!.reject(e);\n this.attemptAuthDeferred = null;\n return;\n }\n\n if (!this.emailSid && this.chosenFlow?.stages.includes(AuthType.Email)) {\n try {\n await this.requestEmailToken();\n // NB. promise is not resolved here - at some point, doRequest\n // will be called again and if the user has jumped through all\n // the hoops correctly, auth will be complete and the request\n // will succeed.\n // Also, we should expose the fact that this request has compledted\n // so clients can know that the email has actually been sent.\n } catch (e) {\n // we failed to request an email token, so fail the request.\n // This could be due to the email already beeing registered\n // (or not being registered, depending on what we're trying\n // to do) or it could be a network failure. Either way, pass\n // the failure up as the user can't complete auth if we can't\n // send the email, for whatever reason.\n this.attemptAuthDeferred!.reject(e);\n this.attemptAuthDeferred = null;\n }\n }\n }\n }\n\n /**\n * Pick the next stage and call the callback\n *\n * @internal\n * @throws {@link NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n private startNextAuthStage(): void {\n const nextStage = this.chooseStage();\n if (!nextStage) {\n throw new Error(\"No incomplete flows from the server\");\n }\n this.currentStage = nextStage;\n\n if (nextStage === AuthType.Dummy) {\n this.submitAuthDict({\n type: \"m.login.dummy\",\n });\n return;\n }\n\n if (this.data?.errcode || this.data?.error) {\n this.stateUpdatedCallback(nextStage, {\n errcode: this.data?.errcode || \"\",\n error: this.data?.error || \"\",\n });\n return;\n }\n\n this.stateUpdatedCallback(nextStage, nextStage === EMAIL_STAGE_TYPE ? { emailSid: this.emailSid } : {});\n }\n\n /**\n * Pick the next auth stage\n *\n * @internal\n * @returns login type\n * @throws {@link NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n private chooseStage(): AuthType | undefined {\n if (this.chosenFlow === null) {\n this.chosenFlow = this.chooseFlow();\n }\n logger.log(\"Active flow => %s\", JSON.stringify(this.chosenFlow));\n const nextStage = this.firstUncompletedStage(this.chosenFlow);\n logger.log(\"Next stage: %s\", nextStage);\n return nextStage;\n }\n\n /**\n * Pick one of the flows from the returned list\n * If a flow using all of the inputs is found, it will\n * be returned, otherwise, null will be returned.\n *\n * Only flows using all given inputs are chosen because it\n * is likely to be surprising if the user provides a\n * credential and it is not used. For example, for registration,\n * this could result in the email not being used which would leave\n * the account with no means to reset a password.\n *\n * @internal\n * @returns flow\n * @throws {@link NoAuthFlowFoundError} If no suitable authentication flow can be found\n */\n private chooseFlow(): UIAFlow {\n const flows = this.data.flows || [];\n\n // we've been given an email or we've already done an email part\n const haveEmail = Boolean(this.inputs.emailAddress) || Boolean(this.emailSid);\n const haveMsisdn = Boolean(this.inputs.phoneCountry) && Boolean(this.inputs.phoneNumber);\n\n for (const flow of flows) {\n let flowHasEmail = false;\n let flowHasMsisdn = false;\n for (const stage of flow.stages) {\n if (stage === EMAIL_STAGE_TYPE) {\n flowHasEmail = true;\n } else if (stage == MSISDN_STAGE_TYPE) {\n flowHasMsisdn = true;\n }\n }\n\n if (flowHasEmail == haveEmail && flowHasMsisdn == haveMsisdn) {\n return flow;\n }\n }\n\n const requiredStages: string[] = [];\n if (haveEmail) requiredStages.push(EMAIL_STAGE_TYPE);\n if (haveMsisdn) requiredStages.push(MSISDN_STAGE_TYPE);\n // Throw an error with a fairly generic description, but with more\n // information such that the app can give a better one if so desired.\n throw new NoAuthFlowFoundError(\"No appropriate authentication flow found\", requiredStages, flows);\n }\n\n /**\n * Get the first uncompleted stage in the given flow\n *\n * @internal\n * @returns login type\n */\n private firstUncompletedStage(flow: UIAFlow): AuthType | undefined {\n const completed = this.data.completed || [];\n return flow.stages.find((stageType) => !completed.includes(stageType));\n }\n}\n", - "/*\nCopyright 2018 André Jaenisch\nCopyright 2019, 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport log, { Logger } from \"loglevel\";\n\n// This is to demonstrate, that you can use any namespace you want.\n// Namespaces allow you to turn on/off the logging for specific parts of the\n// application.\n// An idea would be to control this via an environment variable (on Node.js).\n// See https://www.npmjs.com/package/debug to see how this could be implemented\n// Part of #332 is introducing a logging library in the first place.\nconst DEFAULT_NAMESPACE = \"matrix\";\n\n// because rageshakes in react-sdk hijack the console log, also at module load time,\n// initializing the logger here races with the initialization of rageshakes.\n// to avoid the issue, we override the methodFactory of loglevel that binds to the\n// console methods at initialization time by a factory that looks up the console methods\n// when logging so we always get the current value of console methods.\nlog.methodFactory = function (methodName, logLevel, loggerName) {\n return function (this: PrefixedLogger, ...args): void {\n /* eslint-disable @typescript-eslint/no-invalid-this */\n if (this.prefix) {\n args.unshift(this.prefix);\n }\n /* eslint-enable @typescript-eslint/no-invalid-this */\n const supportedByConsole =\n methodName === \"error\" || methodName === \"warn\" || methodName === \"trace\" || methodName === \"info\";\n /* eslint-disable no-console */\n if (supportedByConsole) {\n return console[methodName](...args);\n } else {\n return console.log(...args);\n }\n /* eslint-enable no-console */\n };\n};\n\n/**\n * Drop-in replacement for `console` using {@link https://www.npmjs.com/package/loglevel|loglevel}.\n * Can be tailored down to specific use cases if needed.\n */\nexport const logger = log.getLogger(DEFAULT_NAMESPACE) as PrefixedLogger;\nlogger.setLevel(log.levels.DEBUG, false);\n\nexport interface PrefixedLogger extends Logger {\n withPrefix: (prefix: string) => PrefixedLogger;\n prefix: string;\n}\n\nfunction extendLogger(logger: Logger): void {\n (logger).withPrefix = function (prefix: string): PrefixedLogger {\n const existingPrefix = this.prefix || \"\";\n return getPrefixedLogger(existingPrefix + prefix);\n };\n}\n\nextendLogger(logger);\n\nfunction getPrefixedLogger(prefix: string): PrefixedLogger {\n const prefixLogger = log.getLogger(`${DEFAULT_NAMESPACE}-${prefix}`) as PrefixedLogger;\n if (prefixLogger.prefix !== prefix) {\n // Only do this setup work the first time through, as loggers are saved by name.\n extendLogger(prefixLogger);\n prefixLogger.prefix = prefix;\n prefixLogger.setLevel(log.levels.DEBUG, false);\n }\n return prefixLogger;\n}\n", - "/*\nCopyright 2015-2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { WidgetApi } from \"matrix-widget-api\";\n\nimport { MemoryCryptoStore } from \"./crypto/store/memory-crypto-store\";\nimport { MemoryStore } from \"./store/memory\";\nimport { MatrixScheduler } from \"./scheduler\";\nimport { MatrixClient, ICreateClientOpts } from \"./client\";\nimport { RoomWidgetClient, ICapabilities } from \"./embedded\";\nimport { CryptoStore } from \"./crypto/store/base\";\n\nexport * from \"./client\";\nexport * from \"./embedded\";\nexport * from \"./http-api\";\nexport * from \"./autodiscovery\";\nexport * from \"./sync-accumulator\";\nexport * from \"./errors\";\nexport * from \"./models/beacon\";\nexport * from \"./models/event\";\nexport * from \"./models/room\";\nexport * from \"./models/event-timeline\";\nexport * from \"./models/event-timeline-set\";\nexport * from \"./models/poll\";\nexport * from \"./models/room-member\";\nexport * from \"./models/room-state\";\nexport * from \"./models/user\";\nexport * from \"./scheduler\";\nexport * from \"./filter\";\nexport * from \"./timeline-window\";\nexport * from \"./interactive-auth\";\nexport * from \"./service-types\";\nexport * from \"./store/memory\";\nexport * from \"./store/indexeddb\";\nexport * from \"./crypto/store/memory-crypto-store\";\nexport * from \"./crypto/store/indexeddb-crypto-store\";\nexport * from \"./content-repo\";\nexport * from \"./@types/event\";\nexport * from \"./@types/PushRules\";\nexport * from \"./@types/partials\";\nexport * from \"./@types/requests\";\nexport * from \"./@types/search\";\nexport * from \"./models/room-summary\";\nexport * as ContentHelpers from \"./content-helpers\";\nexport * as SecretStorage from \"./secret-storage\";\nexport type { ICryptoCallbacks } from \"./crypto\"; // used to be located here\nexport { createNewMatrixCall } from \"./webrtc/call\";\nexport type { MatrixCall } from \"./webrtc/call\";\nexport { GroupCallEvent, GroupCallIntent, GroupCallState, GroupCallType } from \"./webrtc/groupCall\";\nexport type { GroupCall } from \"./webrtc/groupCall\";\nexport type { CryptoApi } from \"./crypto-api\";\n\nlet cryptoStoreFactory = (): CryptoStore => new MemoryCryptoStore();\n\n/**\n * Configure a different factory to be used for creating crypto stores\n *\n * @param fac - a function which will return a new {@link CryptoStore}\n */\nexport function setCryptoStoreFactory(fac: () => CryptoStore): void {\n cryptoStoreFactory = fac;\n}\n\nfunction amendClientOpts(opts: ICreateClientOpts): ICreateClientOpts {\n opts.store =\n opts.store ??\n new MemoryStore({\n localStorage: global.localStorage,\n });\n opts.scheduler = opts.scheduler ?? new MatrixScheduler();\n opts.cryptoStore = opts.cryptoStore ?? cryptoStoreFactory();\n\n return opts;\n}\n\n/**\n * Construct a Matrix Client. Similar to {@link MatrixClient}\n * except that the 'request', 'store' and 'scheduler' dependencies are satisfied.\n * @param opts - The configuration options for this client. These configuration\n * options will be passed directly to {@link MatrixClient}.\n *\n * @returns A new matrix client.\n * @see {@link MatrixClient} for the full list of options for\n * `opts`.\n */\nexport function createClient(opts: ICreateClientOpts): MatrixClient {\n return new MatrixClient(amendClientOpts(opts));\n}\n\nexport function createRoomWidgetClient(\n widgetApi: WidgetApi,\n capabilities: ICapabilities,\n roomId: string,\n opts: ICreateClientOpts,\n): MatrixClient {\n return new RoomWidgetClient(widgetApi, capabilities, roomId, amendClientOpts(opts));\n}\n", - "/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixClient } from \"../client\";\nimport { IEncryptedFile, RelationType, UNSTABLE_MSC3089_BRANCH } from \"../@types/event\";\nimport { IContent, MatrixEvent } from \"./event\";\nimport { MSC3089TreeSpace } from \"./MSC3089TreeSpace\";\nimport { EventTimeline } from \"./event-timeline\";\nimport { FileType } from \"../http-api\";\nimport type { ISendEventResponse } from \"../@types/requests\";\n\n/**\n * Represents a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089) branch - a reference\n * to a file (leaf) in the tree. Note that this is UNSTABLE and subject to breaking changes\n * without notice.\n */\nexport class MSC3089Branch {\n public constructor(\n private client: MatrixClient,\n public readonly indexEvent: MatrixEvent,\n public readonly directory: MSC3089TreeSpace,\n ) {\n // Nothing to do\n }\n\n /**\n * The file ID.\n */\n public get id(): string {\n const stateKey = this.indexEvent.getStateKey();\n if (!stateKey) {\n throw new Error(\"State key not found for branch\");\n }\n return stateKey;\n }\n\n /**\n * Whether this branch is active/valid.\n */\n public get isActive(): boolean {\n return this.indexEvent.getContent()[\"active\"] === true;\n }\n\n /**\n * Version for the file, one-indexed.\n */\n public get version(): number {\n return this.indexEvent.getContent()[\"version\"] ?? 1;\n }\n\n private get roomId(): string {\n return this.indexEvent.getRoomId()!;\n }\n\n /**\n * Deletes the file from the tree, including all prior edits/versions.\n * @returns Promise which resolves when complete.\n */\n public async delete(): Promise {\n await this.client.sendStateEvent(this.roomId, UNSTABLE_MSC3089_BRANCH.name, {}, this.id);\n await this.client.redactEvent(this.roomId, this.id);\n\n const nextVersion = (await this.getVersionHistory())[1]; // [0] will be us\n if (nextVersion) await nextVersion.delete(); // implicit recursion\n }\n\n /**\n * Gets the name for this file.\n * @returns The name, or \"Unnamed File\" if unknown.\n */\n public getName(): string {\n return this.indexEvent.getContent()[\"name\"] || \"Unnamed File\";\n }\n\n /**\n * Sets the name for this file.\n * @param name - The new name for this file.\n * @returns Promise which resolves when complete.\n */\n public async setName(name: string): Promise {\n await this.client.sendStateEvent(\n this.roomId,\n UNSTABLE_MSC3089_BRANCH.name,\n {\n ...this.indexEvent.getContent(),\n name: name,\n },\n this.id,\n );\n }\n\n /**\n * Gets whether or not a file is locked.\n * @returns True if locked, false otherwise.\n */\n public isLocked(): boolean {\n return this.indexEvent.getContent()[\"locked\"] || false;\n }\n\n /**\n * Sets a file as locked or unlocked.\n * @param locked - True to lock the file, false otherwise.\n * @returns Promise which resolves when complete.\n */\n public async setLocked(locked: boolean): Promise {\n await this.client.sendStateEvent(\n this.roomId,\n UNSTABLE_MSC3089_BRANCH.name,\n {\n ...this.indexEvent.getContent(),\n locked: locked,\n },\n this.id,\n );\n }\n\n /**\n * Gets information about the file needed to download it.\n * @returns Information about the file.\n */\n public async getFileInfo(): Promise<{ info: IEncryptedFile; httpUrl: string }> {\n const event = await this.getFileEvent();\n\n const file = event.getOriginalContent()[\"file\"];\n const httpUrl = this.client.mxcUrlToHttp(file[\"url\"]);\n\n if (!httpUrl) {\n throw new Error(`No HTTP URL available for ${file[\"url\"]}`);\n }\n\n return { info: file, httpUrl: httpUrl };\n }\n\n /**\n * Gets the event the file points to.\n * @returns Promise which resolves to the file's event.\n */\n public async getFileEvent(): Promise {\n const room = this.client.getRoom(this.roomId);\n if (!room) throw new Error(\"Unknown room\");\n\n let event: MatrixEvent | undefined = room.getUnfilteredTimelineSet().findEventById(this.id);\n\n // keep scrolling back if needed until we find the event or reach the start of the room:\n while (!event && room.getLiveTimeline().getState(EventTimeline.BACKWARDS)!.paginationToken) {\n await this.client.scrollback(room, 100);\n event = room.getUnfilteredTimelineSet().findEventById(this.id);\n }\n\n if (!event) throw new Error(\"Failed to find event\");\n\n // Sometimes the event isn't decrypted for us, so do that. We specifically set `emit: true`\n // to ensure that the relations system in the sdk will function.\n await this.client.decryptEventIfNeeded(event, { emit: true, isRetry: true });\n\n return event;\n }\n\n /**\n * Creates a new version of this file with contents in a type that is compatible with MatrixClient.uploadContent().\n * @param name - The name of the file.\n * @param encryptedContents - The encrypted contents.\n * @param info - The encrypted file information.\n * @param additionalContent - Optional event content fields to include in the message.\n * @returns Promise which resolves to the file event's sent response.\n */\n public async createNewVersion(\n name: string,\n encryptedContents: FileType,\n info: Partial,\n additionalContent?: IContent,\n ): Promise {\n const fileEventResponse = await this.directory.createFile(name, encryptedContents, info, {\n ...(additionalContent ?? {}),\n \"m.new_content\": true,\n \"m.relates_to\": {\n rel_type: RelationType.Replace,\n event_id: this.id,\n },\n });\n\n // Update the version of the new event\n await this.client.sendStateEvent(\n this.roomId,\n UNSTABLE_MSC3089_BRANCH.name,\n {\n active: true,\n name: name,\n version: this.version + 1,\n },\n fileEventResponse[\"event_id\"],\n );\n\n // Deprecate ourselves\n await this.client.sendStateEvent(\n this.roomId,\n UNSTABLE_MSC3089_BRANCH.name,\n {\n ...this.indexEvent.getContent(),\n active: false,\n },\n this.id,\n );\n\n return fileEventResponse;\n }\n\n /**\n * Gets the file's version history, starting at this file.\n * @returns Promise which resolves to the file's version history, with the\n * first element being the current version and the last element being the first version.\n */\n public async getVersionHistory(): Promise {\n const fileHistory: MSC3089Branch[] = [];\n fileHistory.push(this); // start with ourselves\n\n const room = this.client.getRoom(this.roomId);\n if (!room) throw new Error(\"Invalid or unknown room\");\n\n // Clone the timeline to reverse it, getting most-recent-first ordering, hopefully\n // shortening the awful loop below. Without the clone, we can unintentionally mutate\n // the timeline.\n const timelineEvents = [...room.getLiveTimeline().getEvents()].reverse();\n\n // XXX: This is a very inefficient search, but it's the best we can do with the\n // relations structure we have in the SDK. As of writing, it is not worth the\n // investment in improving the structure.\n let childEvent: MatrixEvent | undefined;\n let parentEvent = await this.getFileEvent();\n do {\n childEvent = timelineEvents.find((e) => e.replacingEventId() === parentEvent.getId());\n if (childEvent) {\n const branch = this.directory.getFile(childEvent.getId()!);\n if (branch) {\n fileHistory.push(branch);\n parentEvent = childEvent;\n } else {\n break; // prevent infinite loop\n }\n }\n } while (childEvent);\n\n return fileHistory;\n }\n}\n", - "/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport promiseRetry from \"p-retry\";\n\nimport { MatrixClient } from \"../client\";\nimport { EventType, IEncryptedFile, MsgType, UNSTABLE_MSC3089_BRANCH, UNSTABLE_MSC3089_LEAF } from \"../@types/event\";\nimport { Room } from \"./room\";\nimport { logger } from \"../logger\";\nimport { IContent, MatrixEvent } from \"./event\";\nimport {\n averageBetweenStrings,\n DEFAULT_ALPHABET,\n lexicographicCompare,\n nextString,\n prevString,\n simpleRetryOperation,\n} from \"../utils\";\nimport { MSC3089Branch } from \"./MSC3089Branch\";\nimport { isRoomSharedHistory } from \"../crypto/algorithms/megolm\";\nimport { ISendEventResponse } from \"../@types/requests\";\nimport { FileType } from \"../http-api\";\n\n/**\n * The recommended defaults for a tree space's power levels. Note that this\n * is UNSTABLE and subject to breaking changes without notice.\n */\nexport const DEFAULT_TREE_POWER_LEVELS_TEMPLATE = {\n // Owner\n invite: 100,\n kick: 100,\n ban: 100,\n\n // Editor\n redact: 50,\n state_default: 50,\n events_default: 50,\n\n // Viewer\n users_default: 0,\n\n // Mixed\n events: {\n [EventType.RoomPowerLevels]: 100,\n [EventType.RoomHistoryVisibility]: 100,\n [EventType.RoomTombstone]: 100,\n [EventType.RoomEncryption]: 100,\n [EventType.RoomName]: 50,\n [EventType.RoomMessage]: 50,\n [EventType.RoomMessageEncrypted]: 50,\n [EventType.Sticker]: 50,\n },\n\n users: {}, // defined by calling code\n};\n\n/**\n * Ease-of-use representation for power levels represented as simple roles.\n * Note that this is UNSTABLE and subject to breaking changes without notice.\n */\nexport enum TreePermissions {\n Viewer = \"viewer\", // Default\n Editor = \"editor\", // \"Moderator\" or ~PL50\n Owner = \"owner\", // \"Admin\" or PL100\n}\n\n/**\n * Represents a [MSC3089](https://github.com/matrix-org/matrix-doc/pull/3089)\n * file tree Space. Note that this is UNSTABLE and subject to breaking changes\n * without notice.\n */\nexport class MSC3089TreeSpace {\n public readonly room: Room;\n\n public constructor(private client: MatrixClient, public readonly roomId: string) {\n this.room = this.client.getRoom(this.roomId)!;\n\n if (!this.room) throw new Error(\"Unknown room\");\n }\n\n /**\n * Syntactic sugar for room ID of the Space.\n */\n public get id(): string {\n return this.roomId;\n }\n\n /**\n * Whether or not this is a top level space.\n */\n public get isTopLevel(): boolean {\n // XXX: This is absolutely not how you find out if the space is top level\n // but is safe for a managed usecase like we offer in the SDK.\n const parentEvents = this.room.currentState.getStateEvents(EventType.SpaceParent);\n if (!parentEvents?.length) return true;\n return parentEvents.every((e) => !e.getContent()?.[\"via\"]);\n }\n\n /**\n * Sets the name of the tree space.\n * @param name - The new name for the space.\n * @returns Promise which resolves when complete.\n */\n public async setName(name: string): Promise {\n await this.client.sendStateEvent(this.roomId, EventType.RoomName, { name }, \"\");\n }\n\n /**\n * Invites a user to the tree space. They will be given the default Viewer\n * permission level unless specified elsewhere.\n * @param userId - The user ID to invite.\n * @param andSubspaces - True (default) to invite the user to all\n * directories/subspaces too, recursively.\n * @param shareHistoryKeys - True (default) to share encryption keys\n * with the invited user. This will allow them to decrypt the events (files)\n * in the tree. Keys will not be shared if the room is lacking appropriate\n * history visibility (by default, history visibility is \"shared\" in trees,\n * which is an appropriate visibility for these purposes).\n * @returns Promise which resolves when complete.\n */\n public async invite(userId: string, andSubspaces = true, shareHistoryKeys = true): Promise {\n const promises: Promise[] = [this.retryInvite(userId)];\n if (andSubspaces) {\n promises.push(...this.getDirectories().map((d) => d.invite(userId, andSubspaces, shareHistoryKeys)));\n }\n return Promise.all(promises).then(() => {\n // Note: key sharing is default on because for file trees it is relatively important that the invite\n // target can actually decrypt the files. The implied use case is that by inviting a user to the tree\n // it means the sender would like the receiver to view/download the files contained within, much like\n // sharing a folder in other circles.\n if (shareHistoryKeys && isRoomSharedHistory(this.room)) {\n // noinspection JSIgnoredPromiseFromCall - we aren't concerned as much if this fails.\n this.client.sendSharedHistoryKeys(this.roomId, [userId]);\n }\n });\n }\n\n private retryInvite(userId: string): Promise {\n return simpleRetryOperation(async () => {\n await this.client.invite(this.roomId, userId).catch((e) => {\n // We don't want to retry permission errors forever...\n if (e?.errcode === \"M_FORBIDDEN\") {\n throw new promiseRetry.AbortError(e);\n }\n throw e;\n });\n });\n }\n\n /**\n * Sets the permissions of a user to the given role. Note that if setting a user\n * to Owner then they will NOT be able to be demoted. If the user does not have\n * permission to change the power level of the target, an error will be thrown.\n * @param userId - The user ID to change the role of.\n * @param role - The role to assign.\n * @returns Promise which resolves when complete.\n */\n public async setPermissions(userId: string, role: TreePermissions): Promise {\n const currentPls = this.room.currentState.getStateEvents(EventType.RoomPowerLevels, \"\");\n if (Array.isArray(currentPls)) throw new Error(\"Unexpected return type for power levels\");\n\n const pls = currentPls?.getContent() || {};\n const viewLevel = pls[\"users_default\"] || 0;\n const editLevel = pls[\"events_default\"] || 50;\n const adminLevel = pls[\"events\"]?.[EventType.RoomPowerLevels] || 100;\n\n const users = pls[\"users\"] || {};\n switch (role) {\n case TreePermissions.Viewer:\n users[userId] = viewLevel;\n break;\n case TreePermissions.Editor:\n users[userId] = editLevel;\n break;\n case TreePermissions.Owner:\n users[userId] = adminLevel;\n break;\n default:\n throw new Error(\"Invalid role: \" + role);\n }\n pls[\"users\"] = users;\n\n await this.client.sendStateEvent(this.roomId, EventType.RoomPowerLevels, pls, \"\");\n }\n\n /**\n * Gets the current permissions of a user. Note that any users missing explicit permissions (or not\n * in the space) will be considered Viewers. Appropriate membership checks need to be performed\n * elsewhere.\n * @param userId - The user ID to check permissions of.\n * @returns The permissions for the user, defaulting to Viewer.\n */\n public getPermissions(userId: string): TreePermissions {\n const currentPls = this.room.currentState.getStateEvents(EventType.RoomPowerLevels, \"\");\n if (Array.isArray(currentPls)) throw new Error(\"Unexpected return type for power levels\");\n\n const pls = currentPls?.getContent() || {};\n const viewLevel = pls[\"users_default\"] || 0;\n const editLevel = pls[\"events_default\"] || 50;\n const adminLevel = pls[\"events\"]?.[EventType.RoomPowerLevels] || 100;\n\n const userLevel = pls[\"users\"]?.[userId] || viewLevel;\n if (userLevel >= adminLevel) return TreePermissions.Owner;\n if (userLevel >= editLevel) return TreePermissions.Editor;\n return TreePermissions.Viewer;\n }\n\n /**\n * Creates a directory under this tree space, represented as another tree space.\n * @param name - The name for the directory.\n * @returns Promise which resolves to the created directory.\n */\n public async createDirectory(name: string): Promise {\n const directory = await this.client.unstableCreateFileTree(name);\n\n await this.client.sendStateEvent(\n this.roomId,\n EventType.SpaceChild,\n {\n via: [this.client.getDomain()],\n },\n directory.roomId,\n );\n\n await this.client.sendStateEvent(\n directory.roomId,\n EventType.SpaceParent,\n {\n via: [this.client.getDomain()],\n },\n this.roomId,\n );\n\n return directory;\n }\n\n /**\n * Gets a list of all known immediate subdirectories to this tree space.\n * @returns The tree spaces (directories). May be empty, but not null.\n */\n public getDirectories(): MSC3089TreeSpace[] {\n const trees: MSC3089TreeSpace[] = [];\n const children = this.room.currentState.getStateEvents(EventType.SpaceChild);\n for (const child of children) {\n try {\n const stateKey = child.getStateKey();\n if (stateKey) {\n const tree = this.client.unstableGetFileTreeSpace(stateKey);\n if (tree) trees.push(tree);\n }\n } catch (e) {\n logger.warn(\"Unable to create tree space instance for listing. Are we joined?\", e);\n }\n }\n return trees;\n }\n\n /**\n * Gets a subdirectory of a given ID under this tree space. Note that this will not recurse\n * into children and instead only look one level deep.\n * @param roomId - The room ID (directory ID) to find.\n * @returns The directory, or undefined if not found.\n */\n public getDirectory(roomId: string): MSC3089TreeSpace | undefined {\n return this.getDirectories().find((r) => r.roomId === roomId);\n }\n\n /**\n * Deletes the tree, kicking all members and deleting **all subdirectories**.\n * @returns Promise which resolves when complete.\n */\n public async delete(): Promise {\n const subdirectories = this.getDirectories();\n for (const dir of subdirectories) {\n await dir.delete();\n }\n\n const kickMemberships = [\"invite\", \"knock\", \"join\"];\n const members = this.room.currentState.getStateEvents(EventType.RoomMember);\n for (const member of members) {\n const isNotUs = member.getStateKey() !== this.client.getUserId();\n if (isNotUs && kickMemberships.includes(member.getContent().membership!)) {\n const stateKey = member.getStateKey();\n if (!stateKey) {\n throw new Error(\"State key not found for branch\");\n }\n await this.client.kick(this.roomId, stateKey, \"Room deleted\");\n }\n }\n\n await this.client.leave(this.roomId);\n }\n\n private getOrderedChildren(children: MatrixEvent[]): { roomId: string; order: string }[] {\n const ordered: { roomId: string; order: string }[] = children\n .map((c) => ({ roomId: c.getStateKey(), order: c.getContent()[\"order\"] }))\n .filter((c) => c.roomId) as { roomId: string; order: string }[];\n ordered.sort((a, b) => {\n if (a.order && !b.order) {\n return -1;\n } else if (!a.order && b.order) {\n return 1;\n } else if (!a.order && !b.order) {\n const roomA = this.client.getRoom(a.roomId);\n const roomB = this.client.getRoom(b.roomId);\n if (!roomA || !roomB) {\n // just don't bother trying to do more partial sorting\n return lexicographicCompare(a.roomId, b.roomId);\n }\n\n const createTsA = roomA.currentState.getStateEvents(EventType.RoomCreate, \"\")?.getTs() ?? 0;\n const createTsB = roomB.currentState.getStateEvents(EventType.RoomCreate, \"\")?.getTs() ?? 0;\n if (createTsA === createTsB) {\n return lexicographicCompare(a.roomId, b.roomId);\n }\n return createTsA - createTsB;\n } else {\n // both not-null orders\n return lexicographicCompare(a.order, b.order);\n }\n });\n return ordered;\n }\n\n private getParentRoom(): Room {\n const parents = this.room.currentState.getStateEvents(EventType.SpaceParent);\n const parent = parents[0]; // XXX: Wild assumption\n if (!parent) throw new Error(\"Expected to have a parent in a non-top level space\");\n\n // XXX: We are assuming the parent is a valid tree space.\n // We probably don't need to validate the parent room state for this usecase though.\n const stateKey = parent.getStateKey();\n if (!stateKey) throw new Error(\"No state key found for parent\");\n const parentRoom = this.client.getRoom(stateKey);\n if (!parentRoom) throw new Error(\"Unable to locate room for parent\");\n\n return parentRoom;\n }\n\n /**\n * Gets the current order index for this directory. Note that if this is the top level space\n * then -1 will be returned.\n * @returns The order index of this space.\n */\n public getOrder(): number {\n if (this.isTopLevel) return -1;\n\n const parentRoom = this.getParentRoom();\n const children = parentRoom.currentState.getStateEvents(EventType.SpaceChild);\n const ordered = this.getOrderedChildren(children);\n\n return ordered.findIndex((c) => c.roomId === this.roomId);\n }\n\n /**\n * Sets the order index for this directory within its parent. Note that if this is a top level\n * space then an error will be thrown. -1 can be used to move the child to the start, and numbers\n * larger than the number of children can be used to move the child to the end.\n * @param index - The new order index for this space.\n * @returns Promise which resolves when complete.\n * @throws Throws if this is a top level space.\n */\n public async setOrder(index: number): Promise {\n if (this.isTopLevel) throw new Error(\"Cannot set order of top level spaces currently\");\n\n const parentRoom = this.getParentRoom();\n const children = parentRoom.currentState.getStateEvents(EventType.SpaceChild);\n const ordered = this.getOrderedChildren(children);\n index = Math.max(Math.min(index, ordered.length - 1), 0);\n\n const currentIndex = this.getOrder();\n const movingUp = currentIndex < index;\n if (movingUp && index === ordered.length - 1) {\n index--;\n } else if (!movingUp && index === 0) {\n index++;\n }\n\n const prev = ordered[movingUp ? index : index - 1];\n const next = ordered[movingUp ? index + 1 : index];\n\n let newOrder = DEFAULT_ALPHABET[0];\n let ensureBeforeIsSane = false;\n if (!prev) {\n // Move to front\n if (next?.order) {\n newOrder = prevString(next.order);\n }\n } else if (index === ordered.length - 1) {\n // Move to back\n if (next?.order) {\n newOrder = nextString(next.order);\n }\n } else {\n // Move somewhere in the middle\n const startOrder = prev?.order;\n const endOrder = next?.order;\n if (startOrder && endOrder) {\n if (startOrder === endOrder) {\n // Error case: just move +1 to break out of awful math\n newOrder = nextString(startOrder);\n } else {\n newOrder = averageBetweenStrings(startOrder, endOrder);\n }\n } else {\n if (startOrder) {\n // We're at the end (endOrder is null, so no explicit order)\n newOrder = nextString(startOrder);\n } else if (endOrder) {\n // We're at the start (startOrder is null, so nothing before us)\n newOrder = prevString(endOrder);\n } else {\n // Both points are unknown. We're likely in a range where all the children\n // don't have particular order values, so we may need to update them too.\n // The other possibility is there's only us as a child, but we should have\n // shown up in the other states.\n ensureBeforeIsSane = true;\n }\n }\n }\n\n if (ensureBeforeIsSane) {\n // We were asked by the order algorithm to prepare the moving space for a landing\n // in the undefined order part of the order array, which means we need to update the\n // spaces that come before it with a stable order value.\n let lastOrder: string | undefined;\n for (let i = 0; i <= index; i++) {\n const target = ordered[i];\n if (i === 0) {\n lastOrder = target.order;\n }\n if (!target.order) {\n // XXX: We should be creating gaps to avoid conflicts\n lastOrder = lastOrder ? nextString(lastOrder) : DEFAULT_ALPHABET[0];\n const currentChild = parentRoom.currentState.getStateEvents(EventType.SpaceChild, target.roomId);\n const content = currentChild?.getContent() ?? { via: [this.client.getDomain()] };\n await this.client.sendStateEvent(\n parentRoom.roomId,\n EventType.SpaceChild,\n {\n ...content,\n order: lastOrder,\n },\n target.roomId,\n );\n } else {\n lastOrder = target.order;\n }\n }\n if (lastOrder) {\n newOrder = nextString(lastOrder);\n }\n }\n\n // TODO: Deal with order conflicts by reordering\n\n // Now we can finally update our own order state\n const currentChild = parentRoom.currentState.getStateEvents(EventType.SpaceChild, this.roomId);\n const content = currentChild?.getContent() ?? { via: [this.client.getDomain()] };\n await this.client.sendStateEvent(\n parentRoom.roomId,\n EventType.SpaceChild,\n {\n ...content,\n\n // TODO: Safely constrain to 50 character limit required by spaces.\n order: newOrder,\n },\n this.roomId,\n );\n }\n\n /**\n * Creates (uploads) a new file to this tree. The file must have already been encrypted for the room.\n * The file contents are in a type that is compatible with MatrixClient.uploadContent().\n * @param name - The name of the file.\n * @param encryptedContents - The encrypted contents.\n * @param info - The encrypted file information.\n * @param additionalContent - Optional event content fields to include in the message.\n * @returns Promise which resolves to the file event's sent response.\n */\n public async createFile(\n name: string,\n encryptedContents: FileType,\n info: Partial,\n additionalContent?: IContent,\n ): Promise {\n const { content_uri: mxc } = await this.client.uploadContent(encryptedContents, {\n includeFilename: false,\n });\n info.url = mxc;\n\n const fileContent = {\n msgtype: MsgType.File,\n body: name,\n url: mxc,\n file: info,\n };\n\n additionalContent = additionalContent ?? {};\n if (additionalContent[\"m.new_content\"]) {\n // We do the right thing according to the spec, but due to how relations are\n // handled we also end up duplicating this information to the regular `content`\n // as well.\n additionalContent[\"m.new_content\"] = fileContent;\n }\n\n const res = await this.client.sendMessage(this.roomId, {\n ...additionalContent,\n ...fileContent,\n [UNSTABLE_MSC3089_LEAF.name]: {},\n });\n\n await this.client.sendStateEvent(\n this.roomId,\n UNSTABLE_MSC3089_BRANCH.name,\n {\n active: true,\n name: name,\n },\n res[\"event_id\"],\n );\n\n return res;\n }\n\n /**\n * Retrieves a file from the tree.\n * @param fileEventId - The event ID of the file.\n * @returns The file, or null if not found.\n */\n public getFile(fileEventId: string): MSC3089Branch | null {\n const branch = this.room.currentState.getStateEvents(UNSTABLE_MSC3089_BRANCH.name, fileEventId);\n return branch ? new MSC3089Branch(this.client, branch, this) : null;\n }\n\n /**\n * Gets an array of all known files for the tree.\n * @returns The known files. May be empty, but not null.\n */\n public listFiles(): MSC3089Branch[] {\n return this.listAllFiles().filter((b) => b.isActive);\n }\n\n /**\n * Gets an array of all known files for the tree, including inactive/invalid ones.\n * @returns The known files. May be empty, but not null.\n */\n public listAllFiles(): MSC3089Branch[] {\n const branches = this.room.currentState.getStateEvents(UNSTABLE_MSC3089_BRANCH.name) ?? [];\n return branches.map((e) => new MSC3089Branch(this.client, e, this));\n }\n}\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MBeaconEventContent } from \"../@types/beacon\";\nimport { BeaconInfoState, BeaconLocationState, parseBeaconContent, parseBeaconInfoContent } from \"../content-helpers\";\nimport { MatrixEvent } from \"./event\";\nimport { sortEventsByLatestContentTimestamp } from \"../utils\";\nimport { TypedEventEmitter } from \"./typed-event-emitter\";\n\nexport enum BeaconEvent {\n New = \"Beacon.new\",\n Update = \"Beacon.update\",\n LivenessChange = \"Beacon.LivenessChange\",\n Destroy = \"Beacon.Destroy\",\n LocationUpdate = \"Beacon.LocationUpdate\",\n}\n\nexport type BeaconEventHandlerMap = {\n [BeaconEvent.Update]: (event: MatrixEvent, beacon: Beacon) => void;\n [BeaconEvent.LivenessChange]: (isLive: boolean, beacon: Beacon) => void;\n [BeaconEvent.Destroy]: (beaconIdentifier: string) => void;\n [BeaconEvent.LocationUpdate]: (locationState: BeaconLocationState) => void;\n [BeaconEvent.Destroy]: (beaconIdentifier: string) => void;\n};\n\nexport const isTimestampInDuration = (startTimestamp: number, durationMs: number, timestamp: number): boolean =>\n timestamp >= startTimestamp && startTimestamp + durationMs >= timestamp;\n\n// beacon info events are uniquely identified by\n// `_`\nexport type BeaconIdentifier = string;\nexport const getBeaconInfoIdentifier = (event: MatrixEvent): BeaconIdentifier =>\n `${event.getRoomId()}_${event.getStateKey()}`;\n\n// https://github.com/matrix-org/matrix-spec-proposals/pull/3672\nexport class Beacon extends TypedEventEmitter, BeaconEventHandlerMap> {\n public readonly roomId: string;\n // beaconInfo is assigned by setBeaconInfo in the constructor\n // ! to make tsc believe it is definitely assigned\n private _beaconInfo!: BeaconInfoState;\n private _isLive?: boolean;\n private livenessWatchTimeout?: ReturnType;\n private _latestLocationEvent?: MatrixEvent;\n\n public constructor(private rootEvent: MatrixEvent) {\n super();\n this.roomId = this.rootEvent.getRoomId()!;\n this.setBeaconInfo(this.rootEvent);\n }\n\n public get isLive(): boolean {\n return !!this._isLive;\n }\n\n public get identifier(): BeaconIdentifier {\n return getBeaconInfoIdentifier(this.rootEvent);\n }\n\n public get beaconInfoId(): string {\n return this.rootEvent.getId()!;\n }\n\n public get beaconInfoOwner(): string {\n return this.rootEvent.getStateKey()!;\n }\n\n public get beaconInfoEventType(): string {\n return this.rootEvent.getType();\n }\n\n public get beaconInfo(): BeaconInfoState {\n return this._beaconInfo;\n }\n\n public get latestLocationState(): BeaconLocationState | undefined {\n return this._latestLocationEvent && parseBeaconContent(this._latestLocationEvent.getContent());\n }\n\n public get latestLocationEvent(): MatrixEvent | undefined {\n return this._latestLocationEvent;\n }\n\n public update(beaconInfoEvent: MatrixEvent): void {\n if (getBeaconInfoIdentifier(beaconInfoEvent) !== this.identifier) {\n throw new Error(\"Invalid updating event\");\n }\n // don't update beacon with an older event\n if (beaconInfoEvent.getTs() < this.rootEvent.getTs()) {\n return;\n }\n this.rootEvent = beaconInfoEvent;\n this.setBeaconInfo(this.rootEvent);\n\n this.emit(BeaconEvent.Update, beaconInfoEvent, this);\n this.clearLatestLocation();\n }\n\n public destroy(): void {\n if (this.livenessWatchTimeout) {\n clearTimeout(this.livenessWatchTimeout);\n }\n\n this._isLive = false;\n this.emit(BeaconEvent.Destroy, this.identifier);\n }\n\n /**\n * Monitor liveness of a beacon\n * Emits BeaconEvent.LivenessChange when beacon expires\n */\n public monitorLiveness(): void {\n if (this.livenessWatchTimeout) {\n clearTimeout(this.livenessWatchTimeout);\n }\n\n this.checkLiveness();\n if (!this.beaconInfo) return;\n if (this.isLive) {\n const expiryInMs = this.beaconInfo.timestamp! + this.beaconInfo.timeout - Date.now();\n if (expiryInMs > 1) {\n this.livenessWatchTimeout = setTimeout(() => {\n this.monitorLiveness();\n }, expiryInMs);\n }\n } else if (this.beaconInfo.timestamp! > Date.now()) {\n // beacon start timestamp is in the future\n // check liveness again then\n this.livenessWatchTimeout = setTimeout(() => {\n this.monitorLiveness();\n }, this.beaconInfo.timestamp! - Date.now());\n }\n }\n\n /**\n * Process Beacon locations\n * Emits BeaconEvent.LocationUpdate\n */\n public addLocations(beaconLocationEvents: MatrixEvent[]): void {\n // discard locations for beacons that are not live\n if (!this.isLive) {\n return;\n }\n\n const validLocationEvents = beaconLocationEvents.filter((event) => {\n const content = event.getContent();\n const parsed = parseBeaconContent(content);\n if (!parsed.uri || !parsed.timestamp) return false; // we won't be able to process these\n const { timestamp } = parsed;\n return (\n this._beaconInfo.timestamp &&\n // only include positions that were taken inside the beacon's live period\n isTimestampInDuration(this._beaconInfo.timestamp, this._beaconInfo.timeout, timestamp) &&\n // ignore positions older than our current latest location\n (!this.latestLocationState || timestamp > this.latestLocationState.timestamp!)\n );\n });\n const latestLocationEvent = validLocationEvents.sort(sortEventsByLatestContentTimestamp)?.[0];\n\n if (latestLocationEvent) {\n this._latestLocationEvent = latestLocationEvent;\n this.emit(BeaconEvent.LocationUpdate, this.latestLocationState!);\n }\n }\n\n private clearLatestLocation = (): void => {\n this._latestLocationEvent = undefined;\n this.emit(BeaconEvent.LocationUpdate, this.latestLocationState!);\n };\n\n private setBeaconInfo(event: MatrixEvent): void {\n this._beaconInfo = parseBeaconInfoContent(event.getContent());\n this.checkLiveness();\n }\n\n private checkLiveness(): void {\n const prevLiveness = this.isLive;\n\n // element web sets a beacon's start timestamp to the senders local current time\n // when Alice's system clock deviates slightly from Bob's a beacon Alice intended to be live\n // may have a start timestamp in the future from Bob's POV\n // handle this by adding 6min of leniency to the start timestamp when it is in the future\n if (!this.beaconInfo) return;\n const startTimestamp =\n this.beaconInfo.timestamp! > Date.now()\n ? this.beaconInfo.timestamp! - 360000 /* 6min */\n : this.beaconInfo.timestamp;\n this._isLive =\n !!this._beaconInfo.live &&\n !!startTimestamp &&\n isTimestampInDuration(startTimestamp, this._beaconInfo.timeout, Date.now());\n\n if (prevLiveness !== this.isLive) {\n this.emit(BeaconEvent.LivenessChange, this.isLive, this);\n }\n }\n}\n", - "/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixEvent } from \"./event\";\nimport { Direction } from \"./event-timeline\";\n\nexport class EventContext {\n private timeline: MatrixEvent[];\n private ourEventIndex = 0;\n private paginateTokens: Record = {\n [Direction.Backward]: null,\n [Direction.Forward]: null,\n };\n\n /**\n * Construct a new EventContext\n *\n * An eventcontext is used for circumstances such as search results, when we\n * have a particular event of interest, and a bunch of events before and after\n * it.\n *\n * It also stores pagination tokens for going backwards and forwards in the\n * timeline.\n *\n * @param ourEvent - the event at the centre of this context\n */\n public constructor(public readonly ourEvent: MatrixEvent) {\n this.timeline = [ourEvent];\n }\n\n /**\n * Get the main event of interest\n *\n * This is a convenience function for getTimeline()[getOurEventIndex()].\n *\n * @returns The event at the centre of this context.\n */\n public getEvent(): MatrixEvent {\n return this.timeline[this.ourEventIndex];\n }\n\n /**\n * Get the list of events in this context\n *\n * @returns An array of MatrixEvents\n */\n public getTimeline(): MatrixEvent[] {\n return this.timeline;\n }\n\n /**\n * Get the index in the timeline of our event\n */\n public getOurEventIndex(): number {\n return this.ourEventIndex;\n }\n\n /**\n * Get a pagination token.\n *\n * @param backwards - true to get the pagination token for going\n */\n public getPaginateToken(backwards = false): string | null {\n return this.paginateTokens[backwards ? Direction.Backward : Direction.Forward];\n }\n\n /**\n * Set a pagination token.\n *\n * Generally this will be used only by the matrix js sdk.\n *\n * @param token - pagination token\n * @param backwards - true to set the pagination token for going\n * backwards in time\n */\n public setPaginateToken(token?: string, backwards = false): void {\n this.paginateTokens[backwards ? Direction.Backward : Direction.Forward] = token ?? null;\n }\n\n /**\n * Add more events to the timeline\n *\n * @param events - new events, in timeline order\n * @param atStart - true to insert new events at the start\n */\n public addEvents(events: MatrixEvent[], atStart = false): void {\n // TODO: should we share logic with Room.addEventsToTimeline?\n // Should Room even use EventContext?\n\n if (atStart) {\n this.timeline = events.concat(this.timeline);\n this.ourEventIndex += events.length;\n } else {\n this.timeline = this.timeline.concat(events);\n }\n }\n}\n", - "/*\nCopyright 2015 - 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Enum for event statuses.\n * @readonly\n */\nexport enum EventStatus {\n /** The event was not sent and will no longer be retried. */\n NOT_SENT = \"not_sent\",\n\n /** The message is being encrypted */\n ENCRYPTING = \"encrypting\",\n\n /** The event is in the process of being sent. */\n SENDING = \"sending\",\n\n /** The event is in a queue waiting to be sent. */\n QUEUED = \"queued\",\n\n /** The event has been sent to the server, but we have not yet received the echo. */\n SENT = \"sent\",\n\n /** The event was cancelled before it was successfully sent. */\n CANCELLED = \"cancelled\",\n}\n", - "/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventTimeline, IAddEventOptions } from \"./event-timeline\";\nimport { MatrixEvent } from \"./event\";\nimport { logger } from \"../logger\";\nimport { Room, RoomEvent } from \"./room\";\nimport { Filter } from \"../filter\";\nimport { RoomState } from \"./room-state\";\nimport { TypedEventEmitter } from \"./typed-event-emitter\";\nimport { RelationsContainer } from \"./relations-container\";\nimport { MatrixClient } from \"../client\";\nimport { Thread, ThreadFilterType } from \"./thread\";\n\nconst DEBUG = true;\n\n/* istanbul ignore next */\nlet debuglog: (...args: any[]) => void;\nif (DEBUG) {\n // using bind means that we get to keep useful line numbers in the console\n debuglog = logger.log.bind(logger);\n} else {\n /* istanbul ignore next */\n debuglog = function (): void {};\n}\n\ninterface IOpts {\n // Set to true to enable improved timeline support.\n timelineSupport?: boolean;\n // The filter object, if any, for this timelineSet.\n filter?: Filter;\n pendingEvents?: boolean;\n}\n\nexport enum DuplicateStrategy {\n Ignore = \"ignore\",\n Replace = \"replace\",\n}\n\nexport interface IRoomTimelineData {\n // the timeline the event was added to/removed from\n timeline: EventTimeline;\n // true if the event was a real-time event added to the end of the live timeline\n liveEvent?: boolean;\n}\n\nexport interface IAddEventToTimelineOptions\n extends Pick {\n /** Whether the sync response came from cache */\n fromCache?: boolean;\n}\n\nexport interface IAddLiveEventOptions\n extends Pick {\n /** Applies to events in the timeline only. If this is 'replace' then if a\n * duplicate is encountered, the event passed to this function will replace\n * the existing event in the timeline. If this is not specified, or is\n * 'ignore', then the event passed to this function will be ignored\n * entirely, preserving the existing event in the timeline. Events are\n * identical based on their event ID only. */\n duplicateStrategy?: DuplicateStrategy;\n}\n\ntype EmittedEvents = RoomEvent.Timeline | RoomEvent.TimelineReset;\n\nexport type EventTimelineSetHandlerMap = {\n /**\n * Fires whenever the timeline in a room is updated.\n * @param event - The matrix event which caused this event to fire.\n * @param room - The room, if any, whose timeline was updated.\n * @param toStartOfTimeline - True if this event was added to the start\n * @param removed - True if this event has just been removed from the timeline\n * (beginning; oldest) of the timeline e.g. due to pagination.\n *\n * @param data - more data about the event\n *\n * @example\n * ```\n * matrixClient.on(\"Room.timeline\",\n * function(event, room, toStartOfTimeline, removed, data) {\n * if (!toStartOfTimeline && data.liveEvent) {\n * var messageToAppend = room.timeline.[room.timeline.length - 1];\n * }\n * });\n * ```\n */\n [RoomEvent.Timeline]: (\n event: MatrixEvent,\n room: Room | undefined,\n toStartOfTimeline: boolean | undefined,\n removed: boolean,\n data: IRoomTimelineData,\n ) => void;\n /**\n * Fires whenever the live timeline in a room is reset.\n *\n * When we get a 'limited' sync (for example, after a network outage), we reset\n * the live timeline to be empty before adding the recent events to the new\n * timeline. This event is fired after the timeline is reset, and before the\n * new events are added.\n *\n * @param room - The room whose live timeline was reset, if any\n * @param timelineSet - timelineSet room whose live timeline was reset\n * @param resetAllTimelines - True if all timelines were reset.\n */\n [RoomEvent.TimelineReset]: (\n room: Room | undefined,\n eventTimelineSet: EventTimelineSet,\n resetAllTimelines: boolean,\n ) => void;\n};\n\nexport class EventTimelineSet extends TypedEventEmitter {\n public readonly relations: RelationsContainer;\n private readonly timelineSupport: boolean;\n private readonly displayPendingEvents: boolean;\n private liveTimeline: EventTimeline;\n private timelines: EventTimeline[];\n private _eventIdToTimeline = new Map();\n private filter?: Filter;\n\n /**\n * Construct a set of EventTimeline objects, typically on behalf of a given\n * room. A room may have multiple EventTimelineSets for different levels\n * of filtering. The global notification list is also an EventTimelineSet, but\n * lacks a room.\n *\n *

This is an ordered sequence of timelines, which may or may not\n * be continuous. Each timeline lists a series of events, as well as tracking\n * the room state at the start and the end of the timeline (if appropriate).\n * It also tracks forward and backward pagination tokens, as well as containing\n * links to the next timeline in the sequence.\n *\n *

There is one special timeline - the 'live' timeline, which represents the\n * timeline to which events are being added in real-time as they are received\n * from the /sync API. Note that you should not retain references to this\n * timeline - even if it is the current timeline right now, it may not remain\n * so if the server gives us a timeline gap in /sync.\n *\n *

In order that we can find events from their ids later, we also maintain a\n * map from event_id to timeline and index.\n *\n * @param room - Room for this timelineSet. May be null for non-room cases, such as the\n * notification timeline.\n * @param opts - Options inherited from Room.\n * @param client - the Matrix client which owns this EventTimelineSet,\n * can be omitted if room is specified.\n * @param thread - the thread to which this timeline set relates.\n * @param isThreadTimeline - Whether this timeline set relates to a thread list timeline\n * (e.g., All threads or My threads)\n */\n public constructor(\n public readonly room: Room | undefined,\n opts: IOpts = {},\n client?: MatrixClient,\n public readonly thread?: Thread,\n public readonly threadListType: ThreadFilterType | null = null,\n ) {\n super();\n\n this.timelineSupport = Boolean(opts.timelineSupport);\n this.liveTimeline = new EventTimeline(this);\n this.displayPendingEvents = opts.pendingEvents !== false;\n\n // just a list - *not* ordered.\n this.timelines = [this.liveTimeline];\n this._eventIdToTimeline = new Map();\n\n this.filter = opts.filter;\n\n this.relations = this.room?.relations ?? new RelationsContainer(room?.client ?? client!);\n }\n\n /**\n * Get all the timelines in this set\n * @returns the timelines in this set\n */\n public getTimelines(): EventTimeline[] {\n return this.timelines;\n }\n\n /**\n * Get the filter object this timeline set is filtered on, if any\n * @returns the optional filter for this timelineSet\n */\n public getFilter(): Filter | undefined {\n return this.filter;\n }\n\n /**\n * Set the filter object this timeline set is filtered on\n * (passed to the server when paginating via /messages).\n * @param filter - the filter for this timelineSet\n */\n public setFilter(filter?: Filter): void {\n this.filter = filter;\n }\n\n /**\n * Get the list of pending sent events for this timelineSet's room, filtered\n * by the timelineSet's filter if appropriate.\n *\n * @returns A list of the sent events\n * waiting for remote echo.\n *\n * @throws If `opts.pendingEventOrdering` was not 'detached'\n */\n public getPendingEvents(): MatrixEvent[] {\n if (!this.room || !this.displayPendingEvents) {\n return [];\n }\n\n return this.room.getPendingEvents();\n }\n /**\n * Get the live timeline for this room.\n *\n * @returns live timeline\n */\n public getLiveTimeline(): EventTimeline {\n return this.liveTimeline;\n }\n\n /**\n * Set the live timeline for this room.\n *\n * @returns live timeline\n */\n public setLiveTimeline(timeline: EventTimeline): void {\n this.liveTimeline = timeline;\n }\n\n /**\n * Return the timeline (if any) this event is in.\n * @param eventId - the eventId being sought\n * @returns timeline\n */\n public eventIdToTimeline(eventId: string): EventTimeline | undefined {\n return this._eventIdToTimeline.get(eventId);\n }\n\n /**\n * Track a new event as if it were in the same timeline as an old event,\n * replacing it.\n * @param oldEventId - event ID of the original event\n * @param newEventId - event ID of the replacement event\n */\n public replaceEventId(oldEventId: string, newEventId: string): void {\n const existingTimeline = this._eventIdToTimeline.get(oldEventId);\n if (existingTimeline) {\n this._eventIdToTimeline.delete(oldEventId);\n this._eventIdToTimeline.set(newEventId, existingTimeline);\n }\n }\n\n /**\n * Reset the live timeline, and start a new one.\n *\n *

This is used when /sync returns a 'limited' timeline.\n *\n * @param backPaginationToken - token for back-paginating the new timeline\n * @param forwardPaginationToken - token for forward-paginating the old live timeline,\n * if absent or null, all timelines are reset.\n *\n * @remarks\n * Fires {@link RoomEvent.TimelineReset}\n */\n public resetLiveTimeline(backPaginationToken?: string, forwardPaginationToken?: string): void {\n // Each EventTimeline has RoomState objects tracking the state at the start\n // and end of that timeline. The copies at the end of the live timeline are\n // special because they will have listeners attached to monitor changes to\n // the current room state, so we move this RoomState from the end of the\n // current live timeline to the end of the new one and, if necessary,\n // replace it with a newly created one. We also make a copy for the start\n // of the new timeline.\n\n // if timeline support is disabled, forget about the old timelines\n const resetAllTimelines = !this.timelineSupport || !forwardPaginationToken;\n\n const oldTimeline = this.liveTimeline;\n const newTimeline = resetAllTimelines\n ? oldTimeline.forkLive(EventTimeline.FORWARDS)\n : oldTimeline.fork(EventTimeline.FORWARDS);\n\n if (resetAllTimelines) {\n this.timelines = [newTimeline];\n this._eventIdToTimeline = new Map();\n } else {\n this.timelines.push(newTimeline);\n }\n\n if (forwardPaginationToken) {\n // Now set the forward pagination token on the old live timeline\n // so it can be forward-paginated.\n oldTimeline.setPaginationToken(forwardPaginationToken, EventTimeline.FORWARDS);\n }\n\n // make sure we set the pagination token before firing timelineReset,\n // otherwise clients which start back-paginating will fail, and then get\n // stuck without realising that they *can* back-paginate.\n newTimeline.setPaginationToken(backPaginationToken ?? null, EventTimeline.BACKWARDS);\n\n // Now we can swap the live timeline to the new one.\n this.liveTimeline = newTimeline;\n this.emit(RoomEvent.TimelineReset, this.room, this, resetAllTimelines);\n }\n\n /**\n * Get the timeline which contains the given event, if any\n *\n * @param eventId - event ID to look for\n * @returns timeline containing\n * the given event, or null if unknown\n */\n public getTimelineForEvent(eventId?: string): EventTimeline | null {\n if (eventId === null || eventId === undefined) {\n return null;\n }\n const res = this._eventIdToTimeline.get(eventId);\n return res === undefined ? null : res;\n }\n\n /**\n * Get an event which is stored in our timelines\n *\n * @param eventId - event ID to look for\n * @returns the given event, or undefined if unknown\n */\n public findEventById(eventId: string): MatrixEvent | undefined {\n const tl = this.getTimelineForEvent(eventId);\n if (!tl) {\n return undefined;\n }\n return tl.getEvents().find(function (ev) {\n return ev.getId() == eventId;\n });\n }\n\n /**\n * Add a new timeline to this timeline list\n *\n * @returns newly-created timeline\n */\n public addTimeline(): EventTimeline {\n if (!this.timelineSupport) {\n throw new Error(\n \"timeline support is disabled. Set the 'timelineSupport'\" +\n \" parameter to true when creating MatrixClient to enable\" +\n \" it.\",\n );\n }\n\n const timeline = new EventTimeline(this);\n this.timelines.push(timeline);\n return timeline;\n }\n\n /**\n * Add events to a timeline\n *\n *

Will fire \"Room.timeline\" for each event added.\n *\n * @param events - A list of events to add.\n *\n * @param toStartOfTimeline - True to add these events to the start\n * (oldest) instead of the end (newest) of the timeline. If true, the oldest\n * event will be the last element of 'events'.\n *\n * @param timeline - timeline to\n * add events to.\n *\n * @param paginationToken - token for the next batch of events\n *\n * @remarks\n * Fires {@link RoomEvent.Timeline}\n *\n */\n public addEventsToTimeline(\n events: MatrixEvent[],\n toStartOfTimeline: boolean,\n timeline: EventTimeline,\n paginationToken?: string | null,\n ): void {\n if (!timeline) {\n throw new Error(\"'timeline' not specified for EventTimelineSet.addEventsToTimeline\");\n }\n\n if (!toStartOfTimeline && timeline == this.liveTimeline) {\n throw new Error(\n \"EventTimelineSet.addEventsToTimeline cannot be used for adding events to \" +\n \"the live timeline - use Room.addLiveEvents instead\",\n );\n }\n\n if (this.filter) {\n events = this.filter.filterRoomTimeline(events);\n if (!events.length) {\n return;\n }\n }\n\n const direction = toStartOfTimeline ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS;\n const inverseDirection = toStartOfTimeline ? EventTimeline.FORWARDS : EventTimeline.BACKWARDS;\n\n // Adding events to timelines can be quite complicated. The following\n // illustrates some of the corner-cases.\n //\n // Let's say we start by knowing about four timelines. timeline3 and\n // timeline4 are neighbours:\n //\n // timeline1 timeline2 timeline3 timeline4\n // [M] [P] [S] <------> [T]\n //\n // Now we paginate timeline1, and get the following events from the server:\n // [M, N, P, R, S, T, U].\n //\n // 1. First, we ignore event M, since we already know about it.\n //\n // 2. Next, we append N to timeline 1.\n //\n // 3. Next, we don't add event P, since we already know about it,\n // but we do link together the timelines. We now have:\n //\n // timeline1 timeline2 timeline3 timeline4\n // [M, N] <---> [P] [S] <------> [T]\n //\n // 4. Now we add event R to timeline2:\n //\n // timeline1 timeline2 timeline3 timeline4\n // [M, N] <---> [P, R] [S] <------> [T]\n //\n // Note that we have switched the timeline we are working on from\n // timeline1 to timeline2.\n //\n // 5. We ignore event S, but again join the timelines:\n //\n // timeline1 timeline2 timeline3 timeline4\n // [M, N] <---> [P, R] <---> [S] <------> [T]\n //\n // 6. We ignore event T, and the timelines are already joined, so there\n // is nothing to do.\n //\n // 7. Finally, we add event U to timeline4:\n //\n // timeline1 timeline2 timeline3 timeline4\n // [M, N] <---> [P, R] <---> [S] <------> [T, U]\n //\n // The important thing to note in the above is what happened when we\n // already knew about a given event:\n //\n // - if it was appropriate, we joined up the timelines (steps 3, 5).\n // - in any case, we started adding further events to the timeline which\n // contained the event we knew about (steps 3, 5, 6).\n //\n //\n // So much for adding events to the timeline. But what do we want to do\n // with the pagination token?\n //\n // In the case above, we will be given a pagination token which tells us how to\n // get events beyond 'U' - in this case, it makes sense to store this\n // against timeline4. But what if timeline4 already had 'U' and beyond? in\n // that case, our best bet is to throw away the pagination token we were\n // given and stick with whatever token timeline4 had previously. In short,\n // we want to only store the pagination token if the last event we receive\n // is one we didn't previously know about.\n //\n // We make an exception for this if it turns out that we already knew about\n // *all* of the events, and we weren't able to join up any timelines. When\n // that happens, it means our existing pagination token is faulty, since it\n // is only telling us what we already know. Rather than repeatedly\n // paginating with the same token, we might as well use the new pagination\n // token in the hope that we eventually work our way out of the mess.\n\n let didUpdate = false;\n let lastEventWasNew = false;\n for (const event of events) {\n const eventId = event.getId()!;\n\n const existingTimeline = this._eventIdToTimeline.get(eventId);\n\n if (!existingTimeline) {\n // we don't know about this event yet. Just add it to the timeline.\n this.addEventToTimeline(event, timeline, {\n toStartOfTimeline,\n });\n lastEventWasNew = true;\n didUpdate = true;\n continue;\n }\n\n lastEventWasNew = false;\n\n if (existingTimeline == timeline) {\n debuglog(\"Event \" + eventId + \" already in timeline \" + timeline);\n continue;\n }\n\n const neighbour = timeline.getNeighbouringTimeline(direction);\n if (neighbour) {\n // this timeline already has a neighbour in the relevant direction;\n // let's assume the timelines are already correctly linked up, and\n // skip over to it.\n //\n // there's probably some edge-case here where we end up with an\n // event which is in a timeline a way down the chain, and there is\n // a break in the chain somewhere. But I can't really imagine how\n // that would happen, so I'm going to ignore it for now.\n //\n if (existingTimeline == neighbour) {\n debuglog(\"Event \" + eventId + \" in neighbouring timeline - \" + \"switching to \" + existingTimeline);\n } else {\n debuglog(\"Event \" + eventId + \" already in a different \" + \"timeline \" + existingTimeline);\n }\n timeline = existingTimeline;\n continue;\n }\n\n // time to join the timelines.\n logger.info(\n \"Already have timeline for \" + eventId + \" - joining timeline \" + timeline + \" to \" + existingTimeline,\n );\n\n // Variables to keep the line length limited below.\n const existingIsLive = existingTimeline === this.liveTimeline;\n const timelineIsLive = timeline === this.liveTimeline;\n\n const backwardsIsLive = direction === EventTimeline.BACKWARDS && existingIsLive;\n const forwardsIsLive = direction === EventTimeline.FORWARDS && timelineIsLive;\n\n if (backwardsIsLive || forwardsIsLive) {\n // The live timeline should never be spliced into a non-live position.\n // We use independent logging to better discover the problem at a glance.\n if (backwardsIsLive) {\n logger.warn(\n \"Refusing to set a preceding existingTimeLine on our \" +\n \"timeline as the existingTimeLine is live (\" +\n existingTimeline +\n \")\",\n );\n }\n if (forwardsIsLive) {\n logger.warn(\n \"Refusing to set our preceding timeline on a existingTimeLine \" +\n \"as our timeline is live (\" +\n timeline +\n \")\",\n );\n }\n continue; // abort splicing - try next event\n }\n\n timeline.setNeighbouringTimeline(existingTimeline, direction);\n existingTimeline.setNeighbouringTimeline(timeline, inverseDirection);\n\n timeline = existingTimeline;\n didUpdate = true;\n }\n\n // see above - if the last event was new to us, or if we didn't find any\n // new information, we update the pagination token for whatever\n // timeline we ended up on.\n if (lastEventWasNew || !didUpdate) {\n if (direction === EventTimeline.FORWARDS && timeline === this.liveTimeline) {\n logger.warn({ lastEventWasNew, didUpdate }); // for debugging\n logger.warn(\n `Refusing to set forwards pagination token of live timeline ` + `${timeline} to ${paginationToken}`,\n );\n return;\n }\n timeline.setPaginationToken(paginationToken ?? null, direction);\n }\n }\n\n /**\n * Add an event to the end of this live timeline.\n *\n * @param event - Event to be added\n * @param options - addLiveEvent options\n */\n public addLiveEvent(\n event: MatrixEvent,\n { duplicateStrategy, fromCache, roomState, timelineWasEmpty }: IAddLiveEventOptions,\n ): void;\n /**\n * @deprecated In favor of the overload with `IAddLiveEventOptions`\n */\n public addLiveEvent(\n event: MatrixEvent,\n duplicateStrategy?: DuplicateStrategy,\n fromCache?: boolean,\n roomState?: RoomState,\n ): void;\n public addLiveEvent(\n event: MatrixEvent,\n duplicateStrategyOrOpts?: DuplicateStrategy | IAddLiveEventOptions,\n fromCache = false,\n roomState?: RoomState,\n ): void {\n let duplicateStrategy = (duplicateStrategyOrOpts as DuplicateStrategy) || DuplicateStrategy.Ignore;\n let timelineWasEmpty: boolean | undefined;\n if (typeof duplicateStrategyOrOpts === \"object\") {\n ({\n duplicateStrategy = DuplicateStrategy.Ignore,\n fromCache = false,\n roomState,\n timelineWasEmpty,\n } = duplicateStrategyOrOpts);\n } else if (duplicateStrategyOrOpts !== undefined) {\n // Deprecation warning\n // FIXME: Remove after 2023-06-01 (technical debt)\n logger.warn(\n \"Overload deprecated: \" +\n \"`EventTimelineSet.addLiveEvent(event, duplicateStrategy?, fromCache?, roomState?)` \" +\n \"is deprecated in favor of the overload with \" +\n \"`EventTimelineSet.addLiveEvent(event, IAddLiveEventOptions)`\",\n );\n }\n\n if (this.filter) {\n const events = this.filter.filterRoomTimeline([event]);\n if (!events.length) {\n return;\n }\n }\n\n const timeline = this._eventIdToTimeline.get(event.getId()!);\n if (timeline) {\n if (duplicateStrategy === DuplicateStrategy.Replace) {\n debuglog(\"EventTimelineSet.addLiveEvent: replacing duplicate event \" + event.getId());\n const tlEvents = timeline.getEvents();\n for (let j = 0; j < tlEvents.length; j++) {\n if (tlEvents[j].getId() === event.getId()) {\n // still need to set the right metadata on this event\n if (!roomState) {\n roomState = timeline.getState(EventTimeline.FORWARDS);\n }\n EventTimeline.setEventMetadata(event, roomState!, false);\n tlEvents[j] = event;\n\n // XXX: we need to fire an event when this happens.\n break;\n }\n }\n } else {\n debuglog(\"EventTimelineSet.addLiveEvent: ignoring duplicate event \" + event.getId());\n }\n return;\n }\n\n this.addEventToTimeline(event, this.liveTimeline, {\n toStartOfTimeline: false,\n fromCache,\n roomState,\n timelineWasEmpty,\n });\n }\n\n /**\n * Add event to the given timeline, and emit Room.timeline. Assumes\n * we have already checked we don't know about this event.\n *\n * Will fire \"Room.timeline\" for each event added.\n *\n * @param options - addEventToTimeline options\n *\n * @remarks\n * Fires {@link RoomEvent.Timeline}\n */\n public addEventToTimeline(\n event: MatrixEvent,\n timeline: EventTimeline,\n { toStartOfTimeline, fromCache, roomState, timelineWasEmpty }: IAddEventToTimelineOptions,\n ): void;\n /**\n * @deprecated In favor of the overload with `IAddEventToTimelineOptions`\n */\n public addEventToTimeline(\n event: MatrixEvent,\n timeline: EventTimeline,\n toStartOfTimeline: boolean,\n fromCache?: boolean,\n roomState?: RoomState,\n ): void;\n public addEventToTimeline(\n event: MatrixEvent,\n timeline: EventTimeline,\n toStartOfTimelineOrOpts: boolean | IAddEventToTimelineOptions,\n fromCache = false,\n roomState?: RoomState,\n ): void {\n let toStartOfTimeline = !!toStartOfTimelineOrOpts;\n let timelineWasEmpty: boolean | undefined;\n if (typeof toStartOfTimelineOrOpts === \"object\") {\n ({ toStartOfTimeline, fromCache = false, roomState, timelineWasEmpty } = toStartOfTimelineOrOpts);\n } else if (toStartOfTimelineOrOpts !== undefined) {\n // Deprecation warning\n // FIXME: Remove after 2023-06-01 (technical debt)\n logger.warn(\n \"Overload deprecated: \" +\n \"`EventTimelineSet.addEventToTimeline(event, timeline, toStartOfTimeline, fromCache?, roomState?)` \" +\n \"is deprecated in favor of the overload with \" +\n \"`EventTimelineSet.addEventToTimeline(event, timeline, IAddEventToTimelineOptions)`\",\n );\n }\n\n if (timeline.getTimelineSet() !== this) {\n throw new Error(`EventTimelineSet.addEventToTimeline: Timeline=${timeline.toString()} does not belong \" +\n \"in timelineSet(threadId=${this.thread?.id})`);\n }\n\n // Make sure events don't get mixed in timelines they shouldn't be in (e.g. a\n // threaded message should not be in the main timeline).\n //\n // We can only run this check for timelines with a `room` because `canContain`\n // requires it\n if (this.room && !this.canContain(event)) {\n let eventDebugString = `event=${event.getId()}`;\n if (event.threadRootId) {\n eventDebugString += `(belongs to thread=${event.threadRootId})`;\n }\n logger.warn(\n `EventTimelineSet.addEventToTimeline: Ignoring ${eventDebugString} that does not belong ` +\n `in timeline=${timeline.toString()} timelineSet(threadId=${this.thread?.id})`,\n );\n return;\n }\n\n const eventId = event.getId()!;\n timeline.addEvent(event, {\n toStartOfTimeline,\n roomState,\n timelineWasEmpty,\n });\n this._eventIdToTimeline.set(eventId, timeline);\n\n this.relations.aggregateParentEvent(event);\n this.relations.aggregateChildEvent(event, this);\n\n const data: IRoomTimelineData = {\n timeline: timeline,\n liveEvent: !toStartOfTimeline && timeline == this.liveTimeline && !fromCache,\n };\n this.emit(RoomEvent.Timeline, event, this.room, Boolean(toStartOfTimeline), false, data);\n }\n\n /**\n * Replaces event with ID oldEventId with one with newEventId, if oldEventId is\n * recognised. Otherwise, add to the live timeline. Used to handle remote echos.\n *\n * @param localEvent - the new event to be added to the timeline\n * @param oldEventId - the ID of the original event\n * @param newEventId - the ID of the replacement event\n *\n * @remarks\n * Fires {@link RoomEvent.Timeline}\n */\n public handleRemoteEcho(localEvent: MatrixEvent, oldEventId: string, newEventId: string): void {\n // XXX: why don't we infer newEventId from localEvent?\n const existingTimeline = this._eventIdToTimeline.get(oldEventId);\n if (existingTimeline) {\n this._eventIdToTimeline.delete(oldEventId);\n this._eventIdToTimeline.set(newEventId, existingTimeline);\n } else if (!this.filter || this.filter.filterRoomTimeline([localEvent]).length) {\n this.addEventToTimeline(localEvent, this.liveTimeline, {\n toStartOfTimeline: false,\n });\n }\n }\n\n /**\n * Removes a single event from this room.\n *\n * @param eventId - The id of the event to remove\n *\n * @returns the removed event, or null if the event was not found\n * in this room.\n */\n public removeEvent(eventId: string): MatrixEvent | null {\n const timeline = this._eventIdToTimeline.get(eventId);\n if (!timeline) {\n return null;\n }\n\n const removed = timeline.removeEvent(eventId);\n if (removed) {\n this._eventIdToTimeline.delete(eventId);\n const data = {\n timeline: timeline,\n };\n this.emit(RoomEvent.Timeline, removed, this.room, undefined, true, data);\n }\n return removed;\n }\n\n /**\n * Determine where two events appear in the timeline relative to one another\n *\n * @param eventId1 - The id of the first event\n * @param eventId2 - The id of the second event\n\n * @returns a number less than zero if eventId1 precedes eventId2, and\n * greater than zero if eventId1 succeeds eventId2. zero if they are the\n * same event; null if we can't tell (either because we don't know about one\n * of the events, or because they are in separate timelines which don't join\n * up).\n */\n public compareEventOrdering(eventId1: string, eventId2: string): number | null {\n if (eventId1 == eventId2) {\n // optimise this case\n return 0;\n }\n\n const timeline1 = this._eventIdToTimeline.get(eventId1);\n const timeline2 = this._eventIdToTimeline.get(eventId2);\n\n if (timeline1 === undefined) {\n return null;\n }\n if (timeline2 === undefined) {\n return null;\n }\n\n if (timeline1 === timeline2) {\n // both events are in the same timeline - figure out their relative indices\n let idx1: number | undefined = undefined;\n let idx2: number | undefined = undefined;\n const events = timeline1.getEvents();\n for (let idx = 0; idx < events.length && (idx1 === undefined || idx2 === undefined); idx++) {\n const evId = events[idx].getId();\n if (evId == eventId1) {\n idx1 = idx;\n }\n if (evId == eventId2) {\n idx2 = idx;\n }\n }\n return idx1! - idx2!;\n }\n\n // the events are in different timelines. Iterate through the\n // linkedlist to see which comes first.\n\n // first work forwards from timeline1\n let tl: EventTimeline | null = timeline1;\n while (tl) {\n if (tl === timeline2) {\n // timeline1 is before timeline2\n return -1;\n }\n tl = tl.getNeighbouringTimeline(EventTimeline.FORWARDS);\n }\n\n // now try backwards from timeline1\n tl = timeline1;\n while (tl) {\n if (tl === timeline2) {\n // timeline2 is before timeline1\n return 1;\n }\n tl = tl.getNeighbouringTimeline(EventTimeline.BACKWARDS);\n }\n\n // the timelines are not contiguous.\n return null;\n }\n\n /**\n * Determine whether a given event can sanely be added to this event timeline set,\n * for timeline sets relating to a thread, only return true for events in the same\n * thread timeline, for timeline sets not relating to a thread only return true\n * for events which should be shown in the main room timeline.\n * Requires the `room` property to have been set at EventTimelineSet construction time.\n *\n * @param event - the event to check whether it belongs to this timeline set.\n * @throws Error if `room` was not set when constructing this timeline set.\n * @returns whether the event belongs to this timeline set.\n */\n public canContain(event: MatrixEvent): boolean {\n if (!this.room) {\n throw new Error(\n \"Cannot call `EventTimelineSet::canContain without a `room` set. \" +\n \"Set the room when creating the EventTimelineSet to call this method.\",\n );\n }\n\n const { threadId, shouldLiveInRoom } = this.room.eventShouldLiveIn(event);\n\n if (this.thread) {\n return this.thread.id === threadId;\n }\n return shouldLiveInRoom;\n }\n}\n", - "/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from \"../logger\";\nimport { IMarkerFoundOptions, RoomState } from \"./room-state\";\nimport { EventTimelineSet } from \"./event-timeline-set\";\nimport { MatrixEvent } from \"./event\";\nimport { Filter } from \"../filter\";\nimport { EventType } from \"../@types/event\";\n\nexport interface IInitialiseStateOptions extends Pick {\n // This is a separate interface without any extra stuff currently added on\n // top of `IMarkerFoundOptions` just because it feels like they have\n // different concerns. One shouldn't necessarily look to add to\n // `IMarkerFoundOptions` just because they want to add an extra option to\n // `initialiseState`.\n}\n\nexport interface IAddEventOptions extends Pick {\n /** Whether to insert the new event at the start of the timeline where the\n * oldest events are (timeline is in chronological order, oldest to most\n * recent) */\n toStartOfTimeline: boolean;\n /** The state events to reconcile metadata from */\n roomState?: RoomState;\n}\n\nexport enum Direction {\n Backward = \"b\",\n Forward = \"f\",\n}\n\nexport class EventTimeline {\n /**\n * Symbolic constant for methods which take a 'direction' argument:\n * refers to the start of the timeline, or backwards in time.\n */\n public static readonly BACKWARDS = Direction.Backward;\n\n /**\n * Symbolic constant for methods which take a 'direction' argument:\n * refers to the end of the timeline, or forwards in time.\n */\n public static readonly FORWARDS = Direction.Forward;\n\n /**\n * Static helper method to set sender and target properties\n *\n * @param event - the event whose metadata is to be set\n * @param stateContext - the room state to be queried\n * @param toStartOfTimeline - if true the event's forwardLooking flag is set false\n */\n public static setEventMetadata(event: MatrixEvent, stateContext: RoomState, toStartOfTimeline: boolean): void {\n // When we try to generate a sentinel member before we have that member\n // in the members object, we still generate a sentinel but it doesn't\n // have a membership event, so test to see if events.member is set. We\n // check this to avoid overriding non-sentinel members by sentinel ones\n // when adding the event to a filtered timeline\n if (!event.sender?.events?.member) {\n event.sender = stateContext.getSentinelMember(event.getSender()!);\n }\n if (!event.target?.events?.member && event.getType() === EventType.RoomMember) {\n event.target = stateContext.getSentinelMember(event.getStateKey()!);\n }\n\n if (event.isState()) {\n // room state has no concept of 'old' or 'current', but we want the\n // room state to regress back to previous values if toStartOfTimeline\n // is set, which means inspecting prev_content if it exists. This\n // is done by toggling the forwardLooking flag.\n if (toStartOfTimeline) {\n event.forwardLooking = false;\n }\n }\n }\n\n private readonly roomId: string | null;\n private readonly name: string;\n private events: MatrixEvent[] = [];\n private baseIndex = 0;\n\n private startState?: RoomState;\n private endState?: RoomState;\n // If we have a roomId then we delegate pagination token storage to the room state objects `startState` and\n // `endState`, but for things like the notification timeline which mix multiple rooms we store the tokens ourselves.\n private startToken: string | null = null;\n private endToken: string | null = null;\n\n private prevTimeline: EventTimeline | null = null;\n private nextTimeline: EventTimeline | null = null;\n public paginationRequests: Record | null> = {\n [Direction.Backward]: null,\n [Direction.Forward]: null,\n };\n\n /**\n * Construct a new EventTimeline\n *\n *

An EventTimeline represents a contiguous sequence of events in a room.\n *\n *

As well as keeping track of the events themselves, it stores the state of\n * the room at the beginning and end of the timeline, and pagination tokens for\n * going backwards and forwards in the timeline.\n *\n *

In order that clients can meaningfully maintain an index into a timeline,\n * the EventTimeline object tracks a 'baseIndex'. This starts at zero, but is\n * incremented when events are prepended to the timeline. The index of an event\n * relative to baseIndex therefore remains constant.\n *\n *

Once a timeline joins up with its neighbour, they are linked together into a\n * doubly-linked list.\n *\n * @param eventTimelineSet - the set of timelines this is part of\n */\n public constructor(private readonly eventTimelineSet: EventTimelineSet) {\n this.roomId = eventTimelineSet.room?.roomId ?? null;\n if (this.roomId) {\n this.startState = new RoomState(this.roomId);\n this.endState = new RoomState(this.roomId);\n }\n\n // this is used by client.js\n this.paginationRequests = { b: null, f: null };\n\n this.name = this.roomId + \":\" + new Date().toISOString();\n }\n\n /**\n * Initialise the start and end state with the given events\n *\n *

This can only be called before any events are added.\n *\n * @param stateEvents - list of state events to initialise the\n * state with.\n * @throws Error if an attempt is made to call this after addEvent is called.\n */\n public initialiseState(stateEvents: MatrixEvent[], { timelineWasEmpty }: IInitialiseStateOptions = {}): void {\n if (this.events.length > 0) {\n throw new Error(\"Cannot initialise state after events are added\");\n }\n\n this.startState?.setStateEvents(stateEvents, { timelineWasEmpty });\n this.endState?.setStateEvents(stateEvents, { timelineWasEmpty });\n }\n\n /**\n * Forks the (live) timeline, taking ownership of the existing directional state of this timeline.\n * All attached listeners will keep receiving state updates from the new live timeline state.\n * The end state of this timeline gets replaced with an independent copy of the current RoomState,\n * and will need a new pagination token if it ever needs to paginate forwards.\n\n * @param direction - EventTimeline.BACKWARDS to get the state at the\n * start of the timeline; EventTimeline.FORWARDS to get the state at the end\n * of the timeline.\n *\n * @returns the new timeline\n */\n public forkLive(direction: Direction): EventTimeline {\n const forkState = this.getState(direction);\n const timeline = new EventTimeline(this.eventTimelineSet);\n timeline.startState = forkState?.clone();\n // Now clobber the end state of the new live timeline with that from the\n // previous live timeline. It will be identical except that we'll keep\n // using the same RoomMember objects for the 'live' set of members with any\n // listeners still attached\n timeline.endState = forkState;\n // Firstly, we just stole the current timeline's end state, so it needs a new one.\n // Make an immutable copy of the state so back pagination will get the correct sentinels.\n this.endState = forkState?.clone();\n return timeline;\n }\n\n /**\n * Creates an independent timeline, inheriting the directional state from this timeline.\n *\n * @param direction - EventTimeline.BACKWARDS to get the state at the\n * start of the timeline; EventTimeline.FORWARDS to get the state at the end\n * of the timeline.\n *\n * @returns the new timeline\n */\n public fork(direction: Direction): EventTimeline {\n const forkState = this.getState(direction);\n const timeline = new EventTimeline(this.eventTimelineSet);\n timeline.startState = forkState?.clone();\n timeline.endState = forkState?.clone();\n return timeline;\n }\n\n /**\n * Get the ID of the room for this timeline\n * @returns room ID\n */\n public getRoomId(): string | null {\n return this.roomId;\n }\n\n /**\n * Get the filter for this timeline's timelineSet (if any)\n * @returns filter\n */\n public getFilter(): Filter | undefined {\n return this.eventTimelineSet.getFilter();\n }\n\n /**\n * Get the timelineSet for this timeline\n * @returns timelineSet\n */\n public getTimelineSet(): EventTimelineSet {\n return this.eventTimelineSet;\n }\n\n /**\n * Get the base index.\n *\n *

This is an index which is incremented when events are prepended to the\n * timeline. An individual event therefore stays at the same index in the array\n * relative to the base index (although note that a given event's index may\n * well be less than the base index, thus giving that event a negative relative\n * index).\n */\n public getBaseIndex(): number {\n return this.baseIndex;\n }\n\n /**\n * Get the list of events in this context\n *\n * @returns An array of MatrixEvents\n */\n public getEvents(): MatrixEvent[] {\n return this.events;\n }\n\n /**\n * Get the room state at the start/end of the timeline\n *\n * @param direction - EventTimeline.BACKWARDS to get the state at the\n * start of the timeline; EventTimeline.FORWARDS to get the state at the end\n * of the timeline.\n *\n * @returns state at the start/end of the timeline\n */\n public getState(direction: Direction): RoomState | undefined {\n if (direction == EventTimeline.BACKWARDS) {\n return this.startState;\n } else if (direction == EventTimeline.FORWARDS) {\n return this.endState;\n } else {\n throw new Error(\"Invalid direction '\" + direction + \"'\");\n }\n }\n\n /**\n * Get a pagination token\n *\n * @param direction - EventTimeline.BACKWARDS to get the pagination\n * token for going backwards in time; EventTimeline.FORWARDS to get the\n * pagination token for going forwards in time.\n *\n * @returns pagination token\n */\n public getPaginationToken(direction: Direction): string | null {\n if (this.roomId) {\n return this.getState(direction)!.paginationToken;\n } else if (direction === Direction.Backward) {\n return this.startToken;\n } else {\n return this.endToken;\n }\n }\n\n /**\n * Set a pagination token\n *\n * @param token - pagination token\n *\n * @param direction - EventTimeline.BACKWARDS to set the pagination\n * token for going backwards in time; EventTimeline.FORWARDS to set the\n * pagination token for going forwards in time.\n */\n public setPaginationToken(token: string | null, direction: Direction): void {\n if (this.roomId) {\n this.getState(direction)!.paginationToken = token;\n } else if (direction === Direction.Backward) {\n this.startToken = token;\n } else {\n this.endToken = token;\n }\n }\n\n /**\n * Get the next timeline in the series\n *\n * @param direction - EventTimeline.BACKWARDS to get the previous\n * timeline; EventTimeline.FORWARDS to get the next timeline.\n *\n * @returns previous or following timeline, if they have been\n * joined up.\n */\n public getNeighbouringTimeline(direction: Direction): EventTimeline | null {\n if (direction == EventTimeline.BACKWARDS) {\n return this.prevTimeline;\n } else if (direction == EventTimeline.FORWARDS) {\n return this.nextTimeline;\n } else {\n throw new Error(\"Invalid direction '\" + direction + \"'\");\n }\n }\n\n /**\n * Set the next timeline in the series\n *\n * @param neighbour - previous/following timeline\n *\n * @param direction - EventTimeline.BACKWARDS to set the previous\n * timeline; EventTimeline.FORWARDS to set the next timeline.\n *\n * @throws Error if an attempt is made to set the neighbouring timeline when\n * it is already set.\n */\n public setNeighbouringTimeline(neighbour: EventTimeline, direction: Direction): void {\n if (this.getNeighbouringTimeline(direction)) {\n throw new Error(\n \"timeline already has a neighbouring timeline - \" +\n \"cannot reset neighbour (direction: \" +\n direction +\n \")\",\n );\n }\n\n if (direction == EventTimeline.BACKWARDS) {\n this.prevTimeline = neighbour;\n } else if (direction == EventTimeline.FORWARDS) {\n this.nextTimeline = neighbour;\n } else {\n throw new Error(\"Invalid direction '\" + direction + \"'\");\n }\n\n // make sure we don't try to paginate this timeline\n this.setPaginationToken(null, direction);\n }\n\n /**\n * Add a new event to the timeline, and update the state\n *\n * @param event - new event\n * @param options - addEvent options\n */\n public addEvent(event: MatrixEvent, { toStartOfTimeline, roomState, timelineWasEmpty }: IAddEventOptions): void;\n /**\n * @deprecated In favor of the overload with `IAddEventOptions`\n */\n public addEvent(event: MatrixEvent, toStartOfTimeline: boolean, roomState?: RoomState): void;\n public addEvent(\n event: MatrixEvent,\n toStartOfTimelineOrOpts: boolean | IAddEventOptions,\n roomState?: RoomState,\n ): void {\n let toStartOfTimeline = !!toStartOfTimelineOrOpts;\n let timelineWasEmpty: boolean | undefined;\n if (typeof toStartOfTimelineOrOpts === \"object\") {\n ({ toStartOfTimeline, roomState, timelineWasEmpty } = toStartOfTimelineOrOpts);\n } else if (toStartOfTimelineOrOpts !== undefined) {\n // Deprecation warning\n // FIXME: Remove after 2023-06-01 (technical debt)\n logger.warn(\n \"Overload deprecated: \" +\n \"`EventTimeline.addEvent(event, toStartOfTimeline, roomState?)` \" +\n \"is deprecated in favor of the overload with `EventTimeline.addEvent(event, IAddEventOptions)`\",\n );\n }\n\n if (!roomState) {\n roomState = toStartOfTimeline ? this.startState : this.endState;\n }\n\n const timelineSet = this.getTimelineSet();\n\n if (timelineSet.room) {\n EventTimeline.setEventMetadata(event, roomState!, toStartOfTimeline);\n\n // modify state but only on unfiltered timelineSets\n if (event.isState() && timelineSet.room.getUnfilteredTimelineSet() === timelineSet) {\n roomState?.setStateEvents([event], { timelineWasEmpty });\n // it is possible that the act of setting the state event means we\n // can set more metadata (specifically sender/target props), so try\n // it again if the prop wasn't previously set. It may also mean that\n // the sender/target is updated (if the event set was a room member event)\n // so we want to use the *updated* member (new avatar/name) instead.\n //\n // However, we do NOT want to do this on member events if we're going\n // back in time, else we'll set the .sender value for BEFORE the given\n // member event, whereas we want to set the .sender value for the ACTUAL\n // member event itself.\n if (!event.sender || (event.getType() === EventType.RoomMember && !toStartOfTimeline)) {\n EventTimeline.setEventMetadata(event, roomState!, toStartOfTimeline);\n }\n }\n }\n\n let insertIndex: number;\n\n if (toStartOfTimeline) {\n insertIndex = 0;\n } else {\n insertIndex = this.events.length;\n }\n\n this.events.splice(insertIndex, 0, event); // insert element\n if (toStartOfTimeline) {\n this.baseIndex++;\n }\n }\n\n /**\n * Remove an event from the timeline\n *\n * @param eventId - ID of event to be removed\n * @returns removed event, or null if not found\n */\n public removeEvent(eventId: string): MatrixEvent | null {\n for (let i = this.events.length - 1; i >= 0; i--) {\n const ev = this.events[i];\n if (ev.getId() == eventId) {\n this.events.splice(i, 1);\n if (i < this.baseIndex) {\n this.baseIndex--;\n }\n return ev;\n }\n }\n return null;\n }\n\n /**\n * Return a string to identify this timeline, for debugging\n *\n * @returns name for this timeline\n */\n public toString(): string {\n return this.name;\n }\n}\n", - "/*\nCopyright 2015 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MatrixEvent} and {@link RoomEvent} for\n * the public classes.\n */\n\nimport { ExtensibleEvent, ExtensibleEvents, Optional } from \"matrix-events-sdk\";\n\nimport type { IEventDecryptionResult } from \"../@types/crypto\";\nimport { logger } from \"../logger\";\nimport { VerificationRequest } from \"../crypto/verification/request/VerificationRequest\";\nimport { EVENT_VISIBILITY_CHANGE_TYPE, EventType, MsgType, RelationType } from \"../@types/event\";\nimport { Crypto } from \"../crypto\";\nimport { deepSortedObjectEntries, internaliseString } from \"../utils\";\nimport { RoomMember } from \"./room-member\";\nimport { Thread, ThreadEvent, EventHandlerMap as ThreadEventHandlerMap, THREAD_RELATION_TYPE } from \"./thread\";\nimport { IActionsObject } from \"../pushprocessor\";\nimport { TypedReEmitter } from \"../ReEmitter\";\nimport { MatrixError } from \"../http-api\";\nimport { TypedEventEmitter } from \"./typed-event-emitter\";\nimport { EventStatus } from \"./event-status\";\nimport { DecryptionError } from \"../crypto/algorithms\";\nimport { CryptoBackend } from \"../common-crypto/CryptoBackend\";\nimport { WITHHELD_MESSAGES } from \"../crypto/OlmDevice\";\n\nexport { EventStatus } from \"./event-status\";\n\n/* eslint-disable camelcase */\nexport interface IContent {\n [key: string]: any;\n \"msgtype\"?: MsgType | string;\n \"membership\"?: string;\n \"avatar_url\"?: string;\n \"displayname\"?: string;\n \"m.relates_to\"?: IEventRelation;\n\n \"org.matrix.msc3952.mentions\"?: IMentions;\n}\n\ntype StrippedState = Required>;\n\nexport interface IUnsigned {\n \"age\"?: number;\n \"prev_sender\"?: string;\n \"prev_content\"?: IContent;\n \"redacted_because\"?: IEvent;\n \"transaction_id\"?: string;\n \"invite_room_state\"?: StrippedState[];\n \"m.relations\"?: Record; // No common pattern for aggregated relations\n}\n\nexport interface IThreadBundledRelationship {\n latest_event: IEvent;\n count: number;\n current_user_participated?: boolean;\n}\n\nexport interface IEvent {\n event_id: string;\n type: string;\n content: IContent;\n sender: string;\n room_id?: string;\n origin_server_ts: number;\n txn_id?: string;\n state_key?: string;\n membership?: string;\n unsigned: IUnsigned;\n redacts?: string;\n\n /**\n * @deprecated in favour of `sender`\n */\n user_id?: string;\n /**\n * @deprecated in favour of `unsigned.prev_content`\n */\n prev_content?: IContent;\n /**\n * @deprecated in favour of `origin_server_ts`\n */\n age?: number;\n}\n\nexport interface IAggregatedRelation {\n origin_server_ts: number;\n event_id?: string;\n sender?: string;\n type?: string;\n count?: number;\n key?: string;\n}\n\nexport interface IEventRelation {\n \"rel_type\"?: RelationType | string;\n \"event_id\"?: string;\n \"is_falling_back\"?: boolean;\n \"m.in_reply_to\"?: {\n event_id?: string;\n };\n \"key\"?: string;\n}\n\nexport interface IMentions {\n user_ids?: string[];\n room?: boolean;\n}\n\n/**\n * When an event is a visibility change event, as per MSC3531,\n * the visibility change implied by the event.\n */\nexport interface IVisibilityChange {\n /**\n * If `true`, the target event should be made visible.\n * Otherwise, it should be hidden.\n */\n visible: boolean;\n\n /**\n * The event id affected.\n */\n eventId: string;\n\n /**\n * Optionally, a human-readable reason explaining why\n * the event was hidden. Ignored if the event was made\n * visible.\n */\n reason: string | null;\n}\n\nexport interface IClearEvent {\n room_id?: string;\n type: string;\n content: Omit;\n unsigned?: IUnsigned;\n}\n/* eslint-enable camelcase */\n\ninterface IKeyRequestRecipient {\n userId: string;\n deviceId: \"*\" | string;\n}\n\nexport interface IDecryptOptions {\n // Emits \"event.decrypted\" if set to true\n emit?: boolean;\n // True if this is a retry (enables more logging)\n isRetry?: boolean;\n // whether the message should be re-decrypted if it was previously successfully decrypted with an untrusted key\n forceRedecryptIfUntrusted?: boolean;\n}\n\n/**\n * Message hiding, as specified by https://github.com/matrix-org/matrix-doc/pull/3531.\n */\nexport type MessageVisibility = IMessageVisibilityHidden | IMessageVisibilityVisible;\n/**\n * Variant of `MessageVisibility` for the case in which the message should be displayed.\n */\nexport interface IMessageVisibilityVisible {\n readonly visible: true;\n}\n/**\n * Variant of `MessageVisibility` for the case in which the message should be hidden.\n */\nexport interface IMessageVisibilityHidden {\n readonly visible: false;\n /**\n * Optionally, a human-readable reason to show to the user indicating why the\n * message has been hidden (e.g. \"Message Pending Moderation\").\n */\n readonly reason: string | null;\n}\n// A singleton implementing `IMessageVisibilityVisible`.\nconst MESSAGE_VISIBLE: IMessageVisibilityVisible = Object.freeze({ visible: true });\n\nexport enum MatrixEventEvent {\n Decrypted = \"Event.decrypted\",\n BeforeRedaction = \"Event.beforeRedaction\",\n VisibilityChange = \"Event.visibilityChange\",\n LocalEventIdReplaced = \"Event.localEventIdReplaced\",\n Status = \"Event.status\",\n Replaced = \"Event.replaced\",\n RelationsCreated = \"Event.relationsCreated\",\n}\n\nexport type MatrixEventEmittedEvents = MatrixEventEvent | ThreadEvent.Update;\n\nexport type MatrixEventHandlerMap = {\n /**\n * Fires when an event is decrypted\n *\n * @param event - The matrix event which has been decrypted\n * @param err - The error that occurred during decryption, or `undefined` if no error occurred.\n */\n [MatrixEventEvent.Decrypted]: (event: MatrixEvent, err?: Error) => void;\n [MatrixEventEvent.BeforeRedaction]: (event: MatrixEvent, redactionEvent: MatrixEvent) => void;\n [MatrixEventEvent.VisibilityChange]: (event: MatrixEvent, visible: boolean) => void;\n [MatrixEventEvent.LocalEventIdReplaced]: (event: MatrixEvent) => void;\n [MatrixEventEvent.Status]: (event: MatrixEvent, status: EventStatus | null) => void;\n [MatrixEventEvent.Replaced]: (event: MatrixEvent) => void;\n [MatrixEventEvent.RelationsCreated]: (relationType: string, eventType: string) => void;\n} & Pick;\n\nexport class MatrixEvent extends TypedEventEmitter {\n private pushActions: IActionsObject | null = null;\n private _replacingEvent: MatrixEvent | null = null;\n private _localRedactionEvent: MatrixEvent | null = null;\n private _isCancelled = false;\n private clearEvent?: IClearEvent;\n\n /* Message hiding, as specified by https://github.com/matrix-org/matrix-doc/pull/3531.\n\n Note: We're returning this object, so any value stored here MUST be frozen.\n */\n private visibility: MessageVisibility = MESSAGE_VISIBLE;\n\n // Not all events will be extensible-event compatible, so cache a flag in\n // addition to a falsy cached event value. We check the flag later on in\n // a public getter to decide if the cache is valid.\n private _hasCachedExtEv = false;\n private _cachedExtEv: Optional = undefined;\n\n /* curve25519 key which we believe belongs to the sender of the event. See\n * getSenderKey()\n */\n private senderCurve25519Key: string | null = null;\n\n /* ed25519 key which the sender of this event (for olm) or the creator of\n * the megolm session (for megolm) claims to own. See getClaimedEd25519Key()\n */\n private claimedEd25519Key: string | null = null;\n\n /* curve25519 keys of devices involved in telling us about the\n * senderCurve25519Key and claimedEd25519Key.\n * See getForwardingCurve25519KeyChain().\n */\n private forwardingCurve25519KeyChain: string[] = [];\n\n /* where the decryption key is untrusted\n */\n private untrusted: boolean | null = null;\n\n /* if we have a process decrypting this event, a Promise which resolves\n * when it is finished. Normally null.\n */\n private decryptionPromise: Promise | null = null;\n\n /* flag to indicate if we should retry decrypting this event after the\n * first attempt (eg, we have received new data which means that a second\n * attempt may succeed)\n */\n private retryDecryption = false;\n\n /* The txnId with which this event was sent if it was during this session,\n * allows for a unique ID which does not change when the event comes back down sync.\n */\n private txnId?: string;\n\n /**\n * A reference to the thread this event belongs to\n */\n private thread?: Thread;\n private threadId?: string;\n\n /*\n * True if this event is an encrypted event which we failed to decrypt, the receiver's device is unverified and\n * the sender has disabled encrypting to unverified devices.\n */\n private encryptedDisabledForUnverifiedDevices = false;\n\n /* Set an approximate timestamp for the event relative the local clock.\n * This will inherently be approximate because it doesn't take into account\n * the time between the server putting the 'age' field on the event as it sent\n * it to us and the time we're now constructing this event, but that's better\n * than assuming the local clock is in sync with the origin HS's clock.\n */\n public localTimestamp: number;\n\n /**\n * The room member who sent this event, or null e.g.\n * this is a presence event. This is only guaranteed to be set for events that\n * appear in a timeline, ie. do not guarantee that it will be set on state\n * events.\n * @privateRemarks\n * Should be read-only\n */\n public sender: RoomMember | null = null;\n /**\n * The room member who is the target of this event, e.g.\n * the invitee, the person being banned, etc.\n * @privateRemarks\n * Should be read-only\n */\n public target: RoomMember | null = null;\n /**\n * The sending status of the event.\n * @privateRemarks\n * Should be read-only\n */\n public status: EventStatus | null = null;\n /**\n * most recent error associated with sending the event, if any\n * @privateRemarks\n * Should be read-only\n */\n public error: MatrixError | null = null;\n /**\n * True if this event is 'forward looking', meaning\n * that getDirectionalContent() will return event.content and not event.prev_content.\n * Only state events may be backwards looking\n * Default: true. This property is experimental and may change.\n * @privateRemarks\n * Should be read-only\n */\n public forwardLooking = true;\n\n /* If the event is a `m.key.verification.request` (or to_device `m.key.verification.start`) event,\n * `Crypto` will set this the `VerificationRequest` for the event\n * so it can be easily accessed from the timeline.\n */\n public verificationRequest?: VerificationRequest;\n\n private readonly reEmitter: TypedReEmitter;\n\n /**\n * Construct a Matrix Event object\n *\n * @param event - The raw (possibly encrypted) event. Do not access\n * this property directly unless you absolutely have to. Prefer the getter\n * methods defined on this class. Using the getter methods shields your app\n * from changes to event JSON between Matrix versions.\n */\n public constructor(public event: Partial = {}) {\n super();\n\n // intern the values of matrix events to force share strings and reduce the\n // amount of needless string duplication. This can save moderate amounts of\n // memory (~10% on a 350MB heap).\n // 'membership' at the event level (rather than the content level) is a legacy\n // field that Element never otherwise looks at, but it will still take up a lot\n // of space if we don't intern it.\n ([\"state_key\", \"type\", \"sender\", \"room_id\", \"membership\"] as const).forEach((prop) => {\n if (typeof event[prop] !== \"string\") return;\n event[prop] = internaliseString(event[prop]!);\n });\n\n ([\"membership\", \"avatar_url\", \"displayname\"] as const).forEach((prop) => {\n if (typeof event.content?.[prop] !== \"string\") return;\n event.content[prop] = internaliseString(event.content[prop]!);\n });\n\n ([\"rel_type\"] as const).forEach((prop) => {\n if (typeof event.content?.[\"m.relates_to\"]?.[prop] !== \"string\") return;\n event.content[\"m.relates_to\"][prop] = internaliseString(event.content[\"m.relates_to\"][prop]!);\n });\n\n this.txnId = event.txn_id;\n this.localTimestamp = Date.now() - (this.getAge() ?? 0);\n this.reEmitter = new TypedReEmitter(this);\n }\n\n /**\n * Unstable getter to try and get an extensible event. Note that this might\n * return a falsy value if the event could not be parsed as an extensible\n * event.\n *\n * @deprecated Use stable functions where possible.\n */\n public get unstableExtensibleEvent(): Optional {\n if (!this._hasCachedExtEv) {\n this._cachedExtEv = ExtensibleEvents.parse(this.getEffectiveEvent());\n }\n return this._cachedExtEv;\n }\n\n private invalidateExtensibleEvent(): void {\n // just reset the flag - that'll trick the getter into parsing a new event\n this._hasCachedExtEv = false;\n }\n\n /**\n * Gets the event as though it would appear unencrypted. If the event is already not\n * encrypted, it is simply returned as-is.\n * @returns The event in wire format.\n */\n public getEffectiveEvent(): IEvent {\n const content = Object.assign({}, this.getContent()); // clone for mutation\n\n if (this.getWireType() === EventType.RoomMessageEncrypted) {\n // Encrypted events sometimes aren't symmetrical on the `content` so we'll copy\n // that over too, but only for missing properties. We don't copy over mismatches\n // between the plain and decrypted copies of `content` because we assume that the\n // app is relying on the decrypted version, so we want to expose that as a source\n // of truth here too.\n for (const [key, value] of Object.entries(this.getWireContent())) {\n // Skip fields from the encrypted event schema though - we don't want to leak\n // these.\n if ([\"algorithm\", \"ciphertext\", \"device_id\", \"sender_key\", \"session_id\"].includes(key)) {\n continue;\n }\n\n if (content[key] === undefined) content[key] = value;\n }\n }\n\n // clearEvent doesn't have all the fields, so we'll copy what we can from this.event.\n // We also copy over our \"fixed\" content key.\n return Object.assign({}, this.event, this.clearEvent, { content }) as IEvent;\n }\n\n /**\n * Get the event_id for this event.\n * @returns The event ID, e.g. $143350589368169JsLZx:localhost\n * \n */\n public getId(): string | undefined {\n return this.event.event_id;\n }\n\n /**\n * Get the user_id for this event.\n * @returns The user ID, e.g. `@alice:matrix.org`\n */\n public getSender(): string | undefined {\n return this.event.sender || this.event.user_id; // v2 / v1\n }\n\n /**\n * Get the (decrypted, if necessary) type of event.\n *\n * @returns The event type, e.g. `m.room.message`\n */\n public getType(): EventType | string {\n if (this.clearEvent) {\n return this.clearEvent.type;\n }\n return this.event.type!;\n }\n\n /**\n * Get the (possibly encrypted) type of the event that will be sent to the\n * homeserver.\n *\n * @returns The event type.\n */\n public getWireType(): EventType | string {\n return this.event.type!;\n }\n\n /**\n * Get the room_id for this event. This will return `undefined`\n * for `m.presence` events.\n * @returns The room ID, e.g. !cURbafjkfsMDVwdRDQ:matrix.org\n * \n */\n public getRoomId(): string | undefined {\n return this.event.room_id;\n }\n\n /**\n * Get the timestamp of this event.\n * @returns The event timestamp, e.g. `1433502692297`\n */\n public getTs(): number {\n return this.event.origin_server_ts!;\n }\n\n /**\n * Get the timestamp of this event, as a Date object.\n * @returns The event date, e.g. `new Date(1433502692297)`\n */\n public getDate(): Date | null {\n return this.event.origin_server_ts ? new Date(this.event.origin_server_ts) : null;\n }\n\n /**\n * Get a string containing details of this event\n *\n * This is intended for logging, to help trace errors. Example output:\n *\n * @example\n * ```\n * id=$HjnOHV646n0SjLDAqFrgIjim7RCpB7cdMXFrekWYAn type=m.room.encrypted\n * sender=@user:example.com room=!room:example.com ts=2022-10-25T17:30:28.404Z\n * ```\n */\n public getDetails(): string {\n let details = `id=${this.getId()} type=${this.getWireType()} sender=${this.getSender()}`;\n const room = this.getRoomId();\n if (room) {\n details += ` room=${room}`;\n }\n const date = this.getDate();\n if (date) {\n details += ` ts=${date.toISOString()}`;\n }\n return details;\n }\n\n /**\n * Get the (decrypted, if necessary) event content JSON, even if the event\n * was replaced by another event.\n *\n * @returns The event content JSON, or an empty object.\n */\n public getOriginalContent(): T {\n if (this._localRedactionEvent) {\n return {} as T;\n }\n if (this.clearEvent) {\n return (this.clearEvent.content || {}) as T;\n }\n return (this.event.content || {}) as T;\n }\n\n /**\n * Get the (decrypted, if necessary) event content JSON,\n * or the content from the replacing event, if any.\n * See `makeReplaced`.\n *\n * @returns The event content JSON, or an empty object.\n */\n public getContent(): T {\n if (this._localRedactionEvent) {\n return {} as T;\n } else if (this._replacingEvent) {\n return this._replacingEvent.getContent()[\"m.new_content\"] || {};\n } else {\n return this.getOriginalContent();\n }\n }\n\n /**\n * Get the (possibly encrypted) event content JSON that will be sent to the\n * homeserver.\n *\n * @returns The event content JSON, or an empty object.\n */\n public getWireContent(): IContent {\n return this.event.content || {};\n }\n\n /**\n * Get the event ID of the thread head\n */\n public get threadRootId(): string | undefined {\n const relatesTo = this.getWireContent()?.[\"m.relates_to\"];\n if (relatesTo?.rel_type === THREAD_RELATION_TYPE.name) {\n return relatesTo.event_id;\n } else {\n return this.getThread()?.id || this.threadId;\n }\n }\n\n /**\n * A helper to check if an event is a thread's head or not\n */\n public get isThreadRoot(): boolean {\n const threadDetails = this.getServerAggregatedRelation(THREAD_RELATION_TYPE.name);\n\n // Bundled relationships only returned when the sync response is limited\n // hence us having to check both bundled relation and inspect the thread\n // model\n return !!threadDetails || this.getThread()?.id === this.getId();\n }\n\n public get replyEventId(): string | undefined {\n return this.getWireContent()[\"m.relates_to\"]?.[\"m.in_reply_to\"]?.event_id;\n }\n\n public get relationEventId(): string | undefined {\n return this.getWireContent()?.[\"m.relates_to\"]?.event_id;\n }\n\n /**\n * Get the previous event content JSON. This will only return something for\n * state events which exist in the timeline.\n * @returns The previous event content JSON, or an empty object.\n */\n public getPrevContent(): IContent {\n // v2 then v1 then default\n return this.getUnsigned().prev_content || this.event.prev_content || {};\n }\n\n /**\n * Get either 'content' or 'prev_content' depending on if this event is\n * 'forward-looking' or not. This can be modified via event.forwardLooking.\n * In practice, this means we get the chronologically earlier content value\n * for this event (this method should surely be called getEarlierContent)\n * This method is experimental and may change.\n * @returns event.content if this event is forward-looking, else\n * event.prev_content.\n */\n public getDirectionalContent(): IContent {\n return this.forwardLooking ? this.getContent() : this.getPrevContent();\n }\n\n /**\n * Get the age of this event. This represents the age of the event when the\n * event arrived at the device, and not the age of the event when this\n * function was called.\n * Can only be returned once the server has echo'ed back\n * @returns The age of this event in milliseconds.\n */\n public getAge(): number | undefined {\n return this.getUnsigned().age || this.event.age; // v2 / v1\n }\n\n /**\n * Get the age of the event when this function was called.\n * This is the 'age' field adjusted according to how long this client has\n * had the event.\n * @returns The age of this event in milliseconds.\n */\n public getLocalAge(): number {\n return Date.now() - this.localTimestamp;\n }\n\n /**\n * Get the event state_key if it has one. This will return undefined\n * for message events.\n * @returns The event's `state_key`.\n */\n public getStateKey(): string | undefined {\n return this.event.state_key;\n }\n\n /**\n * Check if this event is a state event.\n * @returns True if this is a state event.\n */\n public isState(): boolean {\n return this.event.state_key !== undefined;\n }\n\n /**\n * Replace the content of this event with encrypted versions.\n * (This is used when sending an event; it should not be used by applications).\n *\n * @internal\n *\n * @param cryptoType - type of the encrypted event - typically\n * \"m.room.encrypted\"\n *\n * @param cryptoContent - raw 'content' for the encrypted event.\n *\n * @param senderCurve25519Key - curve25519 key to record for the\n * sender of this event.\n * See {@link MatrixEvent#getSenderKey}.\n *\n * @param claimedEd25519Key - claimed ed25519 key to record for the\n * sender if this event.\n * See {@link MatrixEvent#getClaimedEd25519Key}\n */\n public makeEncrypted(\n cryptoType: string,\n cryptoContent: object,\n senderCurve25519Key: string,\n claimedEd25519Key: string,\n ): void {\n // keep the plain-text data for 'view source'\n this.clearEvent = {\n type: this.event.type!,\n content: this.event.content!,\n };\n this.event.type = cryptoType;\n this.event.content = cryptoContent;\n this.senderCurve25519Key = senderCurve25519Key;\n this.claimedEd25519Key = claimedEd25519Key;\n }\n\n /**\n * Check if this event is currently being decrypted.\n *\n * @returns True if this event is currently being decrypted, else false.\n */\n public isBeingDecrypted(): boolean {\n return this.decryptionPromise != null;\n }\n\n public getDecryptionPromise(): Promise | null {\n return this.decryptionPromise;\n }\n\n /**\n * Check if this event is an encrypted event which we failed to decrypt\n *\n * (This implies that we might retry decryption at some point in the future)\n *\n * @returns True if this event is an encrypted event which we\n * couldn't decrypt.\n */\n public isDecryptionFailure(): boolean {\n return this.clearEvent?.content?.msgtype === \"m.bad.encrypted\";\n }\n\n /*\n * True if this event is an encrypted event which we failed to decrypt, the receiver's device is unverified and\n * the sender has disabled encrypting to unverified devices.\n */\n public get isEncryptedDisabledForUnverifiedDevices(): boolean {\n return this.isDecryptionFailure() && this.encryptedDisabledForUnverifiedDevices;\n }\n\n public shouldAttemptDecryption(): boolean {\n if (this.isRedacted()) return false;\n if (this.isBeingDecrypted()) return false;\n if (this.clearEvent) return false;\n if (!this.isEncrypted()) return false;\n\n return true;\n }\n\n /**\n * Start the process of trying to decrypt this event.\n *\n * (This is used within the SDK: it isn't intended for use by applications)\n *\n * @internal\n *\n * @param crypto - crypto module\n *\n * @returns promise which resolves (to undefined) when the decryption\n * attempt is completed.\n */\n public async attemptDecryption(crypto: CryptoBackend, options: IDecryptOptions = {}): Promise {\n // start with a couple of sanity checks.\n if (!this.isEncrypted()) {\n throw new Error(\"Attempt to decrypt event which isn't encrypted\");\n }\n\n const alreadyDecrypted = this.clearEvent && !this.isDecryptionFailure();\n const forceRedecrypt = options.forceRedecryptIfUntrusted && this.isKeySourceUntrusted();\n if (alreadyDecrypted && !forceRedecrypt) {\n // we may want to just ignore this? let's start with rejecting it.\n throw new Error(\"Attempt to decrypt event which has already been decrypted\");\n }\n\n // if we already have a decryption attempt in progress, then it may\n // fail because it was using outdated info. We now have reason to\n // succeed where it failed before, but we don't want to have multiple\n // attempts going at the same time, so just set a flag that says we have\n // new info.\n //\n if (this.decryptionPromise) {\n logger.log(`Event ${this.getId()} already being decrypted; queueing a retry`);\n this.retryDecryption = true;\n return this.decryptionPromise;\n }\n\n this.decryptionPromise = this.decryptionLoop(crypto, options);\n return this.decryptionPromise;\n }\n\n /**\n * Cancel any room key request for this event and resend another.\n *\n * @param crypto - crypto module\n * @param userId - the user who received this event\n *\n * @returns a promise that resolves when the request is queued\n */\n public cancelAndResendKeyRequest(crypto: Crypto, userId: string): Promise {\n const wireContent = this.getWireContent();\n return crypto.requestRoomKey(\n {\n algorithm: wireContent.algorithm,\n room_id: this.getRoomId()!,\n session_id: wireContent.session_id,\n sender_key: wireContent.sender_key,\n },\n this.getKeyRequestRecipients(userId),\n true,\n );\n }\n\n /**\n * Calculate the recipients for keyshare requests.\n *\n * @param userId - the user who received this event.\n *\n * @returns array of recipients\n */\n public getKeyRequestRecipients(userId: string): IKeyRequestRecipient[] {\n // send the request to all of our own devices\n const recipients = [\n {\n userId,\n deviceId: \"*\",\n },\n ];\n\n return recipients;\n }\n\n private async decryptionLoop(crypto: CryptoBackend, options: IDecryptOptions = {}): Promise {\n // make sure that this method never runs completely synchronously.\n // (doing so would mean that we would clear decryptionPromise *before*\n // it is set in attemptDecryption - and hence end up with a stuck\n // `decryptionPromise`).\n await Promise.resolve();\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n this.retryDecryption = false;\n\n let res: IEventDecryptionResult;\n let err: Error | undefined = undefined;\n try {\n if (!crypto) {\n res = this.badEncryptedMessage(\"Encryption not enabled\");\n } else {\n res = await crypto.decryptEvent(this);\n if (options.isRetry === true) {\n logger.info(`Decrypted event on retry (${this.getDetails()})`);\n }\n }\n } catch (e) {\n const detailedError = e instanceof DecryptionError ? (e).detailedString : String(e);\n\n err = e as Error;\n\n // see if we have a retry queued.\n //\n // NB: make sure to keep this check in the same tick of the\n // event loop as `decryptionPromise = null` below - otherwise we\n // risk a race:\n //\n // * A: we check retryDecryption here and see that it is\n // false\n // * B: we get a second call to attemptDecryption, which sees\n // that decryptionPromise is set so sets\n // retryDecryption\n // * A: we continue below, clear decryptionPromise, and\n // never do the retry.\n //\n if (this.retryDecryption) {\n // decryption error, but we have a retry queued.\n logger.log(`Error decrypting event (${this.getDetails()}), but retrying: ${detailedError}`);\n continue;\n }\n\n // decryption error, no retries queued. Warn about the error and\n // set it to m.bad.encrypted.\n //\n // the detailedString already includes the name and message of the error, and the stack isn't much use,\n // so we don't bother to log `e` separately.\n logger.warn(`Error decrypting event (${this.getDetails()}): ${detailedError}`);\n\n res = this.badEncryptedMessage(String(e));\n }\n\n // at this point, we've either successfully decrypted the event, or have given up\n // (and set res to a 'badEncryptedMessage'). Either way, we can now set the\n // cleartext of the event and raise Event.decrypted.\n //\n // make sure we clear 'decryptionPromise' before sending the 'Event.decrypted' event,\n // otherwise the app will be confused to see `isBeingDecrypted` still set when\n // there isn't an `Event.decrypted` on the way.\n //\n // see also notes on retryDecryption above.\n //\n this.decryptionPromise = null;\n this.retryDecryption = false;\n this.setClearData(res);\n\n // Before we emit the event, clear the push actions so that they can be recalculated\n // by relevant code. We do this because the clear event has now changed, making it\n // so that existing rules can be re-run over the applicable properties. Stuff like\n // highlighting when the user's name is mentioned rely on this happening. We also want\n // to set the push actions before emitting so that any notification listeners don't\n // pick up the wrong contents.\n this.setPushActions(null);\n\n if (options.emit !== false) {\n this.emit(MatrixEventEvent.Decrypted, this, err);\n }\n\n return;\n }\n }\n\n private badEncryptedMessage(reason: string): IEventDecryptionResult {\n return {\n clearEvent: {\n type: EventType.RoomMessage,\n content: {\n msgtype: \"m.bad.encrypted\",\n body: \"** Unable to decrypt: \" + reason + \" **\",\n },\n },\n encryptedDisabledForUnverifiedDevices: reason === `DecryptionError: ${WITHHELD_MESSAGES[\"m.unverified\"]}`,\n };\n }\n\n /**\n * Update the cleartext data on this event.\n *\n * (This is used after decrypting an event; it should not be used by applications).\n *\n * @internal\n *\n * @param decryptionResult - the decryption result, including the plaintext and some key info\n *\n * @remarks\n * Fires {@link MatrixEventEvent.Decrypted}\n */\n private setClearData(decryptionResult: IEventDecryptionResult): void {\n this.clearEvent = decryptionResult.clearEvent;\n this.senderCurve25519Key = decryptionResult.senderCurve25519Key ?? null;\n this.claimedEd25519Key = decryptionResult.claimedEd25519Key ?? null;\n this.forwardingCurve25519KeyChain = decryptionResult.forwardingCurve25519KeyChain || [];\n this.untrusted = decryptionResult.untrusted || false;\n this.encryptedDisabledForUnverifiedDevices = decryptionResult.encryptedDisabledForUnverifiedDevices || false;\n this.invalidateExtensibleEvent();\n }\n\n /**\n * Gets the cleartext content for this event. If the event is not encrypted,\n * or encryption has not been completed, this will return null.\n *\n * @returns The cleartext (decrypted) content for the event\n */\n public getClearContent(): IContent | null {\n return this.clearEvent ? this.clearEvent.content : null;\n }\n\n /**\n * Check if the event is encrypted.\n * @returns True if this event is encrypted.\n */\n public isEncrypted(): boolean {\n return !this.isState() && this.event.type === EventType.RoomMessageEncrypted;\n }\n\n /**\n * The curve25519 key for the device that we think sent this event\n *\n * For an Olm-encrypted event, this is inferred directly from the DH\n * exchange at the start of the session: the curve25519 key is involved in\n * the DH exchange, so only a device which holds the private part of that\n * key can establish such a session.\n *\n * For a megolm-encrypted event, it is inferred from the Olm message which\n * established the megolm session\n */\n public getSenderKey(): string | null {\n return this.senderCurve25519Key;\n }\n\n /**\n * The additional keys the sender of this encrypted event claims to possess.\n *\n * Just a wrapper for #getClaimedEd25519Key (q.v.)\n */\n public getKeysClaimed(): Partial> {\n if (!this.claimedEd25519Key) return {};\n\n return {\n ed25519: this.claimedEd25519Key,\n };\n }\n\n /**\n * Get the ed25519 the sender of this event claims to own.\n *\n * For Olm messages, this claim is encoded directly in the plaintext of the\n * event itself. For megolm messages, it is implied by the m.room_key event\n * which established the megolm session.\n *\n * Until we download the device list of the sender, it's just a claim: the\n * device list gives a proof that the owner of the curve25519 key used for\n * this event (and returned by #getSenderKey) also owns the ed25519 key by\n * signing the public curve25519 key with the ed25519 key.\n *\n * In general, applications should not use this method directly, but should\n * instead use MatrixClient.getEventSenderDeviceInfo.\n */\n public getClaimedEd25519Key(): string | null {\n return this.claimedEd25519Key;\n }\n\n /**\n * Get the curve25519 keys of the devices which were involved in telling us\n * about the claimedEd25519Key and sender curve25519 key.\n *\n * Normally this will be empty, but in the case of a forwarded megolm\n * session, the sender keys are sent to us by another device (the forwarding\n * device), which we need to trust to do this. In that case, the result will\n * be a list consisting of one entry.\n *\n * If the device that sent us the key (A) got it from another device which\n * it wasn't prepared to vouch for (B), the result will be [A, B]. And so on.\n *\n * @returns base64-encoded curve25519 keys, from oldest to newest.\n */\n public getForwardingCurve25519KeyChain(): string[] {\n return this.forwardingCurve25519KeyChain;\n }\n\n /**\n * Whether the decryption key was obtained from an untrusted source. If so,\n * we cannot verify the authenticity of the message.\n */\n public isKeySourceUntrusted(): boolean | undefined {\n return !!this.untrusted;\n }\n\n public getUnsigned(): IUnsigned {\n return this.event.unsigned || {};\n }\n\n public setUnsigned(unsigned: IUnsigned): void {\n this.event.unsigned = unsigned;\n }\n\n public unmarkLocallyRedacted(): boolean {\n const value = this._localRedactionEvent;\n this._localRedactionEvent = null;\n if (this.event.unsigned) {\n this.event.unsigned.redacted_because = undefined;\n }\n return !!value;\n }\n\n public markLocallyRedacted(redactionEvent: MatrixEvent): void {\n if (this._localRedactionEvent) return;\n this.emit(MatrixEventEvent.BeforeRedaction, this, redactionEvent);\n this._localRedactionEvent = redactionEvent;\n if (!this.event.unsigned) {\n this.event.unsigned = {};\n }\n this.event.unsigned.redacted_because = redactionEvent.event as IEvent;\n }\n\n /**\n * Change the visibility of an event, as per https://github.com/matrix-org/matrix-doc/pull/3531 .\n *\n * @param visibilityChange - event holding a hide/unhide payload, or nothing\n * if the event is being reset to its original visibility (presumably\n * by a visibility event being redacted).\n *\n * @remarks\n * Fires {@link MatrixEventEvent.VisibilityChange} if `visibilityEvent`\n * caused a change in the actual visibility of this event, either by making it\n * visible (if it was hidden), by making it hidden (if it was visible) or by\n * changing the reason (if it was hidden).\n */\n public applyVisibilityEvent(visibilityChange?: IVisibilityChange): void {\n const visible = visibilityChange?.visible ?? true;\n const reason = visibilityChange?.reason ?? null;\n let change = false;\n if (this.visibility.visible !== visible) {\n change = true;\n } else if (!this.visibility.visible && this.visibility[\"reason\"] !== reason) {\n change = true;\n }\n if (change) {\n if (visible) {\n this.visibility = MESSAGE_VISIBLE;\n } else {\n this.visibility = Object.freeze({\n visible: false,\n reason,\n });\n }\n this.emit(MatrixEventEvent.VisibilityChange, this, visible);\n }\n }\n\n /**\n * Return instructions to display or hide the message.\n *\n * @returns Instructions determining whether the message\n * should be displayed.\n */\n public messageVisibility(): MessageVisibility {\n // Note: We may return `this.visibility` without fear, as\n // this is a shallow frozen object.\n return this.visibility;\n }\n\n /**\n * Update the content of an event in the same way it would be by the server\n * if it were redacted before it was sent to us\n *\n * @param redactionEvent - event causing the redaction\n */\n public makeRedacted(redactionEvent: MatrixEvent): void {\n // quick sanity-check\n if (!redactionEvent.event) {\n throw new Error(\"invalid redactionEvent in makeRedacted\");\n }\n\n this._localRedactionEvent = null;\n\n this.emit(MatrixEventEvent.BeforeRedaction, this, redactionEvent);\n\n this._replacingEvent = null;\n // we attempt to replicate what we would see from the server if\n // the event had been redacted before we saw it.\n //\n // The server removes (most of) the content of the event, and adds a\n // \"redacted_because\" key to the unsigned section containing the\n // redacted event.\n if (!this.event.unsigned) {\n this.event.unsigned = {};\n }\n this.event.unsigned.redacted_because = redactionEvent.event as IEvent;\n\n for (const key in this.event) {\n if (this.event.hasOwnProperty(key) && !REDACT_KEEP_KEYS.has(key)) {\n delete this.event[key as keyof IEvent];\n }\n }\n\n // If the event is encrypted prune the decrypted bits\n if (this.isEncrypted()) {\n this.clearEvent = undefined;\n }\n\n const keeps =\n this.getType() in REDACT_KEEP_CONTENT_MAP\n ? REDACT_KEEP_CONTENT_MAP[this.getType() as keyof typeof REDACT_KEEP_CONTENT_MAP]\n : {};\n const content = this.getContent();\n for (const key in content) {\n if (content.hasOwnProperty(key) && !keeps[key]) {\n delete content[key];\n }\n }\n\n this.invalidateExtensibleEvent();\n }\n\n /**\n * Check if this event has been redacted\n *\n * @returns True if this event has been redacted\n */\n public isRedacted(): boolean {\n return Boolean(this.getUnsigned().redacted_because);\n }\n\n /**\n * Check if this event is a redaction of another event\n *\n * @returns True if this event is a redaction\n */\n public isRedaction(): boolean {\n return this.getType() === EventType.RoomRedaction;\n }\n\n /**\n * Return the visibility change caused by this event,\n * as per https://github.com/matrix-org/matrix-doc/pull/3531.\n *\n * @returns If the event is a well-formed visibility change event,\n * an instance of `IVisibilityChange`, otherwise `null`.\n */\n public asVisibilityChange(): IVisibilityChange | null {\n if (!EVENT_VISIBILITY_CHANGE_TYPE.matches(this.getType())) {\n // Not a visibility change event.\n return null;\n }\n const relation = this.getRelation();\n if (!relation || relation.rel_type != \"m.reference\") {\n // Ill-formed, ignore this event.\n return null;\n }\n const eventId = relation.event_id;\n if (!eventId) {\n // Ill-formed, ignore this event.\n return null;\n }\n const content = this.getWireContent();\n const visible = !!content.visible;\n const reason = content.reason;\n if (reason && typeof reason != \"string\") {\n // Ill-formed, ignore this event.\n return null;\n }\n // Well-formed visibility change event.\n return {\n visible,\n reason,\n eventId,\n };\n }\n\n /**\n * Check if this event alters the visibility of another event,\n * as per https://github.com/matrix-org/matrix-doc/pull/3531.\n *\n * @returns True if this event alters the visibility\n * of another event.\n */\n public isVisibilityEvent(): boolean {\n return EVENT_VISIBILITY_CHANGE_TYPE.matches(this.getType());\n }\n\n /**\n * Get the (decrypted, if necessary) redaction event JSON\n * if event was redacted\n *\n * @returns The redaction event JSON, or an empty object\n */\n public getRedactionEvent(): IEvent | {} | null {\n if (!this.isRedacted()) return null;\n\n if (this.clearEvent?.unsigned) {\n return this.clearEvent?.unsigned.redacted_because ?? null;\n } else if (this.event.unsigned?.redacted_because) {\n return this.event.unsigned.redacted_because;\n } else {\n return {};\n }\n }\n\n /**\n * Get the push actions, if known, for this event\n *\n * @returns push actions\n */\n public getPushActions(): IActionsObject | null {\n return this.pushActions;\n }\n\n /**\n * Set the push actions for this event.\n *\n * @param pushActions - push actions\n */\n public setPushActions(pushActions: IActionsObject | null): void {\n this.pushActions = pushActions;\n }\n\n /**\n * Replace the `event` property and recalculate any properties based on it.\n * @param event - the object to assign to the `event` property\n */\n public handleRemoteEcho(event: object): void {\n const oldUnsigned = this.getUnsigned();\n const oldId = this.getId();\n this.event = event;\n // if this event was redacted before it was sent, it's locally marked as redacted.\n // At this point, we've received the remote echo for the event, but not yet for\n // the redaction that we are sending ourselves. Preserve the locally redacted\n // state by copying over redacted_because so we don't get a flash of\n // redacted, not-redacted, redacted as remote echos come in\n if (oldUnsigned.redacted_because) {\n if (!this.event.unsigned) {\n this.event.unsigned = {};\n }\n this.event.unsigned.redacted_because = oldUnsigned.redacted_because;\n }\n // successfully sent.\n this.setStatus(null);\n if (this.getId() !== oldId) {\n // emit the event if it changed\n this.emit(MatrixEventEvent.LocalEventIdReplaced, this);\n }\n\n this.localTimestamp = Date.now() - this.getAge()!;\n }\n\n /**\n * Whether the event is in any phase of sending, send failure, waiting for\n * remote echo, etc.\n */\n public isSending(): boolean {\n return !!this.status;\n }\n\n /**\n * Update the event's sending status and emit an event as well.\n *\n * @param status - The new status\n */\n public setStatus(status: EventStatus | null): void {\n this.status = status;\n this.emit(MatrixEventEvent.Status, this, status);\n }\n\n public replaceLocalEventId(eventId: string): void {\n this.event.event_id = eventId;\n this.emit(MatrixEventEvent.LocalEventIdReplaced, this);\n }\n\n /**\n * Get whether the event is a relation event, and of a given type if\n * `relType` is passed in. State events cannot be relation events\n *\n * @param relType - if given, checks that the relation is of the\n * given type\n */\n public isRelation(relType?: string): boolean {\n // Relation info is lifted out of the encrypted content when sent to\n // encrypted rooms, so we have to check `getWireContent` for this.\n const relation = this.getWireContent()?.[\"m.relates_to\"];\n if (this.isState() && relation?.rel_type === RelationType.Replace) {\n // State events cannot be m.replace relations\n return false;\n }\n return !!(relation?.rel_type && relation.event_id && (relType ? relation.rel_type === relType : true));\n }\n\n /**\n * Get relation info for the event, if any.\n */\n public getRelation(): IEventRelation | null {\n if (!this.isRelation()) {\n return null;\n }\n return this.getWireContent()[\"m.relates_to\"] ?? null;\n }\n\n /**\n * Set an event that replaces the content of this event, through an m.replace relation.\n *\n * @param newEvent - the event with the replacing content, if any.\n *\n * @remarks\n * Fires {@link MatrixEventEvent.Replaced}\n */\n public makeReplaced(newEvent?: MatrixEvent): void {\n // don't allow redacted events to be replaced.\n // if newEvent is null we allow to go through though,\n // as with local redaction, the replacing event might get\n // cancelled, which should be reflected on the target event.\n if (this.isRedacted() && newEvent) {\n return;\n }\n // don't allow state events to be replaced using this mechanism as per MSC2676\n if (this.isState()) {\n return;\n }\n if (this._replacingEvent !== newEvent) {\n this._replacingEvent = newEvent ?? null;\n this.emit(MatrixEventEvent.Replaced, this);\n this.invalidateExtensibleEvent();\n }\n }\n\n /**\n * Returns the status of any associated edit or redaction\n * (not for reactions/annotations as their local echo doesn't affect the original event),\n * or else the status of the event.\n */\n public getAssociatedStatus(): EventStatus | null {\n if (this._replacingEvent) {\n return this._replacingEvent.status;\n } else if (this._localRedactionEvent) {\n return this._localRedactionEvent.status;\n }\n return this.status;\n }\n\n public getServerAggregatedRelation(relType: RelationType | string): T | undefined {\n return this.getUnsigned()[\"m.relations\"]?.[relType];\n }\n\n /**\n * Returns the event ID of the event replacing the content of this event, if any.\n */\n public replacingEventId(): string | undefined {\n const replaceRelation = this.getServerAggregatedRelation(RelationType.Replace);\n if (replaceRelation) {\n return replaceRelation.event_id;\n } else if (this._replacingEvent) {\n return this._replacingEvent.getId();\n }\n }\n\n /**\n * Returns the event replacing the content of this event, if any.\n * Replacements are aggregated on the server, so this would only\n * return an event in case it came down the sync, or for local echo of edits.\n */\n public replacingEvent(): MatrixEvent | null {\n return this._replacingEvent;\n }\n\n /**\n * Returns the origin_server_ts of the event replacing the content of this event, if any.\n */\n public replacingEventDate(): Date | undefined {\n const replaceRelation = this.getServerAggregatedRelation(RelationType.Replace);\n if (replaceRelation) {\n const ts = replaceRelation.origin_server_ts;\n if (Number.isFinite(ts)) {\n return new Date(ts);\n }\n } else if (this._replacingEvent) {\n return this._replacingEvent.getDate() ?? undefined;\n }\n }\n\n /**\n * Returns the event that wants to redact this event, but hasn't been sent yet.\n * @returns the event\n */\n public localRedactionEvent(): MatrixEvent | null {\n return this._localRedactionEvent;\n }\n\n /**\n * For relations and redactions, returns the event_id this event is referring to.\n */\n public getAssociatedId(): string | undefined {\n const relation = this.getRelation();\n if (this.replyEventId) {\n return this.replyEventId;\n } else if (relation) {\n return relation.event_id;\n } else if (this.isRedaction()) {\n return this.event.redacts;\n }\n }\n\n /**\n * Checks if this event is associated with another event. See `getAssociatedId`.\n * @deprecated use hasAssociation instead.\n */\n public hasAssocation(): boolean {\n return !!this.getAssociatedId();\n }\n\n /**\n * Checks if this event is associated with another event. See `getAssociatedId`.\n */\n public hasAssociation(): boolean {\n return !!this.getAssociatedId();\n }\n\n /**\n * Update the related id with a new one.\n *\n * Used to replace a local id with remote one before sending\n * an event with a related id.\n *\n * @param eventId - the new event id\n */\n public updateAssociatedId(eventId: string): void {\n const relation = this.getRelation();\n if (relation) {\n relation.event_id = eventId;\n } else if (this.isRedaction()) {\n this.event.redacts = eventId;\n }\n }\n\n /**\n * Flags an event as cancelled due to future conditions. For example, a verification\n * request event in the same sync transaction may be flagged as cancelled to warn\n * listeners that a cancellation event is coming down the same pipe shortly.\n * @param cancelled - Whether the event is to be cancelled or not.\n */\n public flagCancelled(cancelled = true): void {\n this._isCancelled = cancelled;\n }\n\n /**\n * Gets whether or not the event is flagged as cancelled. See flagCancelled() for\n * more information.\n * @returns True if the event is cancelled, false otherwise.\n */\n public isCancelled(): boolean {\n return this._isCancelled;\n }\n\n /**\n * Get a copy/snapshot of this event. The returned copy will be loosely linked\n * back to this instance, though will have \"frozen\" event information. Other\n * properties of this MatrixEvent instance will be copied verbatim, which can\n * mean they are in reference to this instance despite being on the copy too.\n * The reference the snapshot uses does not change, however members aside from\n * the underlying event will not be deeply cloned, thus may be mutated internally.\n * For example, the sender profile will be copied over at snapshot time, and\n * the sender profile internally may mutate without notice to the consumer.\n *\n * This is meant to be used to snapshot the event details themselves, not the\n * features (such as sender) surrounding the event.\n * @returns A snapshot of this event.\n */\n public toSnapshot(): MatrixEvent {\n const ev = new MatrixEvent(JSON.parse(JSON.stringify(this.event)));\n for (const [p, v] of Object.entries(this)) {\n if (p !== \"event\") {\n // exclude the thing we just cloned\n // @ts-ignore - XXX: this is just nasty\n ev[p as keyof MatrixEvent] = v;\n }\n }\n return ev;\n }\n\n /**\n * Determines if this event is equivalent to the given event. This only checks\n * the event object itself, not the other properties of the event. Intended for\n * use with toSnapshot() to identify events changing.\n * @param otherEvent - The other event to check against.\n * @returns True if the events are the same, false otherwise.\n */\n public isEquivalentTo(otherEvent: MatrixEvent): boolean {\n if (!otherEvent) return false;\n if (otherEvent === this) return true;\n const myProps = deepSortedObjectEntries(this.event);\n const theirProps = deepSortedObjectEntries(otherEvent.event);\n return JSON.stringify(myProps) === JSON.stringify(theirProps);\n }\n\n /**\n * Summarise the event as JSON. This is currently used by React SDK's view\n * event source feature and Seshat's event indexing, so take care when\n * adjusting the output here.\n *\n * If encrypted, include both the decrypted and encrypted view of the event.\n *\n * This is named `toJSON` for use with `JSON.stringify` which checks objects\n * for functions named `toJSON` and will call them to customise the output\n * if they are defined.\n */\n public toJSON(): object {\n const event = this.getEffectiveEvent();\n\n if (!this.isEncrypted()) {\n return event;\n }\n\n return {\n decrypted: event,\n encrypted: this.event,\n };\n }\n\n public setVerificationRequest(request: VerificationRequest): void {\n this.verificationRequest = request;\n }\n\n public setTxnId(txnId: string): void {\n this.txnId = txnId;\n }\n\n public getTxnId(): string | undefined {\n return this.txnId;\n }\n\n /**\n * Set the instance of a thread associated with the current event\n * @param thread - the thread\n */\n public setThread(thread?: Thread): void {\n if (this.thread) {\n this.reEmitter.stopReEmitting(this.thread, [ThreadEvent.Update]);\n }\n this.thread = thread;\n this.setThreadId(thread?.id);\n if (thread) {\n this.reEmitter.reEmit(thread, [ThreadEvent.Update]);\n }\n }\n\n /**\n * Get the instance of the thread associated with the current event\n */\n public getThread(): Thread | undefined {\n return this.thread;\n }\n\n public setThreadId(threadId?: string): void {\n this.threadId = threadId;\n }\n}\n\n/* REDACT_KEEP_KEYS gives the keys we keep when an event is redacted\n *\n * This is specified here:\n * http://matrix.org/speculator/spec/HEAD/client_server/latest.html#redactions\n *\n * Also:\n * - We keep 'unsigned' since that is created by the local server\n * - We keep user_id for backwards-compat with v1\n */\nconst REDACT_KEEP_KEYS = new Set([\n \"event_id\",\n \"type\",\n \"room_id\",\n \"user_id\",\n \"sender\",\n \"state_key\",\n \"prev_state\",\n \"content\",\n \"unsigned\",\n \"origin_server_ts\",\n]);\n\n// a map from state event type to the .content keys we keep when an event is redacted\nconst REDACT_KEEP_CONTENT_MAP: Record> = {\n [EventType.RoomMember]: { membership: 1 },\n [EventType.RoomCreate]: { creator: 1 },\n [EventType.RoomJoinRules]: { join_rule: 1 },\n [EventType.RoomPowerLevels]: {\n ban: 1,\n events: 1,\n events_default: 1,\n kick: 1,\n redact: 1,\n state_default: 1,\n users: 1,\n users_default: 1,\n },\n} as const;\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { UnstableValue } from \"matrix-events-sdk\";\n\nimport { MatrixClient } from \"../client\";\nimport { IContent, MatrixEvent } from \"./event\";\nimport { EventTimeline } from \"./event-timeline\";\nimport { Preset } from \"../@types/partials\";\nimport { globToRegexp } from \"../utils\";\nimport { Room } from \"./room\";\n\n/// The event type storing the user's individual policies.\n///\n/// Exported for testing purposes.\nexport const POLICIES_ACCOUNT_EVENT_TYPE = new UnstableValue(\"m.policies\", \"org.matrix.msc3847.policies\");\n\n/// The key within the user's individual policies storing the user's ignored invites.\n///\n/// Exported for testing purposes.\nexport const IGNORE_INVITES_ACCOUNT_EVENT_KEY = new UnstableValue(\n \"m.ignore.invites\",\n \"org.matrix.msc3847.ignore.invites\",\n);\n\n/// The types of recommendations understood.\nenum PolicyRecommendation {\n Ban = \"m.ban\",\n}\n\n/**\n * The various scopes for policies.\n */\nexport enum PolicyScope {\n /**\n * The policy deals with an individual user, e.g. reject invites\n * from this user.\n */\n User = \"m.policy.user\",\n\n /**\n * The policy deals with a room, e.g. reject invites towards\n * a specific room.\n */\n Room = \"m.policy.room\",\n\n /**\n * The policy deals with a server, e.g. reject invites from\n * this server.\n */\n Server = \"m.policy.server\",\n}\n\n/**\n * A container for ignored invites.\n *\n * # Performance\n *\n * This implementation is extremely naive. It expects that we are dealing\n * with a very short list of sources (e.g. only one). If real-world\n * applications turn out to require longer lists, we may need to rework\n * our data structures.\n */\nexport class IgnoredInvites {\n public constructor(private readonly client: MatrixClient) {}\n\n /**\n * Add a new rule.\n *\n * @param scope - The scope for this rule.\n * @param entity - The entity covered by this rule. Globs are supported.\n * @param reason - A human-readable reason for introducing this new rule.\n * @returns The event id for the new rule.\n */\n public async addRule(scope: PolicyScope, entity: string, reason: string): Promise {\n const target = await this.getOrCreateTargetRoom();\n const response = await this.client.sendStateEvent(target.roomId, scope, {\n entity,\n reason,\n recommendation: PolicyRecommendation.Ban,\n });\n return response.event_id;\n }\n\n /**\n * Remove a rule.\n */\n public async removeRule(event: MatrixEvent): Promise {\n await this.client.redactEvent(event.getRoomId()!, event.getId()!);\n }\n\n /**\n * Add a new room to the list of sources. If the user isn't a member of the\n * room, attempt to join it.\n *\n * @param roomId - A valid room id. If this room is already in the list\n * of sources, it will not be duplicated.\n * @returns `true` if the source was added, `false` if it was already present.\n * @throws If `roomId` isn't the id of a room that the current user is already\n * member of or can join.\n *\n * # Safety\n *\n * This method will rewrite the `Policies` object in the user's account data.\n * This rewrite is inherently racy and could overwrite or be overwritten by\n * other concurrent rewrites of the same object.\n */\n public async addSource(roomId: string): Promise {\n // We attempt to join the room *before* calling\n // `await this.getOrCreateSourceRooms()` to decrease the duration\n // of the racy section.\n await this.client.joinRoom(roomId);\n // Race starts.\n const sources = (await this.getOrCreateSourceRooms()).map((room) => room.roomId);\n if (sources.includes(roomId)) {\n return false;\n }\n sources.push(roomId);\n await this.withIgnoreInvitesPolicies((ignoreInvitesPolicies) => {\n ignoreInvitesPolicies.sources = sources;\n });\n\n // Race ends.\n return true;\n }\n\n /**\n * Find out whether an invite should be ignored.\n *\n * @param sender - The user id for the user who issued the invite.\n * @param roomId - The room to which the user is invited.\n * @returns A rule matching the entity, if any was found, `null` otherwise.\n */\n public async getRuleForInvite({\n sender,\n roomId,\n }: {\n sender: string;\n roomId: string;\n }): Promise> {\n // In this implementation, we perform a very naive lookup:\n // - search in each policy room;\n // - turn each (potentially glob) rule entity into a regexp.\n //\n // Real-world testing will tell us whether this is performant enough.\n // In the (unfortunately likely) case it isn't, there are several manners\n // in which we could optimize this:\n // - match several entities per go;\n // - pre-compile each rule entity into a regexp;\n // - pre-compile entire rooms into a single regexp.\n const policyRooms = await this.getOrCreateSourceRooms();\n const senderServer = sender.split(\":\")[1];\n const roomServer = roomId.split(\":\")[1];\n for (const room of policyRooms) {\n const state = room.getUnfilteredTimelineSet().getLiveTimeline().getState(EventTimeline.FORWARDS)!;\n\n for (const { scope, entities } of [\n { scope: PolicyScope.Room, entities: [roomId] },\n { scope: PolicyScope.User, entities: [sender] },\n { scope: PolicyScope.Server, entities: [senderServer, roomServer] },\n ]) {\n const events = state.getStateEvents(scope);\n for (const event of events) {\n const content = event.getContent();\n if (content?.recommendation != PolicyRecommendation.Ban) {\n // Ignoring invites only looks at `m.ban` recommendations.\n continue;\n }\n const glob = content?.entity;\n if (!glob) {\n // Invalid event.\n continue;\n }\n let regexp: RegExp;\n try {\n regexp = new RegExp(globToRegexp(glob, false));\n } catch (ex) {\n // Assume invalid event.\n continue;\n }\n for (const entity of entities) {\n if (entity && regexp.test(entity)) {\n return event;\n }\n }\n // No match.\n }\n }\n }\n return null;\n }\n\n /**\n * Get the target room, i.e. the room in which any new rule should be written.\n *\n * If there is no target room setup, a target room is created.\n *\n * Note: This method is public for testing reasons. Most clients should not need\n * to call it directly.\n *\n * # Safety\n *\n * This method will rewrite the `Policies` object in the user's account data.\n * This rewrite is inherently racy and could overwrite or be overwritten by\n * other concurrent rewrites of the same object.\n */\n public async getOrCreateTargetRoom(): Promise {\n const ignoreInvitesPolicies = this.getIgnoreInvitesPolicies();\n let target = ignoreInvitesPolicies.target;\n // Validate `target`. If it is invalid, trash out the current `target`\n // and create a new room.\n if (typeof target !== \"string\") {\n target = null;\n }\n if (target) {\n // Check that the room exists and is valid.\n const room = this.client.getRoom(target);\n if (room) {\n return room;\n } else {\n target = null;\n }\n }\n // We need to create our own policy room for ignoring invites.\n target = (\n await this.client.createRoom({\n name: \"Individual Policy Room\",\n preset: Preset.PrivateChat,\n })\n ).room_id;\n await this.withIgnoreInvitesPolicies((ignoreInvitesPolicies) => {\n ignoreInvitesPolicies.target = target;\n });\n\n // Since we have just called `createRoom`, `getRoom` should not be `null`.\n return this.client.getRoom(target)!;\n }\n\n /**\n * Get the list of source rooms, i.e. the rooms from which rules need to be read.\n *\n * If no source rooms are setup, the target room is used as sole source room.\n *\n * Note: This method is public for testing reasons. Most clients should not need\n * to call it directly.\n *\n * # Safety\n *\n * This method will rewrite the `Policies` object in the user's account data.\n * This rewrite is inherently racy and could overwrite or be overwritten by\n * other concurrent rewrites of the same object.\n */\n public async getOrCreateSourceRooms(): Promise {\n const ignoreInvitesPolicies = this.getIgnoreInvitesPolicies();\n let sources: string[] = ignoreInvitesPolicies.sources;\n\n // Validate `sources`. If it is invalid, trash out the current `sources`\n // and create a new list of sources from `target`.\n let hasChanges = false;\n if (!Array.isArray(sources)) {\n // `sources` could not be an array.\n hasChanges = true;\n sources = [];\n }\n let sourceRooms = sources\n // `sources` could contain non-string / invalid room ids\n .filter((roomId) => typeof roomId === \"string\")\n .map((roomId) => this.client.getRoom(roomId))\n .filter((room) => !!room) as Room[];\n if (sourceRooms.length != sources.length) {\n hasChanges = true;\n }\n if (sourceRooms.length == 0) {\n // `sources` could be empty (possibly because we've removed\n // invalid content)\n const target = await this.getOrCreateTargetRoom();\n hasChanges = true;\n sourceRooms = [target];\n }\n if (hasChanges) {\n // Reload `policies`/`ignoreInvitesPolicies` in case it has been changed\n // during or by our call to `this.getTargetRoom()`.\n await this.withIgnoreInvitesPolicies((ignoreInvitesPolicies) => {\n ignoreInvitesPolicies.sources = sources;\n });\n }\n return sourceRooms;\n }\n\n /**\n * Fetch the `IGNORE_INVITES_POLICIES` object from account data.\n *\n * If both an unstable prefix version and a stable prefix version are available,\n * it will return the stable prefix version preferentially.\n *\n * The result is *not* validated but is guaranteed to be a non-null object.\n *\n * @returns A non-null object.\n */\n private getIgnoreInvitesPolicies(): { [key: string]: any } {\n return this.getPoliciesAndIgnoreInvitesPolicies().ignoreInvitesPolicies;\n }\n\n /**\n * Modify in place the `IGNORE_INVITES_POLICIES` object from account data.\n */\n private async withIgnoreInvitesPolicies(\n cb: (ignoreInvitesPolicies: { [key: string]: any }) => void,\n ): Promise {\n const { policies, ignoreInvitesPolicies } = this.getPoliciesAndIgnoreInvitesPolicies();\n cb(ignoreInvitesPolicies);\n policies[IGNORE_INVITES_ACCOUNT_EVENT_KEY.name] = ignoreInvitesPolicies;\n await this.client.setAccountData(POLICIES_ACCOUNT_EVENT_TYPE.name, policies);\n }\n\n /**\n * As `getIgnoreInvitesPolicies` but also return the `POLICIES_ACCOUNT_EVENT_TYPE`\n * object.\n */\n private getPoliciesAndIgnoreInvitesPolicies(): {\n policies: { [key: string]: any };\n ignoreInvitesPolicies: { [key: string]: any };\n } {\n let policies: IContent = {};\n for (const key of [POLICIES_ACCOUNT_EVENT_TYPE.name, POLICIES_ACCOUNT_EVENT_TYPE.altName]) {\n if (!key) {\n continue;\n }\n const value = this.client.getAccountData(key)?.getContent();\n if (value) {\n policies = value;\n break;\n }\n }\n\n let ignoreInvitesPolicies = {};\n let hasIgnoreInvitesPolicies = false;\n for (const key of [IGNORE_INVITES_ACCOUNT_EVENT_KEY.name, IGNORE_INVITES_ACCOUNT_EVENT_KEY.altName]) {\n if (!key) {\n continue;\n }\n const value = policies[key];\n if (value && typeof value == \"object\") {\n ignoreInvitesPolicies = value;\n hasIgnoreInvitesPolicies = true;\n break;\n }\n }\n if (!hasIgnoreInvitesPolicies) {\n policies[IGNORE_INVITES_ACCOUNT_EVENT_KEY.name] = ignoreInvitesPolicies;\n }\n\n return { policies, ignoreInvitesPolicies };\n }\n}\n", - "/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { M_POLL_END, M_POLL_RESPONSE } from \"../@types/polls\";\nimport { MatrixClient } from \"../client\";\nimport { PollStartEvent } from \"../extensible_events_v1/PollStartEvent\";\nimport { MatrixEvent } from \"./event\";\nimport { Relations } from \"./relations\";\nimport { Room } from \"./room\";\nimport { TypedEventEmitter } from \"./typed-event-emitter\";\n\nexport enum PollEvent {\n New = \"Poll.new\",\n End = \"Poll.end\",\n Update = \"Poll.update\",\n Responses = \"Poll.Responses\",\n Destroy = \"Poll.Destroy\",\n UndecryptableRelations = \"Poll.UndecryptableRelations\",\n}\n\nexport type PollEventHandlerMap = {\n [PollEvent.Update]: (event: MatrixEvent, poll: Poll) => void;\n [PollEvent.Destroy]: (pollIdentifier: string) => void;\n [PollEvent.End]: () => void;\n [PollEvent.Responses]: (responses: Relations) => void;\n [PollEvent.UndecryptableRelations]: (count: number) => void;\n};\n\nconst filterResponseRelations = (\n relationEvents: MatrixEvent[],\n pollEndTimestamp: number,\n): {\n responseEvents: MatrixEvent[];\n} => {\n const responseEvents = relationEvents.filter((event) => {\n if (event.isDecryptionFailure()) {\n return;\n }\n return (\n M_POLL_RESPONSE.matches(event.getType()) &&\n // From MSC3381:\n // \"Votes sent on or before the end event's timestamp are valid votes\"\n event.getTs() <= pollEndTimestamp\n );\n });\n\n return { responseEvents };\n};\n\nexport class Poll extends TypedEventEmitter, PollEventHandlerMap> {\n public readonly roomId: string;\n public readonly pollEvent: PollStartEvent;\n private _isFetchingResponses = false;\n private relationsNextBatch: string | undefined;\n private responses: null | Relations = null;\n private endEvent: MatrixEvent | undefined;\n /**\n * Keep track of undecryptable relations\n * As incomplete result sets affect poll results\n */\n private undecryptableRelationEventIds = new Set();\n\n public constructor(public readonly rootEvent: MatrixEvent, private matrixClient: MatrixClient, private room: Room) {\n super();\n if (!this.rootEvent.getRoomId() || !this.rootEvent.getId()) {\n throw new Error(\"Invalid poll start event.\");\n }\n this.roomId = this.rootEvent.getRoomId()!;\n this.pollEvent = this.rootEvent.unstableExtensibleEvent as unknown as PollStartEvent;\n }\n\n public get pollId(): string {\n return this.rootEvent.getId()!;\n }\n\n public get endEventId(): string | undefined {\n return this.endEvent?.getId();\n }\n\n public get isEnded(): boolean {\n return !!this.endEvent;\n }\n\n public get isFetchingResponses(): boolean {\n return this._isFetchingResponses;\n }\n\n public get undecryptableRelationsCount(): number {\n return this.undecryptableRelationEventIds.size;\n }\n\n public async getResponses(): Promise {\n // if we have already fetched some responses\n // just return them\n if (this.responses) {\n return this.responses;\n }\n\n // if there is no fetching in progress\n // start fetching\n if (!this.isFetchingResponses) {\n await this.fetchResponses();\n }\n // return whatever responses we got from the first page\n return this.responses!;\n }\n\n /**\n *\n * @param event - event with a relation to the rootEvent\n * @returns void\n */\n public onNewRelation(event: MatrixEvent): void {\n if (M_POLL_END.matches(event.getType()) && this.validateEndEvent(event)) {\n this.endEvent = event;\n this.refilterResponsesOnEnd();\n this.emit(PollEvent.End);\n }\n\n // wait for poll responses to be initialised\n if (!this.responses) {\n return;\n }\n\n const pollEndTimestamp = this.endEvent?.getTs() || Number.MAX_SAFE_INTEGER;\n const { responseEvents } = filterResponseRelations([event], pollEndTimestamp);\n\n this.countUndecryptableEvents([event]);\n\n if (responseEvents.length) {\n responseEvents.forEach((event) => {\n this.responses!.addEvent(event);\n });\n\n this.emit(PollEvent.Responses, this.responses);\n }\n }\n\n private async fetchResponses(): Promise {\n this._isFetchingResponses = true;\n\n // we want:\n // - stable and unstable M_POLL_RESPONSE\n // - stable and unstable M_POLL_END\n // so make one api call and filter by event type client side\n const allRelations = await this.matrixClient.relations(\n this.roomId,\n this.rootEvent.getId()!,\n \"m.reference\",\n undefined,\n {\n from: this.relationsNextBatch || undefined,\n },\n );\n\n await Promise.all(allRelations.events.map((event) => this.matrixClient.decryptEventIfNeeded(event)));\n\n const responses =\n this.responses ||\n new Relations(\"m.reference\", M_POLL_RESPONSE.name, this.matrixClient, [M_POLL_RESPONSE.altName!]);\n\n const pollEndEvent = allRelations.events.find((event) => M_POLL_END.matches(event.getType()));\n\n if (this.validateEndEvent(pollEndEvent)) {\n this.endEvent = pollEndEvent;\n this.refilterResponsesOnEnd();\n this.emit(PollEvent.End);\n }\n\n const pollCloseTimestamp = this.endEvent?.getTs() || Number.MAX_SAFE_INTEGER;\n\n const { responseEvents } = filterResponseRelations(allRelations.events, pollCloseTimestamp);\n\n responseEvents.forEach((event) => {\n responses.addEvent(event);\n });\n\n this.relationsNextBatch = allRelations.nextBatch ?? undefined;\n this.responses = responses;\n this.countUndecryptableEvents(allRelations.events);\n\n // while there are more pages of relations\n // fetch them\n if (this.relationsNextBatch) {\n // don't await\n // we want to return the first page as soon as possible\n this.fetchResponses();\n } else {\n // no more pages\n this._isFetchingResponses = false;\n }\n\n // emit after updating _isFetchingResponses state\n this.emit(PollEvent.Responses, this.responses);\n }\n\n /**\n * Only responses made before the poll ended are valid\n * Refilter after an end event is recieved\n * To ensure responses are valid\n */\n private refilterResponsesOnEnd(): void {\n if (!this.responses) {\n return;\n }\n\n const pollEndTimestamp = this.endEvent?.getTs() || Number.MAX_SAFE_INTEGER;\n this.responses.getRelations().forEach((event) => {\n if (event.getTs() > pollEndTimestamp) {\n this.responses?.removeEvent(event);\n }\n });\n\n this.emit(PollEvent.Responses, this.responses);\n }\n\n private countUndecryptableEvents = (events: MatrixEvent[]): void => {\n const undecryptableEventIds = events\n .filter((event) => event.isDecryptionFailure())\n .map((event) => event.getId()!);\n\n const previousCount = this.undecryptableRelationsCount;\n this.undecryptableRelationEventIds = new Set([...this.undecryptableRelationEventIds, ...undecryptableEventIds]);\n\n if (this.undecryptableRelationsCount !== previousCount) {\n this.emit(PollEvent.UndecryptableRelations, this.undecryptableRelationsCount);\n }\n };\n\n private validateEndEvent(endEvent?: MatrixEvent): boolean {\n if (!endEvent) {\n return false;\n }\n /**\n * Repeated end events are ignored -\n * only the first (valid) closure event by origin_server_ts is counted.\n */\n if (this.endEvent && this.endEvent.getTs() < endEvent.getTs()) {\n return false;\n }\n\n /**\n * MSC3381\n * If a m.poll.end event is received from someone other than the poll creator or user with permission to redact\n * others' messages in the room, the event must be ignored by clients due to being invalid.\n */\n const roomCurrentState = this.room.currentState;\n const endEventSender = endEvent.getSender();\n return (\n !!endEventSender &&\n (endEventSender === this.rootEvent.getSender() ||\n roomCurrentState.maySendRedactionForEvent(this.rootEvent, endEventSender))\n );\n }\n}\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {\n CachedReceipt,\n MAIN_ROOM_TIMELINE,\n Receipt,\n ReceiptCache,\n ReceiptType,\n WrappedReceipt,\n} from \"../@types/read_receipts\";\nimport { ListenerMap, TypedEventEmitter } from \"./typed-event-emitter\";\nimport * as utils from \"../utils\";\nimport { MatrixEvent } from \"./event\";\nimport { EventType } from \"../@types/event\";\nimport { EventTimelineSet } from \"./event-timeline-set\";\nimport { MapWithDefault } from \"../utils\";\nimport { NotificationCountType } from \"./room\";\n\nexport function synthesizeReceipt(userId: string, event: MatrixEvent, receiptType: ReceiptType): MatrixEvent {\n return new MatrixEvent({\n content: {\n [event.getId()!]: {\n [receiptType]: {\n [userId]: {\n ts: event.getTs(),\n thread_id: event.threadRootId ?? MAIN_ROOM_TIMELINE,\n },\n },\n },\n },\n type: EventType.Receipt,\n room_id: event.getRoomId(),\n });\n}\n\nconst ReceiptPairRealIndex = 0;\nconst ReceiptPairSyntheticIndex = 1;\n\nexport abstract class ReadReceipt<\n Events extends string,\n Arguments extends ListenerMap,\n SuperclassArguments extends ListenerMap = Arguments,\n> extends TypedEventEmitter {\n // receipts should clobber based on receipt_type and user_id pairs hence\n // the form of this structure. This is sub-optimal for the exposed APIs\n // which pass in an event ID and get back some receipts, so we also store\n // a pre-cached list for this purpose.\n // Map: receipt type → user Id → receipt\n private receipts = new MapWithDefault>(\n () => new Map(),\n );\n private receiptCacheByEventId: ReceiptCache = new Map();\n\n public abstract getUnfilteredTimelineSet(): EventTimelineSet;\n public abstract timeline: MatrixEvent[];\n\n /**\n * Gets the latest receipt for a given user in the room\n * @param userId - The id of the user for which we want the receipt\n * @param ignoreSynthesized - Whether to ignore synthesized receipts or not\n * @param receiptType - Optional. The type of the receipt we want to get\n * @returns the latest receipts of the chosen type for the chosen user\n */\n public getReadReceiptForUserId(\n userId: string,\n ignoreSynthesized = false,\n receiptType = ReceiptType.Read,\n ): WrappedReceipt | null {\n const [realReceipt, syntheticReceipt] = this.receipts.get(receiptType)?.get(userId) ?? [null, null];\n if (ignoreSynthesized) {\n return realReceipt;\n }\n\n return syntheticReceipt ?? realReceipt;\n }\n\n /**\n * Get the ID of the event that a given user has read up to, or null if we\n * have received no read receipts from them.\n * @param userId - The user ID to get read receipt event ID for\n * @param ignoreSynthesized - If true, return only receipts that have been\n * sent by the server, not implicit ones generated\n * by the JS SDK.\n * @returns ID of the latest event that the given user has read, or null.\n */\n public getEventReadUpTo(userId: string, ignoreSynthesized = false): string | null {\n // XXX: This is very very ugly and I hope I won't have to ever add a new\n // receipt type here again. IMHO this should be done by the server in\n // some more intelligent manner or the client should just use timestamps\n\n const timelineSet = this.getUnfilteredTimelineSet();\n const publicReadReceipt = this.getReadReceiptForUserId(userId, ignoreSynthesized, ReceiptType.Read);\n const privateReadReceipt = this.getReadReceiptForUserId(userId, ignoreSynthesized, ReceiptType.ReadPrivate);\n\n // If we have both, compare them\n let comparison: number | null | undefined;\n if (publicReadReceipt?.eventId && privateReadReceipt?.eventId) {\n comparison = timelineSet.compareEventOrdering(publicReadReceipt?.eventId, privateReadReceipt?.eventId);\n }\n\n // If we didn't get a comparison try to compare the ts of the receipts\n if (!comparison && publicReadReceipt?.data?.ts && privateReadReceipt?.data?.ts) {\n comparison = publicReadReceipt?.data?.ts - privateReadReceipt?.data?.ts;\n }\n\n // The public receipt is more likely to drift out of date so the private\n // one has precedence\n if (!comparison) return privateReadReceipt?.eventId ?? publicReadReceipt?.eventId ?? null;\n\n // If public read receipt is older, return the private one\n return (comparison < 0 ? privateReadReceipt?.eventId : publicReadReceipt?.eventId) ?? null;\n }\n\n public addReceiptToStructure(\n eventId: string,\n receiptType: ReceiptType,\n userId: string,\n receipt: Receipt,\n synthetic: boolean,\n ): void {\n const receiptTypesMap = this.receipts.getOrCreate(receiptType);\n let pair = receiptTypesMap.get(userId);\n\n if (!pair) {\n pair = [null, null];\n receiptTypesMap.set(userId, pair);\n }\n\n let existingReceipt = pair[ReceiptPairRealIndex];\n if (synthetic) {\n existingReceipt = pair[ReceiptPairSyntheticIndex] ?? pair[ReceiptPairRealIndex];\n }\n\n if (existingReceipt) {\n // we only want to add this receipt if we think it is later than the one we already have.\n // This is managed server-side, but because we synthesize RRs locally we have to do it here too.\n const ordering = this.getUnfilteredTimelineSet().compareEventOrdering(existingReceipt.eventId, eventId);\n if (ordering !== null && ordering >= 0) {\n return;\n }\n }\n\n const wrappedReceipt: WrappedReceipt = {\n eventId,\n data: receipt,\n };\n\n const realReceipt = synthetic ? pair[ReceiptPairRealIndex] : wrappedReceipt;\n const syntheticReceipt = synthetic ? wrappedReceipt : pair[ReceiptPairSyntheticIndex];\n\n let ordering: number | null = null;\n if (realReceipt && syntheticReceipt) {\n ordering = this.getUnfilteredTimelineSet().compareEventOrdering(\n realReceipt.eventId,\n syntheticReceipt.eventId,\n );\n }\n\n const preferSynthetic = ordering === null || ordering < 0;\n\n // we don't bother caching just real receipts by event ID as there's nothing that would read it.\n // Take the current cached receipt before we overwrite the pair elements.\n const cachedReceipt = pair[ReceiptPairSyntheticIndex] ?? pair[ReceiptPairRealIndex];\n\n if (synthetic && preferSynthetic) {\n pair[ReceiptPairSyntheticIndex] = wrappedReceipt;\n } else if (!synthetic) {\n pair[ReceiptPairRealIndex] = wrappedReceipt;\n\n if (!preferSynthetic) {\n pair[ReceiptPairSyntheticIndex] = null;\n }\n }\n\n const newCachedReceipt = pair[ReceiptPairSyntheticIndex] ?? pair[ReceiptPairRealIndex];\n if (cachedReceipt === newCachedReceipt) return;\n\n // clean up any previous cache entry\n if (cachedReceipt && this.receiptCacheByEventId.get(cachedReceipt.eventId)) {\n const previousEventId = cachedReceipt.eventId;\n // Remove the receipt we're about to clobber out of existence from the cache\n this.receiptCacheByEventId.set(\n previousEventId,\n this.receiptCacheByEventId.get(previousEventId)!.filter((r) => {\n return r.type !== receiptType || r.userId !== userId;\n }),\n );\n\n if (this.receiptCacheByEventId.get(previousEventId)!.length < 1) {\n this.receiptCacheByEventId.delete(previousEventId); // clean up the cache keys\n }\n }\n\n // cache the new one\n if (!this.receiptCacheByEventId.get(eventId)) {\n this.receiptCacheByEventId.set(eventId, []);\n }\n this.receiptCacheByEventId.get(eventId)!.push({\n userId: userId,\n type: receiptType as ReceiptType,\n data: receipt,\n });\n }\n\n /**\n * Get a list of receipts for the given event.\n * @param event - the event to get receipts for\n * @returns A list of receipts with a userId, type and data keys or\n * an empty list.\n */\n public getReceiptsForEvent(event: MatrixEvent): CachedReceipt[] {\n return this.receiptCacheByEventId.get(event.getId()!) || [];\n }\n\n public abstract addReceipt(event: MatrixEvent, synthetic: boolean): void;\n\n public abstract setUnread(type: NotificationCountType, count: number): void;\n\n /**\n * This issue should also be addressed on synapse's side and is tracked as part\n * of https://github.com/matrix-org/synapse/issues/14837\n *\n * Retrieves the read receipt for the logged in user and checks if it matches\n * the last event in the room and whether that event originated from the logged\n * in user.\n * Under those conditions we can consider the context as read. This is useful\n * because we never send read receipts against our own events\n * @param userId - the logged in user\n */\n public fixupNotifications(userId: string): void {\n const receipt = this.getReadReceiptForUserId(userId, false);\n\n const lastEvent = this.timeline[this.timeline.length - 1];\n if (lastEvent && receipt?.eventId === lastEvent.getId() && userId === lastEvent.getSender()) {\n this.setUnread(NotificationCountType.Total, 0);\n this.setUnread(NotificationCountType.Highlight, 0);\n }\n }\n\n /**\n * Add a temporary local-echo receipt to the room to reflect in the\n * client the fact that we've sent one.\n * @param userId - The user ID if the receipt sender\n * @param e - The event that is to be acknowledged\n * @param receiptType - The type of receipt\n */\n public addLocalEchoReceipt(userId: string, e: MatrixEvent, receiptType: ReceiptType): void {\n this.addReceipt(synthesizeReceipt(userId, e, receiptType), true);\n }\n\n /**\n * Get a list of user IDs who have read up to the given event.\n * @param event - the event to get read receipts for.\n * @returns A list of user IDs.\n */\n public getUsersReadUpTo(event: MatrixEvent): string[] {\n return this.getReceiptsForEvent(event)\n .filter(function (receipt) {\n return utils.isSupportedReceiptType(receipt.type);\n })\n .map(function (receipt) {\n return receipt.userId;\n });\n }\n\n /**\n * Determines if the given user has read a particular event ID with the known\n * history of the room. This is not a definitive check as it relies only on\n * what is available to the room at the time of execution.\n * @param userId - The user ID to check the read state of.\n * @param eventId - The event ID to check if the user read.\n * @returns True if the user has read the event, false otherwise.\n */\n public hasUserReadEvent(userId: string, eventId: string): boolean {\n const readUpToId = this.getEventReadUpTo(userId, false);\n if (readUpToId === eventId) return true;\n\n if (\n this.timeline?.length &&\n this.timeline[this.timeline.length - 1].getSender() &&\n this.timeline[this.timeline.length - 1].getSender() === userId\n ) {\n // It doesn't matter where the event is in the timeline, the user has read\n // it because they've sent the latest event.\n return true;\n }\n\n for (let i = this.timeline?.length - 1; i >= 0; --i) {\n const ev = this.timeline[i];\n\n // If we encounter the target event first, the user hasn't read it\n // however if we encounter the readUpToId first then the user has read\n // it. These rules apply because we're iterating bottom-up.\n if (ev.getId() === eventId) return false;\n if (ev.getId() === readUpToId) return true;\n }\n\n // We don't know if the user has read it, so assume not.\n return false;\n }\n}\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { Relations } from \"./relations\";\nimport { EventType, RelationType } from \"../@types/event\";\nimport { EventStatus, MatrixEvent, MatrixEventEvent } from \"./event\";\nimport { EventTimelineSet } from \"./event-timeline-set\";\nimport { MatrixClient } from \"../client\";\nimport { Room } from \"./room\";\n\nexport class RelationsContainer {\n // A tree of objects to access a set of related children for an event, as in:\n // this.relations.get(parentEventId).get(relationType).get(relationEventType)\n private relations = new Map>>();\n\n public constructor(private readonly client: MatrixClient, private readonly room?: Room) {}\n\n /**\n * Get a collection of child events to a given event in this timeline set.\n *\n * @param eventId - The ID of the event that you'd like to access child events for.\n * For example, with annotations, this would be the ID of the event being annotated.\n * @param relationType - The type of relationship involved, such as \"m.annotation\", \"m.reference\", \"m.replace\", etc.\n * @param eventType - The relation event's type, such as \"m.reaction\", etc.\n * @throws If `eventId, relationType or eventType`\n * are not valid.\n *\n * @returns\n * A container for relation events or undefined if there are no relation events for\n * the relationType.\n */\n public getChildEventsForEvent(\n eventId: string,\n relationType: RelationType | string,\n eventType: EventType | string,\n ): Relations | undefined {\n return this.relations.get(eventId)?.get(relationType)?.get(eventType);\n }\n\n public getAllChildEventsForEvent(parentEventId: string): MatrixEvent[] {\n const relationsForEvent =\n this.relations.get(parentEventId) ?? new Map>();\n const events: MatrixEvent[] = [];\n for (const relationsRecord of relationsForEvent.values()) {\n for (const relations of relationsRecord.values()) {\n events.push(...relations.getRelations());\n }\n }\n return events;\n }\n\n /**\n * Set an event as the target event if any Relations exist for it already.\n * Child events can point to other child events as their parent, so this method may be\n * called for events which are also logically child events.\n *\n * @param event - The event to check as relation target.\n */\n public aggregateParentEvent(event: MatrixEvent): void {\n const relationsForEvent = this.relations.get(event.getId()!);\n if (!relationsForEvent) return;\n\n for (const relationsWithRelType of relationsForEvent.values()) {\n for (const relationsWithEventType of relationsWithRelType.values()) {\n relationsWithEventType.setTargetEvent(event);\n }\n }\n }\n\n /**\n * Add relation events to the relevant relation collection.\n *\n * @param event - The new child event to be aggregated.\n * @param timelineSet - The event timeline set within which to search for the related event if any.\n */\n public aggregateChildEvent(event: MatrixEvent, timelineSet?: EventTimelineSet): void {\n if (event.isRedacted() || event.status === EventStatus.CANCELLED) {\n return;\n }\n\n const relation = event.getRelation();\n if (!relation) return;\n\n const onEventDecrypted = (): void => {\n if (event.isDecryptionFailure()) {\n // This could for example happen if the encryption keys are not yet available.\n // The event may still be decrypted later. Register the listener again.\n event.once(MatrixEventEvent.Decrypted, onEventDecrypted);\n return;\n }\n\n this.aggregateChildEvent(event, timelineSet);\n };\n\n // If the event is currently encrypted, wait until it has been decrypted.\n if (event.isBeingDecrypted() || event.shouldAttemptDecryption()) {\n event.once(MatrixEventEvent.Decrypted, onEventDecrypted);\n return;\n }\n\n const { event_id: relatesToEventId, rel_type: relationType } = relation;\n const eventType = event.getType();\n\n let relationsForEvent = this.relations.get(relatesToEventId!);\n if (!relationsForEvent) {\n relationsForEvent = new Map>();\n this.relations.set(relatesToEventId!, relationsForEvent);\n }\n\n let relationsWithRelType = relationsForEvent.get(relationType!);\n if (!relationsWithRelType) {\n relationsWithRelType = new Map();\n relationsForEvent.set(relationType!, relationsWithRelType);\n }\n\n let relationsWithEventType = relationsWithRelType.get(eventType);\n if (!relationsWithEventType) {\n relationsWithEventType = new Relations(relationType!, eventType, this.client);\n relationsWithRelType.set(eventType, relationsWithEventType);\n\n const room = this.room ?? timelineSet?.room;\n const relatesToEvent =\n timelineSet?.findEventById(relatesToEventId!) ??\n room?.findEventById(relatesToEventId!) ??\n room?.getPendingEvent(relatesToEventId!);\n if (relatesToEvent) {\n relationsWithEventType.setTargetEvent(relatesToEvent);\n }\n }\n\n relationsWithEventType.addEvent(event);\n }\n}\n", - "/*\nCopyright 2019, 2021, 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventStatus, IAggregatedRelation, MatrixEvent, MatrixEventEvent } from \"./event\";\nimport { logger } from \"../logger\";\nimport { RelationType } from \"../@types/event\";\nimport { TypedEventEmitter } from \"./typed-event-emitter\";\nimport { MatrixClient } from \"../client\";\nimport { Room } from \"./room\";\n\nexport enum RelationsEvent {\n Add = \"Relations.add\",\n Remove = \"Relations.remove\",\n Redaction = \"Relations.redaction\",\n}\n\nexport type EventHandlerMap = {\n [RelationsEvent.Add]: (event: MatrixEvent) => void;\n [RelationsEvent.Remove]: (event: MatrixEvent) => void;\n [RelationsEvent.Redaction]: (event: MatrixEvent) => void;\n};\n\nconst matchesEventType = (eventType: string, targetEventType: string, altTargetEventTypes: string[] = []): boolean =>\n [targetEventType, ...altTargetEventTypes].includes(eventType);\n\n/**\n * A container for relation events that supports easy access to common ways of\n * aggregating such events. Each instance holds events that of a single relation\n * type and event type. All of the events also relate to the same original event.\n *\n * The typical way to get one of these containers is via\n * EventTimelineSet#getRelationsForEvent.\n */\nexport class Relations extends TypedEventEmitter {\n private relationEventIds = new Set();\n private relations = new Set();\n private annotationsByKey: Record> = {};\n private annotationsBySender: Record> = {};\n private sortedAnnotationsByKey: [string, Set][] = [];\n private targetEvent: MatrixEvent | null = null;\n private creationEmitted = false;\n private readonly client: MatrixClient;\n\n /**\n * @param relationType - The type of relation involved, such as \"m.annotation\", \"m.reference\", \"m.replace\", etc.\n * @param eventType - The relation event's type, such as \"m.reaction\", etc.\n * @param client - The client which created this instance. For backwards compatibility also accepts a Room.\n * @param altEventTypes - alt event types for relation events, for example to support unstable prefixed event types\n */\n public constructor(\n public readonly relationType: RelationType | string,\n public readonly eventType: string,\n client: MatrixClient | Room,\n public readonly altEventTypes?: string[],\n ) {\n super();\n this.client = client instanceof Room ? client.client : client;\n }\n\n /**\n * Add relation events to this collection.\n *\n * @param event - The new relation event to be added.\n */\n public async addEvent(event: MatrixEvent): Promise {\n if (this.relationEventIds.has(event.getId()!)) {\n return;\n }\n\n const relation = event.getRelation();\n if (!relation) {\n logger.error(\"Event must have relation info\");\n return;\n }\n\n const relationType = relation.rel_type;\n const eventType = event.getType();\n\n if (this.relationType !== relationType || !matchesEventType(eventType, this.eventType, this.altEventTypes)) {\n logger.error(\"Event relation info doesn't match this container\");\n return;\n }\n\n // If the event is in the process of being sent, listen for cancellation\n // so we can remove the event from the collection.\n if (event.isSending()) {\n event.on(MatrixEventEvent.Status, this.onEventStatus);\n }\n\n this.relations.add(event);\n this.relationEventIds.add(event.getId()!);\n\n if (this.relationType === RelationType.Annotation) {\n this.addAnnotationToAggregation(event);\n } else if (this.relationType === RelationType.Replace && this.targetEvent && !this.targetEvent.isState()) {\n const lastReplacement = await this.getLastReplacement();\n this.targetEvent.makeReplaced(lastReplacement!);\n }\n\n event.on(MatrixEventEvent.BeforeRedaction, this.onBeforeRedaction);\n\n this.emit(RelationsEvent.Add, event);\n\n this.maybeEmitCreated();\n }\n\n /**\n * Remove relation event from this collection.\n *\n * @param event - The relation event to remove.\n */\n public async removeEvent(event: MatrixEvent): Promise {\n if (!this.relations.has(event)) {\n return;\n }\n\n this.relations.delete(event);\n\n if (this.relationType === RelationType.Annotation) {\n this.removeAnnotationFromAggregation(event);\n } else if (this.relationType === RelationType.Replace && this.targetEvent && !this.targetEvent.isState()) {\n const lastReplacement = await this.getLastReplacement();\n this.targetEvent.makeReplaced(lastReplacement!);\n }\n\n this.emit(RelationsEvent.Remove, event);\n }\n\n /**\n * Listens for event status changes to remove cancelled events.\n *\n * @param event - The event whose status has changed\n * @param status - The new status\n */\n private onEventStatus = (event: MatrixEvent, status: EventStatus | null): void => {\n if (!event.isSending()) {\n // Sending is done, so we don't need to listen anymore\n event.removeListener(MatrixEventEvent.Status, this.onEventStatus);\n return;\n }\n if (status !== EventStatus.CANCELLED) {\n return;\n }\n // Event was cancelled, remove from the collection\n event.removeListener(MatrixEventEvent.Status, this.onEventStatus);\n this.removeEvent(event);\n };\n\n /**\n * Get all relation events in this collection.\n *\n * These are currently in the order of insertion to this collection, which\n * won't match timeline order in the case of scrollback.\n * TODO: Tweak `addEvent` to insert correctly for scrollback.\n *\n * Relation events in insertion order.\n */\n public getRelations(): MatrixEvent[] {\n return [...this.relations];\n }\n\n private addAnnotationToAggregation(event: MatrixEvent): void {\n const { key } = event.getRelation() ?? {};\n if (!key) return;\n\n let eventsForKey = this.annotationsByKey[key];\n if (!eventsForKey) {\n eventsForKey = this.annotationsByKey[key] = new Set();\n this.sortedAnnotationsByKey.push([key, eventsForKey]);\n }\n // Add the new event to the set for this key\n eventsForKey.add(event);\n // Re-sort the [key, events] pairs in descending order of event count\n this.sortedAnnotationsByKey.sort((a, b) => {\n const aEvents = a[1];\n const bEvents = b[1];\n return bEvents.size - aEvents.size;\n });\n\n const sender = event.getSender()!;\n let eventsFromSender = this.annotationsBySender[sender];\n if (!eventsFromSender) {\n eventsFromSender = this.annotationsBySender[sender] = new Set();\n }\n // Add the new event to the set for this sender\n eventsFromSender.add(event);\n }\n\n private removeAnnotationFromAggregation(event: MatrixEvent): void {\n const { key } = event.getRelation() ?? {};\n if (!key) return;\n\n const eventsForKey = this.annotationsByKey[key];\n if (eventsForKey) {\n eventsForKey.delete(event);\n\n // Re-sort the [key, events] pairs in descending order of event count\n this.sortedAnnotationsByKey.sort((a, b) => {\n const aEvents = a[1];\n const bEvents = b[1];\n return bEvents.size - aEvents.size;\n });\n }\n\n const sender = event.getSender()!;\n const eventsFromSender = this.annotationsBySender[sender];\n if (eventsFromSender) {\n eventsFromSender.delete(event);\n }\n }\n\n /**\n * For relations that have been redacted, we want to remove them from\n * aggregation data sets and emit an update event.\n *\n * To do so, we listen for `Event.beforeRedaction`, which happens:\n * - after the server accepted the redaction and remote echoed back to us\n * - before the original event has been marked redacted in the client\n *\n * @param redactedEvent - The original relation event that is about to be redacted.\n */\n private onBeforeRedaction = async (redactedEvent: MatrixEvent): Promise => {\n if (!this.relations.has(redactedEvent)) {\n return;\n }\n\n this.relations.delete(redactedEvent);\n\n if (this.relationType === RelationType.Annotation) {\n // Remove the redacted annotation from aggregation by key\n this.removeAnnotationFromAggregation(redactedEvent);\n } else if (this.relationType === RelationType.Replace && this.targetEvent && !this.targetEvent.isState()) {\n const lastReplacement = await this.getLastReplacement();\n this.targetEvent.makeReplaced(lastReplacement!);\n }\n\n redactedEvent.removeListener(MatrixEventEvent.BeforeRedaction, this.onBeforeRedaction);\n\n this.emit(RelationsEvent.Redaction, redactedEvent);\n };\n\n /**\n * Get all events in this collection grouped by key and sorted by descending\n * event count in each group.\n *\n * This is currently only supported for the annotation relation type.\n *\n * An array of [key, events] pairs sorted by descending event count.\n * The events are stored in a Set (which preserves insertion order).\n */\n public getSortedAnnotationsByKey(): [string, Set][] | null {\n if (this.relationType !== RelationType.Annotation) {\n // Other relation types are not grouped currently.\n return null;\n }\n\n return this.sortedAnnotationsByKey;\n }\n\n /**\n * Get all events in this collection grouped by sender.\n *\n * This is currently only supported for the annotation relation type.\n *\n * An object with each relation sender as a key and the matching Set of\n * events for that sender as a value.\n */\n public getAnnotationsBySender(): Record> | null {\n if (this.relationType !== RelationType.Annotation) {\n // Other relation types are not grouped currently.\n return null;\n }\n\n return this.annotationsBySender;\n }\n\n /**\n * Returns the most recent (and allowed) m.replace relation, if any.\n *\n * This is currently only supported for the m.replace relation type,\n * once the target event is known, see `addEvent`.\n */\n public async getLastReplacement(): Promise {\n if (this.relationType !== RelationType.Replace) {\n // Aggregating on last only makes sense for this relation type\n return null;\n }\n if (!this.targetEvent) {\n // Don't know which replacements to accept yet.\n // This method shouldn't be called before the original\n // event is known anyway.\n return null;\n }\n\n // the all-knowning server tells us that the event at some point had\n // this timestamp for its replacement, so any following replacement should definitely not be less\n const replaceRelation = this.targetEvent.getServerAggregatedRelation(RelationType.Replace);\n const minTs = replaceRelation?.origin_server_ts;\n\n const lastReplacement = this.getRelations().reduce((last, event) => {\n if (event.getSender() !== this.targetEvent!.getSender()) {\n return last;\n }\n if (minTs && minTs > event.getTs()) {\n return last;\n }\n if (last && last.getTs() > event.getTs()) {\n return last;\n }\n return event;\n }, null);\n\n if (lastReplacement?.shouldAttemptDecryption() && this.client.isCryptoEnabled()) {\n await lastReplacement.attemptDecryption(this.client.crypto!);\n } else if (lastReplacement?.isBeingDecrypted()) {\n await lastReplacement.getDecryptionPromise();\n }\n\n return lastReplacement;\n }\n\n /*\n * @param targetEvent - the event the relations are related to.\n */\n public async setTargetEvent(event: MatrixEvent): Promise {\n if (this.targetEvent) {\n return;\n }\n this.targetEvent = event;\n\n if (this.relationType === RelationType.Replace && !this.targetEvent.isState()) {\n const replacement = await this.getLastReplacement();\n // this is the initial update, so only call it if we already have something\n // to not emit Event.replaced needlessly\n if (replacement) {\n this.targetEvent.makeReplaced(replacement);\n }\n }\n\n this.maybeEmitCreated();\n }\n\n private maybeEmitCreated(): void {\n if (this.creationEmitted) {\n return;\n }\n // Only emit we're \"created\" once we have a target event instance _and_\n // at least one related event.\n if (!this.targetEvent || !this.relations.size) {\n return;\n }\n this.creationEmitted = true;\n this.targetEvent.emit(MatrixEventEvent.RelationsCreated, this.relationType, this.eventType);\n }\n}\n", - "/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { getHttpUriForMxc } from \"../content-repo\";\nimport * as utils from \"../utils\";\nimport { User } from \"./user\";\nimport { MatrixEvent } from \"./event\";\nimport { RoomState } from \"./room-state\";\nimport { logger } from \"../logger\";\nimport { TypedEventEmitter } from \"./typed-event-emitter\";\nimport { EventType } from \"../@types/event\";\n\nexport enum RoomMemberEvent {\n Membership = \"RoomMember.membership\",\n Name = \"RoomMember.name\",\n PowerLevel = \"RoomMember.powerLevel\",\n Typing = \"RoomMember.typing\",\n}\n\nexport type RoomMemberEventHandlerMap = {\n /**\n * Fires whenever any room member's membership state changes.\n * @param event - The matrix event which caused this event to fire.\n * @param member - The member whose RoomMember.membership changed.\n * @param oldMembership - The previous membership state. Null if it's a new member.\n * @example\n * ```\n * matrixClient.on(\"RoomMember.membership\", function(event, member, oldMembership){\n * var newState = member.membership;\n * });\n * ```\n */\n [RoomMemberEvent.Membership]: (event: MatrixEvent, member: RoomMember, oldMembership?: string) => void;\n /**\n * Fires whenever any room member's name changes.\n * @param event - The matrix event which caused this event to fire.\n * @param member - The member whose RoomMember.name changed.\n * @param oldName - The previous name. Null if the member didn't have a name previously.\n * @example\n * ```\n * matrixClient.on(\"RoomMember.name\", function(event, member){\n * var newName = member.name;\n * });\n * ```\n */\n [RoomMemberEvent.Name]: (event: MatrixEvent, member: RoomMember, oldName: string | null) => void;\n /**\n * Fires whenever any room member's power level changes.\n * @param event - The matrix event which caused this event to fire.\n * @param member - The member whose RoomMember.powerLevel changed.\n * @example\n * ```\n * matrixClient.on(\"RoomMember.powerLevel\", function(event, member){\n * var newPowerLevel = member.powerLevel;\n * var newNormPowerLevel = member.powerLevelNorm;\n * });\n * ```\n */\n [RoomMemberEvent.PowerLevel]: (event: MatrixEvent, member: RoomMember) => void;\n /**\n * Fires whenever any room member's typing state changes.\n * @param event - The matrix event which caused this event to fire.\n * @param member - The member whose RoomMember.typing changed.\n * @example\n * ```\n * matrixClient.on(\"RoomMember.typing\", function(event, member){\n * var isTyping = member.typing;\n * });\n * ```\n */\n [RoomMemberEvent.Typing]: (event: MatrixEvent, member: RoomMember) => void;\n};\n\nexport class RoomMember extends TypedEventEmitter {\n private _isOutOfBand = false;\n private modified = -1;\n public requestedProfileInfo = false; // used by sync.ts\n\n // XXX these should be read-only\n /**\n * True if the room member is currently typing.\n */\n public typing = false;\n /**\n * The human-readable name for this room member. This will be\n * disambiguated with a suffix of \" (\\@user_id:matrix.org)\" if another member shares the\n * same displayname.\n */\n public name: string;\n /**\n * The ambiguous displayname of this room member.\n */\n public rawDisplayName: string;\n /**\n * The power level for this room member.\n */\n public powerLevel = 0;\n /**\n * The normalised power level (0-100) for this room member.\n */\n public powerLevelNorm = 0;\n /**\n * The User object for this room member, if one exists.\n */\n public user?: User;\n /**\n * The membership state for this room member e.g. 'join'.\n */\n public membership?: string;\n /**\n * True if the member's name is disambiguated.\n */\n public disambiguate = false;\n /**\n * The events describing this RoomMember.\n */\n public events: {\n /**\n * The m.room.member event for this RoomMember.\n */\n member?: MatrixEvent;\n } = {};\n\n /**\n * Construct a new room member.\n *\n * @param roomId - The room ID of the member.\n * @param userId - The user ID of the member.\n */\n public constructor(public readonly roomId: string, public readonly userId: string) {\n super();\n\n this.name = userId;\n this.rawDisplayName = userId;\n this.updateModifiedTime();\n }\n\n /**\n * Mark the member as coming from a channel that is not sync\n */\n public markOutOfBand(): void {\n this._isOutOfBand = true;\n }\n\n /**\n * @returns does the member come from a channel that is not sync?\n * This is used to store the member seperately\n * from the sync state so it available across browser sessions.\n */\n public isOutOfBand(): boolean {\n return this._isOutOfBand;\n }\n\n /**\n * Update this room member's membership event. May fire \"RoomMember.name\" if\n * this event updates this member's name.\n * @param event - The `m.room.member` event\n * @param roomState - Optional. The room state to take into account\n * when calculating (e.g. for disambiguating users with the same name).\n *\n * @remarks\n * Fires {@link RoomMemberEvent.Name}\n * Fires {@link RoomMemberEvent.Membership}\n */\n public setMembershipEvent(event: MatrixEvent, roomState?: RoomState): void {\n const displayName = event.getDirectionalContent().displayname ?? \"\";\n\n if (event.getType() !== EventType.RoomMember) {\n return;\n }\n\n this._isOutOfBand = false;\n\n this.events.member = event;\n\n const oldMembership = this.membership;\n this.membership = event.getDirectionalContent().membership;\n if (this.membership === undefined) {\n // logging to diagnose https://github.com/vector-im/element-web/issues/20962\n // (logs event content, although only of membership events)\n logger.trace(\n `membership event with membership undefined (forwardLooking: ${event.forwardLooking})!`,\n event.getContent(),\n `prevcontent is `,\n event.getPrevContent(),\n );\n }\n\n this.disambiguate = shouldDisambiguate(this.userId, displayName, roomState);\n\n const oldName = this.name;\n this.name = calculateDisplayName(this.userId, displayName, this.disambiguate);\n\n // not quite raw: we strip direction override chars so it can safely be inserted into\n // blocks of text without breaking the text direction\n this.rawDisplayName = utils.removeDirectionOverrideChars(event.getDirectionalContent().displayname ?? \"\");\n if (!this.rawDisplayName || !utils.removeHiddenChars(this.rawDisplayName)) {\n this.rawDisplayName = this.userId;\n }\n\n if (oldMembership !== this.membership) {\n this.updateModifiedTime();\n this.emit(RoomMemberEvent.Membership, event, this, oldMembership);\n }\n if (oldName !== this.name) {\n this.updateModifiedTime();\n this.emit(RoomMemberEvent.Name, event, this, oldName);\n }\n }\n\n /**\n * Update this room member's power level event. May fire\n * \"RoomMember.powerLevel\" if this event updates this member's power levels.\n * @param powerLevelEvent - The `m.room.power_levels` event\n *\n * @remarks\n * Fires {@link RoomMemberEvent.PowerLevel}\n */\n public setPowerLevelEvent(powerLevelEvent: MatrixEvent): void {\n if (powerLevelEvent.getType() !== EventType.RoomPowerLevels || powerLevelEvent.getStateKey() !== \"\") {\n return;\n }\n\n const evContent = powerLevelEvent.getDirectionalContent();\n\n let maxLevel = evContent.users_default || 0;\n const users: { [userId: string]: number } = evContent.users || {};\n Object.values(users).forEach((lvl: number) => {\n maxLevel = Math.max(maxLevel, lvl);\n });\n const oldPowerLevel = this.powerLevel;\n const oldPowerLevelNorm = this.powerLevelNorm;\n\n if (users[this.userId] !== undefined && Number.isInteger(users[this.userId])) {\n this.powerLevel = users[this.userId];\n } else if (evContent.users_default !== undefined) {\n this.powerLevel = evContent.users_default;\n } else {\n this.powerLevel = 0;\n }\n this.powerLevelNorm = 0;\n if (maxLevel > 0) {\n this.powerLevelNorm = (this.powerLevel * 100) / maxLevel;\n }\n\n // emit for changes in powerLevelNorm as well (since the app will need to\n // redraw everyone's level if the max has changed)\n if (oldPowerLevel !== this.powerLevel || oldPowerLevelNorm !== this.powerLevelNorm) {\n this.updateModifiedTime();\n this.emit(RoomMemberEvent.PowerLevel, powerLevelEvent, this);\n }\n }\n\n /**\n * Update this room member's typing event. May fire \"RoomMember.typing\" if\n * this event changes this member's typing state.\n * @param event - The typing event\n *\n * @remarks\n * Fires {@link RoomMemberEvent.Typing}\n */\n public setTypingEvent(event: MatrixEvent): void {\n if (event.getType() !== \"m.typing\") {\n return;\n }\n const oldTyping = this.typing;\n this.typing = false;\n const typingList = event.getContent().user_ids;\n if (!Array.isArray(typingList)) {\n // malformed event :/ bail early. TODO: whine?\n return;\n }\n if (typingList.indexOf(this.userId) !== -1) {\n this.typing = true;\n }\n if (oldTyping !== this.typing) {\n this.updateModifiedTime();\n this.emit(RoomMemberEvent.Typing, event, this);\n }\n }\n\n /**\n * Update the last modified time to the current time.\n */\n private updateModifiedTime(): void {\n this.modified = Date.now();\n }\n\n /**\n * Get the timestamp when this RoomMember was last updated. This timestamp is\n * updated when properties on this RoomMember are updated.\n * It is updated before firing events.\n * @returns The timestamp\n */\n public getLastModifiedTime(): number {\n return this.modified;\n }\n\n public isKicked(): boolean {\n return (\n this.membership === \"leave\" &&\n this.events.member !== undefined &&\n this.events.member.getSender() !== this.events.member.getStateKey()\n );\n }\n\n /**\n * If this member was invited with the is_direct flag set, return\n * the user that invited this member\n * @returns user id of the inviter\n */\n public getDMInviter(): string | undefined {\n // when not available because that room state hasn't been loaded in,\n // we don't really know, but more likely to not be a direct chat\n if (this.events.member) {\n // TODO: persist the is_direct flag on the member as more member events\n // come in caused by displayName changes.\n\n // the is_direct flag is set on the invite member event.\n // This is copied on the prev_content section of the join member event\n // when the invite is accepted.\n\n const memberEvent = this.events.member;\n let memberContent = memberEvent.getContent();\n let inviteSender: string | undefined = memberEvent.getSender();\n\n if (memberContent.membership === \"join\") {\n memberContent = memberEvent.getPrevContent();\n inviteSender = memberEvent.getUnsigned().prev_sender;\n }\n\n if (memberContent.membership === \"invite\" && memberContent.is_direct) {\n return inviteSender;\n }\n }\n }\n\n /**\n * Get the avatar URL for a room member.\n * @param baseUrl - The base homeserver URL See\n * {@link MatrixClient#getHomeserverUrl}.\n * @param width - The desired width of the thumbnail.\n * @param height - The desired height of the thumbnail.\n * @param resizeMethod - The thumbnail resize method to use, either\n * \"crop\" or \"scale\".\n * @param allowDefault - (optional) Passing false causes this method to\n * return null if the user has no avatar image. Otherwise, a default image URL\n * will be returned. Default: true. (Deprecated)\n * @param allowDirectLinks - (optional) If true, the avatar URL will be\n * returned even if it is a direct hyperlink rather than a matrix content URL.\n * If false, any non-matrix content URLs will be ignored. Setting this option to\n * true will expose URLs that, if fetched, will leak information about the user\n * to anyone who they share a room with.\n * @returns the avatar URL or null.\n */\n public getAvatarUrl(\n baseUrl: string,\n width: number,\n height: number,\n resizeMethod: string,\n allowDefault = true,\n allowDirectLinks: boolean,\n ): string | null {\n const rawUrl = this.getMxcAvatarUrl();\n\n if (!rawUrl && !allowDefault) {\n return null;\n }\n const httpUrl = getHttpUriForMxc(baseUrl, rawUrl, width, height, resizeMethod, allowDirectLinks);\n if (httpUrl) {\n return httpUrl;\n }\n return null;\n }\n\n /**\n * get the mxc avatar url, either from a state event, or from a lazily loaded member\n * @returns the mxc avatar url\n */\n public getMxcAvatarUrl(): string | undefined {\n if (this.events.member) {\n return this.events.member.getDirectionalContent().avatar_url;\n } else if (this.user) {\n return this.user.avatarUrl;\n }\n }\n}\n\nconst MXID_PATTERN = /@.+:.+/;\nconst LTR_RTL_PATTERN = /[\\u200E\\u200F\\u202A-\\u202F]/;\n\nfunction shouldDisambiguate(selfUserId: string, displayName?: string, roomState?: RoomState): boolean {\n if (!displayName || displayName === selfUserId) return false;\n\n // First check if the displayname is something we consider truthy\n // after stripping it of zero width characters and padding spaces\n if (!utils.removeHiddenChars(displayName)) return false;\n\n if (!roomState) return false;\n\n // Next check if the name contains something that look like a mxid\n // If it does, it may be someone trying to impersonate someone else\n // Show full mxid in this case\n if (MXID_PATTERN.test(displayName)) return true;\n\n // Also show mxid if the display name contains any LTR/RTL characters as these\n // make it very difficult for us to find similar *looking* display names\n // E.g \"Mark\" could be cloned by writing \"kraM\" but in RTL.\n if (LTR_RTL_PATTERN.test(displayName)) return true;\n\n // Also show mxid if there are other people with the same or similar\n // displayname, after hidden character removal.\n const userIds = roomState.getUserIdsWithDisplayName(displayName);\n if (userIds.some((u) => u !== selfUserId)) return true;\n\n return false;\n}\n\nfunction calculateDisplayName(selfUserId: string, displayName: string | undefined, disambiguate: boolean): string {\n if (!displayName || displayName === selfUserId) return selfUserId;\n\n if (disambiguate) return utils.removeDirectionOverrideChars(displayName) + \" (\" + selfUserId + \")\";\n\n // First check if the displayname is something we consider truthy\n // after stripping it of zero width characters and padding spaces\n if (!utils.removeHiddenChars(displayName)) return selfUserId;\n\n // We always strip the direction override characters (LRO and RLO).\n // These override the text direction for all subsequent characters\n // in the paragraph so if display names contained these, they'd\n // need to be wrapped in something to prevent this from leaking out\n // (which we can do in HTML but not text) or we'd need to add\n // control characters to the string to reset any overrides (eg.\n // adding PDF characters at the end). As far as we can see,\n // there should be no reason these would be necessary - rtl display\n // names should flip into the correct direction automatically based on\n // the characters, and you can still embed rtl in ltr or vice versa\n // with the embed chars or marker chars.\n return utils.removeDirectionOverrideChars(displayName);\n}\n", - "/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { RoomMember } from \"./room-member\";\nimport { logger } from \"../logger\";\nimport * as utils from \"../utils\";\nimport { EventType, UNSTABLE_MSC2716_MARKER } from \"../@types/event\";\nimport { IEvent, MatrixEvent, MatrixEventEvent } from \"./event\";\nimport { MatrixClient } from \"../client\";\nimport { GuestAccess, HistoryVisibility, IJoinRuleEventContent, JoinRule } from \"../@types/partials\";\nimport { TypedEventEmitter } from \"./typed-event-emitter\";\nimport { Beacon, BeaconEvent, BeaconEventHandlerMap, getBeaconInfoIdentifier, BeaconIdentifier } from \"./beacon\";\nimport { TypedReEmitter } from \"../ReEmitter\";\nimport { M_BEACON, M_BEACON_INFO } from \"../@types/beacon\";\n\nexport interface IMarkerFoundOptions {\n /** Whether the timeline was empty before the marker event arrived in the\n * room. This could be happen in a variety of cases:\n * 1. From the initial sync\n * 2. It's the first state we're seeing after joining the room\n * 3. Or whether it's coming from `syncFromCache`\n *\n * A marker event refers to `UNSTABLE_MSC2716_MARKER` and indicates that\n * history was imported somewhere back in time. It specifically points to an\n * MSC2716 insertion event where the history was imported at. Marker events\n * are sent as state events so they are easily discoverable by clients and\n * homeservers and don't get lost in timeline gaps.\n */\n timelineWasEmpty?: boolean;\n}\n\n// possible statuses for out-of-band member loading\nenum OobStatus {\n NotStarted,\n InProgress,\n Finished,\n}\n\nexport interface IPowerLevelsContent {\n users?: Record;\n events?: Record;\n // eslint-disable-next-line camelcase\n users_default?: number;\n // eslint-disable-next-line camelcase\n events_default?: number;\n // eslint-disable-next-line camelcase\n state_default?: number;\n ban?: number;\n kick?: number;\n redact?: number;\n}\n\nexport enum RoomStateEvent {\n Events = \"RoomState.events\",\n Members = \"RoomState.members\",\n NewMember = \"RoomState.newMember\",\n Update = \"RoomState.update\", // signals batches of updates without specificity\n BeaconLiveness = \"RoomState.BeaconLiveness\",\n Marker = \"RoomState.Marker\",\n}\n\nexport type RoomStateEventHandlerMap = {\n /**\n * Fires whenever the event dictionary in room state is updated.\n * @param event - The matrix event which caused this event to fire.\n * @param state - The room state whose RoomState.events dictionary\n * was updated.\n * @param prevEvent - The event being replaced by the new state, if\n * known. Note that this can differ from `getPrevContent()` on the new state event\n * as this is the store's view of the last state, not the previous state provided\n * by the server.\n * @example\n * ```\n * matrixClient.on(\"RoomState.events\", function(event, state, prevEvent){\n * var newStateEvent = event;\n * });\n * ```\n */\n [RoomStateEvent.Events]: (event: MatrixEvent, state: RoomState, lastStateEvent: MatrixEvent | null) => void;\n /**\n * Fires whenever a member in the members dictionary is updated in any way.\n * @param event - The matrix event which caused this event to fire.\n * @param state - The room state whose RoomState.members dictionary\n * was updated.\n * @param member - The room member that was updated.\n * @example\n * ```\n * matrixClient.on(\"RoomState.members\", function(event, state, member){\n * var newMembershipState = member.membership;\n * });\n * ```\n */\n [RoomStateEvent.Members]: (event: MatrixEvent, state: RoomState, member: RoomMember) => void;\n /**\n * Fires whenever a member is added to the members dictionary. The RoomMember\n * will not be fully populated yet (e.g. no membership state) but will already\n * be available in the members dictionary.\n * @param event - The matrix event which caused this event to fire.\n * @param state - The room state whose RoomState.members dictionary\n * was updated with a new entry.\n * @param member - The room member that was added.\n * @example\n * ```\n * matrixClient.on(\"RoomState.newMember\", function(event, state, member){\n * // add event listeners on 'member'\n * });\n * ```\n */\n [RoomStateEvent.NewMember]: (event: MatrixEvent, state: RoomState, member: RoomMember) => void;\n [RoomStateEvent.Update]: (state: RoomState) => void;\n [RoomStateEvent.BeaconLiveness]: (state: RoomState, hasLiveBeacons: boolean) => void;\n [RoomStateEvent.Marker]: (event: MatrixEvent, setStateOptions?: IMarkerFoundOptions) => void;\n [BeaconEvent.New]: (event: MatrixEvent, beacon: Beacon) => void;\n};\n\ntype EmittedEvents = RoomStateEvent | BeaconEvent;\ntype EventHandlerMap = RoomStateEventHandlerMap & BeaconEventHandlerMap;\n\nexport class RoomState extends TypedEventEmitter {\n public readonly reEmitter = new TypedReEmitter(this);\n private sentinels: Record = {}; // userId: RoomMember\n // stores fuzzy matches to a list of userIDs (applies utils.removeHiddenChars to keys)\n private displayNameToUserIds = new Map();\n private userIdsToDisplayNames: Record = {};\n private tokenToInvite: Record = {}; // 3pid invite state_key to m.room.member invite\n private joinedMemberCount: number | null = null; // cache of the number of joined members\n // joined members count from summary api\n // once set, we know the server supports the summary api\n // and we should only trust that\n // we could also only trust that before OOB members\n // are loaded but doesn't seem worth the hassle atm\n private summaryJoinedMemberCount: number | null = null;\n // same for invited member count\n private invitedMemberCount: number | null = null;\n private summaryInvitedMemberCount: number | null = null;\n private modified = -1;\n\n // XXX: Should be read-only\n // The room member dictionary, keyed on the user's ID.\n public members: Record = {}; // userId: RoomMember\n // The state events dictionary, keyed on the event type and then the state_key value.\n public events = new Map>(); // Map>\n // The pagination token for this state.\n public paginationToken: string | null = null;\n\n public readonly beacons = new Map();\n private _liveBeaconIds: BeaconIdentifier[] = [];\n\n /**\n * Construct room state.\n *\n * Room State represents the state of the room at a given point.\n * It can be mutated by adding state events to it.\n * There are two types of room member associated with a state event:\n * normal member objects (accessed via getMember/getMembers) which mutate\n * with the state to represent the current state of that room/user, e.g.\n * the object returned by `getMember('@bob:example.com')` will mutate to\n * get a different display name if Bob later changes his display name\n * in the room.\n * There are also 'sentinel' members (accessed via getSentinelMember).\n * These also represent the state of room members at the point in time\n * represented by the RoomState object, but unlike objects from getMember,\n * sentinel objects will always represent the room state as at the time\n * getSentinelMember was called, so if Bob subsequently changes his display\n * name, a room member object previously acquired with getSentinelMember\n * will still have his old display name. Calling getSentinelMember again\n * after the display name change will return a new RoomMember object\n * with Bob's new display name.\n *\n * @param roomId - Optional. The ID of the room which has this state.\n * If none is specified it just tracks paginationTokens, useful for notifTimelineSet\n * @param oobMemberFlags - Optional. The state of loading out of bound members.\n * As the timeline might get reset while they are loading, this state needs to be inherited\n * and shared when the room state is cloned for the new timeline.\n * This should only be passed from clone.\n */\n public constructor(public readonly roomId: string, private oobMemberFlags = { status: OobStatus.NotStarted }) {\n super();\n this.updateModifiedTime();\n }\n\n /**\n * Returns the number of joined members in this room\n * This method caches the result.\n * @returns The number of members in this room whose membership is 'join'\n */\n public getJoinedMemberCount(): number {\n if (this.summaryJoinedMemberCount !== null) {\n return this.summaryJoinedMemberCount;\n }\n if (this.joinedMemberCount === null) {\n this.joinedMemberCount = this.getMembers().reduce((count, m) => {\n return m.membership === \"join\" ? count + 1 : count;\n }, 0);\n }\n return this.joinedMemberCount;\n }\n\n /**\n * Set the joined member count explicitly (like from summary part of the sync response)\n * @param count - the amount of joined members\n */\n public setJoinedMemberCount(count: number): void {\n this.summaryJoinedMemberCount = count;\n }\n\n /**\n * Returns the number of invited members in this room\n * @returns The number of members in this room whose membership is 'invite'\n */\n public getInvitedMemberCount(): number {\n if (this.summaryInvitedMemberCount !== null) {\n return this.summaryInvitedMemberCount;\n }\n if (this.invitedMemberCount === null) {\n this.invitedMemberCount = this.getMembers().reduce((count, m) => {\n return m.membership === \"invite\" ? count + 1 : count;\n }, 0);\n }\n return this.invitedMemberCount;\n }\n\n /**\n * Set the amount of invited members in this room\n * @param count - the amount of invited members\n */\n public setInvitedMemberCount(count: number): void {\n this.summaryInvitedMemberCount = count;\n }\n\n /**\n * Get all RoomMembers in this room.\n * @returns A list of RoomMembers.\n */\n public getMembers(): RoomMember[] {\n return Object.values(this.members);\n }\n\n /**\n * Get all RoomMembers in this room, excluding the user IDs provided.\n * @param excludedIds - The user IDs to exclude.\n * @returns A list of RoomMembers.\n */\n public getMembersExcept(excludedIds: string[]): RoomMember[] {\n return this.getMembers().filter((m) => !excludedIds.includes(m.userId));\n }\n\n /**\n * Get a room member by their user ID.\n * @param userId - The room member's user ID.\n * @returns The member or null if they do not exist.\n */\n public getMember(userId: string): RoomMember | null {\n return this.members[userId] || null;\n }\n\n /**\n * Get a room member whose properties will not change with this room state. You\n * typically want this if you want to attach a RoomMember to a MatrixEvent which\n * may no longer be represented correctly by Room.currentState or Room.oldState.\n * The term 'sentinel' refers to the fact that this RoomMember is an unchanging\n * guardian for state at this particular point in time.\n * @param userId - The room member's user ID.\n * @returns The member or null if they do not exist.\n */\n public getSentinelMember(userId: string): RoomMember | null {\n if (!userId) return null;\n let sentinel = this.sentinels[userId];\n\n if (sentinel === undefined) {\n sentinel = new RoomMember(this.roomId, userId);\n const member = this.members[userId];\n if (member?.events.member) {\n sentinel.setMembershipEvent(member.events.member, this);\n }\n this.sentinels[userId] = sentinel;\n }\n return sentinel;\n }\n\n /**\n * Get state events from the state of the room.\n * @param eventType - The event type of the state event.\n * @param stateKey - Optional. The state_key of the state event. If\n * this is `undefined` then all matching state events will be\n * returned.\n * @returns A list of events if state_key was\n * `undefined`, else a single event (or null if no match found).\n */\n public getStateEvents(eventType: EventType | string): MatrixEvent[];\n public getStateEvents(eventType: EventType | string, stateKey: string): MatrixEvent | null;\n public getStateEvents(eventType: EventType | string, stateKey?: string): MatrixEvent[] | MatrixEvent | null {\n if (!this.events.has(eventType)) {\n // no match\n return stateKey === undefined ? [] : null;\n }\n if (stateKey === undefined) {\n // return all values\n return Array.from(this.events.get(eventType)!.values());\n }\n const event = this.events.get(eventType)!.get(stateKey);\n return event ? event : null;\n }\n\n public get hasLiveBeacons(): boolean {\n return !!this.liveBeaconIds?.length;\n }\n\n public get liveBeaconIds(): BeaconIdentifier[] {\n return this._liveBeaconIds;\n }\n\n /**\n * Creates a copy of this room state so that mutations to either won't affect the other.\n * @returns the copy of the room state\n */\n public clone(): RoomState {\n const copy = new RoomState(this.roomId, this.oobMemberFlags);\n\n // Ugly hack: because setStateEvents will mark\n // members as susperseding future out of bound members\n // if loading is in progress (through oobMemberFlags)\n // since these are not new members, we're merely copying them\n // set the status to not started\n // after copying, we set back the status\n const status = this.oobMemberFlags.status;\n this.oobMemberFlags.status = OobStatus.NotStarted;\n\n Array.from(this.events.values()).forEach((eventsByStateKey) => {\n copy.setStateEvents(Array.from(eventsByStateKey.values()));\n });\n\n // Ugly hack: see above\n this.oobMemberFlags.status = status;\n\n if (this.summaryInvitedMemberCount !== null) {\n copy.setInvitedMemberCount(this.getInvitedMemberCount());\n }\n if (this.summaryJoinedMemberCount !== null) {\n copy.setJoinedMemberCount(this.getJoinedMemberCount());\n }\n\n // copy out of band flags if needed\n if (this.oobMemberFlags.status == OobStatus.Finished) {\n // copy markOutOfBand flags\n this.getMembers().forEach((member) => {\n if (member.isOutOfBand()) {\n copy.getMember(member.userId)?.markOutOfBand();\n }\n });\n }\n\n return copy;\n }\n\n /**\n * Add previously unknown state events.\n * When lazy loading members while back-paginating,\n * the relevant room state for the timeline chunk at the end\n * of the chunk can be set with this method.\n * @param events - state events to prepend\n */\n public setUnknownStateEvents(events: MatrixEvent[]): void {\n const unknownStateEvents = events.filter((event) => {\n return !this.events.has(event.getType()) || !this.events.get(event.getType())!.has(event.getStateKey()!);\n });\n\n this.setStateEvents(unknownStateEvents);\n }\n\n /**\n * Add an array of one or more state MatrixEvents, overwriting any existing\n * state with the same `{type, stateKey}` tuple. Will fire \"RoomState.events\"\n * for every event added. May fire \"RoomState.members\" if there are\n * `m.room.member` events. May fire \"RoomStateEvent.Marker\" if there are\n * `UNSTABLE_MSC2716_MARKER` events.\n * @param stateEvents - a list of state events for this room.\n *\n * @remarks\n * Fires {@link RoomStateEvent.Members}\n * Fires {@link RoomStateEvent.NewMember}\n * Fires {@link RoomStateEvent.Events}\n * Fires {@link RoomStateEvent.Marker}\n */\n public setStateEvents(stateEvents: MatrixEvent[], markerFoundOptions?: IMarkerFoundOptions): void {\n this.updateModifiedTime();\n\n // update the core event dict\n stateEvents.forEach((event) => {\n if (event.getRoomId() !== this.roomId || !event.isState()) return;\n\n if (M_BEACON_INFO.matches(event.getType())) {\n this.setBeacon(event);\n }\n\n const lastStateEvent = this.getStateEventMatching(event);\n this.setStateEvent(event);\n if (event.getType() === EventType.RoomMember) {\n this.updateDisplayNameCache(event.getStateKey()!, event.getContent().displayname ?? \"\");\n this.updateThirdPartyTokenCache(event);\n }\n this.emit(RoomStateEvent.Events, event, this, lastStateEvent);\n });\n\n this.onBeaconLivenessChange();\n // update higher level data structures. This needs to be done AFTER the\n // core event dict as these structures may depend on other state events in\n // the given array (e.g. disambiguating display names in one go to do both\n // clashing names rather than progressively which only catches 1 of them).\n stateEvents.forEach((event) => {\n if (event.getRoomId() !== this.roomId || !event.isState()) return;\n\n if (event.getType() === EventType.RoomMember) {\n const userId = event.getStateKey()!;\n\n // leave events apparently elide the displayname or avatar_url,\n // so let's fake one up so that we don't leak user ids\n // into the timeline\n if (event.getContent().membership === \"leave\" || event.getContent().membership === \"ban\") {\n event.getContent().avatar_url = event.getContent().avatar_url || event.getPrevContent().avatar_url;\n event.getContent().displayname =\n event.getContent().displayname || event.getPrevContent().displayname;\n }\n\n const member = this.getOrCreateMember(userId, event);\n member.setMembershipEvent(event, this);\n this.updateMember(member);\n this.emit(RoomStateEvent.Members, event, this, member);\n } else if (event.getType() === EventType.RoomPowerLevels) {\n // events with unknown state keys should be ignored\n // and should not aggregate onto members power levels\n if (event.getStateKey() !== \"\") {\n return;\n }\n const members = Object.values(this.members);\n members.forEach((member) => {\n // We only propagate `RoomState.members` event if the\n // power levels has been changed\n // large room suffer from large re-rendering especially when not needed\n const oldLastModified = member.getLastModifiedTime();\n member.setPowerLevelEvent(event);\n if (oldLastModified !== member.getLastModifiedTime()) {\n this.emit(RoomStateEvent.Members, event, this, member);\n }\n });\n\n // assume all our sentinels are now out-of-date\n this.sentinels = {};\n } else if (UNSTABLE_MSC2716_MARKER.matches(event.getType())) {\n this.emit(RoomStateEvent.Marker, event, markerFoundOptions);\n }\n });\n\n this.emit(RoomStateEvent.Update, this);\n }\n\n public async processBeaconEvents(events: MatrixEvent[], matrixClient: MatrixClient): Promise {\n if (\n !events.length ||\n // discard locations if we have no beacons\n !this.beacons.size\n ) {\n return;\n }\n\n const beaconByEventIdDict = [...this.beacons.values()].reduce>((dict, beacon) => {\n dict[beacon.beaconInfoId] = beacon;\n return dict;\n }, {});\n\n const processBeaconRelation = (beaconInfoEventId: string, event: MatrixEvent): void => {\n if (!M_BEACON.matches(event.getType())) {\n return;\n }\n\n const beacon = beaconByEventIdDict[beaconInfoEventId];\n\n if (beacon) {\n beacon.addLocations([event]);\n }\n };\n\n for (const event of events) {\n const relatedToEventId = event.getRelation()?.event_id;\n // not related to a beacon we know about; discard\n if (!relatedToEventId || !beaconByEventIdDict[relatedToEventId]) return;\n if (!M_BEACON.matches(event.getType()) && !event.isEncrypted()) return;\n\n try {\n await matrixClient.decryptEventIfNeeded(event);\n processBeaconRelation(relatedToEventId, event);\n } catch {\n if (event.isDecryptionFailure()) {\n // add an event listener for once the event is decrypted.\n event.once(MatrixEventEvent.Decrypted, async () => {\n processBeaconRelation(relatedToEventId, event);\n });\n }\n }\n }\n }\n\n /**\n * Looks up a member by the given userId, and if it doesn't exist,\n * create it and emit the `RoomState.newMember` event.\n * This method makes sure the member is added to the members dictionary\n * before emitting, as this is done from setStateEvents and setOutOfBandMember.\n * @param userId - the id of the user to look up\n * @param event - the membership event for the (new) member. Used to emit.\n * @returns the member, existing or newly created.\n *\n * @remarks\n * Fires {@link RoomStateEvent.NewMember}\n */\n private getOrCreateMember(userId: string, event: MatrixEvent): RoomMember {\n let member = this.members[userId];\n if (!member) {\n member = new RoomMember(this.roomId, userId);\n // add member to members before emitting any events,\n // as event handlers often lookup the member\n this.members[userId] = member;\n this.emit(RoomStateEvent.NewMember, event, this, member);\n }\n return member;\n }\n\n private setStateEvent(event: MatrixEvent): void {\n if (!this.events.has(event.getType())) {\n this.events.set(event.getType(), new Map());\n }\n this.events.get(event.getType())!.set(event.getStateKey()!, event);\n }\n\n /**\n * @experimental\n */\n private setBeacon(event: MatrixEvent): void {\n const beaconIdentifier = getBeaconInfoIdentifier(event);\n\n if (this.beacons.has(beaconIdentifier)) {\n const beacon = this.beacons.get(beaconIdentifier)!;\n\n if (event.isRedacted()) {\n if (beacon.beaconInfoId === (event.getRedactionEvent())?.redacts) {\n beacon.destroy();\n this.beacons.delete(beaconIdentifier);\n }\n return;\n }\n\n return beacon.update(event);\n }\n\n if (event.isRedacted()) {\n return;\n }\n\n const beacon = new Beacon(event);\n\n this.reEmitter.reEmit(beacon, [\n BeaconEvent.New,\n BeaconEvent.Update,\n BeaconEvent.Destroy,\n BeaconEvent.LivenessChange,\n ]);\n\n this.emit(BeaconEvent.New, event, beacon);\n beacon.on(BeaconEvent.LivenessChange, this.onBeaconLivenessChange.bind(this));\n beacon.on(BeaconEvent.Destroy, this.onBeaconLivenessChange.bind(this));\n\n this.beacons.set(beacon.identifier, beacon);\n }\n\n /**\n * @experimental\n * Check liveness of room beacons\n * emit RoomStateEvent.BeaconLiveness event\n */\n private onBeaconLivenessChange(): void {\n this._liveBeaconIds = Array.from(this.beacons.values())\n .filter((beacon) => beacon.isLive)\n .map((beacon) => beacon.identifier);\n\n this.emit(RoomStateEvent.BeaconLiveness, this, this.hasLiveBeacons);\n }\n\n private getStateEventMatching(event: MatrixEvent): MatrixEvent | null {\n return this.events.get(event.getType())?.get(event.getStateKey()!) ?? null;\n }\n\n private updateMember(member: RoomMember): void {\n // this member may have a power level already, so set it.\n const pwrLvlEvent = this.getStateEvents(EventType.RoomPowerLevels, \"\");\n if (pwrLvlEvent) {\n member.setPowerLevelEvent(pwrLvlEvent);\n }\n\n // blow away the sentinel which is now outdated\n delete this.sentinels[member.userId];\n\n this.members[member.userId] = member;\n this.joinedMemberCount = null;\n this.invitedMemberCount = null;\n }\n\n /**\n * Get the out-of-band members loading state, whether loading is needed or not.\n * Note that loading might be in progress and hence isn't needed.\n * @returns whether or not the members of this room need to be loaded\n */\n public needsOutOfBandMembers(): boolean {\n return this.oobMemberFlags.status === OobStatus.NotStarted;\n }\n\n /**\n * Check if loading of out-of-band-members has completed\n *\n * @returns true if the full membership list of this room has been loaded. False if it is not started or is in\n * progress.\n */\n public outOfBandMembersReady(): boolean {\n return this.oobMemberFlags.status === OobStatus.Finished;\n }\n\n /**\n * Mark this room state as waiting for out-of-band members,\n * ensuring it doesn't ask for them to be requested again\n * through needsOutOfBandMembers\n */\n public markOutOfBandMembersStarted(): void {\n if (this.oobMemberFlags.status !== OobStatus.NotStarted) {\n return;\n }\n this.oobMemberFlags.status = OobStatus.InProgress;\n }\n\n /**\n * Mark this room state as having failed to fetch out-of-band members\n */\n public markOutOfBandMembersFailed(): void {\n if (this.oobMemberFlags.status !== OobStatus.InProgress) {\n return;\n }\n this.oobMemberFlags.status = OobStatus.NotStarted;\n }\n\n /**\n * Clears the loaded out-of-band members\n */\n public clearOutOfBandMembers(): void {\n let count = 0;\n Object.keys(this.members).forEach((userId) => {\n const member = this.members[userId];\n if (member.isOutOfBand()) {\n ++count;\n delete this.members[userId];\n }\n });\n logger.log(`LL: RoomState removed ${count} members...`);\n this.oobMemberFlags.status = OobStatus.NotStarted;\n }\n\n /**\n * Sets the loaded out-of-band members.\n * @param stateEvents - array of membership state events\n */\n public setOutOfBandMembers(stateEvents: MatrixEvent[]): void {\n logger.log(`LL: RoomState about to set ${stateEvents.length} OOB members ...`);\n if (this.oobMemberFlags.status !== OobStatus.InProgress) {\n return;\n }\n logger.log(`LL: RoomState put in finished state ...`);\n this.oobMemberFlags.status = OobStatus.Finished;\n stateEvents.forEach((e) => this.setOutOfBandMember(e));\n this.emit(RoomStateEvent.Update, this);\n }\n\n /**\n * Sets a single out of band member, used by both setOutOfBandMembers and clone\n * @param stateEvent - membership state event\n */\n private setOutOfBandMember(stateEvent: MatrixEvent): void {\n if (stateEvent.getType() !== EventType.RoomMember) {\n return;\n }\n const userId = stateEvent.getStateKey()!;\n const existingMember = this.getMember(userId);\n // never replace members received as part of the sync\n if (existingMember && !existingMember.isOutOfBand()) {\n return;\n }\n\n const member = this.getOrCreateMember(userId, stateEvent);\n member.setMembershipEvent(stateEvent, this);\n // needed to know which members need to be stored seperately\n // as they are not part of the sync accumulator\n // this is cleared by setMembershipEvent so when it's updated through /sync\n member.markOutOfBand();\n\n this.updateDisplayNameCache(member.userId, member.name);\n\n this.setStateEvent(stateEvent);\n this.updateMember(member);\n this.emit(RoomStateEvent.Members, stateEvent, this, member);\n }\n\n /**\n * Set the current typing event for this room.\n * @param event - The typing event\n */\n public setTypingEvent(event: MatrixEvent): void {\n Object.values(this.members).forEach(function (member) {\n member.setTypingEvent(event);\n });\n }\n\n /**\n * Get the m.room.member event which has the given third party invite token.\n *\n * @param token - The token\n * @returns The m.room.member event or null\n */\n public getInviteForThreePidToken(token: string): MatrixEvent | null {\n return this.tokenToInvite[token] || null;\n }\n\n /**\n * Update the last modified time to the current time.\n */\n private updateModifiedTime(): void {\n this.modified = Date.now();\n }\n\n /**\n * Get the timestamp when this room state was last updated. This timestamp is\n * updated when this object has received new state events.\n * @returns The timestamp\n */\n public getLastModifiedTime(): number {\n return this.modified;\n }\n\n /**\n * Get user IDs with the specified or similar display names.\n * @param displayName - The display name to get user IDs from.\n * @returns An array of user IDs or an empty array.\n */\n public getUserIdsWithDisplayName(displayName: string): string[] {\n return this.displayNameToUserIds.get(utils.removeHiddenChars(displayName)) ?? [];\n }\n\n /**\n * Returns true if userId is in room, event is not redacted and either sender of\n * mxEvent or has power level sufficient to redact events other than their own.\n * @param mxEvent - The event to test permission for\n * @param userId - The user ID of the user to test permission for\n * @returns true if the given used ID can redact given event\n */\n public maySendRedactionForEvent(mxEvent: MatrixEvent, userId: string): boolean {\n const member = this.getMember(userId);\n if (!member || member.membership === \"leave\") return false;\n\n if (mxEvent.status || mxEvent.isRedacted()) return false;\n\n // The user may have been the sender, but they can't redact their own message\n // if redactions are blocked.\n const canRedact = this.maySendEvent(EventType.RoomRedaction, userId);\n if (mxEvent.getSender() === userId) return canRedact;\n\n return this.hasSufficientPowerLevelFor(\"redact\", member.powerLevel);\n }\n\n /**\n * Returns true if the given power level is sufficient for action\n * @param action - The type of power level to check\n * @param powerLevel - The power level of the member\n * @returns true if the given power level is sufficient\n */\n public hasSufficientPowerLevelFor(action: \"ban\" | \"kick\" | \"redact\", powerLevel: number): boolean {\n const powerLevelsEvent = this.getStateEvents(EventType.RoomPowerLevels, \"\");\n\n let powerLevels: IPowerLevelsContent = {};\n if (powerLevelsEvent) {\n powerLevels = powerLevelsEvent.getContent();\n }\n\n let requiredLevel = 50;\n if (utils.isNumber(powerLevels[action])) {\n requiredLevel = powerLevels[action]!;\n }\n\n return powerLevel >= requiredLevel;\n }\n\n /**\n * Short-form for maySendEvent('m.room.message', userId)\n * @param userId - The user ID of the user to test permission for\n * @returns true if the given user ID should be permitted to send\n * message events into the given room.\n */\n public maySendMessage(userId: string): boolean {\n return this.maySendEventOfType(EventType.RoomMessage, userId, false);\n }\n\n /**\n * Returns true if the given user ID has permission to send a normal\n * event of type `eventType` into this room.\n * @param eventType - The type of event to test\n * @param userId - The user ID of the user to test permission for\n * @returns true if the given user ID should be permitted to send\n * the given type of event into this room,\n * according to the room's state.\n */\n public maySendEvent(eventType: EventType | string, userId: string): boolean {\n return this.maySendEventOfType(eventType, userId, false);\n }\n\n /**\n * Returns true if the given MatrixClient has permission to send a state\n * event of type `stateEventType` into this room.\n * @param stateEventType - The type of state events to test\n * @param cli - The client to test permission for\n * @returns true if the given client should be permitted to send\n * the given type of state event into this room,\n * according to the room's state.\n */\n public mayClientSendStateEvent(stateEventType: EventType | string, cli: MatrixClient): boolean {\n if (cli.isGuest() || !cli.credentials.userId) {\n return false;\n }\n return this.maySendStateEvent(stateEventType, cli.credentials.userId);\n }\n\n /**\n * Returns true if the given user ID has permission to send a state\n * event of type `stateEventType` into this room.\n * @param stateEventType - The type of state events to test\n * @param userId - The user ID of the user to test permission for\n * @returns true if the given user ID should be permitted to send\n * the given type of state event into this room,\n * according to the room's state.\n */\n public maySendStateEvent(stateEventType: EventType | string, userId: string): boolean {\n return this.maySendEventOfType(stateEventType, userId, true);\n }\n\n /**\n * Returns true if the given user ID has permission to send a normal or state\n * event of type `eventType` into this room.\n * @param eventType - The type of event to test\n * @param userId - The user ID of the user to test permission for\n * @param state - If true, tests if the user may send a state\n event of this type. Otherwise tests whether\n they may send a regular event.\n * @returns true if the given user ID should be permitted to send\n * the given type of event into this room,\n * according to the room's state.\n */\n private maySendEventOfType(eventType: EventType | string, userId: string, state: boolean): boolean {\n const powerLevelsEvent = this.getStateEvents(EventType.RoomPowerLevels, \"\");\n\n let powerLevels: IPowerLevelsContent;\n let eventsLevels: Record = {};\n\n let stateDefault = 0;\n let eventsDefault = 0;\n let powerLevel = 0;\n if (powerLevelsEvent) {\n powerLevels = powerLevelsEvent.getContent();\n eventsLevels = powerLevels.events || {};\n\n if (Number.isSafeInteger(powerLevels.state_default)) {\n stateDefault = powerLevels.state_default!;\n } else {\n stateDefault = 50;\n }\n\n const userPowerLevel = powerLevels.users && powerLevels.users[userId];\n if (Number.isSafeInteger(userPowerLevel)) {\n powerLevel = userPowerLevel!;\n } else if (Number.isSafeInteger(powerLevels.users_default)) {\n powerLevel = powerLevels.users_default!;\n }\n\n if (Number.isSafeInteger(powerLevels.events_default)) {\n eventsDefault = powerLevels.events_default!;\n }\n }\n\n let requiredLevel = state ? stateDefault : eventsDefault;\n if (Number.isSafeInteger(eventsLevels[eventType])) {\n requiredLevel = eventsLevels[eventType];\n }\n return powerLevel >= requiredLevel;\n }\n\n /**\n * Returns true if the given user ID has permission to trigger notification\n * of type `notifLevelKey`\n * @param notifLevelKey - The level of notification to test (eg. 'room')\n * @param userId - The user ID of the user to test permission for\n * @returns true if the given user ID has permission to trigger a\n * notification of this type.\n */\n public mayTriggerNotifOfType(notifLevelKey: string, userId: string): boolean {\n const member = this.getMember(userId);\n if (!member) {\n return false;\n }\n\n const powerLevelsEvent = this.getStateEvents(EventType.RoomPowerLevels, \"\");\n\n let notifLevel = 50;\n if (\n powerLevelsEvent &&\n powerLevelsEvent.getContent() &&\n powerLevelsEvent.getContent().notifications &&\n utils.isNumber(powerLevelsEvent.getContent().notifications[notifLevelKey])\n ) {\n notifLevel = powerLevelsEvent.getContent().notifications[notifLevelKey];\n }\n\n return member.powerLevel >= notifLevel;\n }\n\n /**\n * Returns the join rule based on the m.room.join_rule state event, defaulting to `invite`.\n * @returns the join_rule applied to this room\n */\n public getJoinRule(): JoinRule {\n const joinRuleEvent = this.getStateEvents(EventType.RoomJoinRules, \"\");\n const joinRuleContent: Partial = joinRuleEvent?.getContent() ?? {};\n return joinRuleContent[\"join_rule\"] || JoinRule.Invite;\n }\n\n /**\n * Returns the history visibility based on the m.room.history_visibility state event, defaulting to `shared`.\n * @returns the history_visibility applied to this room\n */\n public getHistoryVisibility(): HistoryVisibility {\n const historyVisibilityEvent = this.getStateEvents(EventType.RoomHistoryVisibility, \"\");\n const historyVisibilityContent = historyVisibilityEvent?.getContent() ?? {};\n return historyVisibilityContent[\"history_visibility\"] || HistoryVisibility.Shared;\n }\n\n /**\n * Returns the guest access based on the m.room.guest_access state event, defaulting to `shared`.\n * @returns the guest_access applied to this room\n */\n public getGuestAccess(): GuestAccess {\n const guestAccessEvent = this.getStateEvents(EventType.RoomGuestAccess, \"\");\n const guestAccessContent = guestAccessEvent?.getContent() ?? {};\n return guestAccessContent[\"guest_access\"] || GuestAccess.Forbidden;\n }\n\n /**\n * Find the predecessor room based on this room state.\n *\n * @param msc3946ProcessDynamicPredecessor - if true, look for an\n * m.room.predecessor state event and use it if found (MSC3946).\n * @returns null if this room has no predecessor. Otherwise, returns\n * the roomId, last eventId and viaServers of the predecessor room.\n *\n * If msc3946ProcessDynamicPredecessor is true, use m.predecessor events\n * as well as m.room.create events to find predecessors.\n *\n * Note: if an m.predecessor event is used, eventId may be undefined\n * since last_known_event_id is optional.\n *\n * Note: viaServers may be undefined, and will definitely be undefined if\n * this predecessor comes from a RoomCreate event (rather than a\n * RoomPredecessor, which has the optional via_servers property).\n */\n public findPredecessor(\n msc3946ProcessDynamicPredecessor = false,\n ): { roomId: string; eventId?: string; viaServers?: string[] } | null {\n // Note: the tests for this function are against Room.findPredecessor,\n // which just calls through to here.\n\n if (msc3946ProcessDynamicPredecessor) {\n const predecessorEvent = this.getStateEvents(EventType.RoomPredecessor, \"\");\n if (predecessorEvent) {\n const content = predecessorEvent.getContent<{\n predecessor_room_id: string;\n last_known_event_id?: string;\n via_servers?: string[];\n }>();\n const roomId = content.predecessor_room_id;\n let eventId = content.last_known_event_id;\n if (typeof eventId !== \"string\") {\n eventId = undefined;\n }\n let viaServers = content.via_servers;\n if (!Array.isArray(viaServers)) {\n viaServers = undefined;\n }\n if (typeof roomId === \"string\") {\n return { roomId, eventId, viaServers };\n }\n }\n }\n\n const createEvent = this.getStateEvents(EventType.RoomCreate, \"\");\n if (createEvent) {\n const predecessor = createEvent.getContent<{\n predecessor?: Partial<{\n room_id: string;\n event_id: string;\n }>;\n }>()[\"predecessor\"];\n if (predecessor) {\n const roomId = predecessor[\"room_id\"];\n if (typeof roomId === \"string\") {\n let eventId = predecessor[\"event_id\"];\n if (typeof eventId !== \"string\" || eventId === \"\") {\n eventId = undefined;\n }\n return { roomId, eventId };\n }\n }\n }\n return null;\n }\n\n private updateThirdPartyTokenCache(memberEvent: MatrixEvent): void {\n if (!memberEvent.getContent().third_party_invite) {\n return;\n }\n const token = (memberEvent.getContent().third_party_invite.signed || {}).token;\n if (!token) {\n return;\n }\n const threePidInvite = this.getStateEvents(EventType.RoomThirdPartyInvite, token);\n if (!threePidInvite) {\n return;\n }\n this.tokenToInvite[token] = memberEvent;\n }\n\n private updateDisplayNameCache(userId: string, displayName: string): void {\n const oldName = this.userIdsToDisplayNames[userId];\n delete this.userIdsToDisplayNames[userId];\n if (oldName) {\n // Remove the old name from the cache.\n // We clobber the user_id > name lookup but the name -> [user_id] lookup\n // means we need to remove that user ID from that array rather than nuking\n // the lot.\n const strippedOldName = utils.removeHiddenChars(oldName);\n\n const existingUserIds = this.displayNameToUserIds.get(strippedOldName);\n if (existingUserIds) {\n // remove this user ID from this array\n const filteredUserIDs = existingUserIds.filter((id) => id !== userId);\n this.displayNameToUserIds.set(strippedOldName, filteredUserIDs);\n }\n }\n\n this.userIdsToDisplayNames[userId] = displayName;\n\n const strippedDisplayname = displayName && utils.removeHiddenChars(displayName);\n // an empty stripped displayname (undefined/'') will be set to MXID in room-member.js\n if (strippedDisplayname) {\n const arr = this.displayNameToUserIds.get(strippedDisplayname) ?? [];\n arr.push(userId);\n this.displayNameToUserIds.set(strippedDisplayname, arr);\n }\n }\n}\n", - "/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport interface IRoomSummary {\n \"m.heroes\": string[];\n \"m.joined_member_count\"?: number;\n \"m.invited_member_count\"?: number;\n}\n\ninterface IInfo {\n /** The title of the room (e.g. `m.room.name`) */\n title: string;\n /** The description of the room (e.g. `m.room.topic`) */\n desc?: string;\n /** The number of joined users. */\n numMembers?: number;\n /** The list of aliases for this room. */\n aliases?: string[];\n /** The timestamp for this room. */\n timestamp?: number;\n}\n\n/**\n * Construct a new Room Summary. A summary can be used for display on a recent\n * list, without having to load the entire room list into memory.\n * @param roomId - Required. The ID of this room.\n * @param info - Optional. The summary info. Additional keys are supported.\n */\nexport class RoomSummary {\n public constructor(public readonly roomId: string, info?: IInfo) {}\n}\n", - "/*\nCopyright 2015 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { M_POLL_START, Optional } from \"matrix-events-sdk\";\n\nimport {\n EventTimelineSet,\n DuplicateStrategy,\n IAddLiveEventOptions,\n EventTimelineSetHandlerMap,\n} from \"./event-timeline-set\";\nimport { Direction, EventTimeline } from \"./event-timeline\";\nimport { getHttpUriForMxc } from \"../content-repo\";\nimport * as utils from \"../utils\";\nimport { normalize, noUnsafeEventProps } from \"../utils\";\nimport { IEvent, IThreadBundledRelationship, MatrixEvent, MatrixEventEvent, MatrixEventHandlerMap } from \"./event\";\nimport { EventStatus } from \"./event-status\";\nimport { RoomMember } from \"./room-member\";\nimport { IRoomSummary, RoomSummary } from \"./room-summary\";\nimport { logger } from \"../logger\";\nimport { TypedReEmitter } from \"../ReEmitter\";\nimport {\n EventType,\n RoomCreateTypeField,\n RoomType,\n UNSTABLE_ELEMENT_FUNCTIONAL_USERS,\n EVENT_VISIBILITY_CHANGE_TYPE,\n RelationType,\n} from \"../@types/event\";\nimport { IRoomVersionsCapability, MatrixClient, PendingEventOrdering, RoomVersionStability } from \"../client\";\nimport { GuestAccess, HistoryVisibility, JoinRule, ResizeMethod } from \"../@types/partials\";\nimport { Filter, IFilterDefinition } from \"../filter\";\nimport { RoomState, RoomStateEvent, RoomStateEventHandlerMap } from \"./room-state\";\nimport { BeaconEvent, BeaconEventHandlerMap } from \"./beacon\";\nimport {\n Thread,\n ThreadEvent,\n EventHandlerMap as ThreadHandlerMap,\n FILTER_RELATED_BY_REL_TYPES,\n THREAD_RELATION_TYPE,\n FILTER_RELATED_BY_SENDERS,\n ThreadFilterType,\n} from \"./thread\";\nimport {\n CachedReceiptStructure,\n MAIN_ROOM_TIMELINE,\n Receipt,\n ReceiptContent,\n ReceiptType,\n} from \"../@types/read_receipts\";\nimport { IStateEventWithRoomId } from \"../@types/search\";\nimport { RelationsContainer } from \"./relations-container\";\nimport { ReadReceipt, synthesizeReceipt } from \"./read-receipt\";\nimport { Poll, PollEvent } from \"./poll\";\n\n// These constants are used as sane defaults when the homeserver doesn't support\n// the m.room_versions capability. In practice, KNOWN_SAFE_ROOM_VERSION should be\n// the same as the common default room version whereas SAFE_ROOM_VERSIONS are the\n// room versions which are considered okay for people to run without being asked\n// to upgrade (ie: \"stable\"). Eventually, we should remove these when all homeservers\n// return an m.room_versions capability.\nexport const KNOWN_SAFE_ROOM_VERSION = \"9\";\nconst SAFE_ROOM_VERSIONS = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"];\n\ninterface IOpts {\n /**\n * Controls where pending messages appear in a room's timeline.\n * If \"chronological\", messages will appear in the timeline when the call to `sendEvent` was made.\n * If \"detached\", pending messages will appear in a separate list,\n * accessible via {@link Room#getPendingEvents}.\n * Default: \"chronological\".\n */\n pendingEventOrdering?: PendingEventOrdering;\n /**\n * Set to true to enable improved timeline support.\n */\n timelineSupport?: boolean;\n lazyLoadMembers?: boolean;\n}\n\nexport interface IRecommendedVersion {\n version: string;\n needsUpgrade: boolean;\n urgent: boolean;\n}\n\n// When inserting a visibility event affecting event `eventId`, we\n// need to scan through existing visibility events for `eventId`.\n// In theory, this could take an unlimited amount of time if:\n//\n// - the visibility event was sent by a moderator; and\n// - `eventId` already has many visibility changes (usually, it should\n// be 2 or less); and\n// - for some reason, the visibility changes are received out of order\n// (usually, this shouldn't happen at all).\n//\n// For this reason, we limit the number of events to scan through,\n// expecting that a broken visibility change for a single event in\n// an extremely uncommon case (possibly a DoS) is a small\n// price to pay to keep matrix-js-sdk responsive.\nconst MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH = 30;\n\nexport type NotificationCount = Partial>;\n\nexport enum NotificationCountType {\n Highlight = \"highlight\",\n Total = \"total\",\n}\n\nexport interface ICreateFilterOpts {\n // Populate the filtered timeline with already loaded events in the room\n // timeline. Useful to disable for some filters that can't be achieved by the\n // client in an efficient manner\n prepopulateTimeline?: boolean;\n useSyncEvents?: boolean;\n pendingEvents?: boolean;\n}\n\nexport enum RoomEvent {\n MyMembership = \"Room.myMembership\",\n Tags = \"Room.tags\",\n AccountData = \"Room.accountData\",\n Receipt = \"Room.receipt\",\n Name = \"Room.name\",\n Redaction = \"Room.redaction\",\n RedactionCancelled = \"Room.redactionCancelled\",\n LocalEchoUpdated = \"Room.localEchoUpdated\",\n Timeline = \"Room.timeline\",\n TimelineReset = \"Room.timelineReset\",\n TimelineRefresh = \"Room.TimelineRefresh\",\n OldStateUpdated = \"Room.OldStateUpdated\",\n CurrentStateUpdated = \"Room.CurrentStateUpdated\",\n HistoryImportedWithinTimeline = \"Room.historyImportedWithinTimeline\",\n UnreadNotifications = \"Room.UnreadNotifications\",\n}\n\nexport type RoomEmittedEvents =\n | RoomEvent\n | RoomStateEvent.Events\n | RoomStateEvent.Members\n | RoomStateEvent.NewMember\n | RoomStateEvent.Update\n | RoomStateEvent.Marker\n | ThreadEvent.New\n | ThreadEvent.Update\n | ThreadEvent.NewReply\n | ThreadEvent.Delete\n | MatrixEventEvent.BeforeRedaction\n | BeaconEvent.New\n | BeaconEvent.Update\n | BeaconEvent.Destroy\n | BeaconEvent.LivenessChange\n | PollEvent.New;\n\nexport type RoomEventHandlerMap = {\n /**\n * Fires when the logged in user's membership in the room is updated.\n *\n * @param room - The room in which the membership has been updated\n * @param membership - The new membership value\n * @param prevMembership - The previous membership value\n */\n [RoomEvent.MyMembership]: (room: Room, membership: string, prevMembership?: string) => void;\n /**\n * Fires whenever a room's tags are updated.\n * @param event - The tags event\n * @param room - The room whose Room.tags was updated.\n * @example\n * ```\n * matrixClient.on(\"Room.tags\", function(event, room){\n * var newTags = event.getContent().tags;\n * if (newTags[\"favourite\"]) showStar(room);\n * });\n * ```\n */\n [RoomEvent.Tags]: (event: MatrixEvent, room: Room) => void;\n /**\n * Fires whenever a room's account_data is updated.\n * @param event - The account_data event\n * @param room - The room whose account_data was updated.\n * @param prevEvent - The event being replaced by\n * the new account data, if known.\n * @example\n * ```\n * matrixClient.on(\"Room.accountData\", function(event, room, oldEvent){\n * if (event.getType() === \"m.room.colorscheme\") {\n * applyColorScheme(event.getContents());\n * }\n * });\n * ```\n */\n [RoomEvent.AccountData]: (event: MatrixEvent, room: Room, lastEvent?: MatrixEvent) => void;\n /**\n * Fires whenever a receipt is received for a room\n * @param event - The receipt event\n * @param room - The room whose receipts was updated.\n * @example\n * ```\n * matrixClient.on(\"Room.receipt\", function(event, room){\n * var receiptContent = event.getContent();\n * });\n * ```\n */\n [RoomEvent.Receipt]: (event: MatrixEvent, room: Room) => void;\n /**\n * Fires whenever the name of a room is updated.\n * @param room - The room whose Room.name was updated.\n * @example\n * ```\n * matrixClient.on(\"Room.name\", function(room){\n * var newName = room.name;\n * });\n * ```\n */\n [RoomEvent.Name]: (room: Room) => void;\n /**\n * Fires when an event we had previously received is redacted.\n *\n * (Note this is *not* fired when the redaction happens before we receive the\n * event).\n *\n * @param event - The matrix redaction event\n * @param room - The room containing the redacted event\n */\n [RoomEvent.Redaction]: (event: MatrixEvent, room: Room) => void;\n /**\n * Fires when an event that was previously redacted isn't anymore.\n * This happens when the redaction couldn't be sent and\n * was subsequently cancelled by the user. Redactions have a local echo\n * which is undone in this scenario.\n *\n * @param event - The matrix redaction event that was cancelled.\n * @param room - The room containing the unredacted event\n */\n [RoomEvent.RedactionCancelled]: (event: MatrixEvent, room: Room) => void;\n /**\n * Fires when the status of a transmitted event is updated.\n *\n *

When an event is first transmitted, a temporary copy of the event is\n * inserted into the timeline, with a temporary event id, and a status of\n * 'SENDING'.\n *\n *

Once the echo comes back from the server, the content of the event\n * (MatrixEvent.event) is replaced by the complete event from the homeserver,\n * thus updating its event id, as well as server-generated fields such as the\n * timestamp. Its status is set to null.\n *\n *

Once the /send request completes, if the remote echo has not already\n * arrived, the event is updated with a new event id and the status is set to\n * 'SENT'. The server-generated fields are of course not updated yet.\n *\n *

If the /send fails, In this case, the event's status is set to\n * 'NOT_SENT'. If it is later resent, the process starts again, setting the\n * status to 'SENDING'. Alternatively, the message may be cancelled, which\n * removes the event from the room, and sets the status to 'CANCELLED'.\n *\n *

This event is raised to reflect each of the transitions above.\n *\n * @param event - The matrix event which has been updated\n *\n * @param room - The room containing the redacted event\n *\n * @param oldEventId - The previous event id (the temporary event id,\n * except when updating a successfully-sent event when its echo arrives)\n *\n * @param oldStatus - The previous event status.\n */\n [RoomEvent.LocalEchoUpdated]: (\n event: MatrixEvent,\n room: Room,\n oldEventId?: string,\n oldStatus?: EventStatus | null,\n ) => void;\n [RoomEvent.OldStateUpdated]: (room: Room, previousRoomState: RoomState, roomState: RoomState) => void;\n [RoomEvent.CurrentStateUpdated]: (room: Room, previousRoomState: RoomState, roomState: RoomState) => void;\n [RoomEvent.HistoryImportedWithinTimeline]: (markerEvent: MatrixEvent, room: Room) => void;\n [RoomEvent.UnreadNotifications]: (unreadNotifications?: NotificationCount, threadId?: string) => void;\n [RoomEvent.TimelineRefresh]: (room: Room, eventTimelineSet: EventTimelineSet) => void;\n [ThreadEvent.New]: (thread: Thread, toStartOfTimeline: boolean) => void;\n /**\n * Fires when a new poll instance is added to the room state\n * @param poll - the new poll\n */\n [PollEvent.New]: (poll: Poll) => void;\n} & Pick &\n EventTimelineSetHandlerMap &\n Pick &\n Pick<\n RoomStateEventHandlerMap,\n | RoomStateEvent.Events\n | RoomStateEvent.Members\n | RoomStateEvent.NewMember\n | RoomStateEvent.Update\n | RoomStateEvent.Marker\n | BeaconEvent.New\n > &\n Pick;\n\nexport class Room extends ReadReceipt {\n public readonly reEmitter: TypedReEmitter;\n private txnToEvent: Map = new Map(); // Pending in-flight requests { string: MatrixEvent }\n private notificationCounts: NotificationCount = {};\n private readonly threadNotifications = new Map();\n public readonly cachedThreadReadReceipts = new Map();\n // Useful to know at what point the current user has started using threads in this room\n private oldestThreadedReceiptTs = Infinity;\n /**\n * A record of the latest unthread receipts per user\n * This is useful in determining whether a user has read a thread or not\n */\n private unthreadedReceipts = new Map();\n private readonly timelineSets: EventTimelineSet[];\n public readonly polls: Map = new Map();\n public readonly threadsTimelineSets: EventTimelineSet[] = [];\n // any filtered timeline sets we're maintaining for this room\n private readonly filteredTimelineSets: Record = {}; // filter_id: timelineSet\n private timelineNeedsRefresh = false;\n private readonly pendingEventList?: MatrixEvent[];\n // read by megolm via getter; boolean value - null indicates \"use global value\"\n private blacklistUnverifiedDevices?: boolean;\n private selfMembership?: string;\n private summaryHeroes: string[] | null = null;\n // flags to stop logspam about missing m.room.create events\n private getTypeWarning = false;\n private getVersionWarning = false;\n private membersPromise?: Promise;\n\n // XXX: These should be read-only\n /**\n * The human-readable display name for this room.\n */\n public name: string;\n /**\n * The un-homoglyphed name for this room.\n */\n public normalizedName: string;\n /**\n * Dict of room tags; the keys are the tag name and the values\n * are any metadata associated with the tag - e.g. `{ \"fav\" : { order: 1 } }`\n */\n public tags: Record> = {}; // $tagName: { $metadata: $value }\n /**\n * accountData Dict of per-room account_data events; the keys are the\n * event type and the values are the events.\n */\n public accountData: Map = new Map(); // $eventType: $event\n /**\n * The room summary.\n */\n public summary: RoomSummary | null = null;\n // legacy fields\n /**\n * The live event timeline for this room, with the oldest event at index 0.\n * Present for backwards compatibility - prefer getLiveTimeline().getEvents()\n */\n public timeline!: MatrixEvent[];\n /**\n * oldState The state of the room at the time of the oldest\n * event in the live timeline. Present for backwards compatibility -\n * prefer getLiveTimeline().getState(EventTimeline.BACKWARDS).\n */\n public oldState!: RoomState;\n /**\n * currentState The state of the room at the time of the\n * newest event in the timeline. Present for backwards compatibility -\n * prefer getLiveTimeline().getState(EventTimeline.FORWARDS).\n */\n public currentState!: RoomState;\n public readonly relations = new RelationsContainer(this.client, this);\n\n /**\n * A collection of events known by the client\n * This is not a comprehensive list of the threads that exist in this room\n */\n private threads = new Map();\n public lastThread?: Thread;\n\n /**\n * A mapping of eventId to all visibility changes to apply\n * to the event, by chronological order, as per\n * https://github.com/matrix-org/matrix-doc/pull/3531\n *\n * # Invariants\n *\n * - within each list, all events are classed by\n * chronological order;\n * - all events are events such that\n * `asVisibilityEvent()` returns a non-null `IVisibilityChange`;\n * - within each list with key `eventId`, all events\n * are in relation to `eventId`.\n *\n * @experimental\n */\n private visibilityEvents = new Map();\n\n /**\n * Construct a new Room.\n *\n *

For a room, we store an ordered sequence of timelines, which may or may not\n * be continuous. Each timeline lists a series of events, as well as tracking\n * the room state at the start and the end of the timeline. It also tracks\n * forward and backward pagination tokens, as well as containing links to the\n * next timeline in the sequence.\n *\n *

There is one special timeline - the 'live' timeline, which represents the\n * timeline to which events are being added in real-time as they are received\n * from the /sync API. Note that you should not retain references to this\n * timeline - even if it is the current timeline right now, it may not remain\n * so if the server gives us a timeline gap in /sync.\n *\n *

In order that we can find events from their ids later, we also maintain a\n * map from event_id to timeline and index.\n *\n * @param roomId - Required. The ID of this room.\n * @param client - Required. The client, used to lazy load members.\n * @param myUserId - Required. The ID of the syncing user.\n * @param opts - Configuration options\n */\n public constructor(\n public readonly roomId: string,\n public readonly client: MatrixClient,\n public readonly myUserId: string,\n private readonly opts: IOpts = {},\n ) {\n super();\n // In some cases, we add listeners for every displayed Matrix event, so it's\n // common to have quite a few more than the default limit.\n this.setMaxListeners(100);\n this.reEmitter = new TypedReEmitter(this);\n\n opts.pendingEventOrdering = opts.pendingEventOrdering || PendingEventOrdering.Chronological;\n\n this.name = roomId;\n this.normalizedName = roomId;\n\n // all our per-room timeline sets. the first one is the unfiltered ones;\n // the subsequent ones are the filtered ones in no particular order.\n this.timelineSets = [new EventTimelineSet(this, opts)];\n this.reEmitter.reEmit(this.getUnfilteredTimelineSet(), [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n\n this.fixUpLegacyTimelineFields();\n\n if (this.opts.pendingEventOrdering === PendingEventOrdering.Detached) {\n this.pendingEventList = [];\n this.client.store.getPendingEvents(this.roomId).then((events) => {\n const mapper = this.client.getEventMapper({\n toDevice: false,\n decrypt: false,\n });\n events.forEach(async (serializedEvent: Partial) => {\n const event = mapper(serializedEvent);\n await client.decryptEventIfNeeded(event);\n event.setStatus(EventStatus.NOT_SENT);\n this.addPendingEvent(event, event.getTxnId()!);\n });\n });\n }\n\n // awaited by getEncryptionTargetMembers while room members are loading\n if (!this.opts.lazyLoadMembers) {\n this.membersPromise = Promise.resolve(false);\n } else {\n this.membersPromise = undefined;\n }\n }\n\n private threadTimelineSetsPromise: Promise<[EventTimelineSet, EventTimelineSet]> | null = null;\n public async createThreadsTimelineSets(): Promise<[EventTimelineSet, EventTimelineSet] | null> {\n if (this.threadTimelineSetsPromise) {\n return this.threadTimelineSetsPromise;\n }\n\n if (this.client?.supportsThreads()) {\n try {\n this.threadTimelineSetsPromise = Promise.all([\n this.createThreadTimelineSet(),\n this.createThreadTimelineSet(ThreadFilterType.My),\n ]);\n const timelineSets = await this.threadTimelineSetsPromise;\n this.threadsTimelineSets.push(...timelineSets);\n return timelineSets;\n } catch (e) {\n this.threadTimelineSetsPromise = null;\n return null;\n }\n }\n return null;\n }\n\n /**\n * Bulk decrypt critical events in a room\n *\n * Critical events represents the minimal set of events to decrypt\n * for a typical UI to function properly\n *\n * - Last event of every room (to generate likely message preview)\n * - All events up to the read receipt (to calculate an accurate notification count)\n *\n * @returns Signals when all events have been decrypted\n */\n public async decryptCriticalEvents(): Promise {\n if (!this.client.isCryptoEnabled()) return;\n\n const readReceiptEventId = this.getEventReadUpTo(this.client.getUserId()!, true);\n const events = this.getLiveTimeline().getEvents();\n const readReceiptTimelineIndex = events.findIndex((matrixEvent) => {\n return matrixEvent.event.event_id === readReceiptEventId;\n });\n\n const decryptionPromises = events\n .slice(readReceiptTimelineIndex)\n .reverse()\n .map((event) => this.client.decryptEventIfNeeded(event, { isRetry: true }));\n\n await Promise.allSettled(decryptionPromises);\n }\n\n /**\n * Bulk decrypt events in a room\n *\n * @returns Signals when all events have been decrypted\n */\n public async decryptAllEvents(): Promise {\n if (!this.client.isCryptoEnabled()) return;\n\n const decryptionPromises = this.getUnfilteredTimelineSet()\n .getLiveTimeline()\n .getEvents()\n .slice(0) // copy before reversing\n .reverse()\n .map((event) => this.client.decryptEventIfNeeded(event, { isRetry: true }));\n\n await Promise.allSettled(decryptionPromises);\n }\n\n /**\n * Gets the creator of the room\n * @returns The creator of the room, or null if it could not be determined\n */\n public getCreator(): string | null {\n const createEvent = this.currentState.getStateEvents(EventType.RoomCreate, \"\");\n return createEvent?.getContent()[\"creator\"] ?? null;\n }\n\n /**\n * Gets the version of the room\n * @returns The version of the room, or null if it could not be determined\n */\n public getVersion(): string {\n const createEvent = this.currentState.getStateEvents(EventType.RoomCreate, \"\");\n if (!createEvent) {\n if (!this.getVersionWarning) {\n logger.warn(\"[getVersion] Room \" + this.roomId + \" does not have an m.room.create event\");\n this.getVersionWarning = true;\n }\n return \"1\";\n }\n return createEvent.getContent()[\"room_version\"] ?? \"1\";\n }\n\n /**\n * Determines whether this room needs to be upgraded to a new version\n * @returns What version the room should be upgraded to, or null if\n * the room does not require upgrading at this time.\n * @deprecated Use #getRecommendedVersion() instead\n */\n public shouldUpgradeToVersion(): string | null {\n // TODO: Remove this function.\n // This makes assumptions about which versions are safe, and can easily\n // be wrong. Instead, people are encouraged to use getRecommendedVersion\n // which determines a safer value. This function doesn't use that function\n // because this is not async-capable, and to avoid breaking the contract\n // we're deprecating this.\n\n if (!SAFE_ROOM_VERSIONS.includes(this.getVersion())) {\n return KNOWN_SAFE_ROOM_VERSION;\n }\n\n return null;\n }\n\n /**\n * Determines the recommended room version for the room. This returns an\n * object with 3 properties: `version` as the new version the\n * room should be upgraded to (may be the same as the current version);\n * `needsUpgrade` to indicate if the room actually can be\n * upgraded (ie: does the current version not match?); and `urgent`\n * to indicate if the new version patches a vulnerability in a previous\n * version.\n * @returns\n * Resolves to the version the room should be upgraded to.\n */\n public async getRecommendedVersion(): Promise {\n const capabilities = await this.client.getCapabilities();\n let versionCap = capabilities[\"m.room_versions\"];\n if (!versionCap) {\n versionCap = {\n default: KNOWN_SAFE_ROOM_VERSION,\n available: {},\n };\n for (const safeVer of SAFE_ROOM_VERSIONS) {\n versionCap.available[safeVer] = RoomVersionStability.Stable;\n }\n }\n\n let result = this.checkVersionAgainstCapability(versionCap);\n if (result.urgent && result.needsUpgrade) {\n // Something doesn't feel right: we shouldn't need to update\n // because the version we're on should be in the protocol's\n // namespace. This usually means that the server was updated\n // before the client was, making us think the newest possible\n // room version is not stable. As a solution, we'll refresh\n // the capability we're using to determine this.\n logger.warn(\n \"Refreshing room version capability because the server looks \" +\n \"to be supporting a newer room version we don't know about.\",\n );\n\n const caps = await this.client.getCapabilities(true);\n versionCap = caps[\"m.room_versions\"];\n if (!versionCap) {\n logger.warn(\"No room version capability - assuming upgrade required.\");\n return result;\n } else {\n result = this.checkVersionAgainstCapability(versionCap);\n }\n }\n\n return result;\n }\n\n private checkVersionAgainstCapability(versionCap: IRoomVersionsCapability): IRecommendedVersion {\n const currentVersion = this.getVersion();\n logger.log(`[${this.roomId}] Current version: ${currentVersion}`);\n logger.log(`[${this.roomId}] Version capability: `, versionCap);\n\n const result: IRecommendedVersion = {\n version: currentVersion,\n needsUpgrade: false,\n urgent: false,\n };\n\n // If the room is on the default version then nothing needs to change\n if (currentVersion === versionCap.default) return result;\n\n const stableVersions = Object.keys(versionCap.available).filter((v) => versionCap.available[v] === \"stable\");\n\n // Check if the room is on an unstable version. We determine urgency based\n // off the version being in the Matrix spec namespace or not (if the version\n // is in the current namespace and unstable, the room is probably vulnerable).\n if (!stableVersions.includes(currentVersion)) {\n result.version = versionCap.default;\n result.needsUpgrade = true;\n result.urgent = !!this.getVersion().match(/^[0-9]+[0-9.]*$/g);\n if (result.urgent) {\n logger.warn(`URGENT upgrade required on ${this.roomId}`);\n } else {\n logger.warn(`Non-urgent upgrade required on ${this.roomId}`);\n }\n return result;\n }\n\n // The room is on a stable, but non-default, version by this point.\n // No upgrade needed.\n return result;\n }\n\n /**\n * Determines whether the given user is permitted to perform a room upgrade\n * @param userId - The ID of the user to test against\n * @returns True if the given user is permitted to upgrade the room\n */\n public userMayUpgradeRoom(userId: string): boolean {\n return this.currentState.maySendStateEvent(EventType.RoomTombstone, userId);\n }\n\n /**\n * Get the list of pending sent events for this room\n *\n * @returns A list of the sent events\n * waiting for remote echo.\n *\n * @throws If `opts.pendingEventOrdering` was not 'detached'\n */\n public getPendingEvents(): MatrixEvent[] {\n if (!this.pendingEventList) {\n throw new Error(\n \"Cannot call getPendingEvents with pendingEventOrdering == \" + this.opts.pendingEventOrdering,\n );\n }\n\n return this.pendingEventList;\n }\n\n /**\n * Removes a pending event for this room\n *\n * @returns True if an element was removed.\n */\n public removePendingEvent(eventId: string): boolean {\n if (!this.pendingEventList) {\n throw new Error(\n \"Cannot call removePendingEvent with pendingEventOrdering == \" + this.opts.pendingEventOrdering,\n );\n }\n\n const removed = utils.removeElement(\n this.pendingEventList,\n function (ev) {\n return ev.getId() == eventId;\n },\n false,\n );\n\n this.savePendingEvents();\n\n return removed;\n }\n\n /**\n * Check whether the pending event list contains a given event by ID.\n * If pending event ordering is not \"detached\" then this returns false.\n *\n * @param eventId - The event ID to check for.\n */\n public hasPendingEvent(eventId: string): boolean {\n return this.pendingEventList?.some((event) => event.getId() === eventId) ?? false;\n }\n\n /**\n * Get a specific event from the pending event list, if configured, null otherwise.\n *\n * @param eventId - The event ID to check for.\n */\n public getPendingEvent(eventId: string): MatrixEvent | null {\n return this.pendingEventList?.find((event) => event.getId() === eventId) ?? null;\n }\n\n /**\n * Get the live unfiltered timeline for this room.\n *\n * @returns live timeline\n */\n public getLiveTimeline(): EventTimeline {\n return this.getUnfilteredTimelineSet().getLiveTimeline();\n }\n\n /**\n * Get the timestamp of the last message in the room\n *\n * @returns the timestamp of the last message in the room\n */\n public getLastActiveTimestamp(): number {\n const timeline = this.getLiveTimeline();\n const events = timeline.getEvents();\n if (events.length) {\n const lastEvent = events[events.length - 1];\n return lastEvent.getTs();\n } else {\n return Number.MIN_SAFE_INTEGER;\n }\n }\n\n /**\n * @returns the membership type (join | leave | invite) for the logged in user\n */\n public getMyMembership(): string {\n return this.selfMembership ?? \"leave\";\n }\n\n /**\n * If this room is a DM we're invited to,\n * try to find out who invited us\n * @returns user id of the inviter\n */\n public getDMInviter(): string | undefined {\n const me = this.getMember(this.myUserId);\n if (me) {\n return me.getDMInviter();\n }\n\n if (this.selfMembership === \"invite\") {\n // fall back to summary information\n const memberCount = this.getInvitedAndJoinedMemberCount();\n if (memberCount === 2) {\n return this.summaryHeroes?.[0];\n }\n }\n }\n\n /**\n * Assuming this room is a DM room, tries to guess with which user.\n * @returns user id of the other member (could be syncing user)\n */\n public guessDMUserId(): string {\n const me = this.getMember(this.myUserId);\n if (me) {\n const inviterId = me.getDMInviter();\n if (inviterId) {\n return inviterId;\n }\n }\n // Remember, we're assuming this room is a DM, so returning the first member we find should be fine\n if (Array.isArray(this.summaryHeroes) && this.summaryHeroes.length) {\n return this.summaryHeroes[0];\n }\n const members = this.currentState.getMembers();\n const anyMember = members.find((m) => m.userId !== this.myUserId);\n if (anyMember) {\n return anyMember.userId;\n }\n // it really seems like I'm the only user in the room\n // so I probably created a room with just me in it\n // and marked it as a DM. Ok then\n return this.myUserId;\n }\n\n public getAvatarFallbackMember(): RoomMember | undefined {\n const memberCount = this.getInvitedAndJoinedMemberCount();\n if (memberCount > 2) {\n return;\n }\n const hasHeroes = Array.isArray(this.summaryHeroes) && this.summaryHeroes.length;\n if (hasHeroes) {\n const availableMember = this.summaryHeroes!.map((userId) => {\n return this.getMember(userId);\n }).find((member) => !!member);\n if (availableMember) {\n return availableMember;\n }\n }\n const members = this.currentState.getMembers();\n // could be different than memberCount\n // as this includes left members\n if (members.length <= 2) {\n const availableMember = members.find((m) => {\n return m.userId !== this.myUserId;\n });\n if (availableMember) {\n return availableMember;\n }\n }\n // if all else fails, try falling back to a user,\n // and create a one-off member for it\n if (hasHeroes) {\n const availableUser = this.summaryHeroes!.map((userId) => {\n return this.client.getUser(userId);\n }).find((user) => !!user);\n if (availableUser) {\n const member = new RoomMember(this.roomId, availableUser.userId);\n member.user = availableUser;\n return member;\n }\n }\n }\n\n /**\n * Sets the membership this room was received as during sync\n * @param membership - join | leave | invite\n */\n public updateMyMembership(membership: string): void {\n const prevMembership = this.selfMembership;\n this.selfMembership = membership;\n if (prevMembership !== membership) {\n if (membership === \"leave\") {\n this.cleanupAfterLeaving();\n }\n this.emit(RoomEvent.MyMembership, this, membership, prevMembership);\n }\n }\n\n private async loadMembersFromServer(): Promise {\n const lastSyncToken = this.client.store.getSyncToken();\n const response = await this.client.members(this.roomId, undefined, \"leave\", lastSyncToken ?? undefined);\n return response.chunk;\n }\n\n private async loadMembers(): Promise<{ memberEvents: MatrixEvent[]; fromServer: boolean }> {\n // were the members loaded from the server?\n let fromServer = false;\n let rawMembersEvents = await this.client.store.getOutOfBandMembers(this.roomId);\n // If the room is encrypted, we always fetch members from the server at\n // least once, in case the latest state wasn't persisted properly. Note\n // that this function is only called once (unless loading the members\n // fails), since loadMembersIfNeeded always returns this.membersPromise\n // if set, which will be the result of the first (successful) call.\n if (rawMembersEvents === null || (this.client.isCryptoEnabled() && this.client.isRoomEncrypted(this.roomId))) {\n fromServer = true;\n rawMembersEvents = await this.loadMembersFromServer();\n logger.log(`LL: got ${rawMembersEvents.length} ` + `members from server for room ${this.roomId}`);\n }\n const memberEvents = rawMembersEvents.filter(noUnsafeEventProps).map(this.client.getEventMapper());\n return { memberEvents, fromServer };\n }\n\n /**\n * Check if loading of out-of-band-members has completed\n *\n * @returns true if the full membership list of this room has been loaded (including if lazy-loading is disabled).\n * False if the load is not started or is in progress.\n */\n public membersLoaded(): boolean {\n if (!this.opts.lazyLoadMembers) {\n return true;\n }\n\n return this.currentState.outOfBandMembersReady();\n }\n\n /**\n * Preloads the member list in case lazy loading\n * of memberships is in use. Can be called multiple times,\n * it will only preload once.\n * @returns when preloading is done and\n * accessing the members on the room will take\n * all members in the room into account\n */\n public loadMembersIfNeeded(): Promise {\n if (this.membersPromise) {\n return this.membersPromise;\n }\n\n // mark the state so that incoming messages while\n // the request is in flight get marked as superseding\n // the OOB members\n this.currentState.markOutOfBandMembersStarted();\n\n const inMemoryUpdate = this.loadMembers()\n .then((result) => {\n this.currentState.setOutOfBandMembers(result.memberEvents);\n return result.fromServer;\n })\n .catch((err) => {\n // allow retries on fail\n this.membersPromise = undefined;\n this.currentState.markOutOfBandMembersFailed();\n throw err;\n });\n // update members in storage, but don't wait for it\n inMemoryUpdate\n .then((fromServer) => {\n if (fromServer) {\n const oobMembers = this.currentState\n .getMembers()\n .filter((m) => m.isOutOfBand())\n .map((m) => m.events.member?.event as IStateEventWithRoomId);\n logger.log(`LL: telling store to write ${oobMembers.length}` + ` members for room ${this.roomId}`);\n const store = this.client.store;\n return (\n store\n .setOutOfBandMembers(this.roomId, oobMembers)\n // swallow any IDB error as we don't want to fail\n // because of this\n .catch((err) => {\n logger.log(\"LL: storing OOB room members failed, oh well\", err);\n })\n );\n }\n })\n .catch((err) => {\n // as this is not awaited anywhere,\n // at least show the error in the console\n logger.error(err);\n });\n\n this.membersPromise = inMemoryUpdate;\n\n return this.membersPromise;\n }\n\n /**\n * Removes the lazily loaded members from storage if needed\n */\n public async clearLoadedMembersIfNeeded(): Promise {\n if (this.opts.lazyLoadMembers && this.membersPromise) {\n await this.loadMembersIfNeeded();\n await this.client.store.clearOutOfBandMembers(this.roomId);\n this.currentState.clearOutOfBandMembers();\n this.membersPromise = undefined;\n }\n }\n\n /**\n * called when sync receives this room in the leave section\n * to do cleanup after leaving a room. Possibly called multiple times.\n */\n private cleanupAfterLeaving(): void {\n this.clearLoadedMembersIfNeeded().catch((err) => {\n logger.error(`error after clearing loaded members from ` + `room ${this.roomId} after leaving`);\n logger.log(err);\n });\n }\n\n /**\n * Empty out the current live timeline and re-request it. This is used when\n * historical messages are imported into the room via MSC2716 `/batch_send`\n * because the client may already have that section of the timeline loaded.\n * We need to force the client to throw away their current timeline so that\n * when they back paginate over the area again with the historical messages\n * in between, it grabs the newly imported messages. We can listen for\n * `UNSTABLE_MSC2716_MARKER`, in order to tell when historical messages are ready\n * to be discovered in the room and the timeline needs a refresh. The SDK\n * emits a `RoomEvent.HistoryImportedWithinTimeline` event when we detect a\n * valid marker and can check the needs refresh status via\n * `room.getTimelineNeedsRefresh()`.\n */\n public async refreshLiveTimeline(): Promise {\n const liveTimelineBefore = this.getLiveTimeline();\n const forwardPaginationToken = liveTimelineBefore.getPaginationToken(EventTimeline.FORWARDS);\n const backwardPaginationToken = liveTimelineBefore.getPaginationToken(EventTimeline.BACKWARDS);\n const eventsBefore = liveTimelineBefore.getEvents();\n const mostRecentEventInTimeline = eventsBefore[eventsBefore.length - 1];\n logger.log(\n `[refreshLiveTimeline for ${this.roomId}] at ` +\n `mostRecentEventInTimeline=${mostRecentEventInTimeline && mostRecentEventInTimeline.getId()} ` +\n `liveTimelineBefore=${liveTimelineBefore.toString()} ` +\n `forwardPaginationToken=${forwardPaginationToken} ` +\n `backwardPaginationToken=${backwardPaginationToken}`,\n );\n\n // Get the main TimelineSet\n const timelineSet = this.getUnfilteredTimelineSet();\n\n let newTimeline: Optional;\n // If there isn't any event in the timeline, let's go fetch the latest\n // event and construct a timeline from it.\n //\n // This should only really happen if the user ran into an error\n // with refreshing the timeline before which left them in a blank\n // timeline from `resetLiveTimeline`.\n if (!mostRecentEventInTimeline) {\n newTimeline = await this.client.getLatestTimeline(timelineSet);\n } else {\n // Empty out all of `this.timelineSets`. But we also need to keep the\n // same `timelineSet` references around so the React code updates\n // properly and doesn't ignore the room events we emit because it checks\n // that the `timelineSet` references are the same. We need the\n // `timelineSet` empty so that the `client.getEventTimeline(...)` call\n // later, will call `/context` and create a new timeline instead of\n // returning the same one.\n this.resetLiveTimeline(null, null);\n\n // Make the UI timeline show the new blank live timeline we just\n // reset so that if the network fails below it's showing the\n // accurate state of what we're working with instead of the\n // disconnected one in the TimelineWindow which is just hanging\n // around by reference.\n this.emit(RoomEvent.TimelineRefresh, this, timelineSet);\n\n // Use `client.getEventTimeline(...)` to construct a new timeline from a\n // `/context` response state and events for the most recent event before\n // we reset everything. The `timelineSet` we pass in needs to be empty\n // in order for this function to call `/context` and generate a new\n // timeline.\n newTimeline = await this.client.getEventTimeline(timelineSet, mostRecentEventInTimeline.getId()!);\n }\n\n // If a racing `/sync` beat us to creating a new timeline, use that\n // instead because it's the latest in the room and any new messages in\n // the scrollback will include the history.\n const liveTimeline = timelineSet.getLiveTimeline();\n if (\n !liveTimeline ||\n (liveTimeline.getPaginationToken(Direction.Forward) === null &&\n liveTimeline.getPaginationToken(Direction.Backward) === null &&\n liveTimeline.getEvents().length === 0)\n ) {\n logger.log(`[refreshLiveTimeline for ${this.roomId}] using our new live timeline`);\n // Set the pagination token back to the live sync token (`null`) instead\n // of using the `/context` historical token (ex. `t12-13_0_0_0_0_0_0_0_0`)\n // so that it matches the next response from `/sync` and we can properly\n // continue the timeline.\n newTimeline!.setPaginationToken(forwardPaginationToken, EventTimeline.FORWARDS);\n\n // Set our new fresh timeline as the live timeline to continue syncing\n // forwards and back paginating from.\n timelineSet.setLiveTimeline(newTimeline!);\n // Fixup `this.oldstate` so that `scrollback` has the pagination tokens\n // available\n this.fixUpLegacyTimelineFields();\n } else {\n logger.log(\n `[refreshLiveTimeline for ${this.roomId}] \\`/sync\\` or some other request beat us to creating a new ` +\n `live timeline after we reset it. We'll use that instead since any events in the scrollback from ` +\n `this timeline will include the history.`,\n );\n }\n\n // The timeline has now been refreshed ✅\n this.setTimelineNeedsRefresh(false);\n\n // Emit an event which clients can react to and re-load the timeline\n // from the SDK\n this.emit(RoomEvent.TimelineRefresh, this, timelineSet);\n }\n\n /**\n * Reset the live timeline of all timelineSets, and start new ones.\n *\n *

This is used when /sync returns a 'limited' timeline.\n *\n * @param backPaginationToken - token for back-paginating the new timeline\n * @param forwardPaginationToken - token for forward-paginating the old live timeline,\n * if absent or null, all timelines are reset, removing old ones (including the previous live\n * timeline which would otherwise be unable to paginate forwards without this token).\n * Removing just the old live timeline whilst preserving previous ones is not supported.\n */\n public resetLiveTimeline(backPaginationToken?: string | null, forwardPaginationToken?: string | null): void {\n for (const timelineSet of this.timelineSets) {\n timelineSet.resetLiveTimeline(backPaginationToken ?? undefined, forwardPaginationToken ?? undefined);\n }\n for (const thread of this.threads.values()) {\n thread.resetLiveTimeline(backPaginationToken, forwardPaginationToken);\n }\n\n this.fixUpLegacyTimelineFields();\n }\n\n /**\n * Fix up this.timeline, this.oldState and this.currentState\n *\n * @internal\n */\n private fixUpLegacyTimelineFields(): void {\n const previousOldState = this.oldState;\n const previousCurrentState = this.currentState;\n\n // maintain this.timeline as a reference to the live timeline,\n // and this.oldState and this.currentState as references to the\n // state at the start and end of that timeline. These are more\n // for backwards-compatibility than anything else.\n this.timeline = this.getLiveTimeline().getEvents();\n this.oldState = this.getLiveTimeline().getState(EventTimeline.BACKWARDS)!;\n this.currentState = this.getLiveTimeline().getState(EventTimeline.FORWARDS)!;\n\n // Let people know to register new listeners for the new state\n // references. The reference won't necessarily change every time so only\n // emit when we see a change.\n if (previousOldState !== this.oldState) {\n this.emit(RoomEvent.OldStateUpdated, this, previousOldState, this.oldState);\n }\n\n if (previousCurrentState !== this.currentState) {\n this.emit(RoomEvent.CurrentStateUpdated, this, previousCurrentState, this.currentState);\n\n // Re-emit various events on the current room state\n // TODO: If currentState really only exists for backwards\n // compatibility, shouldn't we be doing this some other way?\n this.reEmitter.stopReEmitting(previousCurrentState, [\n RoomStateEvent.Events,\n RoomStateEvent.Members,\n RoomStateEvent.NewMember,\n RoomStateEvent.Update,\n RoomStateEvent.Marker,\n BeaconEvent.New,\n BeaconEvent.Update,\n BeaconEvent.Destroy,\n BeaconEvent.LivenessChange,\n ]);\n this.reEmitter.reEmit(this.currentState, [\n RoomStateEvent.Events,\n RoomStateEvent.Members,\n RoomStateEvent.NewMember,\n RoomStateEvent.Update,\n RoomStateEvent.Marker,\n BeaconEvent.New,\n BeaconEvent.Update,\n BeaconEvent.Destroy,\n BeaconEvent.LivenessChange,\n ]);\n }\n }\n\n /**\n * Returns whether there are any devices in the room that are unverified\n *\n * Note: Callers should first check if crypto is enabled on this device. If it is\n * disabled, then we aren't tracking room devices at all, so we can't answer this, and an\n * error will be thrown.\n *\n * @returns the result\n */\n public async hasUnverifiedDevices(): Promise {\n if (!this.client.isRoomEncrypted(this.roomId)) {\n return false;\n }\n const e2eMembers = await this.getEncryptionTargetMembers();\n for (const member of e2eMembers) {\n const devices = this.client.getStoredDevicesForUser(member.userId);\n if (devices.some((device) => device.isUnverified())) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Return the timeline sets for this room.\n * @returns array of timeline sets for this room\n */\n public getTimelineSets(): EventTimelineSet[] {\n return this.timelineSets;\n }\n\n /**\n * Helper to return the main unfiltered timeline set for this room\n * @returns room's unfiltered timeline set\n */\n public getUnfilteredTimelineSet(): EventTimelineSet {\n return this.timelineSets[0];\n }\n\n /**\n * Get the timeline which contains the given event from the unfiltered set, if any\n *\n * @param eventId - event ID to look for\n * @returns timeline containing\n * the given event, or null if unknown\n */\n public getTimelineForEvent(eventId: string): EventTimeline | null {\n const event = this.findEventById(eventId);\n const thread = this.findThreadForEvent(event);\n if (thread) {\n return thread.timelineSet.getTimelineForEvent(eventId);\n } else {\n return this.getUnfilteredTimelineSet().getTimelineForEvent(eventId);\n }\n }\n\n /**\n * Add a new timeline to this room's unfiltered timeline set\n *\n * @returns newly-created timeline\n */\n public addTimeline(): EventTimeline {\n return this.getUnfilteredTimelineSet().addTimeline();\n }\n\n /**\n * Whether the timeline needs to be refreshed in order to pull in new\n * historical messages that were imported.\n * @param value - The value to set\n */\n public setTimelineNeedsRefresh(value: boolean): void {\n this.timelineNeedsRefresh = value;\n }\n\n /**\n * Whether the timeline needs to be refreshed in order to pull in new\n * historical messages that were imported.\n * @returns .\n */\n public getTimelineNeedsRefresh(): boolean {\n return this.timelineNeedsRefresh;\n }\n\n /**\n * Get an event which is stored in our unfiltered timeline set, or in a thread\n *\n * @param eventId - event ID to look for\n * @returns the given event, or undefined if unknown\n */\n public findEventById(eventId: string): MatrixEvent | undefined {\n let event = this.getUnfilteredTimelineSet().findEventById(eventId);\n\n if (!event) {\n const threads = this.getThreads();\n for (let i = 0; i < threads.length; i++) {\n const thread = threads[i];\n event = thread.findEventById(eventId);\n if (event) {\n return event;\n }\n }\n }\n\n return event;\n }\n\n /**\n * Get one of the notification counts for this room\n * @param type - The type of notification count to get. default: 'total'\n * @returns The notification count, or undefined if there is no count\n * for this type.\n */\n public getUnreadNotificationCount(type = NotificationCountType.Total): number {\n let count = this.getRoomUnreadNotificationCount(type);\n for (const threadNotification of this.threadNotifications.values()) {\n count += threadNotification[type] ?? 0;\n }\n return count;\n }\n\n /**\n * Get the notification for the event context (room or thread timeline)\n */\n public getUnreadCountForEventContext(type = NotificationCountType.Total, event: MatrixEvent): number {\n const isThreadEvent = !!event.threadRootId && !event.isThreadRoot;\n\n return (\n (isThreadEvent\n ? this.getThreadUnreadNotificationCount(event.threadRootId, type)\n : this.getRoomUnreadNotificationCount(type)) ?? 0\n );\n }\n\n /**\n * Get one of the notification counts for this room\n * @param type - The type of notification count to get. default: 'total'\n * @returns The notification count, or undefined if there is no count\n * for this type.\n */\n public getRoomUnreadNotificationCount(type = NotificationCountType.Total): number {\n return this.notificationCounts[type] ?? 0;\n }\n\n /**\n * Get one of the notification counts for a thread\n * @param threadId - the root event ID\n * @param type - The type of notification count to get. default: 'total'\n * @returns The notification count, or undefined if there is no count\n * for this type.\n */\n public getThreadUnreadNotificationCount(threadId: string, type = NotificationCountType.Total): number {\n return this.threadNotifications.get(threadId)?.[type] ?? 0;\n }\n\n /**\n * Checks if the current room has unread thread notifications\n * @returns\n */\n public hasThreadUnreadNotification(): boolean {\n for (const notification of this.threadNotifications.values()) {\n if ((notification.highlight ?? 0) > 0 || (notification.total ?? 0) > 0) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Swet one of the notification count for a thread\n * @param threadId - the root event ID\n * @param type - The type of notification count to get. default: 'total'\n * @returns\n */\n public setThreadUnreadNotificationCount(threadId: string, type: NotificationCountType, count: number): void {\n const notification: NotificationCount = {\n highlight: this.threadNotifications.get(threadId)?.highlight,\n total: this.threadNotifications.get(threadId)?.total,\n ...{\n [type]: count,\n },\n };\n\n this.threadNotifications.set(threadId, notification);\n\n this.emit(RoomEvent.UnreadNotifications, notification, threadId);\n }\n\n /**\n * @returns the notification count type for all the threads in the room\n */\n public get threadsAggregateNotificationType(): NotificationCountType | null {\n let type: NotificationCountType | null = null;\n for (const threadNotification of this.threadNotifications.values()) {\n if ((threadNotification.highlight ?? 0) > 0) {\n return NotificationCountType.Highlight;\n } else if ((threadNotification.total ?? 0) > 0 && !type) {\n type = NotificationCountType.Total;\n }\n }\n return type;\n }\n\n /**\n * Resets the thread notifications for this room\n */\n public resetThreadUnreadNotificationCount(notificationsToKeep?: string[]): void {\n if (notificationsToKeep) {\n for (const [threadId] of this.threadNotifications) {\n if (!notificationsToKeep.includes(threadId)) {\n this.threadNotifications.delete(threadId);\n }\n }\n } else {\n this.threadNotifications.clear();\n }\n this.emit(RoomEvent.UnreadNotifications);\n }\n\n /**\n * Set one of the notification counts for this room\n * @param type - The type of notification count to set.\n * @param count - The new count\n */\n public setUnreadNotificationCount(type: NotificationCountType, count: number): void {\n this.notificationCounts[type] = count;\n this.emit(RoomEvent.UnreadNotifications, this.notificationCounts);\n }\n\n public setUnread(type: NotificationCountType, count: number): void {\n return this.setUnreadNotificationCount(type, count);\n }\n\n public setSummary(summary: IRoomSummary): void {\n const heroes = summary[\"m.heroes\"];\n const joinedCount = summary[\"m.joined_member_count\"];\n const invitedCount = summary[\"m.invited_member_count\"];\n if (Number.isInteger(joinedCount)) {\n this.currentState.setJoinedMemberCount(joinedCount!);\n }\n if (Number.isInteger(invitedCount)) {\n this.currentState.setInvitedMemberCount(invitedCount!);\n }\n if (Array.isArray(heroes)) {\n // be cautious about trusting server values,\n // and make sure heroes doesn't contain our own id\n // just to be sure\n this.summaryHeroes = heroes.filter((userId) => {\n return userId !== this.myUserId;\n });\n }\n }\n\n /**\n * Whether to send encrypted messages to devices within this room.\n * @param value - true to blacklist unverified devices, null\n * to use the global value for this room.\n */\n public setBlacklistUnverifiedDevices(value: boolean): void {\n this.blacklistUnverifiedDevices = value;\n }\n\n /**\n * Whether to send encrypted messages to devices within this room.\n * @returns true if blacklisting unverified devices, null\n * if the global value should be used for this room.\n */\n public getBlacklistUnverifiedDevices(): boolean | null {\n if (this.blacklistUnverifiedDevices === undefined) return null;\n return this.blacklistUnverifiedDevices;\n }\n\n /**\n * Get the avatar URL for a room if one was set.\n * @param baseUrl - The homeserver base URL. See\n * {@link MatrixClient#getHomeserverUrl}.\n * @param width - The desired width of the thumbnail.\n * @param height - The desired height of the thumbnail.\n * @param resizeMethod - The thumbnail resize method to use, either\n * \"crop\" or \"scale\".\n * @param allowDefault - True to allow an identicon for this room if an\n * avatar URL wasn't explicitly set. Default: true. (Deprecated)\n * @returns the avatar URL or null.\n */\n public getAvatarUrl(\n baseUrl: string,\n width: number,\n height: number,\n resizeMethod: ResizeMethod,\n allowDefault = true,\n ): string | null {\n const roomAvatarEvent = this.currentState.getStateEvents(EventType.RoomAvatar, \"\");\n if (!roomAvatarEvent && !allowDefault) {\n return null;\n }\n\n const mainUrl = roomAvatarEvent ? roomAvatarEvent.getContent().url : null;\n if (mainUrl) {\n return getHttpUriForMxc(baseUrl, mainUrl, width, height, resizeMethod);\n }\n\n return null;\n }\n\n /**\n * Get the mxc avatar url for the room, if one was set.\n * @returns the mxc avatar url or falsy\n */\n public getMxcAvatarUrl(): string | null {\n return this.currentState.getStateEvents(EventType.RoomAvatar, \"\")?.getContent()?.url || null;\n }\n\n /**\n * Get this room's canonical alias\n * The alias returned by this function may not necessarily\n * still point to this room.\n * @returns The room's canonical alias, or null if there is none\n */\n public getCanonicalAlias(): string | null {\n const canonicalAlias = this.currentState.getStateEvents(EventType.RoomCanonicalAlias, \"\");\n if (canonicalAlias) {\n return canonicalAlias.getContent().alias || null;\n }\n return null;\n }\n\n /**\n * Get this room's alternative aliases\n * @returns The room's alternative aliases, or an empty array\n */\n public getAltAliases(): string[] {\n const canonicalAlias = this.currentState.getStateEvents(EventType.RoomCanonicalAlias, \"\");\n if (canonicalAlias) {\n return canonicalAlias.getContent().alt_aliases || [];\n }\n return [];\n }\n\n /**\n * Add events to a timeline\n *\n *

Will fire \"Room.timeline\" for each event added.\n *\n * @param events - A list of events to add.\n *\n * @param toStartOfTimeline - True to add these events to the start\n * (oldest) instead of the end (newest) of the timeline. If true, the oldest\n * event will be the last element of 'events'.\n *\n * @param timeline - timeline to\n * add events to.\n *\n * @param paginationToken - token for the next batch of events\n *\n * @remarks\n * Fires {@link RoomEvent.Timeline}\n */\n public addEventsToTimeline(\n events: MatrixEvent[],\n toStartOfTimeline: boolean,\n timeline: EventTimeline,\n paginationToken?: string,\n ): void {\n timeline.getTimelineSet().addEventsToTimeline(events, toStartOfTimeline, timeline, paginationToken);\n }\n\n /**\n * Get the instance of the thread associated with the current event\n * @param eventId - the ID of the current event\n * @returns a thread instance if known\n */\n public getThread(eventId: string): Thread | null {\n return this.threads.get(eventId) ?? null;\n }\n\n /**\n * Get all the known threads in the room\n */\n public getThreads(): Thread[] {\n return Array.from(this.threads.values());\n }\n\n /**\n * Get a member from the current room state.\n * @param userId - The user ID of the member.\n * @returns The member or `null`.\n */\n public getMember(userId: string): RoomMember | null {\n return this.currentState.getMember(userId);\n }\n\n /**\n * Get all currently loaded members from the current\n * room state.\n * @returns Room members\n */\n public getMembers(): RoomMember[] {\n return this.currentState.getMembers();\n }\n\n /**\n * Get a list of members whose membership state is \"join\".\n * @returns A list of currently joined members.\n */\n public getJoinedMembers(): RoomMember[] {\n return this.getMembersWithMembership(\"join\");\n }\n\n /**\n * Returns the number of joined members in this room\n * This method caches the result.\n * This is a wrapper around the method of the same name in roomState, returning\n * its result for the room's current state.\n * @returns The number of members in this room whose membership is 'join'\n */\n public getJoinedMemberCount(): number {\n return this.currentState.getJoinedMemberCount();\n }\n\n /**\n * Returns the number of invited members in this room\n * @returns The number of members in this room whose membership is 'invite'\n */\n public getInvitedMemberCount(): number {\n return this.currentState.getInvitedMemberCount();\n }\n\n /**\n * Returns the number of invited + joined members in this room\n * @returns The number of members in this room whose membership is 'invite' or 'join'\n */\n public getInvitedAndJoinedMemberCount(): number {\n return this.getInvitedMemberCount() + this.getJoinedMemberCount();\n }\n\n /**\n * Get a list of members with given membership state.\n * @param membership - The membership state.\n * @returns A list of members with the given membership state.\n */\n public getMembersWithMembership(membership: string): RoomMember[] {\n return this.currentState.getMembers().filter(function (m) {\n return m.membership === membership;\n });\n }\n\n /**\n * Get a list of members we should be encrypting for in this room\n * @returns A list of members who\n * we should encrypt messages for in this room.\n */\n public async getEncryptionTargetMembers(): Promise {\n await this.loadMembersIfNeeded();\n let members = this.getMembersWithMembership(\"join\");\n if (this.shouldEncryptForInvitedMembers()) {\n members = members.concat(this.getMembersWithMembership(\"invite\"));\n }\n return members;\n }\n\n /**\n * Determine whether we should encrypt messages for invited users in this room\n * @returns if we should encrypt messages for invited users\n */\n public shouldEncryptForInvitedMembers(): boolean {\n const ev = this.currentState.getStateEvents(EventType.RoomHistoryVisibility, \"\");\n return ev?.getContent()?.history_visibility !== \"joined\";\n }\n\n /**\n * Get the default room name (i.e. what a given user would see if the\n * room had no m.room.name)\n * @param userId - The userId from whose perspective we want\n * to calculate the default name\n * @returns The default room name\n */\n public getDefaultRoomName(userId: string): string {\n return this.calculateRoomName(userId, true);\n }\n\n /**\n * Check if the given user_id has the given membership state.\n * @param userId - The user ID to check.\n * @param membership - The membership e.g. `'join'`\n * @returns True if this user_id has the given membership state.\n */\n public hasMembershipState(userId: string, membership: string): boolean {\n const member = this.getMember(userId);\n if (!member) {\n return false;\n }\n return member.membership === membership;\n }\n\n /**\n * Add a timelineSet for this room with the given filter\n * @param filter - The filter to be applied to this timelineSet\n * @param opts - Configuration options\n * @returns The timelineSet\n */\n public getOrCreateFilteredTimelineSet(\n filter: Filter,\n { prepopulateTimeline = true, useSyncEvents = true, pendingEvents = true }: ICreateFilterOpts = {},\n ): EventTimelineSet {\n if (this.filteredTimelineSets[filter.filterId!]) {\n return this.filteredTimelineSets[filter.filterId!];\n }\n const opts = Object.assign({ filter, pendingEvents }, this.opts);\n const timelineSet = new EventTimelineSet(this, opts);\n this.reEmitter.reEmit(timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n if (useSyncEvents) {\n this.filteredTimelineSets[filter.filterId!] = timelineSet;\n this.timelineSets.push(timelineSet);\n }\n\n const unfilteredLiveTimeline = this.getLiveTimeline();\n // Not all filter are possible to replicate client-side only\n // When that's the case we do not want to prepopulate from the live timeline\n // as we would get incorrect results compared to what the server would send back\n if (prepopulateTimeline) {\n // populate up the new timelineSet with filtered events from our live\n // unfiltered timeline.\n //\n // XXX: This is risky as our timeline\n // may have grown huge and so take a long time to filter.\n // see https://github.com/vector-im/vector-web/issues/2109\n\n unfilteredLiveTimeline.getEvents().forEach(function (event) {\n timelineSet.addLiveEvent(event);\n });\n\n // find the earliest unfiltered timeline\n let timeline = unfilteredLiveTimeline;\n while (timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)) {\n timeline = timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)!;\n }\n\n timelineSet\n .getLiveTimeline()\n .setPaginationToken(timeline.getPaginationToken(EventTimeline.BACKWARDS), EventTimeline.BACKWARDS);\n } else if (useSyncEvents) {\n const livePaginationToken = unfilteredLiveTimeline.getPaginationToken(Direction.Forward);\n timelineSet.getLiveTimeline().setPaginationToken(livePaginationToken, Direction.Backward);\n }\n\n // alternatively, we could try to do something like this to try and re-paginate\n // in the filtered events from nothing, but Mark says it's an abuse of the API\n // to do so:\n //\n // timelineSet.resetLiveTimeline(\n // unfilteredLiveTimeline.getPaginationToken(EventTimeline.FORWARDS)\n // );\n\n return timelineSet;\n }\n\n private async getThreadListFilter(filterType = ThreadFilterType.All): Promise {\n const myUserId = this.client.getUserId()!;\n const filter = new Filter(myUserId);\n\n const definition: IFilterDefinition = {\n room: {\n timeline: {\n [FILTER_RELATED_BY_REL_TYPES.name]: [THREAD_RELATION_TYPE.name],\n },\n },\n };\n\n if (filterType === ThreadFilterType.My) {\n definition!.room!.timeline![FILTER_RELATED_BY_SENDERS.name] = [myUserId];\n }\n\n filter.setDefinition(definition);\n const filterId = await this.client.getOrCreateFilter(`THREAD_PANEL_${this.roomId}_${filterType}`, filter);\n\n filter.filterId = filterId;\n\n return filter;\n }\n\n private async createThreadTimelineSet(filterType?: ThreadFilterType): Promise {\n let timelineSet: EventTimelineSet;\n if (Thread.hasServerSideListSupport) {\n timelineSet = new EventTimelineSet(\n this,\n {\n ...this.opts,\n pendingEvents: false,\n },\n undefined,\n undefined,\n filterType ?? ThreadFilterType.All,\n );\n this.reEmitter.reEmit(timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n } else if (Thread.hasServerSideSupport) {\n const filter = await this.getThreadListFilter(filterType);\n\n timelineSet = this.getOrCreateFilteredTimelineSet(filter, {\n prepopulateTimeline: false,\n useSyncEvents: false,\n pendingEvents: false,\n });\n } else {\n timelineSet = new EventTimelineSet(this, {\n pendingEvents: false,\n });\n\n Array.from(this.threads).forEach(([, thread]) => {\n if (thread.length === 0) return;\n const currentUserParticipated = thread.timeline.some((event) => {\n return event.getSender() === this.client.getUserId();\n });\n if (filterType !== ThreadFilterType.My || currentUserParticipated) {\n timelineSet.getLiveTimeline().addEvent(thread.rootEvent!, {\n toStartOfTimeline: false,\n });\n }\n });\n }\n\n return timelineSet;\n }\n\n private threadsReady = false;\n\n /**\n * Takes the given thread root events and creates threads for them.\n */\n public processThreadRoots(events: MatrixEvent[], toStartOfTimeline: boolean): void {\n for (const rootEvent of events) {\n EventTimeline.setEventMetadata(rootEvent, this.currentState, toStartOfTimeline);\n if (!this.getThread(rootEvent.getId()!)) {\n this.createThread(rootEvent.getId()!, rootEvent, [], toStartOfTimeline);\n }\n }\n }\n\n /**\n * Fetch the bare minimum of room threads required for the thread list to work reliably.\n * With server support that means fetching one page.\n * Without server support that means fetching as much at once as the server allows us to.\n */\n public async fetchRoomThreads(): Promise {\n if (this.threadsReady || !this.client.supportsThreads()) {\n return;\n }\n\n if (Thread.hasServerSideListSupport) {\n await Promise.all([\n this.fetchRoomThreadList(ThreadFilterType.All),\n this.fetchRoomThreadList(ThreadFilterType.My),\n ]);\n } else {\n const allThreadsFilter = await this.getThreadListFilter();\n\n const { chunk: events } = await this.client.createMessagesRequest(\n this.roomId,\n \"\",\n Number.MAX_SAFE_INTEGER,\n Direction.Backward,\n allThreadsFilter,\n );\n\n if (!events.length) return;\n\n // Sorted by last_reply origin_server_ts\n const threadRoots = events.map(this.client.getEventMapper()).sort((eventA, eventB) => {\n /**\n * `origin_server_ts` in a decentralised world is far from ideal\n * but for lack of any better, we will have to use this\n * Long term the sorting should be handled by homeservers and this\n * is only meant as a short term patch\n */\n const threadAMetadata = eventA.getServerAggregatedRelation(\n THREAD_RELATION_TYPE.name,\n )!;\n const threadBMetadata = eventB.getServerAggregatedRelation(\n THREAD_RELATION_TYPE.name,\n )!;\n return threadAMetadata.latest_event.origin_server_ts - threadBMetadata.latest_event.origin_server_ts;\n });\n\n let latestMyThreadsRootEvent: MatrixEvent | undefined;\n const roomState = this.getLiveTimeline().getState(EventTimeline.FORWARDS);\n for (const rootEvent of threadRoots) {\n const opts = {\n duplicateStrategy: DuplicateStrategy.Ignore,\n fromCache: false,\n roomState,\n };\n this.threadsTimelineSets[0]?.addLiveEvent(rootEvent, opts);\n\n const threadRelationship = rootEvent.getServerAggregatedRelation(\n THREAD_RELATION_TYPE.name,\n );\n if (threadRelationship?.current_user_participated) {\n this.threadsTimelineSets[1]?.addLiveEvent(rootEvent, opts);\n latestMyThreadsRootEvent = rootEvent;\n }\n }\n\n this.processThreadRoots(threadRoots, true);\n\n this.client.decryptEventIfNeeded(threadRoots[threadRoots.length - 1]);\n if (latestMyThreadsRootEvent) {\n this.client.decryptEventIfNeeded(latestMyThreadsRootEvent);\n }\n }\n\n this.on(ThreadEvent.NewReply, this.onThreadNewReply);\n this.on(ThreadEvent.Delete, this.onThreadDelete);\n this.threadsReady = true;\n }\n\n public async processPollEvents(events: MatrixEvent[]): Promise {\n const processPollStartEvent = (event: MatrixEvent): void => {\n if (!M_POLL_START.matches(event.getType())) return;\n try {\n const poll = new Poll(event, this.client, this);\n this.polls.set(event.getId()!, poll);\n this.emit(PollEvent.New, poll);\n } catch {}\n // poll creation can fail for malformed poll start events\n };\n\n const processPollRelationEvent = (event: MatrixEvent): void => {\n const relationEventId = event.relationEventId;\n if (relationEventId && this.polls.has(relationEventId)) {\n const poll = this.polls.get(relationEventId);\n poll?.onNewRelation(event);\n }\n };\n\n const processPollEvent = (event: MatrixEvent): void => {\n processPollStartEvent(event);\n processPollRelationEvent(event);\n };\n\n for (const event of events) {\n try {\n await this.client.decryptEventIfNeeded(event);\n processPollEvent(event);\n } catch {}\n }\n }\n\n /**\n * Fetch a single page of threadlist messages for the specific thread filter\n * @internal\n */\n private async fetchRoomThreadList(filter?: ThreadFilterType): Promise {\n const timelineSet = filter === ThreadFilterType.My ? this.threadsTimelineSets[1] : this.threadsTimelineSets[0];\n\n const { chunk: events, end } = await this.client.createThreadListMessagesRequest(\n this.roomId,\n null,\n undefined,\n Direction.Backward,\n timelineSet.threadListType,\n timelineSet.getFilter(),\n );\n\n timelineSet.getLiveTimeline().setPaginationToken(end ?? null, Direction.Backward);\n\n if (!events.length) return;\n\n const matrixEvents = events.map(this.client.getEventMapper());\n this.processThreadRoots(matrixEvents, true);\n const roomState = this.getLiveTimeline().getState(EventTimeline.FORWARDS);\n for (const rootEvent of matrixEvents) {\n timelineSet.addLiveEvent(rootEvent, {\n duplicateStrategy: DuplicateStrategy.Replace,\n fromCache: false,\n roomState,\n });\n }\n }\n\n private onThreadNewReply(thread: Thread): void {\n this.updateThreadRootEvents(thread, false, true);\n }\n\n private onThreadDelete(thread: Thread): void {\n this.threads.delete(thread.id);\n\n const timeline = this.getTimelineForEvent(thread.id);\n const roomEvent = timeline?.getEvents()?.find((it) => it.getId() === thread.id);\n if (roomEvent) {\n thread.clearEventMetadata(roomEvent);\n } else {\n logger.debug(\"onThreadDelete: Could not find root event in room timeline\");\n }\n for (const timelineSet of this.threadsTimelineSets) {\n timelineSet.removeEvent(thread.id);\n }\n }\n\n /**\n * Forget the timelineSet for this room with the given filter\n *\n * @param filter - the filter whose timelineSet is to be forgotten\n */\n public removeFilteredTimelineSet(filter: Filter): void {\n const timelineSet = this.filteredTimelineSets[filter.filterId!];\n delete this.filteredTimelineSets[filter.filterId!];\n const i = this.timelineSets.indexOf(timelineSet);\n if (i > -1) {\n this.timelineSets.splice(i, 1);\n }\n }\n\n public eventShouldLiveIn(\n event: MatrixEvent,\n events?: MatrixEvent[],\n roots?: Set,\n ): {\n shouldLiveInRoom: boolean;\n shouldLiveInThread: boolean;\n threadId?: string;\n } {\n if (!this.client?.supportsThreads()) {\n return {\n shouldLiveInRoom: true,\n shouldLiveInThread: false,\n };\n }\n\n // A thread root is always shown in both timelines\n if (event.isThreadRoot || roots?.has(event.getId()!)) {\n return {\n shouldLiveInRoom: true,\n shouldLiveInThread: true,\n threadId: event.getId(),\n };\n }\n\n // A thread relation is always only shown in a thread\n if (event.isRelation(THREAD_RELATION_TYPE.name)) {\n return {\n shouldLiveInRoom: false,\n shouldLiveInThread: true,\n threadId: event.threadRootId,\n };\n }\n\n const parentEventId = event.getAssociatedId();\n let parentEvent: MatrixEvent | undefined;\n if (parentEventId) {\n parentEvent = this.findEventById(parentEventId) ?? events?.find((e) => e.getId() === parentEventId);\n }\n\n // Treat relations and redactions as extensions of their parents so evaluate parentEvent instead\n if (parentEvent && (event.isRelation() || event.isRedaction())) {\n return this.eventShouldLiveIn(parentEvent, events, roots);\n }\n\n // Edge case where we know the event is a relation but don't have the parentEvent\n if (roots?.has(event.relationEventId!)) {\n return {\n shouldLiveInRoom: true,\n shouldLiveInThread: true,\n threadId: event.relationEventId,\n };\n }\n\n // We've exhausted all scenarios, can safely assume that this event should live in the room timeline only\n return {\n shouldLiveInRoom: true,\n shouldLiveInThread: false,\n };\n }\n\n public findThreadForEvent(event?: MatrixEvent): Thread | null {\n if (!event) return null;\n\n const { threadId } = this.eventShouldLiveIn(event);\n return threadId ? this.getThread(threadId) : null;\n }\n\n private addThreadedEvents(threadId: string, events: MatrixEvent[], toStartOfTimeline = false): void {\n let thread = this.getThread(threadId);\n\n if (!thread) {\n const rootEvent = this.findEventById(threadId) ?? events.find((e) => e.getId() === threadId);\n thread = this.createThread(threadId, rootEvent, events, toStartOfTimeline);\n }\n\n thread.addEvents(events, toStartOfTimeline);\n }\n\n /**\n * Adds events to a thread's timeline. Will fire \"Thread.update\"\n */\n public processThreadedEvents(events: MatrixEvent[], toStartOfTimeline: boolean): void {\n events.forEach(this.applyRedaction);\n\n const eventsByThread: { [threadId: string]: MatrixEvent[] } = {};\n for (const event of events) {\n const { threadId, shouldLiveInThread } = this.eventShouldLiveIn(event);\n if (shouldLiveInThread && !eventsByThread[threadId!]) {\n eventsByThread[threadId!] = [];\n }\n eventsByThread[threadId!]?.push(event);\n }\n\n Object.entries(eventsByThread).map(([threadId, threadEvents]) =>\n this.addThreadedEvents(threadId, threadEvents, toStartOfTimeline),\n );\n }\n\n private updateThreadRootEvents = (thread: Thread, toStartOfTimeline: boolean, recreateEvent: boolean): void => {\n if (thread.length) {\n this.updateThreadRootEvent(this.threadsTimelineSets?.[0], thread, toStartOfTimeline, recreateEvent);\n if (thread.hasCurrentUserParticipated) {\n this.updateThreadRootEvent(this.threadsTimelineSets?.[1], thread, toStartOfTimeline, recreateEvent);\n }\n }\n };\n\n private updateThreadRootEvent = (\n timelineSet: Optional,\n thread: Thread,\n toStartOfTimeline: boolean,\n recreateEvent: boolean,\n ): void => {\n if (timelineSet && thread.rootEvent) {\n if (recreateEvent) {\n timelineSet.removeEvent(thread.id);\n }\n if (Thread.hasServerSideSupport) {\n timelineSet.addLiveEvent(thread.rootEvent, {\n duplicateStrategy: DuplicateStrategy.Replace,\n fromCache: false,\n roomState: this.currentState,\n });\n } else {\n timelineSet.addEventToTimeline(thread.rootEvent, timelineSet.getLiveTimeline(), { toStartOfTimeline });\n }\n }\n };\n\n public createThread(\n threadId: string,\n rootEvent: MatrixEvent | undefined,\n events: MatrixEvent[] = [],\n toStartOfTimeline: boolean,\n ): Thread {\n if (this.threads.has(threadId)) {\n return this.threads.get(threadId)!;\n }\n\n if (rootEvent) {\n const relatedEvents = this.relations.getAllChildEventsForEvent(rootEvent.getId()!);\n if (relatedEvents?.length) {\n // Include all relations of the root event, given it'll be visible in both timelines,\n // except `m.replace` as that will already be applied atop the event using `MatrixEvent::makeReplaced`\n events = events.concat(relatedEvents.filter((e) => !e.isRelation(RelationType.Replace)));\n }\n }\n\n const thread = new Thread(threadId, rootEvent, {\n room: this,\n client: this.client,\n pendingEventOrdering: this.opts.pendingEventOrdering,\n receipts: this.cachedThreadReadReceipts.get(threadId) ?? [],\n });\n\n // All read receipts should now come down from sync, we do not need to keep\n // a reference to the cached receipts anymore.\n this.cachedThreadReadReceipts.delete(threadId);\n\n // If we managed to create a thread and figure out its `id` then we can use it\n // This has to happen before thread.addEvents, because that adds events to the eventtimeline, and the\n // eventtimeline sometimes looks up thread information via the room.\n this.threads.set(thread.id, thread);\n\n // This is necessary to be able to jump to events in threads:\n // If we jump to an event in a thread where neither the event, nor the root,\n // nor any thread event are loaded yet, we'll load the event as well as the thread root, create the thread,\n // and pass the event through this.\n thread.addEvents(events, false);\n\n this.reEmitter.reEmit(thread, [\n ThreadEvent.Delete,\n ThreadEvent.Update,\n ThreadEvent.NewReply,\n RoomEvent.Timeline,\n RoomEvent.TimelineReset,\n ]);\n const isNewer =\n this.lastThread?.rootEvent &&\n rootEvent?.localTimestamp &&\n this.lastThread.rootEvent?.localTimestamp < rootEvent?.localTimestamp;\n\n if (!this.lastThread || isNewer) {\n this.lastThread = thread;\n }\n\n if (this.threadsReady) {\n this.updateThreadRootEvents(thread, toStartOfTimeline, false);\n }\n this.emit(ThreadEvent.New, thread, toStartOfTimeline);\n\n return thread;\n }\n\n private applyRedaction = (event: MatrixEvent): void => {\n if (event.isRedaction()) {\n const redactId = event.event.redacts;\n\n // if we know about this event, redact its contents now.\n const redactedEvent = redactId ? this.findEventById(redactId) : undefined;\n if (redactedEvent) {\n redactedEvent.makeRedacted(event);\n\n // If this is in the current state, replace it with the redacted version\n if (redactedEvent.isState()) {\n const currentStateEvent = this.currentState.getStateEvents(\n redactedEvent.getType(),\n redactedEvent.getStateKey()!,\n );\n if (currentStateEvent?.getId() === redactedEvent.getId()) {\n this.currentState.setStateEvents([redactedEvent]);\n }\n }\n\n this.emit(RoomEvent.Redaction, event, this);\n\n // TODO: we stash user displaynames (among other things) in\n // RoomMember objects which are then attached to other events\n // (in the sender and target fields). We should get those\n // RoomMember objects to update themselves when the events that\n // they are based on are changed.\n\n // Remove any visibility change on this event.\n this.visibilityEvents.delete(redactId!);\n\n // If this event is a visibility change event, remove it from the\n // list of visibility changes and update any event affected by it.\n if (redactedEvent.isVisibilityEvent()) {\n this.redactVisibilityChangeEvent(event);\n }\n }\n\n // FIXME: apply redactions to notification list\n\n // NB: We continue to add the redaction event to the timeline so\n // clients can say \"so and so redacted an event\" if they wish to. Also\n // this may be needed to trigger an update.\n }\n };\n\n private processLiveEvent(event: MatrixEvent): void {\n this.applyRedaction(event);\n\n // Implement MSC3531: hiding messages.\n if (event.isVisibilityEvent()) {\n // This event changes the visibility of another event, record\n // the visibility change, inform clients if necessary.\n this.applyNewVisibilityEvent(event);\n }\n // If any pending visibility change is waiting for this (older) event,\n this.applyPendingVisibilityEvents(event);\n\n // Sliding Sync modifications:\n // The proxy cannot guarantee every sent event will have a transaction_id field, so we need\n // to check the event ID against the list of pending events if there is no transaction ID\n // field. Only do this for events sent by us though as it's potentially expensive to loop\n // the pending events map.\n const txnId = event.getUnsigned().transaction_id;\n if (!txnId && event.getSender() === this.myUserId) {\n // check the txn map for a matching event ID\n for (const [tid, localEvent] of this.txnToEvent) {\n if (localEvent.getId() === event.getId()) {\n logger.debug(\"processLiveEvent: found sent event without txn ID: \", tid, event.getId());\n // update the unsigned field so we can re-use the same codepaths\n const unsigned = event.getUnsigned();\n unsigned.transaction_id = tid;\n event.setUnsigned(unsigned);\n break;\n }\n }\n }\n }\n\n /**\n * Add an event to the end of this room's live timelines. Will fire\n * \"Room.timeline\".\n *\n * @param event - Event to be added\n * @param addLiveEventOptions - addLiveEvent options\n * @internal\n *\n * @remarks\n * Fires {@link RoomEvent.Timeline}\n */\n private addLiveEvent(event: MatrixEvent, addLiveEventOptions: IAddLiveEventOptions): void {\n const { duplicateStrategy, timelineWasEmpty, fromCache } = addLiveEventOptions;\n\n // add to our timeline sets\n for (const timelineSet of this.timelineSets) {\n timelineSet.addLiveEvent(event, {\n duplicateStrategy,\n fromCache,\n timelineWasEmpty,\n });\n }\n\n // synthesize and inject implicit read receipts\n // Done after adding the event because otherwise the app would get a read receipt\n // pointing to an event that wasn't yet in the timeline\n // Don't synthesize RR for m.room.redaction as this causes the RR to go missing.\n if (event.sender && event.getType() !== EventType.RoomRedaction) {\n this.addReceipt(synthesizeReceipt(event.sender.userId, event, ReceiptType.Read), true);\n\n // Any live events from a user could be taken as implicit\n // presence information: evidence that they are currently active.\n // ...except in a world where we use 'user.currentlyActive' to reduce\n // presence spam, this isn't very useful - we'll get a transition when\n // they are no longer currently active anyway. So don't bother to\n // reset the lastActiveAgo and lastPresenceTs from the RoomState's user.\n }\n }\n\n /**\n * Add a pending outgoing event to this room.\n *\n *

The event is added to either the pendingEventList, or the live timeline,\n * depending on the setting of opts.pendingEventOrdering.\n *\n *

This is an internal method, intended for use by MatrixClient.\n *\n * @param event - The event to add.\n *\n * @param txnId - Transaction id for this outgoing event\n *\n * @throws if the event doesn't have status SENDING, or we aren't given a\n * unique transaction id.\n *\n * @remarks\n * Fires {@link RoomEvent.LocalEchoUpdated}\n */\n public addPendingEvent(event: MatrixEvent, txnId: string): void {\n if (event.status !== EventStatus.SENDING && event.status !== EventStatus.NOT_SENT) {\n throw new Error(\"addPendingEvent called on an event with status \" + event.status);\n }\n\n if (this.txnToEvent.get(txnId)) {\n throw new Error(\"addPendingEvent called on an event with known txnId \" + txnId);\n }\n\n // call setEventMetadata to set up event.sender etc\n // as event is shared over all timelineSets, we set up its metadata based\n // on the unfiltered timelineSet.\n EventTimeline.setEventMetadata(event, this.getLiveTimeline().getState(EventTimeline.FORWARDS)!, false);\n\n this.txnToEvent.set(txnId, event);\n if (this.pendingEventList) {\n if (this.pendingEventList.some((e) => e.status === EventStatus.NOT_SENT)) {\n logger.warn(\"Setting event as NOT_SENT due to messages in the same state\");\n event.setStatus(EventStatus.NOT_SENT);\n }\n this.pendingEventList.push(event);\n this.savePendingEvents();\n if (event.isRelation()) {\n // For pending events, add them to the relations collection immediately.\n // (The alternate case below already covers this as part of adding to\n // the timeline set.)\n this.aggregateNonLiveRelation(event);\n }\n\n if (event.isRedaction()) {\n const redactId = event.event.redacts;\n let redactedEvent = this.pendingEventList.find((e) => e.getId() === redactId);\n if (!redactedEvent && redactId) {\n redactedEvent = this.findEventById(redactId);\n }\n if (redactedEvent) {\n redactedEvent.markLocallyRedacted(event);\n this.emit(RoomEvent.Redaction, event, this);\n }\n }\n } else {\n for (const timelineSet of this.timelineSets) {\n if (timelineSet.getFilter()) {\n if (timelineSet.getFilter()!.filterRoomTimeline([event]).length) {\n timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), {\n toStartOfTimeline: false,\n });\n }\n } else {\n timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), {\n toStartOfTimeline: false,\n });\n }\n }\n }\n\n this.emit(RoomEvent.LocalEchoUpdated, event, this);\n }\n\n /**\n * Persists all pending events to local storage\n *\n * If the current room is encrypted only encrypted events will be persisted\n * all messages that are not yet encrypted will be discarded\n *\n * This is because the flow of EVENT_STATUS transition is\n * `queued => sending => encrypting => sending => sent`\n *\n * Steps 3 and 4 are skipped for unencrypted room.\n * It is better to discard an unencrypted message rather than persisting\n * it locally for everyone to read\n */\n private savePendingEvents(): void {\n if (this.pendingEventList) {\n const pendingEvents = this.pendingEventList\n .map((event) => {\n return {\n ...event.event,\n txn_id: event.getTxnId(),\n };\n })\n .filter((event) => {\n // Filter out the unencrypted messages if the room is encrypted\n const isEventEncrypted = event.type === EventType.RoomMessageEncrypted;\n const isRoomEncrypted = this.client.isRoomEncrypted(this.roomId);\n return isEventEncrypted || !isRoomEncrypted;\n });\n\n this.client.store.setPendingEvents(this.roomId, pendingEvents);\n }\n }\n\n /**\n * Used to aggregate the local echo for a relation, and also\n * for re-applying a relation after it's redaction has been cancelled,\n * as the local echo for the redaction of the relation would have\n * un-aggregated the relation. Note that this is different from regular messages,\n * which are just kept detached for their local echo.\n *\n * Also note that live events are aggregated in the live EventTimelineSet.\n * @param event - the relation event that needs to be aggregated.\n */\n private aggregateNonLiveRelation(event: MatrixEvent): void {\n this.relations.aggregateChildEvent(event);\n }\n\n public getEventForTxnId(txnId: string): MatrixEvent | undefined {\n return this.txnToEvent.get(txnId);\n }\n\n /**\n * Deal with the echo of a message we sent.\n *\n *

We move the event to the live timeline if it isn't there already, and\n * update it.\n *\n * @param remoteEvent - The event received from\n * /sync\n * @param localEvent - The local echo, which\n * should be either in the pendingEventList or the timeline.\n *\n * @internal\n *\n * @remarks\n * Fires {@link RoomEvent.LocalEchoUpdated}\n */\n public handleRemoteEcho(remoteEvent: MatrixEvent, localEvent: MatrixEvent): void {\n const oldEventId = localEvent.getId()!;\n const newEventId = remoteEvent.getId()!;\n const oldStatus = localEvent.status;\n\n logger.debug(`Got remote echo for event ${oldEventId} -> ${newEventId} old status ${oldStatus}`);\n\n // no longer pending\n this.txnToEvent.delete(remoteEvent.getUnsigned().transaction_id!);\n\n // if it's in the pending list, remove it\n if (this.pendingEventList) {\n this.removePendingEvent(oldEventId);\n }\n\n // replace the event source (this will preserve the plaintext payload if\n // any, which is good, because we don't want to try decoding it again).\n localEvent.handleRemoteEcho(remoteEvent.event);\n\n const { shouldLiveInRoom, threadId } = this.eventShouldLiveIn(remoteEvent);\n const thread = threadId ? this.getThread(threadId) : null;\n thread?.setEventMetadata(localEvent);\n thread?.timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId);\n\n if (shouldLiveInRoom) {\n for (const timelineSet of this.timelineSets) {\n // if it's already in the timeline, update the timeline map. If it's not, add it.\n timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId);\n }\n }\n\n this.emit(RoomEvent.LocalEchoUpdated, localEvent, this, oldEventId, oldStatus);\n }\n\n /**\n * Update the status / event id on a pending event, to reflect its transmission\n * progress.\n *\n *

This is an internal method.\n *\n * @param event - local echo event\n * @param newStatus - status to assign\n * @param newEventId - new event id to assign. Ignored unless newStatus == EventStatus.SENT.\n *\n * @remarks\n * Fires {@link RoomEvent.LocalEchoUpdated}\n */\n public updatePendingEvent(event: MatrixEvent, newStatus: EventStatus, newEventId?: string): void {\n logger.log(\n `setting pendingEvent status to ${newStatus} in ${event.getRoomId()} ` +\n `event ID ${event.getId()} -> ${newEventId}`,\n );\n\n // if the message was sent, we expect an event id\n if (newStatus == EventStatus.SENT && !newEventId) {\n throw new Error(\"updatePendingEvent called with status=SENT, but no new event id\");\n }\n\n // SENT races against /sync, so we have to special-case it.\n if (newStatus == EventStatus.SENT) {\n const timeline = this.getTimelineForEvent(newEventId!);\n if (timeline) {\n // we've already received the event via the event stream.\n // nothing more to do here, assuming the transaction ID was correctly matched.\n // Let's check that.\n const remoteEvent = this.findEventById(newEventId!);\n const remoteTxnId = remoteEvent?.getUnsigned().transaction_id;\n if (!remoteTxnId && remoteEvent) {\n // This code path is mostly relevant for the Sliding Sync proxy.\n // The remote event did not contain a transaction ID, so we did not handle\n // the remote echo yet. Handle it now.\n const unsigned = remoteEvent.getUnsigned();\n unsigned.transaction_id = event.getTxnId();\n remoteEvent.setUnsigned(unsigned);\n // the remote event is _already_ in the timeline, so we need to remove it so\n // we can convert the local event into the final event.\n this.removeEvent(remoteEvent.getId()!);\n this.handleRemoteEcho(remoteEvent, event);\n }\n return;\n }\n }\n\n const oldStatus = event.status;\n const oldEventId = event.getId()!;\n\n if (!oldStatus) {\n throw new Error(\"updatePendingEventStatus called on an event which is not a local echo.\");\n }\n\n const allowed = ALLOWED_TRANSITIONS[oldStatus];\n if (!allowed?.includes(newStatus)) {\n throw new Error(`Invalid EventStatus transition ${oldStatus}->${newStatus}`);\n }\n\n event.setStatus(newStatus);\n\n if (newStatus == EventStatus.SENT) {\n // update the event id\n event.replaceLocalEventId(newEventId!);\n\n const { shouldLiveInRoom, threadId } = this.eventShouldLiveIn(event);\n const thread = threadId ? this.getThread(threadId) : undefined;\n thread?.setEventMetadata(event);\n thread?.timelineSet.replaceEventId(oldEventId, newEventId!);\n\n if (shouldLiveInRoom) {\n // if the event was already in the timeline (which will be the case if\n // opts.pendingEventOrdering==chronological), we need to update the\n // timeline map.\n for (const timelineSet of this.timelineSets) {\n timelineSet.replaceEventId(oldEventId, newEventId!);\n }\n }\n } else if (newStatus == EventStatus.CANCELLED) {\n // remove it from the pending event list, or the timeline.\n if (this.pendingEventList) {\n const removedEvent = this.getPendingEvent(oldEventId);\n this.removePendingEvent(oldEventId);\n if (removedEvent?.isRedaction()) {\n this.revertRedactionLocalEcho(removedEvent);\n }\n }\n this.removeEvent(oldEventId);\n }\n this.savePendingEvents();\n\n this.emit(RoomEvent.LocalEchoUpdated, event, this, oldEventId, oldStatus);\n }\n\n private revertRedactionLocalEcho(redactionEvent: MatrixEvent): void {\n const redactId = redactionEvent.event.redacts;\n if (!redactId) {\n return;\n }\n const redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId);\n if (redactedEvent) {\n redactedEvent.unmarkLocallyRedacted();\n // re-render after undoing redaction\n this.emit(RoomEvent.RedactionCancelled, redactionEvent, this);\n // reapply relation now redaction failed\n if (redactedEvent.isRelation()) {\n this.aggregateNonLiveRelation(redactedEvent);\n }\n }\n }\n\n /**\n * Add some events to this room. This can include state events, message\n * events and typing notifications. These events are treated as \"live\" so\n * they will go to the end of the timeline.\n *\n * @param events - A list of events to add.\n * @param addLiveEventOptions - addLiveEvent options\n * @throws If `duplicateStrategy` is not falsey, 'replace' or 'ignore'.\n */\n public addLiveEvents(events: MatrixEvent[], addLiveEventOptions?: IAddLiveEventOptions): void;\n /**\n * @deprecated In favor of the overload with `IAddLiveEventOptions`\n */\n public addLiveEvents(events: MatrixEvent[], duplicateStrategy?: DuplicateStrategy, fromCache?: boolean): void;\n public addLiveEvents(\n events: MatrixEvent[],\n duplicateStrategyOrOpts?: DuplicateStrategy | IAddLiveEventOptions,\n fromCache = false,\n ): void {\n let duplicateStrategy: DuplicateStrategy | undefined = duplicateStrategyOrOpts as DuplicateStrategy;\n let timelineWasEmpty: boolean | undefined = false;\n if (typeof duplicateStrategyOrOpts === \"object\") {\n ({\n duplicateStrategy,\n fromCache = false,\n /* roomState, (not used here) */\n timelineWasEmpty,\n } = duplicateStrategyOrOpts);\n } else if (duplicateStrategyOrOpts !== undefined) {\n // Deprecation warning\n // FIXME: Remove after 2023-06-01 (technical debt)\n logger.warn(\n \"Overload deprecated: \" +\n \"`Room.addLiveEvents(events, duplicateStrategy?, fromCache?)` \" +\n \"is deprecated in favor of the overload with `Room.addLiveEvents(events, IAddLiveEventOptions)`\",\n );\n }\n\n if (duplicateStrategy && [\"replace\", \"ignore\"].indexOf(duplicateStrategy) === -1) {\n throw new Error(\"duplicateStrategy MUST be either 'replace' or 'ignore'\");\n }\n\n // sanity check that the live timeline is still live\n for (let i = 0; i < this.timelineSets.length; i++) {\n const liveTimeline = this.timelineSets[i].getLiveTimeline();\n if (liveTimeline.getPaginationToken(EventTimeline.FORWARDS)) {\n throw new Error(\n \"live timeline \" +\n i +\n \" is no longer live - it has a pagination token \" +\n \"(\" +\n liveTimeline.getPaginationToken(EventTimeline.FORWARDS) +\n \")\",\n );\n }\n if (liveTimeline.getNeighbouringTimeline(EventTimeline.FORWARDS)) {\n throw new Error(`live timeline ${i} is no longer live - it has a neighbouring timeline`);\n }\n }\n\n const threadRoots = this.findThreadRoots(events);\n const eventsByThread: { [threadId: string]: MatrixEvent[] } = {};\n\n const options: IAddLiveEventOptions = {\n duplicateStrategy,\n fromCache,\n timelineWasEmpty,\n };\n\n for (const event of events) {\n // TODO: We should have a filter to say \"only add state event types X Y Z to the timeline\".\n this.processLiveEvent(event);\n\n if (event.getUnsigned().transaction_id) {\n const existingEvent = this.txnToEvent.get(event.getUnsigned().transaction_id!);\n if (existingEvent) {\n // remote echo of an event we sent earlier\n this.handleRemoteEcho(event, existingEvent);\n continue; // we can skip adding the event to the timeline sets, it is already there\n }\n }\n\n const { shouldLiveInRoom, shouldLiveInThread, threadId } = this.eventShouldLiveIn(\n event,\n events,\n threadRoots,\n );\n\n if (shouldLiveInThread && !eventsByThread[threadId ?? \"\"]) {\n eventsByThread[threadId ?? \"\"] = [];\n }\n eventsByThread[threadId ?? \"\"]?.push(event);\n\n if (shouldLiveInRoom) {\n this.addLiveEvent(event, options);\n }\n }\n\n Object.entries(eventsByThread).forEach(([threadId, threadEvents]) => {\n this.addThreadedEvents(threadId, threadEvents, false);\n });\n }\n\n public partitionThreadedEvents(\n events: MatrixEvent[],\n ): [timelineEvents: MatrixEvent[], threadedEvents: MatrixEvent[]] {\n // Indices to the events array, for readability\n const ROOM = 0;\n const THREAD = 1;\n if (this.client.supportsThreads()) {\n const threadRoots = this.findThreadRoots(events);\n return events.reduce(\n (memo, event: MatrixEvent) => {\n const { shouldLiveInRoom, shouldLiveInThread, threadId } = this.eventShouldLiveIn(\n event,\n events,\n threadRoots,\n );\n\n if (shouldLiveInRoom) {\n memo[ROOM].push(event);\n }\n\n if (shouldLiveInThread) {\n event.setThreadId(threadId ?? \"\");\n memo[THREAD].push(event);\n }\n\n return memo;\n },\n [[] as MatrixEvent[], [] as MatrixEvent[]],\n );\n } else {\n // When `experimentalThreadSupport` is disabled treat all events as timelineEvents\n return [events as MatrixEvent[], [] as MatrixEvent[]];\n }\n }\n\n /**\n * Given some events, find the IDs of all the thread roots that are referred to by them.\n */\n private findThreadRoots(events: MatrixEvent[]): Set {\n const threadRoots = new Set();\n for (const event of events) {\n if (event.isRelation(THREAD_RELATION_TYPE.name)) {\n threadRoots.add(event.relationEventId ?? \"\");\n }\n }\n return threadRoots;\n }\n\n /**\n * Add a receipt event to the room.\n * @param event - The m.receipt event.\n * @param synthetic - True if this event is implicit.\n */\n public addReceipt(event: MatrixEvent, synthetic = false): void {\n const content = event.getContent();\n Object.keys(content).forEach((eventId: string) => {\n Object.keys(content[eventId]).forEach((receiptType: ReceiptType | string) => {\n Object.keys(content[eventId][receiptType]).forEach((userId: string) => {\n const receipt = content[eventId][receiptType][userId] as Receipt;\n const receiptForMainTimeline = !receipt.thread_id || receipt.thread_id === MAIN_ROOM_TIMELINE;\n const receiptDestination: Thread | this | undefined = receiptForMainTimeline\n ? this\n : this.threads.get(receipt.thread_id ?? \"\");\n\n if (receiptDestination) {\n receiptDestination.addReceiptToStructure(\n eventId,\n receiptType as ReceiptType,\n userId,\n receipt,\n synthetic,\n );\n\n // If the read receipt sent for the logged in user matches\n // the last event of the live timeline, then we know for a fact\n // that the user has read that message.\n // We can mark the room as read and not wait for the local echo\n // from synapse\n // This needs to be done after the initial sync as we do not want this\n // logic to run whilst the room is being initialised\n if (this.client.isInitialSyncComplete() && userId === this.client.getUserId()) {\n const lastEvent = receiptDestination.timeline[receiptDestination.timeline.length - 1];\n if (lastEvent && eventId === lastEvent.getId() && userId === lastEvent.getSender()) {\n receiptDestination.setUnread(NotificationCountType.Total, 0);\n receiptDestination.setUnread(NotificationCountType.Highlight, 0);\n }\n }\n } else {\n // The thread does not exist locally, keep the read receipt\n // in a cache locally, and re-apply the `addReceipt` logic\n // when the thread is created\n this.cachedThreadReadReceipts.set(receipt.thread_id!, [\n ...(this.cachedThreadReadReceipts.get(receipt.thread_id!) ?? []),\n { eventId, receiptType, userId, receipt, synthetic },\n ]);\n }\n\n const me = this.client.getUserId();\n // Track the time of the current user's oldest threaded receipt in the room.\n if (userId === me && !receiptForMainTimeline && receipt.ts < this.oldestThreadedReceiptTs) {\n this.oldestThreadedReceiptTs = receipt.ts;\n }\n\n // Track each user's unthreaded read receipt.\n if (!receipt.thread_id && receipt.ts > (this.unthreadedReceipts.get(userId)?.ts ?? 0)) {\n this.unthreadedReceipts.set(userId, receipt);\n }\n });\n });\n });\n\n // send events after we've regenerated the structure & cache, otherwise things that\n // listened for the event would read stale data.\n this.emit(RoomEvent.Receipt, event, this);\n }\n\n /**\n * Adds/handles ephemeral events such as typing notifications and read receipts.\n * @param events - A list of events to process\n */\n public addEphemeralEvents(events: MatrixEvent[]): void {\n for (const event of events) {\n if (event.getType() === EventType.Typing) {\n this.currentState.setTypingEvent(event);\n } else if (event.getType() === EventType.Receipt) {\n this.addReceipt(event);\n } // else ignore - life is too short for us to care about these events\n }\n }\n\n /**\n * Removes events from this room.\n * @param eventIds - A list of eventIds to remove.\n */\n public removeEvents(eventIds: string[]): void {\n for (const eventId of eventIds) {\n this.removeEvent(eventId);\n }\n }\n\n /**\n * Removes a single event from this room.\n *\n * @param eventId - The id of the event to remove\n *\n * @returns true if the event was removed from any of the room's timeline sets\n */\n public removeEvent(eventId: string): boolean {\n let removedAny = false;\n for (const timelineSet of this.timelineSets) {\n const removed = timelineSet.removeEvent(eventId);\n if (removed) {\n if (removed.isRedaction()) {\n this.revertRedactionLocalEcho(removed);\n }\n removedAny = true;\n }\n }\n return removedAny;\n }\n\n /**\n * Recalculate various aspects of the room, including the room name and\n * room summary. Call this any time the room's current state is modified.\n * May fire \"Room.name\" if the room name is updated.\n *\n * @remarks\n * Fires {@link RoomEvent.Name}\n */\n public recalculate(): void {\n // set fake stripped state events if this is an invite room so logic remains\n // consistent elsewhere.\n const membershipEvent = this.currentState.getStateEvents(EventType.RoomMember, this.myUserId);\n if (membershipEvent) {\n const membership = membershipEvent.getContent().membership;\n this.updateMyMembership(membership!);\n\n if (membership === \"invite\") {\n const strippedStateEvents = membershipEvent.getUnsigned().invite_room_state || [];\n strippedStateEvents.forEach((strippedEvent) => {\n const existingEvent = this.currentState.getStateEvents(strippedEvent.type, strippedEvent.state_key);\n if (!existingEvent) {\n // set the fake stripped event instead\n this.currentState.setStateEvents([\n new MatrixEvent({\n type: strippedEvent.type,\n state_key: strippedEvent.state_key,\n content: strippedEvent.content,\n event_id: \"$fake\" + Date.now(),\n room_id: this.roomId,\n user_id: this.myUserId, // technically a lie\n }),\n ]);\n }\n });\n }\n }\n\n const oldName = this.name;\n this.name = this.calculateRoomName(this.myUserId);\n this.normalizedName = normalize(this.name);\n this.summary = new RoomSummary(this.roomId, {\n title: this.name,\n });\n\n if (oldName !== this.name) {\n this.emit(RoomEvent.Name, this);\n }\n }\n\n /**\n * Update the room-tag event for the room. The previous one is overwritten.\n * @param event - the m.tag event\n */\n public addTags(event: MatrixEvent): void {\n // event content looks like:\n // content: {\n // tags: {\n // $tagName: { $metadata: $value },\n // $tagName: { $metadata: $value },\n // }\n // }\n\n // XXX: do we need to deep copy here?\n this.tags = event.getContent().tags || {};\n\n // XXX: we could do a deep-comparison to see if the tags have really\n // changed - but do we want to bother?\n this.emit(RoomEvent.Tags, event, this);\n }\n\n /**\n * Update the account_data events for this room, overwriting events of the same type.\n * @param events - an array of account_data events to add\n */\n public addAccountData(events: MatrixEvent[]): void {\n for (const event of events) {\n if (event.getType() === \"m.tag\") {\n this.addTags(event);\n }\n const eventType = event.getType();\n const lastEvent = this.accountData.get(eventType);\n this.accountData.set(eventType, event);\n this.emit(RoomEvent.AccountData, event, this, lastEvent);\n }\n }\n\n /**\n * Access account_data event of given event type for this room\n * @param type - the type of account_data event to be accessed\n * @returns the account_data event in question\n */\n public getAccountData(type: EventType | string): MatrixEvent | undefined {\n return this.accountData.get(type);\n }\n\n /**\n * Returns whether the syncing user has permission to send a message in the room\n * @returns true if the user should be permitted to send\n * message events into the room.\n */\n public maySendMessage(): boolean {\n return (\n this.getMyMembership() === \"join\" &&\n (this.client.isRoomEncrypted(this.roomId)\n ? this.currentState.maySendEvent(EventType.RoomMessageEncrypted, this.myUserId)\n : this.currentState.maySendEvent(EventType.RoomMessage, this.myUserId))\n );\n }\n\n /**\n * Returns whether the given user has permissions to issue an invite for this room.\n * @param userId - the ID of the Matrix user to check permissions for\n * @returns true if the user should be permitted to issue invites for this room.\n */\n public canInvite(userId: string): boolean {\n let canInvite = this.getMyMembership() === \"join\";\n const powerLevelsEvent = this.currentState.getStateEvents(EventType.RoomPowerLevels, \"\");\n const powerLevels = powerLevelsEvent && powerLevelsEvent.getContent();\n const me = this.getMember(userId);\n if (powerLevels && me && powerLevels.invite > me.powerLevel) {\n canInvite = false;\n }\n return canInvite;\n }\n\n /**\n * Returns the join rule based on the m.room.join_rule state event, defaulting to `invite`.\n * @returns the join_rule applied to this room\n */\n public getJoinRule(): JoinRule {\n return this.currentState.getJoinRule();\n }\n\n /**\n * Returns the history visibility based on the m.room.history_visibility state event, defaulting to `shared`.\n * @returns the history_visibility applied to this room\n */\n public getHistoryVisibility(): HistoryVisibility {\n return this.currentState.getHistoryVisibility();\n }\n\n /**\n * Returns the history visibility based on the m.room.history_visibility state event, defaulting to `shared`.\n * @returns the history_visibility applied to this room\n */\n public getGuestAccess(): GuestAccess {\n return this.currentState.getGuestAccess();\n }\n\n /**\n * Returns the type of the room from the `m.room.create` event content or undefined if none is set\n * @returns the type of the room.\n */\n public getType(): RoomType | string | undefined {\n const createEvent = this.currentState.getStateEvents(EventType.RoomCreate, \"\");\n if (!createEvent) {\n if (!this.getTypeWarning) {\n logger.warn(\"[getType] Room \" + this.roomId + \" does not have an m.room.create event\");\n this.getTypeWarning = true;\n }\n return undefined;\n }\n return createEvent.getContent()[RoomCreateTypeField];\n }\n\n /**\n * Returns whether the room is a space-room as defined by MSC1772.\n * @returns true if the room's type is RoomType.Space\n */\n public isSpaceRoom(): boolean {\n return this.getType() === RoomType.Space;\n }\n\n /**\n * Returns whether the room is a call-room as defined by MSC3417.\n * @returns true if the room's type is RoomType.UnstableCall\n */\n public isCallRoom(): boolean {\n return this.getType() === RoomType.UnstableCall;\n }\n\n /**\n * Returns whether the room is a video room.\n * @returns true if the room's type is RoomType.ElementVideo\n */\n public isElementVideoRoom(): boolean {\n return this.getType() === RoomType.ElementVideo;\n }\n\n /**\n * Find the predecessor of this room.\n *\n * @param msc3946ProcessDynamicPredecessor - if true, look for an\n * m.room.predecessor state event and use it if found (MSC3946).\n * @returns null if this room has no predecessor. Otherwise, returns\n * the roomId, last eventId and viaServers of the predecessor room.\n *\n * If msc3946ProcessDynamicPredecessor is true, use m.predecessor events\n * as well as m.room.create events to find predecessors.\n *\n * Note: if an m.predecessor event is used, eventId may be undefined\n * since last_known_event_id is optional.\n *\n * Note: viaServers may be undefined, and will definitely be undefined if\n * this predecessor comes from a RoomCreate event (rather than a\n * RoomPredecessor, which has the optional via_servers property).\n */\n public findPredecessor(\n msc3946ProcessDynamicPredecessor = false,\n ): { roomId: string; eventId?: string; viaServers?: string[] } | null {\n const currentState = this.getLiveTimeline().getState(EventTimeline.FORWARDS);\n if (!currentState) {\n return null;\n }\n return currentState.findPredecessor(msc3946ProcessDynamicPredecessor);\n }\n\n private roomNameGenerator(state: RoomNameState): string {\n if (this.client.roomNameGenerator) {\n const name = this.client.roomNameGenerator(this.roomId, state);\n if (name !== null) {\n return name;\n }\n }\n\n switch (state.type) {\n case RoomNameType.Actual:\n return state.name;\n case RoomNameType.Generated:\n switch (state.subtype) {\n case \"Inviting\":\n return `Inviting ${memberNamesToRoomName(state.names, state.count)}`;\n default:\n return memberNamesToRoomName(state.names, state.count);\n }\n case RoomNameType.EmptyRoom:\n if (state.oldName) {\n return `Empty room (was ${state.oldName})`;\n } else {\n return \"Empty room\";\n }\n }\n }\n\n /**\n * This is an internal method. Calculates the name of the room from the current\n * room state.\n * @param userId - The client's user ID. Used to filter room members\n * correctly.\n * @param ignoreRoomNameEvent - Return the implicit room name that we'd see if there\n * was no m.room.name event.\n * @returns The calculated room name.\n */\n private calculateRoomName(userId: string, ignoreRoomNameEvent = false): string {\n if (!ignoreRoomNameEvent) {\n // check for an alias, if any. for now, assume first alias is the\n // official one.\n const mRoomName = this.currentState.getStateEvents(EventType.RoomName, \"\");\n if (mRoomName?.getContent().name) {\n return this.roomNameGenerator({\n type: RoomNameType.Actual,\n name: mRoomName.getContent().name,\n });\n }\n }\n\n const alias = this.getCanonicalAlias();\n if (alias) {\n return this.roomNameGenerator({\n type: RoomNameType.Actual,\n name: alias,\n });\n }\n\n const joinedMemberCount = this.currentState.getJoinedMemberCount();\n const invitedMemberCount = this.currentState.getInvitedMemberCount();\n // -1 because these numbers include the syncing user\n let inviteJoinCount = joinedMemberCount + invitedMemberCount - 1;\n\n // get service members (e.g. helper bots) for exclusion\n let excludedUserIds: string[] = [];\n const mFunctionalMembers = this.currentState.getStateEvents(UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name, \"\");\n if (Array.isArray(mFunctionalMembers?.getContent().service_members)) {\n excludedUserIds = mFunctionalMembers!.getContent().service_members;\n }\n\n // get members that are NOT ourselves and are actually in the room.\n let otherNames: string[] = [];\n if (this.summaryHeroes) {\n // if we have a summary, the member state events should be in the room state\n this.summaryHeroes.forEach((userId) => {\n // filter service members\n if (excludedUserIds.includes(userId)) {\n inviteJoinCount--;\n return;\n }\n const member = this.getMember(userId);\n otherNames.push(member ? member.name : userId);\n });\n } else {\n let otherMembers = this.currentState.getMembers().filter((m) => {\n return m.userId !== userId && (m.membership === \"invite\" || m.membership === \"join\");\n });\n otherMembers = otherMembers.filter(({ userId }) => {\n // filter service members\n if (excludedUserIds.includes(userId)) {\n inviteJoinCount--;\n return false;\n }\n return true;\n });\n // make sure members have stable order\n otherMembers.sort((a, b) => utils.compare(a.userId, b.userId));\n // only 5 first members, immitate summaryHeroes\n otherMembers = otherMembers.slice(0, 5);\n otherNames = otherMembers.map((m) => m.name);\n }\n\n if (inviteJoinCount) {\n return this.roomNameGenerator({\n type: RoomNameType.Generated,\n names: otherNames,\n count: inviteJoinCount,\n });\n }\n\n const myMembership = this.getMyMembership();\n // if I have created a room and invited people through\n // 3rd party invites\n if (myMembership == \"join\") {\n const thirdPartyInvites = this.currentState.getStateEvents(EventType.RoomThirdPartyInvite);\n\n if (thirdPartyInvites?.length) {\n const thirdPartyNames = thirdPartyInvites.map((i) => {\n return i.getContent().display_name;\n });\n\n return this.roomNameGenerator({\n type: RoomNameType.Generated,\n subtype: \"Inviting\",\n names: thirdPartyNames,\n count: thirdPartyNames.length + 1,\n });\n }\n }\n\n // let's try to figure out who was here before\n let leftNames = otherNames;\n // if we didn't have heroes, try finding them in the room state\n if (!leftNames.length) {\n leftNames = this.currentState\n .getMembers()\n .filter((m) => {\n return m.userId !== userId && m.membership !== \"invite\" && m.membership !== \"join\";\n })\n .map((m) => m.name);\n }\n\n let oldName: string | undefined;\n if (leftNames.length) {\n oldName = this.roomNameGenerator({\n type: RoomNameType.Generated,\n names: leftNames,\n count: leftNames.length + 1,\n });\n }\n\n return this.roomNameGenerator({\n type: RoomNameType.EmptyRoom,\n oldName,\n });\n }\n\n /**\n * When we receive a new visibility change event:\n *\n * - store this visibility change alongside the timeline, in case we\n * later need to apply it to an event that we haven't received yet;\n * - if we have already received the event whose visibility has changed,\n * patch it to reflect the visibility change and inform listeners.\n */\n private applyNewVisibilityEvent(event: MatrixEvent): void {\n const visibilityChange = event.asVisibilityChange();\n if (!visibilityChange) {\n // The event is ill-formed.\n return;\n }\n\n // Ignore visibility change events that are not emitted by moderators.\n const userId = event.getSender();\n if (!userId) {\n return;\n }\n const isPowerSufficient =\n (EVENT_VISIBILITY_CHANGE_TYPE.name &&\n this.currentState.maySendStateEvent(EVENT_VISIBILITY_CHANGE_TYPE.name, userId)) ||\n (EVENT_VISIBILITY_CHANGE_TYPE.altName &&\n this.currentState.maySendStateEvent(EVENT_VISIBILITY_CHANGE_TYPE.altName, userId));\n if (!isPowerSufficient) {\n // Powerlevel is insufficient.\n return;\n }\n\n // Record this change in visibility.\n // If the event is not in our timeline and we only receive it later,\n // we may need to apply the visibility change at a later date.\n\n const visibilityEventsOnOriginalEvent = this.visibilityEvents.get(visibilityChange.eventId);\n if (visibilityEventsOnOriginalEvent) {\n // It would be tempting to simply erase the latest visibility change\n // but we need to record all of the changes in case the latest change\n // is ever redacted.\n //\n // In practice, linear scans through `visibilityEvents` should be fast.\n // However, to protect against a potential DoS attack, we limit the\n // number of iterations in this loop.\n let index = visibilityEventsOnOriginalEvent.length - 1;\n const min = Math.max(\n 0,\n visibilityEventsOnOriginalEvent.length - MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH,\n );\n for (; index >= min; --index) {\n const target = visibilityEventsOnOriginalEvent[index];\n if (target.getTs() < event.getTs()) {\n break;\n }\n }\n if (index === -1) {\n visibilityEventsOnOriginalEvent.unshift(event);\n } else {\n visibilityEventsOnOriginalEvent.splice(index + 1, 0, event);\n }\n } else {\n this.visibilityEvents.set(visibilityChange.eventId, [event]);\n }\n\n // Finally, let's check if the event is already in our timeline.\n // If so, we need to patch it and inform listeners.\n\n const originalEvent = this.findEventById(visibilityChange.eventId);\n if (!originalEvent) {\n return;\n }\n originalEvent.applyVisibilityEvent(visibilityChange);\n }\n\n private redactVisibilityChangeEvent(event: MatrixEvent): void {\n // Sanity checks.\n if (!event.isVisibilityEvent) {\n throw new Error(\"expected a visibility change event\");\n }\n const relation = event.getRelation();\n const originalEventId = relation?.event_id;\n const visibilityEventsOnOriginalEvent = this.visibilityEvents.get(originalEventId!);\n if (!visibilityEventsOnOriginalEvent) {\n // No visibility changes on the original event.\n // In particular, this change event was not recorded,\n // most likely because it was ill-formed.\n return;\n }\n const index = visibilityEventsOnOriginalEvent.findIndex((change) => change.getId() === event.getId());\n if (index === -1) {\n // This change event was not recorded, most likely because\n // it was ill-formed.\n return;\n }\n // Remove visibility change.\n visibilityEventsOnOriginalEvent.splice(index, 1);\n\n // If we removed the latest visibility change event, propagate changes.\n if (index === visibilityEventsOnOriginalEvent.length) {\n const originalEvent = this.findEventById(originalEventId!);\n if (!originalEvent) {\n return;\n }\n if (index === 0) {\n // We have just removed the only visibility change event.\n this.visibilityEvents.delete(originalEventId!);\n originalEvent.applyVisibilityEvent();\n } else {\n const newEvent = visibilityEventsOnOriginalEvent[visibilityEventsOnOriginalEvent.length - 1];\n const newVisibility = newEvent.asVisibilityChange();\n if (!newVisibility) {\n // Event is ill-formed.\n // This breaks our invariant.\n throw new Error(\"at this stage, visibility changes should be well-formed\");\n }\n originalEvent.applyVisibilityEvent(newVisibility);\n }\n }\n }\n\n /**\n * When we receive an event whose visibility has been altered by\n * a (more recent) visibility change event, patch the event in\n * place so that clients now not to display it.\n *\n * @param event - Any matrix event. If this event has at least one a\n * pending visibility change event, apply the latest visibility\n * change event.\n */\n private applyPendingVisibilityEvents(event: MatrixEvent): void {\n const visibilityEvents = this.visibilityEvents.get(event.getId()!);\n if (!visibilityEvents || visibilityEvents.length == 0) {\n // No pending visibility change in store.\n return;\n }\n const visibilityEvent = visibilityEvents[visibilityEvents.length - 1];\n const visibilityChange = visibilityEvent.asVisibilityChange();\n if (!visibilityChange) {\n return;\n }\n if (visibilityChange.visible) {\n // Events are visible by default, no need to apply a visibility change.\n // Note that we need to keep the visibility changes in `visibilityEvents`,\n // in case we later fetch an older visibility change event that is superseded\n // by `visibilityChange`.\n }\n if (visibilityEvent.getTs() < event.getTs()) {\n // Something is wrong, the visibility change cannot happen before the\n // event. Presumably an ill-formed event.\n return;\n }\n event.applyVisibilityEvent(visibilityChange);\n }\n\n /**\n * Find when a client has gained thread capabilities by inspecting the oldest\n * threaded receipt\n * @returns the timestamp of the oldest threaded receipt\n */\n public getOldestThreadedReceiptTs(): number {\n return this.oldestThreadedReceiptTs;\n }\n\n /**\n * Returns the most recent unthreaded receipt for a given user\n * @param userId - the MxID of the User\n * @returns an unthreaded Receipt. Can be undefined if receipts have been disabled\n * or a user chooses to use private read receipts (or we have simply not received\n * a receipt from this user yet).\n */\n public getLastUnthreadedReceiptFor(userId: string): Receipt | undefined {\n return this.unthreadedReceipts.get(userId);\n }\n\n /**\n * This issue should also be addressed on synapse's side and is tracked as part\n * of https://github.com/matrix-org/synapse/issues/14837\n *\n *\n * We consider a room fully read if the current user has sent\n * the last event in the live timeline of that context and if the read receipt\n * we have on record matches.\n * This also detects all unread threads and applies the same logic to those\n * contexts\n */\n public fixupNotifications(userId: string): void {\n super.fixupNotifications(userId);\n\n const unreadThreads = this.getThreads().filter(\n (thread) => this.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Total) > 0,\n );\n\n for (const thread of unreadThreads) {\n thread.fixupNotifications(userId);\n }\n }\n}\n\n// a map from current event status to a list of allowed next statuses\nconst ALLOWED_TRANSITIONS: Record = {\n [EventStatus.ENCRYPTING]: [EventStatus.SENDING, EventStatus.NOT_SENT, EventStatus.CANCELLED],\n [EventStatus.SENDING]: [EventStatus.ENCRYPTING, EventStatus.QUEUED, EventStatus.NOT_SENT, EventStatus.SENT],\n [EventStatus.QUEUED]: [EventStatus.SENDING, EventStatus.NOT_SENT, EventStatus.CANCELLED],\n [EventStatus.SENT]: [],\n [EventStatus.NOT_SENT]: [EventStatus.SENDING, EventStatus.QUEUED, EventStatus.CANCELLED],\n [EventStatus.CANCELLED]: [],\n};\n\nexport enum RoomNameType {\n EmptyRoom,\n Generated,\n Actual,\n}\n\nexport interface EmptyRoomNameState {\n type: RoomNameType.EmptyRoom;\n oldName?: string;\n}\n\nexport interface GeneratedRoomNameState {\n type: RoomNameType.Generated;\n subtype?: \"Inviting\";\n names: string[];\n count: number;\n}\n\nexport interface ActualRoomNameState {\n type: RoomNameType.Actual;\n name: string;\n}\n\nexport type RoomNameState = EmptyRoomNameState | GeneratedRoomNameState | ActualRoomNameState;\n\n// Can be overriden by IMatrixClientCreateOpts::memberNamesToRoomNameFn\nfunction memberNamesToRoomName(names: string[], count: number): string {\n const countWithoutMe = count - 1;\n if (!names.length) {\n return \"Empty room\";\n } else if (names.length === 1 && countWithoutMe <= 1) {\n return names[0];\n } else if (names.length === 2 && countWithoutMe <= 2) {\n return `${names[0]} and ${names[1]}`;\n } else {\n const plural = countWithoutMe > 1;\n if (plural) {\n return `${names[0]} and ${countWithoutMe} others`;\n } else {\n return `${names[0]} and 1 other`;\n }\n }\n}\n", - "/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventContext } from \"./event-context\";\nimport { EventMapper } from \"../event-mapper\";\nimport { IResultContext, ISearchResult } from \"../@types/search\";\n\nexport class SearchResult {\n /**\n * Create a SearchResponse from the response to /search\n */\n\n public static fromJson(jsonObj: ISearchResult, eventMapper: EventMapper): SearchResult {\n const jsonContext = jsonObj.context || ({} as IResultContext);\n let eventsBefore = (jsonContext.events_before || []).map(eventMapper);\n let eventsAfter = (jsonContext.events_after || []).map(eventMapper);\n\n const context = new EventContext(eventMapper(jsonObj.result));\n\n // Filter out any contextual events which do not correspond to the same timeline (thread or room)\n const threadRootId = context.ourEvent.threadRootId;\n eventsBefore = eventsBefore.filter((e) => e.threadRootId === threadRootId);\n eventsAfter = eventsAfter.filter((e) => e.threadRootId === threadRootId);\n\n context.setPaginateToken(jsonContext.start, true);\n context.addEvents(eventsBefore, true);\n context.addEvents(eventsAfter, false);\n context.setPaginateToken(jsonContext.end, false);\n\n return new SearchResult(jsonObj.rank, context);\n }\n\n /**\n * Construct a new SearchResult\n *\n * @param rank - where this SearchResult ranks in the results\n * @param context - the matching event and its\n * context\n */\n public constructor(public readonly rank: number, public readonly context: EventContext) {}\n}\n", - "/*\nCopyright 2021 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { Optional } from \"matrix-events-sdk\";\n\nimport { MatrixClient, PendingEventOrdering } from \"../client\";\nimport { TypedReEmitter } from \"../ReEmitter\";\nimport { RelationType } from \"../@types/event\";\nimport { IThreadBundledRelationship, MatrixEvent, MatrixEventEvent } from \"./event\";\nimport { Direction, EventTimeline } from \"./event-timeline\";\nimport { EventTimelineSet, EventTimelineSetHandlerMap } from \"./event-timeline-set\";\nimport { NotificationCountType, Room, RoomEvent } from \"./room\";\nimport { RoomState } from \"./room-state\";\nimport { ServerControlledNamespacedValue } from \"../NamespacedValue\";\nimport { logger } from \"../logger\";\nimport { ReadReceipt } from \"./read-receipt\";\nimport { CachedReceiptStructure, ReceiptType } from \"../@types/read_receipts\";\n\nexport enum ThreadEvent {\n New = \"Thread.new\",\n Update = \"Thread.update\",\n NewReply = \"Thread.newReply\",\n ViewThread = \"Thread.viewThread\",\n Delete = \"Thread.delete\",\n}\n\ntype EmittedEvents = Exclude | RoomEvent.Timeline | RoomEvent.TimelineReset;\n\nexport type EventHandlerMap = {\n [ThreadEvent.Update]: (thread: Thread) => void;\n [ThreadEvent.NewReply]: (thread: Thread, event: MatrixEvent) => void;\n [ThreadEvent.ViewThread]: () => void;\n [ThreadEvent.Delete]: (thread: Thread) => void;\n} & EventTimelineSetHandlerMap;\n\ninterface IThreadOpts {\n room: Room;\n client: MatrixClient;\n pendingEventOrdering?: PendingEventOrdering;\n receipts?: CachedReceiptStructure[];\n}\n\nexport enum FeatureSupport {\n None = 0,\n Experimental = 1,\n Stable = 2,\n}\n\nexport function determineFeatureSupport(stable: boolean, unstable: boolean): FeatureSupport {\n if (stable) {\n return FeatureSupport.Stable;\n } else if (unstable) {\n return FeatureSupport.Experimental;\n } else {\n return FeatureSupport.None;\n }\n}\n\nexport class Thread extends ReadReceipt {\n public static hasServerSideSupport = FeatureSupport.None;\n public static hasServerSideListSupport = FeatureSupport.None;\n public static hasServerSideFwdPaginationSupport = FeatureSupport.None;\n\n /**\n * A reference to all the events ID at the bottom of the threads\n */\n public readonly timelineSet: EventTimelineSet;\n public timeline: MatrixEvent[] = [];\n\n private _currentUserParticipated = false;\n\n private reEmitter: TypedReEmitter;\n\n private lastEvent: MatrixEvent | undefined;\n private replyCount = 0;\n private lastPendingEvent: MatrixEvent | undefined;\n private pendingReplyCount = 0;\n\n public readonly room: Room;\n public readonly client: MatrixClient;\n private readonly pendingEventOrdering: PendingEventOrdering;\n\n public initialEventsFetched = !Thread.hasServerSideSupport;\n /**\n * An array of events to add to the timeline once the thread has been initialised\n * with server suppport.\n */\n public replayEvents: MatrixEvent[] | null = [];\n\n public constructor(public readonly id: string, public rootEvent: MatrixEvent | undefined, opts: IThreadOpts) {\n super();\n\n if (!opts?.room) {\n // Logging/debugging for https://github.com/vector-im/element-web/issues/22141\n // Hope is that we end up with a more obvious stack trace.\n throw new Error(\"element-web#22141: A thread requires a room in order to function\");\n }\n\n this.room = opts.room;\n this.client = opts.client;\n this.pendingEventOrdering = opts.pendingEventOrdering ?? PendingEventOrdering.Chronological;\n this.timelineSet = new EventTimelineSet(\n this.room,\n {\n timelineSupport: true,\n pendingEvents: true,\n },\n this.client,\n this,\n );\n this.reEmitter = new TypedReEmitter(this);\n\n this.reEmitter.reEmit(this.timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n\n this.room.on(MatrixEventEvent.BeforeRedaction, this.onBeforeRedaction);\n this.room.on(RoomEvent.Redaction, this.onRedaction);\n this.room.on(RoomEvent.LocalEchoUpdated, this.onLocalEcho);\n this.timelineSet.on(RoomEvent.Timeline, this.onTimelineEvent);\n\n this.processReceipts(opts.receipts);\n\n // even if this thread is thought to be originating from this client, we initialise it as we may be in a\n // gappy sync and a thread around this event may already exist.\n this.updateThreadMetadata();\n this.setEventMetadata(this.rootEvent);\n }\n\n private async fetchRootEvent(): Promise {\n this.rootEvent = this.room.findEventById(this.id);\n // If the rootEvent does not exist in the local stores, then fetch it from the server.\n try {\n const eventData = await this.client.fetchRoomEvent(this.roomId, this.id);\n const mapper = this.client.getEventMapper();\n this.rootEvent = mapper(eventData); // will merge with existing event object if such is known\n } catch (e) {\n logger.error(\"Failed to fetch thread root to construct thread with\", e);\n }\n await this.processEvent(this.rootEvent);\n }\n\n public static setServerSideSupport(status: FeatureSupport): void {\n Thread.hasServerSideSupport = status;\n if (status !== FeatureSupport.Stable) {\n FILTER_RELATED_BY_SENDERS.setPreferUnstable(true);\n FILTER_RELATED_BY_REL_TYPES.setPreferUnstable(true);\n THREAD_RELATION_TYPE.setPreferUnstable(true);\n }\n }\n\n public static setServerSideListSupport(status: FeatureSupport): void {\n Thread.hasServerSideListSupport = status;\n }\n\n public static setServerSideFwdPaginationSupport(status: FeatureSupport): void {\n Thread.hasServerSideFwdPaginationSupport = status;\n }\n\n private onBeforeRedaction = (event: MatrixEvent, redaction: MatrixEvent): void => {\n if (\n event?.isRelation(THREAD_RELATION_TYPE.name) &&\n this.room.eventShouldLiveIn(event).threadId === this.id &&\n event.getId() !== this.id && // the root event isn't counted in the length so ignore this redaction\n !redaction.status // only respect it when it succeeds\n ) {\n this.replyCount--;\n this.updatePendingReplyCount();\n this.emit(ThreadEvent.Update, this);\n }\n };\n\n private onRedaction = async (event: MatrixEvent): Promise => {\n if (event.threadRootId !== this.id) return; // ignore redactions for other timelines\n if (this.replyCount <= 0) {\n for (const threadEvent of this.timeline) {\n this.clearEventMetadata(threadEvent);\n }\n this.lastEvent = this.rootEvent;\n this._currentUserParticipated = false;\n this.emit(ThreadEvent.Delete, this);\n } else {\n await this.updateThreadMetadata();\n }\n };\n\n private onTimelineEvent = (\n event: MatrixEvent,\n room: Room | undefined,\n toStartOfTimeline: boolean | undefined,\n ): void => {\n // Add a synthesized receipt when paginating forward in the timeline\n if (!toStartOfTimeline) {\n room!.addLocalEchoReceipt(event.getSender()!, event, ReceiptType.Read);\n }\n this.onEcho(event, toStartOfTimeline ?? false);\n };\n\n private onLocalEcho = (event: MatrixEvent): void => {\n this.onEcho(event, false);\n };\n\n private onEcho = async (event: MatrixEvent, toStartOfTimeline: boolean): Promise => {\n if (event.threadRootId !== this.id) return; // ignore echoes for other timelines\n if (this.lastEvent === event) return; // ignore duplicate events\n await this.updateThreadMetadata();\n if (!event.isRelation(THREAD_RELATION_TYPE.name)) return; // don't send a new reply event for reactions or edits\n if (toStartOfTimeline) return; // ignore messages added to the start of the timeline\n this.emit(ThreadEvent.NewReply, this, event);\n };\n\n public get roomState(): RoomState {\n return this.room.getLiveTimeline().getState(EventTimeline.FORWARDS)!;\n }\n\n private addEventToTimeline(event: MatrixEvent, toStartOfTimeline: boolean): void {\n if (!this.findEventById(event.getId()!)) {\n this.timelineSet.addEventToTimeline(event, this.liveTimeline, {\n toStartOfTimeline,\n fromCache: false,\n roomState: this.roomState,\n });\n this.timeline = this.events;\n }\n }\n\n public addEvents(events: MatrixEvent[], toStartOfTimeline: boolean): void {\n events.forEach((ev) => this.addEvent(ev, toStartOfTimeline, false));\n this.updateThreadMetadata();\n }\n\n /**\n * Add an event to the thread and updates\n * the tail/root references if needed\n * Will fire \"Thread.update\"\n * @param event - The event to add\n * @param toStartOfTimeline - whether the event is being added\n * to the start (and not the end) of the timeline.\n * @param emit - whether to emit the Update event if the thread was updated or not.\n */\n public async addEvent(event: MatrixEvent, toStartOfTimeline: boolean, emit = true): Promise {\n this.setEventMetadata(event);\n\n const lastReply = this.lastReply();\n const isNewestReply = !lastReply || event.localTimestamp >= lastReply!.localTimestamp;\n\n // Add all incoming events to the thread's timeline set when there's no server support\n if (!Thread.hasServerSideSupport) {\n // all the relevant membership info to hydrate events with a sender\n // is held in the main room timeline\n // We want to fetch the room state from there and pass it down to this thread\n // timeline set to let it reconcile an event with its relevant RoomMember\n this.addEventToTimeline(event, toStartOfTimeline);\n\n this.client.decryptEventIfNeeded(event, {});\n } else if (!toStartOfTimeline && this.initialEventsFetched && isNewestReply) {\n this.addEventToTimeline(event, false);\n this.fetchEditsWhereNeeded(event);\n } else if (event.isRelation(RelationType.Annotation) || event.isRelation(RelationType.Replace)) {\n if (!this.initialEventsFetched) {\n /**\n * A thread can be fully discovered via a single sync response\n * And when that's the case we still ask the server to do an initialisation\n * as it's the safest to ensure we have everything.\n * However when we are in that scenario we might loose annotation or edits\n *\n * This fix keeps a reference to those events and replay them once the thread\n * has been initialised properly.\n */\n this.replayEvents?.push(event);\n } else {\n this.addEventToTimeline(event, toStartOfTimeline);\n }\n // Apply annotations and replace relations to the relations of the timeline only\n this.timelineSet.relations?.aggregateParentEvent(event);\n this.timelineSet.relations?.aggregateChildEvent(event, this.timelineSet);\n return;\n }\n\n // If no thread support exists we want to count all thread relation\n // added as a reply. We can't rely on the bundled relationships count\n if ((!Thread.hasServerSideSupport || !this.rootEvent) && event.isRelation(THREAD_RELATION_TYPE.name)) {\n this.replyCount++;\n }\n\n if (emit) {\n this.emit(ThreadEvent.NewReply, this, event);\n this.updateThreadMetadata();\n }\n }\n\n public async processEvent(event: Optional): Promise {\n if (event) {\n this.setEventMetadata(event);\n await this.fetchEditsWhereNeeded(event);\n }\n this.timeline = this.events;\n }\n\n /**\n * Processes the receipts that were caught during initial sync\n * When clients become aware of a thread, they try to retrieve those read receipts\n * and apply them to the current thread\n * @param receipts - A collection of the receipts cached from initial sync\n */\n private processReceipts(receipts: CachedReceiptStructure[] = []): void {\n for (const { eventId, receiptType, userId, receipt, synthetic } of receipts) {\n this.addReceiptToStructure(eventId, receiptType as ReceiptType, userId, receipt, synthetic);\n }\n }\n\n private getRootEventBundledRelationship(rootEvent = this.rootEvent): IThreadBundledRelationship | undefined {\n return rootEvent?.getServerAggregatedRelation(THREAD_RELATION_TYPE.name);\n }\n\n private async processRootEvent(): Promise {\n const bundledRelationship = this.getRootEventBundledRelationship();\n if (Thread.hasServerSideSupport && bundledRelationship) {\n this.replyCount = bundledRelationship.count;\n this._currentUserParticipated = !!bundledRelationship.current_user_participated;\n\n const mapper = this.client.getEventMapper();\n // re-insert roomId\n this.lastEvent = mapper({\n ...bundledRelationship.latest_event,\n room_id: this.roomId,\n });\n this.updatePendingReplyCount();\n await this.processEvent(this.lastEvent);\n }\n }\n\n private updatePendingReplyCount(): void {\n const unfilteredPendingEvents =\n this.pendingEventOrdering === PendingEventOrdering.Detached ? this.room.getPendingEvents() : this.events;\n const pendingEvents = unfilteredPendingEvents.filter(\n (ev) =>\n ev.threadRootId === this.id &&\n ev.isRelation(THREAD_RELATION_TYPE.name) &&\n ev.status !== null &&\n ev.getId() !== this.lastEvent?.getId(),\n );\n this.lastPendingEvent = pendingEvents.length ? pendingEvents[pendingEvents.length - 1] : undefined;\n this.pendingReplyCount = pendingEvents.length;\n }\n\n /**\n * Reset the live timeline of all timelineSets, and start new ones.\n *\n *

This is used when /sync returns a 'limited' timeline. 'Limited' means that there's a gap between the messages\n * /sync returned, and the last known message in our timeline. In such a case, our live timeline isn't live anymore\n * and has to be replaced by a new one. To make sure we can continue paginating our timelines correctly, we have to\n * set new pagination tokens on the old and the new timeline.\n *\n * @param backPaginationToken - token for back-paginating the new timeline\n * @param forwardPaginationToken - token for forward-paginating the old live timeline,\n * if absent or null, all timelines are reset, removing old ones (including the previous live\n * timeline which would otherwise be unable to paginate forwards without this token).\n * Removing just the old live timeline whilst preserving previous ones is not supported.\n */\n public async resetLiveTimeline(\n backPaginationToken?: string | null,\n forwardPaginationToken?: string | null,\n ): Promise {\n const oldLive = this.liveTimeline;\n this.timelineSet.resetLiveTimeline(backPaginationToken ?? undefined, forwardPaginationToken ?? undefined);\n const newLive = this.liveTimeline;\n\n // FIXME: Remove the following as soon as https://github.com/matrix-org/synapse/issues/14830 is resolved.\n //\n // The pagination API for thread timelines currently can't handle the type of pagination tokens returned by sync\n //\n // To make this work anyway, we'll have to transform them into one of the types that the API can handle.\n // One option is passing the tokens to /messages, which can handle sync tokens, and returns the right format.\n // /messages does not return new tokens on requests with a limit of 0.\n // This means our timelines might overlap a slight bit, but that's not an issue, as we deduplicate messages\n // anyway.\n\n let newBackward: string | undefined;\n let oldForward: string | undefined;\n if (backPaginationToken) {\n const res = await this.client.createMessagesRequest(this.roomId, backPaginationToken, 1, Direction.Forward);\n newBackward = res.end;\n }\n if (forwardPaginationToken) {\n const res = await this.client.createMessagesRequest(\n this.roomId,\n forwardPaginationToken,\n 1,\n Direction.Backward,\n );\n oldForward = res.start;\n }\n // Only replace the token if we don't have paginated away from this position already. This situation doesn't\n // occur today, but if the above issue is resolved, we'd have to go down this path.\n if (forwardPaginationToken && oldLive.getPaginationToken(Direction.Forward) === forwardPaginationToken) {\n oldLive.setPaginationToken(oldForward ?? null, Direction.Forward);\n }\n if (backPaginationToken && newLive.getPaginationToken(Direction.Backward) === backPaginationToken) {\n newLive.setPaginationToken(newBackward ?? null, Direction.Backward);\n }\n }\n\n private async updateThreadMetadata(): Promise {\n this.updatePendingReplyCount();\n\n if (Thread.hasServerSideSupport) {\n // Ensure we show *something* as soon as possible, we'll update it as soon as we get better data, but we\n // don't want the thread preview to be empty if we can avoid it\n if (!this.initialEventsFetched) {\n await this.processRootEvent();\n }\n await this.fetchRootEvent();\n }\n await this.processRootEvent();\n\n if (!this.initialEventsFetched) {\n this.initialEventsFetched = true;\n // fetch initial event to allow proper pagination\n try {\n // if the thread has regular events, this will just load the last reply.\n // if the thread is newly created, this will load the root event.\n if (this.replyCount === 0 && this.rootEvent) {\n this.timelineSet.addEventsToTimeline([this.rootEvent], true, this.liveTimeline, null);\n this.liveTimeline.setPaginationToken(null, Direction.Backward);\n } else {\n await this.client.paginateEventTimeline(this.liveTimeline, {\n backwards: true,\n limit: Math.max(1, this.length),\n });\n }\n for (const event of this.replayEvents!) {\n this.addEvent(event, false);\n }\n this.replayEvents = null;\n // just to make sure that, if we've created a timeline window for this thread before the thread itself\n // existed (e.g. when creating a new thread), we'll make sure the panel is force refreshed correctly.\n this.emit(RoomEvent.TimelineReset, this.room, this.timelineSet, true);\n } catch (e) {\n logger.error(\"Failed to load start of newly created thread: \", e);\n this.initialEventsFetched = false;\n }\n }\n\n this.emit(ThreadEvent.Update, this);\n }\n\n // XXX: Workaround for https://github.com/matrix-org/matrix-spec-proposals/pull/2676/files#r827240084\n private async fetchEditsWhereNeeded(...events: MatrixEvent[]): Promise {\n return Promise.all(\n events\n .filter((e) => e.isEncrypted())\n .map((event: MatrixEvent) => {\n if (event.isRelation()) return; // skip - relations don't get edits\n return this.client\n .relations(this.roomId, event.getId()!, RelationType.Replace, event.getType(), {\n limit: 1,\n })\n .then((relations) => {\n if (relations.events.length) {\n event.makeReplaced(relations.events[0]);\n }\n })\n .catch((e) => {\n logger.error(\"Failed to load edits for encrypted thread event\", e);\n });\n }),\n );\n }\n\n public setEventMetadata(event: Optional): void {\n if (event) {\n EventTimeline.setEventMetadata(event, this.roomState, false);\n event.setThread(this);\n }\n }\n\n public clearEventMetadata(event: Optional): void {\n if (event) {\n event.setThread(undefined);\n delete event.event?.unsigned?.[\"m.relations\"]?.[THREAD_RELATION_TYPE.name];\n }\n }\n\n /**\n * Finds an event by ID in the current thread\n */\n public findEventById(eventId: string): MatrixEvent | undefined {\n return this.timelineSet.findEventById(eventId);\n }\n\n /**\n * Return last reply to the thread, if known.\n */\n public lastReply(matches: (ev: MatrixEvent) => boolean = (): boolean => true): MatrixEvent | null {\n for (let i = this.timeline.length - 1; i >= 0; i--) {\n const event = this.timeline[i];\n if (matches(event)) {\n return event;\n }\n }\n return null;\n }\n\n public get roomId(): string {\n return this.room.roomId;\n }\n\n /**\n * The number of messages in the thread\n * Only count rel_type=m.thread as we want to\n * exclude annotations from that number\n */\n public get length(): number {\n return this.replyCount + this.pendingReplyCount;\n }\n\n /**\n * A getter for the last event of the thread.\n * This might be a synthesized event, if so, it will not emit any events to listeners.\n */\n public get replyToEvent(): Optional {\n return this.lastPendingEvent ?? this.lastEvent ?? this.lastReply();\n }\n\n public get events(): MatrixEvent[] {\n return this.liveTimeline.getEvents();\n }\n\n public has(eventId: string): boolean {\n return this.timelineSet.findEventById(eventId) instanceof MatrixEvent;\n }\n\n public get hasCurrentUserParticipated(): boolean {\n return this._currentUserParticipated;\n }\n\n public get liveTimeline(): EventTimeline {\n return this.timelineSet.getLiveTimeline();\n }\n\n public getUnfilteredTimelineSet(): EventTimelineSet {\n return this.timelineSet;\n }\n\n public addReceipt(event: MatrixEvent, synthetic: boolean): void {\n throw new Error(\"Unsupported function on the thread model\");\n }\n\n /**\n * Get the ID of the event that a given user has read up to within this thread,\n * or null if we have received no read receipt (at all) from them.\n * @param userId - The user ID to get read receipt event ID for\n * @param ignoreSynthesized - If true, return only receipts that have been\n * sent by the server, not implicit ones generated\n * by the JS SDK.\n * @returns ID of the latest event that the given user has read, or null.\n */\n public getEventReadUpTo(userId: string, ignoreSynthesized?: boolean): string | null {\n const isCurrentUser = userId === this.client.getUserId();\n const lastReply = this.timeline[this.timeline.length - 1];\n if (isCurrentUser && lastReply) {\n // If the last activity in a thread is prior to the first threaded read receipt\n // sent in the room (suggesting that it was sent before the user started\n // using a client that supported threaded read receipts), we want to\n // consider this thread as read.\n const beforeFirstThreadedReceipt = lastReply.getTs() < this.room.getOldestThreadedReceiptTs();\n const lastReplyId = lastReply.getId();\n // Some unsent events do not have an ID, we do not want to consider them read\n if (beforeFirstThreadedReceipt && lastReplyId) {\n return lastReplyId;\n }\n }\n\n const readUpToId = super.getEventReadUpTo(userId, ignoreSynthesized);\n\n // Check whether the unthreaded read receipt for that user is more recent\n // than the read receipt inside that thread.\n if (lastReply) {\n const unthreadedReceipt = this.room.getLastUnthreadedReceiptFor(userId);\n if (!unthreadedReceipt) {\n return readUpToId;\n }\n\n for (let i = this.timeline?.length - 1; i >= 0; --i) {\n const ev = this.timeline[i];\n // If we encounter the `readUpToId` we do not need to look further\n // there is no \"more recent\" unthreaded read receipt\n if (ev.getId() === readUpToId) return readUpToId;\n\n // Inspecting events from most recent to oldest, we're checking\n // whether an unthreaded read receipt is more recent that the current event.\n // We usually prefer relying on the order of the DAG but in this scenario\n // it is not possible and we have to rely on timestamp\n if (ev.getTs() < unthreadedReceipt.ts) return ev.getId() ?? readUpToId;\n }\n }\n\n return readUpToId;\n }\n\n /**\n * Determine if the given user has read a particular event.\n *\n * It is invalid to call this method with an event that is not part of this thread.\n *\n * This is not a definitive check as it only checks the events that have been\n * loaded client-side at the time of execution.\n * @param userId - The user ID to check the read state of.\n * @param eventId - The event ID to check if the user read.\n * @returns True if the user has read the event, false otherwise.\n */\n public hasUserReadEvent(userId: string, eventId: string): boolean {\n if (userId === this.client.getUserId()) {\n // Consider an event read if it's part of a thread that is before the\n // first threaded receipt sent in that room. It is likely that it is\n // part of a thread that was created before MSC3771 was implemented.\n // Or before the last unthreaded receipt for the logged in user\n const beforeFirstThreadedReceipt =\n (this.lastReply()?.getTs() ?? 0) < this.room.getOldestThreadedReceiptTs();\n const unthreadedReceiptTs = this.room.getLastUnthreadedReceiptFor(userId)?.ts ?? 0;\n const beforeLastUnthreadedReceipt = (this?.lastReply()?.getTs() ?? 0) < unthreadedReceiptTs;\n if (beforeFirstThreadedReceipt || beforeLastUnthreadedReceipt) {\n return true;\n }\n }\n\n return super.hasUserReadEvent(userId, eventId);\n }\n\n public setUnread(type: NotificationCountType, count: number): void {\n return this.room.setThreadUnreadNotificationCount(this.id, type, count);\n }\n}\n\nexport const FILTER_RELATED_BY_SENDERS = new ServerControlledNamespacedValue(\n \"related_by_senders\",\n \"io.element.relation_senders\",\n);\nexport const FILTER_RELATED_BY_REL_TYPES = new ServerControlledNamespacedValue(\n \"related_by_rel_types\",\n \"io.element.relation_types\",\n);\nexport const THREAD_RELATION_TYPE = new ServerControlledNamespacedValue(\"m.thread\", \"io.element.thread\");\n\nexport enum ThreadFilterType {\n \"My\",\n \"All\",\n}\n\nexport function threadFilterTypeToFilter(type: ThreadFilterType | null): \"all\" | \"participated\" {\n switch (type) {\n case ThreadFilterType.My:\n return \"participated\";\n default:\n return \"all\";\n }\n}\n", - "/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// eslint-disable-next-line no-restricted-imports\nimport { EventEmitter } from \"events\";\n\nexport enum EventEmitterEvents {\n NewListener = \"newListener\",\n RemoveListener = \"removeListener\",\n Error = \"error\",\n}\n\ntype AnyListener = (...args: any) => any;\nexport type ListenerMap = { [eventName in E]: AnyListener };\ntype EventEmitterEventListener = (eventName: string, listener: AnyListener) => void;\ntype EventEmitterErrorListener = (error: Error) => void;\n\nexport type Listener, T extends E | EventEmitterEvents> = T extends E\n ? A[T]\n : T extends EventEmitterEvents\n ? EventEmitterErrorListener\n : EventEmitterEventListener;\n\n/**\n * Typed Event Emitter class which can act as a Base Model for all our model\n * and communication events.\n * This makes it much easier for us to distinguish between events, as we now need\n * to properly type this, so that our events are not stringly-based and prone\n * to silly typos.\n */\nexport class TypedEventEmitter<\n Events extends string,\n Arguments extends ListenerMap,\n SuperclassArguments extends ListenerMap = Arguments,\n> extends EventEmitter {\n public addListener(\n event: T,\n listener: Listener,\n ): this {\n return super.addListener(event, listener);\n }\n\n public emit(event: T, ...args: Parameters): boolean;\n public emit(event: T, ...args: Parameters): boolean;\n public emit(event: T, ...args: any[]): boolean {\n return super.emit(event, ...args);\n }\n\n public eventNames(): (Events | EventEmitterEvents)[] {\n return super.eventNames() as Array;\n }\n\n public listenerCount(event: Events | EventEmitterEvents): number {\n return super.listenerCount(event);\n }\n\n public listeners(event: Events | EventEmitterEvents): ReturnType {\n return super.listeners(event);\n }\n\n public off(event: T, listener: Listener): this {\n return super.off(event, listener);\n }\n\n public on(event: T, listener: Listener): this {\n return super.on(event, listener);\n }\n\n public once(event: T, listener: Listener): this {\n return super.once(event, listener);\n }\n\n public prependListener(\n event: T,\n listener: Listener,\n ): this {\n return super.prependListener(event, listener);\n }\n\n public prependOnceListener(\n event: T,\n listener: Listener,\n ): this {\n return super.prependOnceListener(event, listener);\n }\n\n public removeAllListeners(event?: Events | EventEmitterEvents): this {\n return super.removeAllListeners(event);\n }\n\n public removeListener(\n event: T,\n listener: Listener,\n ): this {\n return super.removeListener(event, listener);\n }\n\n public rawListeners(event: Events | EventEmitterEvents): ReturnType {\n return super.rawListeners(event);\n }\n}\n", - "/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixEvent } from \"./event\";\nimport { TypedEventEmitter } from \"./typed-event-emitter\";\n\nexport enum UserEvent {\n DisplayName = \"User.displayName\",\n AvatarUrl = \"User.avatarUrl\",\n Presence = \"User.presence\",\n CurrentlyActive = \"User.currentlyActive\",\n LastPresenceTs = \"User.lastPresenceTs\",\n}\n\nexport type UserEventHandlerMap = {\n /**\n * Fires whenever any user's display name changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.displayName changed.\n * @example\n * ```\n * matrixClient.on(\"User.displayName\", function(event, user){\n * var newName = user.displayName;\n * });\n * ```\n */\n [UserEvent.DisplayName]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's avatar URL changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.avatarUrl changed.\n * @example\n * ```\n * matrixClient.on(\"User.avatarUrl\", function(event, user){\n * var newUrl = user.avatarUrl;\n * });\n * ```\n */\n [UserEvent.AvatarUrl]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's presence changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.presence changed.\n * @example\n * ```\n * matrixClient.on(\"User.presence\", function(event, user){\n * var newPresence = user.presence;\n * });\n * ```\n */\n [UserEvent.Presence]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's currentlyActive changes.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.currentlyActive changed.\n * @example\n * ```\n * matrixClient.on(\"User.currentlyActive\", function(event, user){\n * var newCurrentlyActive = user.currentlyActive;\n * });\n * ```\n */\n [UserEvent.CurrentlyActive]: (event: MatrixEvent | undefined, user: User) => void;\n /**\n * Fires whenever any user's lastPresenceTs changes,\n * ie. whenever any presence event is received for a user.\n * @param event - The matrix event which caused this event to fire.\n * @param user - The user whose User.lastPresenceTs changed.\n * @example\n * ```\n * matrixClient.on(\"User.lastPresenceTs\", function(event, user){\n * var newlastPresenceTs = user.lastPresenceTs;\n * });\n * ```\n */\n [UserEvent.LastPresenceTs]: (event: MatrixEvent | undefined, user: User) => void;\n};\n\nexport class User extends TypedEventEmitter {\n private modified = -1;\n\n /**\n * The 'displayname' of the user if known.\n * @privateRemarks\n * Should be read-only\n */\n public displayName?: string;\n public rawDisplayName?: string;\n /**\n * The 'avatar_url' of the user if known.\n * @privateRemarks\n * Should be read-only\n */\n public avatarUrl?: string;\n /**\n * The presence status message if known.\n * @privateRemarks\n * Should be read-only\n */\n public presenceStatusMsg?: string;\n /**\n * The presence enum if known.\n * @privateRemarks\n * Should be read-only\n */\n public presence = \"offline\";\n /**\n * Timestamp (ms since the epoch) for when we last received presence data for this user.\n * We can subtract lastActiveAgo from this to approximate an absolute value for when a user was last active.\n * @privateRemarks\n * Should be read-only\n */\n public lastActiveAgo = 0;\n /**\n * The time elapsed in ms since the user interacted proactively with the server,\n * or we saw a message from the user\n * @privateRemarks\n * Should be read-only\n */\n public lastPresenceTs = 0;\n /**\n * Whether we should consider lastActiveAgo to be an approximation\n * and that the user should be seen as active 'now'\n * @privateRemarks\n * Should be read-only\n */\n public currentlyActive = false;\n /**\n * The events describing this user.\n * @privateRemarks\n * Should be read-only\n */\n public events: {\n /** The m.presence event for this user. */\n presence?: MatrixEvent;\n profile?: MatrixEvent;\n } = {};\n\n /**\n * Construct a new User. A User must have an ID and can optionally have extra information associated with it.\n * @param userId - Required. The ID of this user.\n */\n public constructor(public readonly userId: string) {\n super();\n this.displayName = userId;\n this.rawDisplayName = userId;\n this.updateModifiedTime();\n }\n\n /**\n * Update this User with the given presence event. May fire \"User.presence\",\n * \"User.avatarUrl\" and/or \"User.displayName\" if this event updates this user's\n * properties.\n * @param event - The `m.presence` event.\n *\n * @remarks\n * Fires {@link UserEvent.Presence}\n * Fires {@link UserEvent.DisplayName}\n * Fires {@link UserEvent.AvatarUrl}\n */\n public setPresenceEvent(event: MatrixEvent): void {\n if (event.getType() !== \"m.presence\") {\n return;\n }\n const firstFire = this.events.presence === null;\n this.events.presence = event;\n\n const eventsToFire: UserEvent[] = [];\n if (event.getContent().presence !== this.presence || firstFire) {\n eventsToFire.push(UserEvent.Presence);\n }\n if (event.getContent().avatar_url && event.getContent().avatar_url !== this.avatarUrl) {\n eventsToFire.push(UserEvent.AvatarUrl);\n }\n if (event.getContent().displayname && event.getContent().displayname !== this.displayName) {\n eventsToFire.push(UserEvent.DisplayName);\n }\n if (\n event.getContent().currently_active !== undefined &&\n event.getContent().currently_active !== this.currentlyActive\n ) {\n eventsToFire.push(UserEvent.CurrentlyActive);\n }\n\n this.presence = event.getContent().presence;\n eventsToFire.push(UserEvent.LastPresenceTs);\n\n if (event.getContent().status_msg) {\n this.presenceStatusMsg = event.getContent().status_msg;\n }\n if (event.getContent().displayname) {\n this.displayName = event.getContent().displayname;\n }\n if (event.getContent().avatar_url) {\n this.avatarUrl = event.getContent().avatar_url;\n }\n this.lastActiveAgo = event.getContent().last_active_ago;\n this.lastPresenceTs = Date.now();\n this.currentlyActive = event.getContent().currently_active;\n\n this.updateModifiedTime();\n\n for (const eventToFire of eventsToFire) {\n this.emit(eventToFire, event, this);\n }\n }\n\n /**\n * Manually set this user's display name. No event is emitted in response to this\n * as there is no underlying MatrixEvent to emit with.\n * @param name - The new display name.\n */\n public setDisplayName(name: string): void {\n const oldName = this.displayName;\n this.displayName = name;\n if (name !== oldName) {\n this.updateModifiedTime();\n }\n }\n\n /**\n * Manually set this user's non-disambiguated display name. No event is emitted\n * in response to this as there is no underlying MatrixEvent to emit with.\n * @param name - The new display name.\n */\n public setRawDisplayName(name?: string): void {\n this.rawDisplayName = name;\n }\n\n /**\n * Manually set this user's avatar URL. No event is emitted in response to this\n * as there is no underlying MatrixEvent to emit with.\n * @param url - The new avatar URL.\n */\n public setAvatarUrl(url?: string): void {\n const oldUrl = this.avatarUrl;\n this.avatarUrl = url;\n if (url !== oldUrl) {\n this.updateModifiedTime();\n }\n }\n\n /**\n * Update the last modified time to the current time.\n */\n private updateModifiedTime(): void {\n this.modified = Date.now();\n }\n\n /**\n * Get the timestamp when this User was last updated. This timestamp is\n * updated when this User receives a new Presence event which has updated a\n * property on this object. It is updated before firing events.\n * @returns The timestamp\n */\n public getLastModifiedTime(): number {\n return this.modified;\n }\n\n /**\n * Get the absolute timestamp when this User was last known active on the server.\n * It is *NOT* accurate if this.currentlyActive is true.\n * @returns The timestamp\n */\n public getLastActiveTs(): number {\n return this.lastPresenceTs - this.lastActiveAgo;\n }\n}\n", - "/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { deepCompare, escapeRegExp, globToRegexp, isNullOrUndefined } from \"./utils\";\nimport { logger } from \"./logger\";\nimport { MatrixClient } from \"./client\";\nimport { MatrixEvent } from \"./models/event\";\nimport {\n ConditionKind,\n IAnnotatedPushRule,\n ICallStartedCondition,\n ICallStartedPrefixCondition,\n IContainsDisplayNameCondition,\n IEventMatchCondition,\n IEventPropertyIsCondition,\n IEventPropertyContainsCondition,\n IPushRule,\n IPushRules,\n IRoomMemberCountCondition,\n ISenderNotificationPermissionCondition,\n PushRuleAction,\n PushRuleActionName,\n PushRuleCondition,\n PushRuleKind,\n PushRuleSet,\n RuleId,\n TweakName,\n} from \"./@types/PushRules\";\nimport { EventType } from \"./@types/event\";\n\nconst RULEKINDS_IN_ORDER = [\n PushRuleKind.Override,\n PushRuleKind.ContentSpecific,\n PushRuleKind.RoomSpecific,\n PushRuleKind.SenderSpecific,\n PushRuleKind.Underride,\n];\n\n// The default override rules to apply to the push rules that arrive from the server.\n// We do this for two reasons:\n// 1. Synapse is unlikely to send us the push rule in an incremental sync - see\n// https://github.com/matrix-org/synapse/pull/4867#issuecomment-481446072 for\n// more details.\n// 2. We often want to start using push rules ahead of the server supporting them,\n// and so we can put them here.\nconst DEFAULT_OVERRIDE_RULES: IPushRule[] = [\n {\n // For homeservers which don't support MSC2153 yet\n rule_id: \".m.rule.reaction\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventMatch,\n key: \"type\",\n pattern: \"m.reaction\",\n },\n ],\n actions: [PushRuleActionName.DontNotify],\n },\n {\n rule_id: RuleId.IsUserMention,\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventPropertyContains,\n key: \"content.org\\\\.matrix\\\\.msc3952\\\\.mentions.user_ids\",\n value: \"\", // The user ID is dynamically added in rewriteDefaultRules.\n },\n ],\n actions: [PushRuleActionName.Notify, { set_tweak: TweakName.Highlight }],\n },\n {\n rule_id: RuleId.IsRoomMention,\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventPropertyIs,\n key: \"content.org\\\\.matrix\\\\.msc3952\\\\.mentions.room\",\n value: true,\n },\n {\n kind: ConditionKind.SenderNotificationPermission,\n key: \"room\",\n },\n ],\n actions: [PushRuleActionName.Notify, { set_tweak: TweakName.Highlight }],\n },\n {\n // For homeservers which don't support MSC3786 yet\n rule_id: \".org.matrix.msc3786.rule.room.server_acl\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventMatch,\n key: \"type\",\n pattern: EventType.RoomServerAcl,\n },\n {\n kind: ConditionKind.EventMatch,\n key: \"state_key\",\n pattern: \"\",\n },\n ],\n actions: [],\n },\n];\n\nconst DEFAULT_UNDERRIDE_RULES: IPushRule[] = [\n {\n // For homeservers which don't support MSC3914 yet\n rule_id: \".org.matrix.msc3914.rule.room.call\",\n default: true,\n enabled: true,\n conditions: [\n {\n kind: ConditionKind.EventMatch,\n key: \"type\",\n pattern: \"org.matrix.msc3401.call\",\n },\n {\n kind: ConditionKind.CallStarted,\n },\n ],\n actions: [PushRuleActionName.Notify, { set_tweak: TweakName.Sound, value: \"default\" }],\n },\n];\n\nexport interface IActionsObject {\n /** Whether this event should notify the user or not. */\n notify: boolean;\n /** How this event should be notified. */\n tweaks: Partial>;\n}\n\nexport class PushProcessor {\n /**\n * Construct a Push Processor.\n * @param client - The Matrix client object to use\n */\n public constructor(private readonly client: MatrixClient) {}\n\n /**\n * Maps the original key from the push rules to a list of property names\n * after unescaping.\n */\n private readonly parsedKeys = new Map();\n\n /**\n * Convert a list of actions into a object with the actions as keys and their values\n * @example\n * eg. `[ 'notify', { set_tweak: 'sound', value: 'default' } ]`\n * becomes `{ notify: true, tweaks: { sound: 'default' } }`\n * @param actionList - The actions list\n *\n * @returns A object with key 'notify' (true or false) and an object of actions\n */\n public static actionListToActionsObject(actionList: PushRuleAction[]): IActionsObject {\n const actionObj: IActionsObject = { notify: false, tweaks: {} };\n for (const action of actionList) {\n if (action === PushRuleActionName.Notify) {\n actionObj.notify = true;\n } else if (typeof action === \"object\") {\n if (action.value === undefined) {\n action.value = true;\n }\n actionObj.tweaks[action.set_tweak] = action.value;\n }\n }\n return actionObj;\n }\n\n /**\n * Rewrites conditions on a client's push rules to match the defaults\n * where applicable. Useful for upgrading push rules to more strict\n * conditions when the server is falling behind on defaults.\n * @param incomingRules - The client's existing push rules\n * @param userId - The Matrix ID of the client.\n * @returns The rewritten rules\n */\n public static rewriteDefaultRules(incomingRules: IPushRules, userId: string | undefined = undefined): IPushRules {\n let newRules: IPushRules = JSON.parse(JSON.stringify(incomingRules)); // deep clone\n\n // These lines are mostly to make the tests happy. We shouldn't run into these\n // properties missing in practice.\n if (!newRules) newRules = {} as IPushRules;\n if (!newRules.global) newRules.global = {} as PushRuleSet;\n if (!newRules.global.override) newRules.global.override = [];\n if (!newRules.global.underride) newRules.global.underride = [];\n\n // Merge the client-level defaults with the ones from the server\n const globalOverrides = newRules.global.override;\n for (const originalOverride of DEFAULT_OVERRIDE_RULES) {\n const existingRule = globalOverrides.find((r) => r.rule_id === originalOverride.rule_id);\n\n // Dynamically add the user ID as the value for the is_user_mention rule.\n let override: IPushRule;\n if (originalOverride.rule_id === RuleId.IsUserMention) {\n // If the user ID wasn't provided, skip the rule.\n if (!userId) {\n continue;\n }\n\n override = JSON.parse(JSON.stringify(originalOverride)); // deep clone\n override.conditions![0].value = userId;\n } else {\n override = originalOverride;\n }\n\n if (existingRule) {\n // Copy over the actions, default, and conditions. Don't touch the user's preference.\n existingRule.default = override.default;\n existingRule.conditions = override.conditions;\n existingRule.actions = override.actions;\n } else {\n // Add the rule\n const ruleId = override.rule_id;\n logger.warn(`Adding default global override for ${ruleId}`);\n globalOverrides.push(override);\n }\n }\n\n const globalUnderrides = newRules.global.underride ?? [];\n for (const underride of DEFAULT_UNDERRIDE_RULES) {\n const existingRule = globalUnderrides.find((r) => r.rule_id === underride.rule_id);\n\n if (existingRule) {\n // Copy over the actions, default, and conditions. Don't touch the user's preference.\n existingRule.default = underride.default;\n existingRule.conditions = underride.conditions;\n existingRule.actions = underride.actions;\n } else {\n // Add the rule\n const ruleId = underride.rule_id;\n logger.warn(`Adding default global underride for ${ruleId}`);\n globalUnderrides.push(underride);\n }\n }\n\n return newRules;\n }\n\n /**\n * Pre-caches the parsed keys for push rules and cleans out any obsolete cache\n * entries. Should be called after push rules are updated.\n * @param newRules - The new push rules.\n */\n public updateCachedPushRuleKeys(newRules: IPushRules): void {\n // These lines are mostly to make the tests happy. We shouldn't run into these\n // properties missing in practice.\n if (!newRules) newRules = {} as IPushRules;\n if (!newRules.global) newRules.global = {} as PushRuleSet;\n if (!newRules.global.override) newRules.global.override = [];\n if (!newRules.global.room) newRules.global.room = [];\n if (!newRules.global.sender) newRules.global.sender = [];\n if (!newRules.global.underride) newRules.global.underride = [];\n\n // Process the 'key' property on event_match conditions pre-cache the\n // values and clean-out any unused values.\n const toRemoveKeys = new Set(this.parsedKeys.keys());\n for (const ruleset of [\n newRules.global.override,\n newRules.global.room,\n newRules.global.sender,\n newRules.global.underride,\n ]) {\n for (const rule of ruleset) {\n if (!rule.conditions) {\n continue;\n }\n\n for (const condition of rule.conditions) {\n if (condition.kind !== ConditionKind.EventMatch) {\n continue;\n }\n\n // Ensure we keep this key.\n toRemoveKeys.delete(condition.key);\n\n // Pre-process the key.\n this.parsedKeys.set(condition.key, PushProcessor.partsForDottedKey(condition.key));\n }\n }\n }\n // Any keys that were previously cached, but are no longer needed should\n // be removed.\n toRemoveKeys.forEach((k) => this.parsedKeys.delete(k));\n }\n\n private static cachedGlobToRegex: Record = {}; // $glob: RegExp\n\n private matchingRuleFromKindSet(ev: MatrixEvent, kindset: PushRuleSet): IAnnotatedPushRule | null {\n for (const kind of RULEKINDS_IN_ORDER) {\n const ruleset = kindset[kind];\n if (!ruleset) {\n continue;\n }\n\n for (const rule of ruleset) {\n if (!rule.enabled) {\n continue;\n }\n\n const rawrule = this.templateRuleToRaw(kind, rule);\n if (!rawrule) {\n continue;\n }\n\n if (this.ruleMatchesEvent(rawrule, ev)) {\n return {\n ...rule,\n kind,\n };\n }\n }\n }\n return null;\n }\n\n private templateRuleToRaw(\n kind: PushRuleKind,\n tprule: IPushRule,\n ): Pick | null {\n const rawrule: Pick = {\n rule_id: tprule.rule_id,\n actions: tprule.actions,\n conditions: [],\n };\n switch (kind) {\n case PushRuleKind.Underride:\n case PushRuleKind.Override:\n rawrule.conditions = tprule.conditions;\n break;\n case PushRuleKind.RoomSpecific:\n if (!tprule.rule_id) {\n return null;\n }\n rawrule.conditions!.push({\n kind: ConditionKind.EventMatch,\n key: \"room_id\",\n value: tprule.rule_id,\n });\n break;\n case PushRuleKind.SenderSpecific:\n if (!tprule.rule_id) {\n return null;\n }\n rawrule.conditions!.push({\n kind: ConditionKind.EventMatch,\n key: \"user_id\",\n value: tprule.rule_id,\n });\n break;\n case PushRuleKind.ContentSpecific:\n if (!tprule.pattern) {\n return null;\n }\n rawrule.conditions!.push({\n kind: ConditionKind.EventMatch,\n key: \"content.body\",\n pattern: tprule.pattern,\n });\n break;\n }\n return rawrule;\n }\n\n private eventFulfillsCondition(cond: PushRuleCondition, ev: MatrixEvent): boolean {\n switch (cond.kind) {\n case ConditionKind.EventMatch:\n return this.eventFulfillsEventMatchCondition(cond, ev);\n case ConditionKind.EventPropertyIs:\n return this.eventFulfillsEventPropertyIsCondition(cond, ev);\n case ConditionKind.EventPropertyContains:\n return this.eventFulfillsEventPropertyContains(cond, ev);\n case ConditionKind.ContainsDisplayName:\n return this.eventFulfillsDisplayNameCondition(cond, ev);\n case ConditionKind.RoomMemberCount:\n return this.eventFulfillsRoomMemberCountCondition(cond, ev);\n case ConditionKind.SenderNotificationPermission:\n return this.eventFulfillsSenderNotifPermCondition(cond, ev);\n case ConditionKind.CallStarted:\n case ConditionKind.CallStartedPrefix:\n return this.eventFulfillsCallStartedCondition(cond, ev);\n }\n\n // unknown conditions: we previously matched all unknown conditions,\n // but given that rules can be added to the base rules on a server,\n // it's probably better to not match unknown conditions.\n return false;\n }\n\n private eventFulfillsSenderNotifPermCondition(\n cond: ISenderNotificationPermissionCondition,\n ev: MatrixEvent,\n ): boolean {\n const notifLevelKey = cond[\"key\"];\n if (!notifLevelKey) {\n return false;\n }\n\n const room = this.client.getRoom(ev.getRoomId());\n if (!room?.currentState) {\n return false;\n }\n\n // Note that this should not be the current state of the room but the state at\n // the point the event is in the DAG. Unfortunately the js-sdk does not store\n // this.\n return room.currentState.mayTriggerNotifOfType(notifLevelKey, ev.getSender()!);\n }\n\n private eventFulfillsRoomMemberCountCondition(cond: IRoomMemberCountCondition, ev: MatrixEvent): boolean {\n if (!cond.is) {\n return false;\n }\n\n const room = this.client.getRoom(ev.getRoomId());\n if (!room || !room.currentState || !room.currentState.members) {\n return false;\n }\n\n const memberCount = room.currentState.getJoinedMemberCount();\n\n const m = cond.is.match(/^([=<>]*)(\\d*)$/);\n if (!m) {\n return false;\n }\n const ineq = m[1];\n const rhs = parseInt(m[2]);\n if (isNaN(rhs)) {\n return false;\n }\n switch (ineq) {\n case \"\":\n case \"==\":\n return memberCount == rhs;\n case \"<\":\n return memberCount < rhs;\n case \">\":\n return memberCount > rhs;\n case \"<=\":\n return memberCount <= rhs;\n case \">=\":\n return memberCount >= rhs;\n default:\n return false;\n }\n }\n\n private eventFulfillsDisplayNameCondition(cond: IContainsDisplayNameCondition, ev: MatrixEvent): boolean {\n let content = ev.getContent();\n if (ev.isEncrypted() && ev.getClearContent()) {\n content = ev.getClearContent()!;\n }\n if (!content || !content.body || typeof content.body != \"string\") {\n return false;\n }\n\n const room = this.client.getRoom(ev.getRoomId());\n const member = room?.currentState?.getMember(this.client.credentials.userId!);\n if (!member) {\n return false;\n }\n\n const displayName = member.name;\n\n // N.B. we can't use \\b as it chokes on unicode. however \\W seems to be okay\n // as shorthand for [^0-9A-Za-z_].\n const pat = new RegExp(\"(^|\\\\W)\" + escapeRegExp(displayName) + \"(\\\\W|$)\", \"i\");\n return content.body.search(pat) > -1;\n }\n\n /**\n * Check whether the given event matches the push rule condition by fetching\n * the property from the event and comparing against the condition's glob-based\n * pattern.\n * @param cond - The push rule condition to check for a match.\n * @param ev - The event to check for a match.\n */\n private eventFulfillsEventMatchCondition(cond: IEventMatchCondition, ev: MatrixEvent): boolean {\n if (!cond.key) {\n return false;\n }\n\n const val = this.valueForDottedKey(cond.key, ev);\n if (typeof val !== \"string\") {\n return false;\n }\n\n // XXX This does not match in a case-insensitive manner.\n //\n // See https://spec.matrix.org/v1.5/client-server-api/#conditions-1\n if (cond.value) {\n return cond.value === val;\n }\n\n if (typeof cond.pattern !== \"string\") {\n return false;\n }\n\n const regex =\n cond.key === \"content.body\"\n ? this.createCachedRegex(\"(^|\\\\W)\", cond.pattern, \"(\\\\W|$)\")\n : this.createCachedRegex(\"^\", cond.pattern, \"$\");\n\n return !!val.match(regex);\n }\n\n /**\n * Check whether the given event matches the push rule condition by fetching\n * the property from the event and comparing exactly against the condition's\n * value.\n * @param cond - The push rule condition to check for a match.\n * @param ev - The event to check for a match.\n */\n private eventFulfillsEventPropertyIsCondition(cond: IEventPropertyIsCondition, ev: MatrixEvent): boolean {\n if (!cond.key || cond.value === undefined) {\n return false;\n }\n return cond.value === this.valueForDottedKey(cond.key, ev);\n }\n\n /**\n * Check whether the given event matches the push rule condition by fetching\n * the property from the event and comparing exactly against the condition's\n * value.\n * @param cond - The push rule condition to check for a match.\n * @param ev - The event to check for a match.\n */\n private eventFulfillsEventPropertyContains(cond: IEventPropertyContainsCondition, ev: MatrixEvent): boolean {\n if (!cond.key || cond.value === undefined) {\n return false;\n }\n const val = this.valueForDottedKey(cond.key, ev);\n if (!Array.isArray(val)) {\n return false;\n }\n return val.includes(cond.value);\n }\n\n private eventFulfillsCallStartedCondition(\n _cond: ICallStartedCondition | ICallStartedPrefixCondition,\n ev: MatrixEvent,\n ): boolean {\n // Since servers don't support properly sending push notification\n // about MSC3401 call events, we do the handling ourselves\n return (\n [\"m.ring\", \"m.prompt\"].includes(ev.getContent()[\"m.intent\"]) &&\n !(\"m.terminated\" in ev.getContent()) &&\n (ev.getPrevContent()[\"m.terminated\"] !== ev.getContent()[\"m.terminated\"] ||\n deepCompare(ev.getPrevContent(), {}))\n );\n }\n\n private createCachedRegex(prefix: string, glob: string, suffix: string): RegExp {\n if (PushProcessor.cachedGlobToRegex[glob]) {\n return PushProcessor.cachedGlobToRegex[glob];\n }\n PushProcessor.cachedGlobToRegex[glob] = new RegExp(\n prefix + globToRegexp(glob) + suffix,\n \"i\", // Case insensitive\n );\n return PushProcessor.cachedGlobToRegex[glob];\n }\n\n /**\n * Parse the key into the separate fields to search by splitting on\n * unescaped \".\", and then removing any escape characters.\n *\n * @param str - The key of the push rule condition: a dotted field.\n * @returns The unescaped parts to fetch.\n * @internal\n */\n public static partsForDottedKey(str: string): string[] {\n const result = [];\n\n // The current field and whether the previous character was the escape\n // character (a backslash).\n let part = \"\";\n let escaped = false;\n\n // Iterate over each character, and decide whether to append to the current\n // part (following the escape rules) or to start a new part (based on the\n // field separator).\n for (const c of str) {\n // If the previous character was the escape character (a backslash)\n // then decide what to append to the current part.\n if (escaped) {\n if (c === \"\\\\\" || c === \".\") {\n // An escaped backslash or dot just gets added.\n part += c;\n } else {\n // A character that shouldn't be escaped gets the backslash prepended.\n part += \"\\\\\" + c;\n }\n // This always resets being escaped.\n escaped = false;\n continue;\n }\n\n if (c == \".\") {\n // The field separator creates a new part.\n result.push(part);\n part = \"\";\n } else if (c == \"\\\\\") {\n // A backslash adds no characters, but starts an escape sequence.\n escaped = true;\n } else {\n // Otherwise, just add the current character.\n part += c;\n }\n }\n\n // Ensure the final part is included. If there's an open escape sequence\n // it should be included.\n if (escaped) {\n part += \"\\\\\";\n }\n result.push(part);\n\n return result;\n }\n\n /**\n * For a dotted field and event, fetch the value at that position, if one\n * exists.\n *\n * @param key - The key of the push rule condition: a dotted field to fetch.\n * @param ev - The matrix event to fetch the field from.\n * @returns The value at the dotted path given by key.\n */\n private valueForDottedKey(key: string, ev: MatrixEvent): any {\n // The key should already have been parsed via updateCachedPushRuleKeys,\n // but if it hasn't (maybe via an old consumer of the SDK which hasn't\n // been updated?) then lazily calculate it here.\n let parts = this.parsedKeys.get(key);\n if (parts === undefined) {\n parts = PushProcessor.partsForDottedKey(key);\n this.parsedKeys.set(key, parts);\n }\n let val: any;\n\n // special-case the first component to deal with encrypted messages\n const firstPart = parts[0];\n let currentIndex = 0;\n if (firstPart === \"content\") {\n val = ev.getContent();\n ++currentIndex;\n } else if (firstPart === \"type\") {\n val = ev.getType();\n ++currentIndex;\n } else {\n // use the raw event for any other fields\n val = ev.event;\n }\n\n for (; currentIndex < parts.length; ++currentIndex) {\n // The previous iteration resulted in null or undefined, bail (and\n // avoid the type error of attempting to retrieve a property).\n if (isNullOrUndefined(val)) {\n return undefined;\n }\n\n const thisPart = parts[currentIndex];\n val = val[thisPart];\n }\n return val;\n }\n\n private matchingRuleForEventWithRulesets(ev: MatrixEvent, rulesets?: IPushRules): IAnnotatedPushRule | null {\n if (!rulesets) {\n return null;\n }\n if (ev.getSender() === this.client.credentials.userId) {\n return null;\n }\n\n return this.matchingRuleFromKindSet(ev, rulesets.global);\n }\n\n private pushActionsForEventAndRulesets(ev: MatrixEvent, rulesets?: IPushRules): IActionsObject {\n const rule = this.matchingRuleForEventWithRulesets(ev, rulesets);\n if (!rule) {\n return {} as IActionsObject;\n }\n\n const actionObj = PushProcessor.actionListToActionsObject(rule.actions);\n\n // Some actions are implicit in some situations: we add those here\n if (actionObj.tweaks.highlight === undefined) {\n // if it isn't specified, highlight if it's a content\n // rule but otherwise not\n actionObj.tweaks.highlight = rule.kind == PushRuleKind.ContentSpecific;\n }\n\n return actionObj;\n }\n\n public ruleMatchesEvent(rule: Partial & Pick, ev: MatrixEvent): boolean {\n // Disable the deprecated mentions push rules if the new mentions property exists.\n if (\n this.client.supportsIntentionalMentions() &&\n ev.getContent()[\"org.matrix.msc3952.mentions\"] !== undefined &&\n (rule.rule_id === RuleId.ContainsUserName ||\n rule.rule_id === RuleId.ContainsDisplayName ||\n rule.rule_id === RuleId.AtRoomNotification)\n ) {\n return false;\n }\n\n return !rule.conditions?.some((cond) => !this.eventFulfillsCondition(cond, ev));\n }\n\n /**\n * Get the user's push actions for the given event\n */\n public actionsForEvent(ev: MatrixEvent): IActionsObject {\n return this.pushActionsForEventAndRulesets(ev, this.client.pushRules);\n }\n\n /**\n * Get one of the users push rules by its ID\n *\n * @param ruleId - The ID of the rule to search for\n * @returns The push rule, or null if no such rule was found\n */\n public getPushRuleById(ruleId: string): IPushRule | null {\n const result = this.getPushRuleAndKindById(ruleId);\n return result?.rule ?? null;\n }\n\n /**\n * Get one of the users push rules by its ID\n *\n * @param ruleId - The ID of the rule to search for\n * @returns rule The push rule, or null if no such rule was found\n * @returns kind - The PushRuleKind of the rule to search for\n */\n public getPushRuleAndKindById(ruleId: string): { rule: IPushRule; kind: PushRuleKind } | null {\n for (const scope of [\"global\"] as const) {\n if (this.client.pushRules?.[scope] === undefined) continue;\n\n for (const kind of RULEKINDS_IN_ORDER) {\n if (this.client.pushRules[scope][kind] === undefined) continue;\n\n for (const rule of this.client.pushRules[scope][kind]!) {\n if (rule.rule_id === ruleId) return { rule, kind };\n }\n }\n }\n return null;\n }\n}\n", - "/*\nCopyright 2018 New Vector Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nconst LOWERCASE = \"abcdefghijklmnopqrstuvwxyz\";\nconst UPPERCASE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nconst DIGITS = \"0123456789\";\n\nexport function randomString(len: number): string {\n return randomStringFrom(len, UPPERCASE + LOWERCASE + DIGITS);\n}\n\nexport function randomLowercaseString(len: number): string {\n return randomStringFrom(len, LOWERCASE);\n}\n\nexport function randomUppercaseString(len: number): string {\n return randomStringFrom(len, UPPERCASE);\n}\n\nfunction randomStringFrom(len: number, chars: string): string {\n let ret = \"\";\n\n for (let i = 0; i < len; ++i) {\n ret += chars.charAt(Math.floor(Math.random() * chars.length));\n }\n\n return ret;\n}\n", - "/*\nCopyright 2016 OpenMarket Ltd\nCopyright 2019 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/* A re-implementation of the javascript callback functions (setTimeout,\n * clearTimeout; setInterval and clearInterval are not yet implemented) which\n * try to improve handling of large clock jumps (as seen when\n * suspending/resuming the system).\n *\n * In particular, if a timeout would have fired while the system was suspended,\n * it will instead fire as soon as possible after resume.\n */\n\nimport { logger } from \"./logger\";\n\n// we schedule a callback at least this often, to check if we've missed out on\n// some wall-clock time due to being suspended.\nconst TIMER_CHECK_PERIOD_MS = 1000;\n\n// counter, for making up ids to return from setTimeout\nlet count = 0;\n\n// the key for our callback with the real global.setTimeout\nlet realCallbackKey: NodeJS.Timeout | number;\n\ntype Callback = {\n runAt: number;\n func: (...params: any[]) => void;\n params: any[];\n key: number;\n};\n\n// a sorted list of the callbacks to be run.\n// each is an object with keys [runAt, func, params, key].\nconst callbackList: Callback[] = [];\n\n// var debuglog = logger.log.bind(logger);\n/* istanbul ignore next */\nconst debuglog = function (...params: any[]): void {};\n\n/**\n * reimplementation of window.setTimeout, which will call the callback if\n * the wallclock time goes past the deadline.\n *\n * @param func - callback to be called after a delay\n * @param delayMs - number of milliseconds to delay by\n *\n * @returns an identifier for this callback, which may be passed into\n * clearTimeout later.\n */\nexport function setTimeout(func: (...params: any[]) => void, delayMs: number, ...params: any[]): number {\n delayMs = delayMs || 0;\n if (delayMs < 0) {\n delayMs = 0;\n }\n\n const runAt = Date.now() + delayMs;\n const key = count++;\n debuglog(\"setTimeout: scheduling cb\", key, \"at\", runAt, \"(delay\", delayMs, \")\");\n const data = {\n runAt: runAt,\n func: func,\n params: params,\n key: key,\n };\n\n // figure out where it goes in the list\n const idx = binarySearch(callbackList, function (el) {\n return el.runAt - runAt;\n });\n\n callbackList.splice(idx, 0, data);\n scheduleRealCallback();\n\n return key;\n}\n\n/**\n * reimplementation of window.clearTimeout, which mirrors setTimeout\n *\n * @param key - result from an earlier setTimeout call\n */\nexport function clearTimeout(key: number): void {\n if (callbackList.length === 0) {\n return;\n }\n\n // remove the element from the list\n let i: number;\n for (i = 0; i < callbackList.length; i++) {\n const cb = callbackList[i];\n if (cb.key == key) {\n callbackList.splice(i, 1);\n break;\n }\n }\n\n // iff it was the first one in the list, reschedule our callback.\n if (i === 0) {\n scheduleRealCallback();\n }\n}\n\n// use the real global.setTimeout to schedule a callback to runCallbacks.\nfunction scheduleRealCallback(): void {\n if (realCallbackKey) {\n global.clearTimeout(realCallbackKey as NodeJS.Timeout);\n }\n\n const first = callbackList[0];\n\n if (!first) {\n debuglog(\"scheduleRealCallback: no more callbacks, not rescheduling\");\n return;\n }\n\n const timestamp = Date.now();\n const delayMs = Math.min(first.runAt - timestamp, TIMER_CHECK_PERIOD_MS);\n\n debuglog(\"scheduleRealCallback: now:\", timestamp, \"delay:\", delayMs);\n realCallbackKey = global.setTimeout(runCallbacks, delayMs);\n}\n\nfunction runCallbacks(): void {\n const timestamp = Date.now();\n debuglog(\"runCallbacks: now:\", timestamp);\n\n // get the list of things to call\n const callbacksToRun: Callback[] = [];\n // eslint-disable-next-line\n while (true) {\n const first = callbackList[0];\n if (!first || first.runAt > timestamp) {\n break;\n }\n const cb = callbackList.shift()!;\n debuglog(\"runCallbacks: popping\", cb.key);\n callbacksToRun.push(cb);\n }\n\n // reschedule the real callback before running our functions, to\n // keep the codepaths the same whether or not our functions\n // register their own setTimeouts.\n scheduleRealCallback();\n\n for (const cb of callbacksToRun) {\n try {\n cb.func.apply(global, cb.params);\n } catch (e) {\n logger.error(\"Uncaught exception in callback function\", e);\n }\n }\n}\n\n/* search in a sorted array.\n *\n * returns the index of the last element for which func returns\n * greater than zero, or array.length if no such element exists.\n */\nfunction binarySearch(array: T[], func: (v: T) => number): number {\n // min is inclusive, max exclusive.\n let min = 0;\n let max = array.length;\n\n while (min < max) {\n const mid = (min + max) >> 1;\n const res = func(array[mid]);\n if (res > 0) {\n // the element at 'mid' is too big; set it as the new max.\n max = mid;\n } else {\n // the element at 'mid' is too small. 'min' is inclusive, so +1.\n min = mid + 1;\n }\n }\n // presumably, min==max now.\n return min;\n}\n", - "/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/* This file replaces rust-crypto/index.ts when the js-sdk is being built for browserify.\n *\n * It is a stub, so that we do not import the whole of the base64'ed wasm artifact into the browserify bundle.\n * It deliberately does nothing except raise an exception.\n */\n\nimport { IHttpOpts, MatrixHttpApi } from \"../http-api\";\n\nexport async function initRustCrypto(\n _http: MatrixHttpApi,\n _userId: string,\n _deviceId: string,\n): Promise {\n throw new Error(\"Rust crypto is not supported under browserify.\");\n}\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/** The prefix used on indexeddbs created by rust-crypto */\nexport const RUST_SDK_STORE_PREFIX = \"matrix-js-sdk\";\n", - "module.exports = require('/home/runner/work/matrix-js-sdk/matrix-js-sdk/src/rust-crypto/browserify-index.ts');", - "/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module which manages queuing, scheduling and retrying\n * of requests.\n */\nimport * as utils from \"./utils\";\nimport { logger } from \"./logger\";\nimport { MatrixEvent } from \"./models/event\";\nimport { EventType } from \"./@types/event\";\nimport { IDeferred } from \"./utils\";\nimport { ConnectionError, MatrixError } from \"./http-api\";\nimport { ISendEventResponse } from \"./@types/requests\";\n\nconst DEBUG = false; // set true to enable console logging.\n\ninterface IQueueEntry {\n event: MatrixEvent;\n defer: IDeferred;\n attempts: number;\n}\n\n/**\n * The function to invoke to process (send) events in the queue.\n * @param event - The event to send.\n * @returns Resolved/rejected depending on the outcome of the request.\n */\ntype ProcessFunction = (event: MatrixEvent) => Promise;\n\n// eslint-disable-next-line camelcase\nexport class MatrixScheduler {\n /**\n * Retries events up to 4 times using exponential backoff. This produces wait\n * times of 2, 4, 8, and 16 seconds (30s total) after which we give up. If the\n * failure was due to a rate limited request, the time specified in the error is\n * waited before being retried.\n * @param attempts - Number of attempts that have been made, including the one that just failed (ie. starting at 1)\n * @see retryAlgorithm\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public static RETRY_BACKOFF_RATELIMIT(event: MatrixEvent | null, attempts: number, err: MatrixError): number {\n if (err.httpStatus === 400 || err.httpStatus === 403 || err.httpStatus === 401) {\n // client error; no amount of retrying with save you now.\n return -1;\n }\n if (err instanceof ConnectionError) {\n return -1;\n }\n\n // if event that we are trying to send is too large in any way then retrying won't help\n if (err.name === \"M_TOO_LARGE\") {\n return -1;\n }\n\n if (err.name === \"M_LIMIT_EXCEEDED\") {\n const waitTime = err.data.retry_after_ms;\n if (waitTime > 0) {\n return waitTime;\n }\n }\n if (attempts > 4) {\n return -1; // give up\n }\n return 1000 * Math.pow(2, attempts);\n }\n\n /**\n * Queues `m.room.message` events and lets other events continue\n * concurrently.\n * @see queueAlgorithm\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n public static QUEUE_MESSAGES(event: MatrixEvent): string | null {\n // enqueue messages or events that associate with another event (redactions and relations)\n if (event.getType() === EventType.RoomMessage || event.hasAssociation()) {\n // put these events in the 'message' queue.\n return \"message\";\n }\n // allow all other events continue concurrently.\n return null;\n }\n\n // queueName: [{\n // event: MatrixEvent, // event to send\n // defer: Deferred, // defer to resolve/reject at the END of the retries\n // attempts: Number // number of times we've called processFn\n // }, ...]\n private readonly queues: Record[]> = {};\n private activeQueues: string[] = [];\n private procFn: ProcessFunction | null = null;\n\n /**\n * Construct a scheduler for Matrix. Requires\n * {@link MatrixScheduler#setProcessFunction} to be provided\n * with a way of processing events.\n * @param retryAlgorithm - Optional. The retry\n * algorithm to apply when determining when to try to send an event again.\n * Defaults to {@link MatrixScheduler.RETRY_BACKOFF_RATELIMIT}.\n * @param queueAlgorithm - Optional. The queuing\n * algorithm to apply when determining which events should be sent before the\n * given event. Defaults to {@link MatrixScheduler.QUEUE_MESSAGES}.\n */\n public constructor(\n /**\n * The retry algorithm to apply when retrying events. To stop retrying, return\n * `-1`. If this event was part of a queue, it will be removed from\n * the queue.\n * @param event - The event being retried.\n * @param attempts - The number of failed attempts. This will always be \\>= 1.\n * @param err - The most recent error message received when trying\n * to send this event.\n * @returns The number of milliseconds to wait before trying again. If\n * this is 0, the request will be immediately retried. If this is\n * `-1`, the event will be marked as\n * {@link EventStatus.NOT_SENT} and will not be retried.\n */\n public readonly retryAlgorithm = MatrixScheduler.RETRY_BACKOFF_RATELIMIT,\n /**\n * The queuing algorithm to apply to events. This function must be idempotent as\n * it may be called multiple times with the same event. All queues created are\n * serviced in a FIFO manner. To send the event ASAP, return `null`\n * which will not put this event in a queue. Events that fail to send that form\n * part of a queue will be removed from the queue and the next event in the\n * queue will be sent.\n * @param event - The event to be sent.\n * @returns The name of the queue to put the event into. If a queue with\n * this name does not exist, it will be created. If this is `null`,\n * the event is not put into a queue and will be sent concurrently.\n */\n public readonly queueAlgorithm = MatrixScheduler.QUEUE_MESSAGES,\n ) {}\n\n /**\n * Retrieve a queue based on an event. The event provided does not need to be in\n * the queue.\n * @param event - An event to get the queue for.\n * @returns A shallow copy of events in the queue or null.\n * Modifying this array will not modify the list itself. Modifying events in\n * this array will modify the underlying event in the queue.\n * @see MatrixScheduler.removeEventFromQueue To remove an event from the queue.\n */\n public getQueueForEvent(event: MatrixEvent): MatrixEvent[] | null {\n const name = this.queueAlgorithm(event);\n if (!name || !this.queues[name]) {\n return null;\n }\n return this.queues[name].map(function (obj) {\n return obj.event;\n });\n }\n\n /**\n * Remove this event from the queue. The event is equal to another event if they\n * have the same ID returned from event.getId().\n * @param event - The event to remove.\n * @returns True if this event was removed.\n */\n public removeEventFromQueue(event: MatrixEvent): boolean {\n const name = this.queueAlgorithm(event);\n if (!name || !this.queues[name]) {\n return false;\n }\n let removed = false;\n utils.removeElement(this.queues[name], (element) => {\n if (element.event.getId() === event.getId()) {\n // XXX we should probably reject the promise?\n // https://github.com/matrix-org/matrix-js-sdk/issues/496\n removed = true;\n return true;\n }\n return false;\n });\n return removed;\n }\n\n /**\n * Set the process function. Required for events in the queue to be processed.\n * If set after events have been added to the queue, this will immediately start\n * processing them.\n * @param fn - The function that can process events\n * in the queue.\n */\n public setProcessFunction(fn: ProcessFunction): void {\n this.procFn = fn;\n this.startProcessingQueues();\n }\n\n /**\n * Queue an event if it is required and start processing queues.\n * @param event - The event that may be queued.\n * @returns A promise if the event was queued, which will be\n * resolved or rejected in due time, else null.\n */\n public queueEvent(event: MatrixEvent): Promise | null {\n const queueName = this.queueAlgorithm(event);\n if (!queueName) {\n return null;\n }\n // add the event to the queue and make a deferred for it.\n if (!this.queues[queueName]) {\n this.queues[queueName] = [];\n }\n const defer = utils.defer();\n this.queues[queueName].push({\n event: event,\n defer: defer,\n attempts: 0,\n });\n debuglog(\"Queue algorithm dumped event %s into queue '%s'\", event.getId(), queueName);\n this.startProcessingQueues();\n return defer.promise;\n }\n\n private startProcessingQueues(): void {\n if (!this.procFn) return;\n // for each inactive queue with events in them\n Object.keys(this.queues)\n .filter((queueName) => {\n return this.activeQueues.indexOf(queueName) === -1 && this.queues[queueName].length > 0;\n })\n .forEach((queueName) => {\n // mark the queue as active\n this.activeQueues.push(queueName);\n // begin processing the head of the queue\n debuglog(\"Spinning up queue: '%s'\", queueName);\n this.processQueue(queueName);\n });\n }\n\n private processQueue = (queueName: string): void => {\n // get head of queue\n const obj = this.peekNextEvent(queueName);\n if (!obj) {\n this.disableQueue(queueName);\n return;\n }\n debuglog(\"Queue '%s' has %s pending events\", queueName, this.queues[queueName].length);\n // fire the process function and if it resolves, resolve the deferred. Else\n // invoke the retry algorithm.\n\n // First wait for a resolved promise, so the resolve handlers for\n // the deferred of the previously sent event can run.\n // This way enqueued relations/redactions to enqueued events can receive\n // the remove id of their target before being sent.\n Promise.resolve()\n .then(() => {\n return this.procFn!(obj.event);\n })\n .then(\n (res) => {\n // remove this from the queue\n this.removeNextEvent(queueName);\n debuglog(\"Queue '%s' sent event %s\", queueName, obj.event.getId());\n obj.defer.resolve(res);\n // keep processing\n this.processQueue(queueName);\n },\n (err) => {\n obj.attempts += 1;\n // ask the retry algorithm when/if we should try again\n const waitTimeMs = this.retryAlgorithm(obj.event, obj.attempts, err);\n debuglog(\n \"retry(%s) err=%s event_id=%s waitTime=%s\",\n obj.attempts,\n err,\n obj.event.getId(),\n waitTimeMs,\n );\n if (waitTimeMs === -1) {\n // give up (you quitter!)\n debuglog(\"Queue '%s' giving up on event %s\", queueName, obj.event.getId());\n // remove this from the queue\n this.clearQueue(queueName, err);\n } else {\n setTimeout(this.processQueue, waitTimeMs, queueName);\n }\n },\n );\n };\n\n private disableQueue(queueName: string): void {\n // queue is empty. Mark as inactive and stop recursing.\n const index = this.activeQueues.indexOf(queueName);\n if (index >= 0) {\n this.activeQueues.splice(index, 1);\n }\n debuglog(\"Stopping queue '%s' as it is now empty\", queueName);\n }\n\n private clearQueue(queueName: string, err: unknown): void {\n debuglog(\"clearing queue '%s'\", queueName);\n let obj: IQueueEntry | undefined;\n while ((obj = this.removeNextEvent(queueName))) {\n obj.defer.reject(err);\n }\n this.disableQueue(queueName);\n }\n\n private peekNextEvent(queueName: string): IQueueEntry | undefined {\n const queue = this.queues[queueName];\n if (!Array.isArray(queue)) {\n return undefined;\n }\n return queue[0];\n }\n\n private removeNextEvent(queueName: string): IQueueEntry | undefined {\n const queue = this.queues[queueName];\n if (!Array.isArray(queue)) {\n return undefined;\n }\n return queue.shift();\n }\n}\n\n/* istanbul ignore next */\nfunction debuglog(...args: any[]): void {\n if (DEBUG) {\n logger.log(...args);\n }\n}\n", - "/*\nCopyright 2021-2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Implementation of server-side secret storage\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#storage\n */\n\n/**\n * Common base interface for Secret Storage Keys.\n *\n * The common properties for all encryption keys used in server-side secret storage.\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#key-storage\n */\nexport interface SecretStorageKeyDescriptionCommon {\n /** A human-readable name for this key. */\n // XXX: according to the spec, this is optional\n name: string;\n\n /** The encryption algorithm used with this key. */\n algorithm: string;\n\n /** Information for deriving this key from a passphrase. */\n // XXX: according to the spec, this is optional\n passphrase: PassphraseInfo;\n}\n\n/**\n * Properties for a SSSS key using the `m.secret_storage.v1.aes-hmac-sha2` algorithm.\n *\n * Corresponds to `AesHmacSha2KeyDescription` in the specification.\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#msecret_storagev1aes-hmac-sha2\n */\nexport interface SecretStorageKeyDescriptionAesV1 extends SecretStorageKeyDescriptionCommon {\n // XXX: strictly speaking, we should be able to enforce the algorithm here. But\n // this interface ends up being incorrectly used where other algorithms are in use (notably\n // in device-dehydration support), and unpicking that is too much like hard work\n // at the moment.\n // algorithm: \"m.secret_storage.v1.aes-hmac-sha2\";\n\n /** The 16-byte AES initialization vector, encoded as base64. */\n iv: string;\n\n /** The MAC of the result of encrypting 32 bytes of 0, encoded as base64. */\n mac: string;\n}\n\n/**\n * Union type for secret storage keys.\n *\n * For now, this is only {@link SecretStorageKeyDescriptionAesV1}, but other interfaces may be added in future.\n */\nexport type SecretStorageKeyDescription = SecretStorageKeyDescriptionAesV1;\n\n/**\n * Information on how to generate the key from a passphrase.\n *\n * @see https://spec.matrix.org/v1.6/client-server-api/#deriving-keys-from-passphrases\n */\nexport interface PassphraseInfo {\n /** The algorithm to be used to derive the key. */\n algorithm: \"m.pbkdf2\";\n\n /** The number of PBKDF2 iterations to use. */\n iterations: number;\n\n /** The salt to be used for PBKDF2. */\n salt: string;\n\n /** The number of bits to generate. Defaults to 256. */\n bits?: number;\n}\n", - "/*\nCopyright 2019 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport enum SERVICE_TYPES {\n IS = \"SERVICE_TYPE_IS\", // An identity server\n IM = \"SERVICE_TYPE_IM\", // An integration manager\n}\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type { SyncCryptoCallbacks } from \"./common-crypto/CryptoBackend\";\nimport { NotificationCountType, Room, RoomEvent } from \"./models/room\";\nimport { logger } from \"./logger\";\nimport * as utils from \"./utils\";\nimport { EventTimeline } from \"./models/event-timeline\";\nimport { ClientEvent, IStoredClientOpts, MatrixClient } from \"./client\";\nimport {\n ISyncStateData,\n SyncState,\n _createAndReEmitRoom,\n SyncApiOptions,\n defaultClientOpts,\n defaultSyncApiOpts,\n} from \"./sync\";\nimport { MatrixEvent } from \"./models/event\";\nimport { Crypto } from \"./crypto\";\nimport { IMinimalEvent, IRoomEvent, IStateEvent, IStrippedState, ISyncResponse } from \"./sync-accumulator\";\nimport { MatrixError } from \"./http-api\";\nimport {\n Extension,\n ExtensionState,\n MSC3575RoomData,\n MSC3575SlidingSyncResponse,\n SlidingSync,\n SlidingSyncEvent,\n SlidingSyncState,\n} from \"./sliding-sync\";\nimport { EventType } from \"./@types/event\";\nimport { IPushRules } from \"./@types/PushRules\";\nimport { RoomStateEvent } from \"./models/room-state\";\nimport { RoomMemberEvent } from \"./models/room-member\";\n\n// Number of consecutive failed syncs that will lead to a syncState of ERROR as opposed\n// to RECONNECTING. This is needed to inform the client of server issues when the\n// keepAlive is successful but the server /sync fails.\nconst FAILED_SYNC_ERROR_THRESHOLD = 3;\n\ntype ExtensionE2EERequest = {\n enabled: boolean;\n};\n\ntype ExtensionE2EEResponse = Pick<\n ISyncResponse,\n | \"device_lists\"\n | \"device_one_time_keys_count\"\n | \"device_unused_fallback_key_types\"\n | \"org.matrix.msc2732.device_unused_fallback_key_types\"\n>;\n\nclass ExtensionE2EE implements Extension {\n public constructor(private readonly crypto: Crypto) {}\n\n public name(): string {\n return \"e2ee\";\n }\n\n public when(): ExtensionState {\n return ExtensionState.PreProcess;\n }\n\n public onRequest(isInitial: boolean): ExtensionE2EERequest | undefined {\n if (!isInitial) {\n return undefined;\n }\n return {\n enabled: true, // this is sticky so only send it on the initial request\n };\n }\n\n public async onResponse(data: ExtensionE2EEResponse): Promise {\n // Handle device list updates\n if (data[\"device_lists\"]) {\n await this.crypto.handleDeviceListChanges(\n {\n oldSyncToken: \"yep\", // XXX need to do this so the device list changes get processed :(\n },\n data[\"device_lists\"],\n );\n }\n\n // Handle one_time_keys_count\n if (data[\"device_one_time_keys_count\"]) {\n const currentCount = data[\"device_one_time_keys_count\"].signed_curve25519 || 0;\n this.crypto.updateOneTimeKeyCount(currentCount);\n }\n if (data[\"device_unused_fallback_key_types\"] || data[\"org.matrix.msc2732.device_unused_fallback_key_types\"]) {\n // The presence of device_unused_fallback_key_types indicates that the\n // server supports fallback keys. If there's no unused\n // signed_curve25519 fallback key we need a new one.\n const unusedFallbackKeys =\n data[\"device_unused_fallback_key_types\"] || data[\"org.matrix.msc2732.device_unused_fallback_key_types\"];\n this.crypto.setNeedsNewFallback(\n Array.isArray(unusedFallbackKeys) && !unusedFallbackKeys.includes(\"signed_curve25519\"),\n );\n }\n this.crypto.onSyncCompleted({});\n }\n}\n\ntype ExtensionToDeviceRequest = {\n since?: string;\n limit?: number;\n enabled?: boolean;\n};\n\ntype ExtensionToDeviceResponse = {\n events: Required[\"to_device\"][\"events\"];\n next_batch: string | null;\n};\n\nclass ExtensionToDevice implements Extension {\n private nextBatch: string | null = null;\n\n public constructor(private readonly client: MatrixClient, private readonly cryptoCallbacks?: SyncCryptoCallbacks) {}\n\n public name(): string {\n return \"to_device\";\n }\n\n public when(): ExtensionState {\n return ExtensionState.PreProcess;\n }\n\n public onRequest(isInitial: boolean): ExtensionToDeviceRequest {\n const extReq: ExtensionToDeviceRequest = {\n since: this.nextBatch !== null ? this.nextBatch : undefined,\n };\n if (isInitial) {\n extReq[\"limit\"] = 100;\n extReq[\"enabled\"] = true;\n }\n return extReq;\n }\n\n public async onResponse(data: ExtensionToDeviceResponse): Promise {\n const cancelledKeyVerificationTxns: string[] = [];\n let events = data[\"events\"] || [];\n if (events.length > 0 && this.cryptoCallbacks) {\n events = await this.cryptoCallbacks.preprocessToDeviceMessages(events);\n }\n events\n .map(this.client.getEventMapper())\n .map((toDeviceEvent) => {\n // map is a cheap inline forEach\n // We want to flag m.key.verification.start events as cancelled\n // if there's an accompanying m.key.verification.cancel event, so\n // we pull out the transaction IDs from the cancellation events\n // so we can flag the verification events as cancelled in the loop\n // below.\n if (toDeviceEvent.getType() === \"m.key.verification.cancel\") {\n const txnId: string | undefined = toDeviceEvent.getContent()[\"transaction_id\"];\n if (txnId) {\n cancelledKeyVerificationTxns.push(txnId);\n }\n }\n\n // as mentioned above, .map is a cheap inline forEach, so return\n // the unmodified event.\n return toDeviceEvent;\n })\n .forEach((toDeviceEvent) => {\n const content = toDeviceEvent.getContent();\n if (toDeviceEvent.getType() == \"m.room.message\" && content.msgtype == \"m.bad.encrypted\") {\n // the mapper already logged a warning.\n logger.log(\"Ignoring undecryptable to-device event from \" + toDeviceEvent.getSender());\n return;\n }\n\n if (\n toDeviceEvent.getType() === \"m.key.verification.start\" ||\n toDeviceEvent.getType() === \"m.key.verification.request\"\n ) {\n const txnId = content[\"transaction_id\"];\n if (cancelledKeyVerificationTxns.includes(txnId)) {\n toDeviceEvent.flagCancelled();\n }\n }\n\n this.client.emit(ClientEvent.ToDeviceEvent, toDeviceEvent);\n });\n\n this.nextBatch = data.next_batch;\n }\n}\n\ntype ExtensionAccountDataRequest = {\n enabled: boolean;\n};\n\ntype ExtensionAccountDataResponse = {\n global: IMinimalEvent[];\n rooms: Record;\n};\n\nclass ExtensionAccountData implements Extension {\n public constructor(private readonly client: MatrixClient) {}\n\n public name(): string {\n return \"account_data\";\n }\n\n public when(): ExtensionState {\n return ExtensionState.PostProcess;\n }\n\n public onRequest(isInitial: boolean): ExtensionAccountDataRequest | undefined {\n if (!isInitial) {\n return undefined;\n }\n return {\n enabled: true,\n };\n }\n\n public onResponse(data: ExtensionAccountDataResponse): void {\n if (data.global && data.global.length > 0) {\n this.processGlobalAccountData(data.global);\n }\n\n for (const roomId in data.rooms) {\n const accountDataEvents = mapEvents(this.client, roomId, data.rooms[roomId]);\n const room = this.client.getRoom(roomId);\n if (!room) {\n logger.warn(\"got account data for room but room doesn't exist on client:\", roomId);\n continue;\n }\n room.addAccountData(accountDataEvents);\n accountDataEvents.forEach((e) => {\n this.client.emit(ClientEvent.Event, e);\n });\n }\n }\n\n private processGlobalAccountData(globalAccountData: IMinimalEvent[]): void {\n const events = mapEvents(this.client, undefined, globalAccountData);\n const prevEventsMap = events.reduce>((m, c) => {\n m[c.getType()] = this.client.store.getAccountData(c.getType());\n return m;\n }, {});\n this.client.store.storeAccountDataEvents(events);\n events.forEach((accountDataEvent) => {\n // Honour push rules that come down the sync stream but also\n // honour push rules that were previously cached. Base rules\n // will be updated when we receive push rules via getPushRules\n // (see sync) before syncing over the network.\n if (accountDataEvent.getType() === EventType.PushRules) {\n const rules = accountDataEvent.getContent();\n this.client.setPushRules(rules);\n }\n const prevEvent = prevEventsMap[accountDataEvent.getType()];\n this.client.emit(ClientEvent.AccountData, accountDataEvent, prevEvent);\n return accountDataEvent;\n });\n }\n}\n\ntype ExtensionTypingRequest = {\n enabled: boolean;\n};\n\ntype ExtensionTypingResponse = {\n rooms: Record;\n};\n\nclass ExtensionTyping implements Extension {\n public constructor(private readonly client: MatrixClient) {}\n\n public name(): string {\n return \"typing\";\n }\n\n public when(): ExtensionState {\n return ExtensionState.PostProcess;\n }\n\n public onRequest(isInitial: boolean): ExtensionTypingRequest | undefined {\n if (!isInitial) {\n return undefined; // don't send a JSON object for subsequent requests, we don't need to.\n }\n return {\n enabled: true,\n };\n }\n\n public onResponse(data: ExtensionTypingResponse): void {\n if (!data?.rooms) {\n return;\n }\n\n for (const roomId in data.rooms) {\n processEphemeralEvents(this.client, roomId, [data.rooms[roomId]]);\n }\n }\n}\n\ntype ExtensionReceiptsRequest = {\n enabled: boolean;\n};\n\ntype ExtensionReceiptsResponse = {\n rooms: Record;\n};\n\nclass ExtensionReceipts implements Extension {\n public constructor(private readonly client: MatrixClient) {}\n\n public name(): string {\n return \"receipts\";\n }\n\n public when(): ExtensionState {\n return ExtensionState.PostProcess;\n }\n\n public onRequest(isInitial: boolean): ExtensionReceiptsRequest | undefined {\n if (isInitial) {\n return {\n enabled: true,\n };\n }\n return undefined; // don't send a JSON object for subsequent requests, we don't need to.\n }\n\n public onResponse(data: ExtensionReceiptsResponse): void {\n if (!data?.rooms) {\n return;\n }\n\n for (const roomId in data.rooms) {\n processEphemeralEvents(this.client, roomId, [data.rooms[roomId]]);\n }\n }\n}\n\n/**\n * A copy of SyncApi such that it can be used as a drop-in replacement for sync v2. For the actual\n * sliding sync API, see sliding-sync.ts or the class SlidingSync.\n */\nexport class SlidingSyncSdk {\n private readonly opts: IStoredClientOpts;\n private readonly syncOpts: SyncApiOptions;\n private syncState: SyncState | null = null;\n private syncStateData?: ISyncStateData;\n private lastPos: string | null = null;\n private failCount = 0;\n private notifEvents: MatrixEvent[] = []; // accumulator of sync events in the current sync response\n\n public constructor(\n private readonly slidingSync: SlidingSync,\n private readonly client: MatrixClient,\n opts?: IStoredClientOpts,\n syncOpts?: SyncApiOptions,\n ) {\n this.opts = defaultClientOpts(opts);\n this.syncOpts = defaultSyncApiOpts(syncOpts);\n\n if (client.getNotifTimelineSet()) {\n client.reEmitter.reEmit(client.getNotifTimelineSet()!, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n }\n\n this.slidingSync.on(SlidingSyncEvent.Lifecycle, this.onLifecycle.bind(this));\n this.slidingSync.on(SlidingSyncEvent.RoomData, this.onRoomData.bind(this));\n const extensions: Extension[] = [\n new ExtensionToDevice(this.client, this.syncOpts.cryptoCallbacks),\n new ExtensionAccountData(this.client),\n new ExtensionTyping(this.client),\n new ExtensionReceipts(this.client),\n ];\n if (this.syncOpts.crypto) {\n extensions.push(new ExtensionE2EE(this.syncOpts.crypto));\n }\n extensions.forEach((ext) => {\n this.slidingSync.registerExtension(ext);\n });\n }\n\n private onRoomData(roomId: string, roomData: MSC3575RoomData): void {\n let room = this.client.store.getRoom(roomId);\n if (!room) {\n if (!roomData.initial) {\n logger.debug(\"initial flag not set but no stored room exists for room \", roomId, roomData);\n return;\n }\n room = _createAndReEmitRoom(this.client, roomId, this.opts);\n }\n this.processRoomData(this.client, room, roomData);\n }\n\n private onLifecycle(state: SlidingSyncState, resp: MSC3575SlidingSyncResponse | null, err?: Error): void {\n if (err) {\n logger.debug(\"onLifecycle\", state, err);\n }\n switch (state) {\n case SlidingSyncState.Complete:\n this.purgeNotifications();\n if (!resp) {\n break;\n }\n // Element won't stop showing the initial loading spinner unless we fire SyncState.Prepared\n if (!this.lastPos) {\n this.updateSyncState(SyncState.Prepared, {\n oldSyncToken: undefined,\n nextSyncToken: resp.pos,\n catchingUp: false,\n fromCache: false,\n });\n }\n // Conversely, Element won't show the room list unless there is at least 1x SyncState.Syncing\n // so hence for the very first sync we will fire prepared then immediately syncing.\n this.updateSyncState(SyncState.Syncing, {\n oldSyncToken: this.lastPos!,\n nextSyncToken: resp.pos,\n catchingUp: false,\n fromCache: false,\n });\n this.lastPos = resp.pos;\n break;\n case SlidingSyncState.RequestFinished:\n if (err) {\n this.failCount += 1;\n this.updateSyncState(\n this.failCount > FAILED_SYNC_ERROR_THRESHOLD ? SyncState.Error : SyncState.Reconnecting,\n {\n error: new MatrixError(err),\n },\n );\n if (this.shouldAbortSync(new MatrixError(err))) {\n return; // shouldAbortSync actually stops syncing too so we don't need to do anything.\n }\n } else {\n this.failCount = 0;\n }\n break;\n }\n }\n\n /**\n * Sync rooms the user has left.\n * @returns Resolved when they've been added to the store.\n */\n public async syncLeftRooms(): Promise {\n return []; // TODO\n }\n\n /**\n * Peek into a room. This will result in the room in question being synced so it\n * is accessible via getRooms(). Live updates for the room will be provided.\n * @param roomId - The room ID to peek into.\n * @returns A promise which resolves once the room has been added to the\n * store.\n */\n public async peek(_roomId: string): Promise {\n return null!; // TODO\n }\n\n /**\n * Stop polling for updates in the peeked room. NOPs if there is no room being\n * peeked.\n */\n public stopPeeking(): void {\n // TODO\n }\n\n /**\n * Returns the current state of this sync object\n * @see MatrixClient#event:\"sync\"\n */\n public getSyncState(): SyncState | null {\n return this.syncState;\n }\n\n /**\n * Returns the additional data object associated with\n * the current sync state, or null if there is no\n * such data.\n * Sync errors, if available, are put in the 'error' key of\n * this object.\n */\n public getSyncStateData(): ISyncStateData | null {\n return this.syncStateData ?? null;\n }\n\n // Helper functions which set up JS SDK structs are below and are identical to the sync v2 counterparts\n\n public createRoom(roomId: string): Room {\n // XXX cargoculted from sync.ts\n const { timelineSupport } = this.client;\n const room = new Room(roomId, this.client, this.client.getUserId()!, {\n lazyLoadMembers: this.opts.lazyLoadMembers,\n pendingEventOrdering: this.opts.pendingEventOrdering,\n timelineSupport,\n });\n this.client.reEmitter.reEmit(room, [\n RoomEvent.Name,\n RoomEvent.Redaction,\n RoomEvent.RedactionCancelled,\n RoomEvent.Receipt,\n RoomEvent.Tags,\n RoomEvent.LocalEchoUpdated,\n RoomEvent.AccountData,\n RoomEvent.MyMembership,\n RoomEvent.Timeline,\n RoomEvent.TimelineReset,\n ]);\n this.registerStateListeners(room);\n return room;\n }\n\n private registerStateListeners(room: Room): void {\n // XXX cargoculted from sync.ts\n // we need to also re-emit room state and room member events, so hook it up\n // to the client now. We need to add a listener for RoomState.members in\n // order to hook them correctly.\n this.client.reEmitter.reEmit(room.currentState, [\n RoomStateEvent.Events,\n RoomStateEvent.Members,\n RoomStateEvent.NewMember,\n RoomStateEvent.Update,\n ]);\n room.currentState.on(RoomStateEvent.NewMember, (event, state, member) => {\n member.user = this.client.getUser(member.userId) ?? undefined;\n this.client.reEmitter.reEmit(member, [\n RoomMemberEvent.Name,\n RoomMemberEvent.Typing,\n RoomMemberEvent.PowerLevel,\n RoomMemberEvent.Membership,\n ]);\n });\n }\n\n /*\n private deregisterStateListeners(room: Room): void { // XXX cargoculted from sync.ts\n // could do with a better way of achieving this.\n room.currentState.removeAllListeners(RoomStateEvent.Events);\n room.currentState.removeAllListeners(RoomStateEvent.Members);\n room.currentState.removeAllListeners(RoomStateEvent.NewMember);\n } */\n\n private shouldAbortSync(error: MatrixError): boolean {\n if (error.errcode === \"M_UNKNOWN_TOKEN\") {\n // The logout already happened, we just need to stop.\n logger.warn(\"Token no longer valid - assuming logout\");\n this.stop();\n this.updateSyncState(SyncState.Error, { error });\n return true;\n }\n return false;\n }\n\n private async processRoomData(client: MatrixClient, room: Room, roomData: MSC3575RoomData): Promise {\n roomData = ensureNameEvent(client, room.roomId, roomData);\n const stateEvents = mapEvents(this.client, room.roomId, roomData.required_state);\n // Prevent events from being decrypted ahead of time\n // this helps large account to speed up faster\n // room::decryptCriticalEvent is in charge of decrypting all the events\n // required for a client to function properly\n let timelineEvents = mapEvents(this.client, room.roomId, roomData.timeline, false);\n const ephemeralEvents: MatrixEvent[] = []; // TODO this.mapSyncEventsFormat(joinObj.ephemeral);\n\n // TODO: handle threaded / beacon events\n\n if (roomData.initial) {\n // we should not know about any of these timeline entries if this is a genuinely new room.\n // If we do, then we've effectively done scrollback (e.g requesting timeline_limit: 1 for\n // this room, then timeline_limit: 50).\n const knownEvents = new Set();\n room.getLiveTimeline()\n .getEvents()\n .forEach((e) => {\n knownEvents.add(e.getId()!);\n });\n // all unknown events BEFORE a known event must be scrollback e.g:\n // D E <-- what we know\n // A B C D E F <-- what we just received\n // means:\n // A B C <-- scrollback\n // D E <-- dupes\n // F <-- new event\n // We bucket events based on if we have seen a known event yet.\n const oldEvents: MatrixEvent[] = [];\n const newEvents: MatrixEvent[] = [];\n let seenKnownEvent = false;\n for (let i = timelineEvents.length - 1; i >= 0; i--) {\n const recvEvent = timelineEvents[i];\n if (knownEvents.has(recvEvent.getId()!)) {\n seenKnownEvent = true;\n continue; // don't include this event, it's a dupe\n }\n if (seenKnownEvent) {\n // old -> new\n oldEvents.push(recvEvent);\n } else {\n // old -> new\n newEvents.unshift(recvEvent);\n }\n }\n timelineEvents = newEvents;\n if (oldEvents.length > 0) {\n // old events are scrollback, insert them now\n room.addEventsToTimeline(oldEvents, true, room.getLiveTimeline(), roomData.prev_batch);\n }\n }\n\n const encrypted = this.client.isRoomEncrypted(room.roomId);\n // we do this first so it's correct when any of the events fire\n if (roomData.notification_count != null) {\n room.setUnreadNotificationCount(NotificationCountType.Total, roomData.notification_count);\n }\n\n if (roomData.highlight_count != null) {\n // We track unread notifications ourselves in encrypted rooms, so don't\n // bother setting it here. We trust our calculations better than the\n // server's for this case, and therefore will assume that our non-zero\n // count is accurate.\n if (!encrypted || (encrypted && room.getUnreadNotificationCount(NotificationCountType.Highlight) <= 0)) {\n room.setUnreadNotificationCount(NotificationCountType.Highlight, roomData.highlight_count);\n }\n }\n\n if (Number.isInteger(roomData.invited_count)) {\n room.currentState.setInvitedMemberCount(roomData.invited_count!);\n }\n if (Number.isInteger(roomData.joined_count)) {\n room.currentState.setJoinedMemberCount(roomData.joined_count!);\n }\n\n if (roomData.invite_state) {\n const inviteStateEvents = mapEvents(this.client, room.roomId, roomData.invite_state);\n this.injectRoomEvents(room, inviteStateEvents);\n if (roomData.initial) {\n room.recalculate();\n this.client.store.storeRoom(room);\n this.client.emit(ClientEvent.Room, room);\n }\n inviteStateEvents.forEach((e) => {\n this.client.emit(ClientEvent.Event, e);\n });\n room.updateMyMembership(\"invite\");\n return;\n }\n\n if (roomData.initial) {\n // set the back-pagination token. Do this *before* adding any\n // events so that clients can start back-paginating.\n room.getLiveTimeline().setPaginationToken(roomData.prev_batch ?? null, EventTimeline.BACKWARDS);\n }\n\n /* TODO\n else if (roomData.limited) {\n\n let limited = true;\n\n // we've got a limited sync, so we *probably* have a gap in the\n // timeline, so should reset. But we might have been peeking or\n // paginating and already have some of the events, in which\n // case we just want to append any subsequent events to the end\n // of the existing timeline.\n //\n // This is particularly important in the case that we already have\n // *all* of the events in the timeline - in that case, if we reset\n // the timeline, we'll end up with an entirely empty timeline,\n // which we'll try to paginate but not get any new events (which\n // will stop us linking the empty timeline into the chain).\n //\n for (let i = timelineEvents.length - 1; i >= 0; i--) {\n const eventId = timelineEvents[i].getId();\n if (room.getTimelineForEvent(eventId)) {\n logger.debug(\"Already have event \" + eventId + \" in limited \" +\n \"sync - not resetting\");\n limited = false;\n\n // we might still be missing some of the events before i;\n // we don't want to be adding them to the end of the\n // timeline because that would put them out of order.\n timelineEvents.splice(0, i);\n\n // XXX: there's a problem here if the skipped part of the\n // timeline modifies the state set in stateEvents, because\n // we'll end up using the state from stateEvents rather\n // than the later state from timelineEvents. We probably\n // need to wind stateEvents forward over the events we're\n // skipping.\n break;\n }\n }\n\n if (limited) {\n room.resetLiveTimeline(\n roomData.prev_batch,\n null, // TODO this.syncOpts.canResetEntireTimeline(room.roomId) ? null : syncEventData.oldSyncToken,\n );\n\n // We have to assume any gap in any timeline is\n // reason to stop incrementally tracking notifications and\n // reset the timeline.\n this.client.resetNotifTimelineSet();\n this.registerStateListeners(room);\n }\n } */\n\n this.injectRoomEvents(room, stateEvents, timelineEvents, roomData.num_live);\n\n // we deliberately don't add ephemeral events to the timeline\n room.addEphemeralEvents(ephemeralEvents);\n\n // local fields must be set before any async calls because call site assumes\n // synchronous execution prior to emitting SlidingSyncState.Complete\n room.updateMyMembership(\"join\");\n\n room.recalculate();\n if (roomData.initial) {\n client.store.storeRoom(room);\n client.emit(ClientEvent.Room, room);\n }\n\n // check if any timeline events should bing and add them to the notifEvents array:\n // we'll purge this once we've fully processed the sync response\n this.addNotifications(timelineEvents);\n\n const processRoomEvent = async (e: MatrixEvent): Promise => {\n client.emit(ClientEvent.Event, e);\n if (e.isState() && e.getType() == EventType.RoomEncryption && this.syncOpts.cryptoCallbacks) {\n await this.syncOpts.cryptoCallbacks.onCryptoEvent(room, e);\n }\n };\n\n await utils.promiseMapSeries(stateEvents, processRoomEvent);\n await utils.promiseMapSeries(timelineEvents, processRoomEvent);\n ephemeralEvents.forEach(function (e) {\n client.emit(ClientEvent.Event, e);\n });\n\n // Decrypt only the last message in all rooms to make sure we can generate a preview\n // And decrypt all events after the recorded read receipt to ensure an accurate\n // notification count\n room.decryptCriticalEvents();\n }\n\n /**\n * Injects events into a room's model.\n * @param stateEventList - A list of state events. This is the state\n * at the *START* of the timeline list if it is supplied.\n * @param timelineEventList - A list of timeline events. Lower index\n * is earlier in time. Higher index is later.\n * @param numLive - the number of events in timelineEventList which just happened,\n * supplied from the server.\n */\n public injectRoomEvents(\n room: Room,\n stateEventList: MatrixEvent[],\n timelineEventList?: MatrixEvent[],\n numLive?: number,\n ): void {\n timelineEventList = timelineEventList || [];\n stateEventList = stateEventList || [];\n numLive = numLive || 0;\n\n // If there are no events in the timeline yet, initialise it with\n // the given state events\n const liveTimeline = room.getLiveTimeline();\n const timelineWasEmpty = liveTimeline.getEvents().length == 0;\n if (timelineWasEmpty) {\n // Passing these events into initialiseState will freeze them, so we need\n // to compute and cache the push actions for them now, otherwise sync dies\n // with an attempt to assign to read only property.\n // XXX: This is pretty horrible and is assuming all sorts of behaviour from\n // these functions that it shouldn't be. We should probably either store the\n // push actions cache elsewhere so we can freeze MatrixEvents, or otherwise\n // find some solution where MatrixEvents are immutable but allow for a cache\n // field.\n for (const ev of stateEventList) {\n this.client.getPushActionsForEvent(ev);\n }\n liveTimeline.initialiseState(stateEventList);\n }\n\n // If the timeline wasn't empty, we process the state events here: they're\n // defined as updates to the state before the start of the timeline, so this\n // starts to roll the state forward.\n // XXX: That's what we *should* do, but this can happen if we were previously\n // peeking in a room, in which case we obviously do *not* want to add the\n // state events here onto the end of the timeline. Historically, the js-sdk\n // has just set these new state events on the old and new state. This seems\n // very wrong because there could be events in the timeline that diverge the\n // state, in which case this is going to leave things out of sync. However,\n // for now I think it;s best to behave the same as the code has done previously.\n if (!timelineWasEmpty) {\n // XXX: As above, don't do this...\n //room.addLiveEvents(stateEventList || []);\n // Do this instead...\n room.oldState.setStateEvents(stateEventList);\n room.currentState.setStateEvents(stateEventList);\n }\n\n // the timeline is broken into 'live' events which just happened and normal timeline events\n // which are still to be appended to the end of the live timeline but happened a while ago.\n // The live events are marked as fromCache=false to ensure that downstream components know\n // this is a live event, not historical (from a remote server cache).\n\n let liveTimelineEvents: MatrixEvent[] = [];\n if (numLive > 0) {\n // last numLive events are live\n liveTimelineEvents = timelineEventList.slice(-1 * numLive);\n // everything else is not live\n timelineEventList = timelineEventList.slice(0, -1 * liveTimelineEvents.length);\n }\n\n // execute the timeline events. This will continue to diverge the current state\n // if the timeline has any state events in it.\n // This also needs to be done before running push rules on the events as they need\n // to be decorated with sender etc.\n room.addLiveEvents(timelineEventList, {\n fromCache: true,\n });\n if (liveTimelineEvents.length > 0) {\n room.addLiveEvents(liveTimelineEvents, {\n fromCache: false,\n });\n }\n\n room.recalculate();\n\n // resolve invites now we have set the latest state\n this.resolveInvites(room);\n }\n\n private resolveInvites(room: Room): void {\n if (!room || !this.opts.resolveInvitesToProfiles) {\n return;\n }\n const client = this.client;\n // For each invited room member we want to give them a displayname/avatar url\n // if they have one (the m.room.member invites don't contain this).\n room.getMembersWithMembership(\"invite\").forEach(function (member) {\n if (member.requestedProfileInfo) return;\n member.requestedProfileInfo = true;\n // try to get a cached copy first.\n const user = client.getUser(member.userId);\n let promise: ReturnType;\n if (user) {\n promise = Promise.resolve({\n avatar_url: user.avatarUrl,\n displayname: user.displayName,\n });\n } else {\n promise = client.getProfileInfo(member.userId);\n }\n promise.then(\n function (info) {\n // slightly naughty by doctoring the invite event but this means all\n // the code paths remain the same between invite/join display name stuff\n // which is a worthy trade-off for some minor pollution.\n const inviteEvent = member.events.member!;\n if (inviteEvent.getContent().membership !== \"invite\") {\n // between resolving and now they have since joined, so don't clobber\n return;\n }\n inviteEvent.getContent().avatar_url = info.avatar_url;\n inviteEvent.getContent().displayname = info.displayname;\n // fire listeners\n member.setMembershipEvent(inviteEvent, room.currentState);\n },\n function (_err) {\n // OH WELL.\n },\n );\n });\n }\n\n public retryImmediately(): boolean {\n return true;\n }\n\n /**\n * Main entry point. Blocks until stop() is called.\n */\n public async sync(): Promise {\n logger.debug(\"Sliding sync init loop\");\n\n // 1) We need to get push rules so we can check if events should bing as we get\n // them from /sync.\n while (!this.client.isGuest()) {\n try {\n logger.debug(\"Getting push rules...\");\n const result = await this.client.getPushRules();\n logger.debug(\"Got push rules\");\n this.client.pushRules = result;\n break;\n } catch (err) {\n logger.error(\"Getting push rules failed\", err);\n if (this.shouldAbortSync(err)) {\n return;\n }\n }\n }\n\n // start syncing\n await this.slidingSync.start();\n }\n\n /**\n * Stops the sync object from syncing.\n */\n public stop(): void {\n logger.debug(\"SyncApi.stop\");\n this.slidingSync.stop();\n }\n\n /**\n * Sets the sync state and emits an event to say so\n * @param newState - The new state string\n * @param data - Object of additional data to emit in the event\n */\n private updateSyncState(newState: SyncState, data?: ISyncStateData): void {\n const old = this.syncState;\n this.syncState = newState;\n this.syncStateData = data;\n this.client.emit(ClientEvent.Sync, this.syncState, old, data);\n }\n\n /**\n * Takes a list of timelineEvents and adds and adds to notifEvents\n * as appropriate.\n * This must be called after the room the events belong to has been stored.\n *\n * @param timelineEventList - A list of timeline events. Lower index\n * is earlier in time. Higher index is later.\n */\n private addNotifications(timelineEventList: MatrixEvent[]): void {\n // gather our notifications into this.notifEvents\n if (!this.client.getNotifTimelineSet()) {\n return;\n }\n for (const timelineEvent of timelineEventList) {\n const pushActions = this.client.getPushActionsForEvent(timelineEvent);\n if (pushActions && pushActions.notify && pushActions.tweaks && pushActions.tweaks.highlight) {\n this.notifEvents.push(timelineEvent);\n }\n }\n }\n\n /**\n * Purge any events in the notifEvents array. Used after a /sync has been complete.\n * This should not be called at a per-room scope (e.g in onRoomData) because otherwise the ordering\n * will be messed up e.g room A gets a bing, room B gets a newer bing, but both in the same /sync\n * response. If we purge at a per-room scope then we could process room B before room A leading to\n * room B appearing earlier in the notifications timeline, even though it has the higher origin_server_ts.\n */\n private purgeNotifications(): void {\n this.notifEvents.sort(function (a, b) {\n return a.getTs() - b.getTs();\n });\n this.notifEvents.forEach((event) => {\n this.client.getNotifTimelineSet()?.addLiveEvent(event);\n });\n this.notifEvents = [];\n }\n}\n\nfunction ensureNameEvent(client: MatrixClient, roomId: string, roomData: MSC3575RoomData): MSC3575RoomData {\n // make sure m.room.name is in required_state if there is a name, replacing anything previously\n // there if need be. This ensures clients transparently 'calculate' the right room name. Native\n // sliding sync clients should just read the \"name\" field.\n if (!roomData.name) {\n return roomData;\n }\n for (const stateEvent of roomData.required_state) {\n if (stateEvent.type === EventType.RoomName && stateEvent.state_key === \"\") {\n stateEvent.content = {\n name: roomData.name,\n };\n return roomData;\n }\n }\n roomData.required_state.push({\n event_id: \"$fake-sliding-sync-name-event-\" + roomId,\n state_key: \"\",\n type: EventType.RoomName,\n content: {\n name: roomData.name,\n },\n sender: client.getUserId()!,\n origin_server_ts: new Date().getTime(),\n });\n return roomData;\n}\n\ntype TaggedEvent = (IStrippedState | IRoomEvent | IStateEvent | IMinimalEvent) & { room_id?: string };\n\n// Helper functions which set up JS SDK structs are below and are identical to the sync v2 counterparts,\n// just outside the class.\nfunction mapEvents(client: MatrixClient, roomId: string | undefined, events: object[], decrypt = true): MatrixEvent[] {\n const mapper = client.getEventMapper({ decrypt });\n return (events as TaggedEvent[]).map(function (e) {\n e.room_id = roomId;\n return mapper(e);\n });\n}\n\nfunction processEphemeralEvents(client: MatrixClient, roomId: string, ephEvents: IMinimalEvent[]): void {\n const ephemeralEvents = mapEvents(client, roomId, ephEvents);\n const room = client.getRoom(roomId);\n if (!room) {\n logger.warn(\"got ephemeral events for room but room doesn't exist on client:\", roomId);\n return;\n }\n room.addEphemeralEvents(ephemeralEvents);\n ephemeralEvents.forEach((e) => {\n client.emit(ClientEvent.Event, e);\n });\n}\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from \"./logger\";\nimport { MatrixClient } from \"./client\";\nimport { IRoomEvent, IStateEvent } from \"./sync-accumulator\";\nimport { TypedEventEmitter } from \"./models/typed-event-emitter\";\nimport { sleep, IDeferred, defer } from \"./utils\";\nimport { HTTPError } from \"./http-api\";\n\n// /sync requests allow you to set a timeout= but the request may continue\n// beyond that and wedge forever, so we need to track how long we are willing\n// to keep open the connection. This constant is *ADDED* to the timeout= value\n// to determine the max time we're willing to wait.\nconst BUFFER_PERIOD_MS = 10 * 1000;\n\nexport const MSC3575_WILDCARD = \"*\";\nexport const MSC3575_STATE_KEY_ME = \"$ME\";\nexport const MSC3575_STATE_KEY_LAZY = \"$LAZY\";\n\n/**\n * Represents a subscription to a room or set of rooms. Controls which events are returned.\n */\nexport interface MSC3575RoomSubscription {\n required_state?: string[][];\n timeline_limit?: number;\n include_old_rooms?: MSC3575RoomSubscription;\n}\n\n/**\n * Controls which rooms are returned in a given list.\n */\nexport interface MSC3575Filter {\n is_dm?: boolean;\n is_encrypted?: boolean;\n is_invite?: boolean;\n room_name_like?: string;\n room_types?: string[];\n not_room_types?: string[];\n spaces?: string[];\n tags?: string[];\n not_tags?: string[];\n}\n\n/**\n * Represents a list subscription.\n */\nexport interface MSC3575List extends MSC3575RoomSubscription {\n ranges: number[][];\n sort?: string[];\n filters?: MSC3575Filter;\n slow_get_all_rooms?: boolean;\n}\n\n/**\n * A complete Sliding Sync request.\n */\nexport interface MSC3575SlidingSyncRequest {\n // json body params\n lists?: Record;\n unsubscribe_rooms?: string[];\n room_subscriptions?: Record;\n extensions?: object;\n txn_id?: string;\n\n // query params\n pos?: string;\n timeout?: number;\n clientTimeout?: number;\n}\n\nexport interface MSC3575RoomData {\n name: string;\n required_state: IStateEvent[];\n timeline: (IRoomEvent | IStateEvent)[];\n notification_count?: number;\n highlight_count?: number;\n joined_count?: number;\n invited_count?: number;\n invite_state?: IStateEvent[];\n initial?: boolean;\n limited?: boolean;\n is_dm?: boolean;\n prev_batch?: string;\n num_live?: number;\n}\n\ninterface ListResponse {\n count: number;\n ops: Operation[];\n}\n\ninterface BaseOperation {\n op: string;\n}\n\ninterface DeleteOperation extends BaseOperation {\n op: \"DELETE\";\n index: number;\n}\n\ninterface InsertOperation extends BaseOperation {\n op: \"INSERT\";\n index: number;\n room_id: string;\n}\n\ninterface InvalidateOperation extends BaseOperation {\n op: \"INVALIDATE\";\n range: [number, number];\n}\n\ninterface SyncOperation extends BaseOperation {\n op: \"SYNC\";\n range: [number, number];\n room_ids: string[];\n}\n\ntype Operation = DeleteOperation | InsertOperation | InvalidateOperation | SyncOperation;\n\n/**\n * A complete Sliding Sync response\n */\nexport interface MSC3575SlidingSyncResponse {\n pos: string;\n txn_id?: string;\n lists: Record;\n rooms: Record;\n extensions: Record;\n}\n\nexport enum SlidingSyncState {\n /**\n * Fired by SlidingSyncEvent.Lifecycle event immediately before processing the response.\n */\n RequestFinished = \"FINISHED\",\n /**\n * Fired by SlidingSyncEvent.Lifecycle event immediately after all room data listeners have been\n * invoked, but before list listeners.\n */\n Complete = \"COMPLETE\",\n}\n\n/**\n * Internal Class. SlidingList represents a single list in sliding sync. The list can have filters,\n * multiple sliding windows, and maintains the index-\\>room_id mapping.\n */\nclass SlidingList {\n private list!: MSC3575List;\n private isModified?: boolean;\n\n // returned data\n public roomIndexToRoomId: Record = {};\n public joinedCount = 0;\n\n /**\n * Construct a new sliding list.\n * @param list - The range, sort and filter values to use for this list.\n */\n public constructor(list: MSC3575List) {\n this.replaceList(list);\n }\n\n /**\n * Mark this list as modified or not. Modified lists will return sticky params with calls to getList.\n * This is useful for the first time the list is sent, or if the list has changed in some way.\n * @param modified - True to mark this list as modified so all sticky parameters will be re-sent.\n */\n public setModified(modified: boolean): void {\n this.isModified = modified;\n }\n\n /**\n * Update the list range for this list. Does not affect modified status as list ranges are non-sticky.\n * @param newRanges - The new ranges for the list\n */\n public updateListRange(newRanges: number[][]): void {\n this.list.ranges = JSON.parse(JSON.stringify(newRanges));\n }\n\n /**\n * Replace list parameters. All fields will be replaced with the new list parameters.\n * @param list - The new list parameters\n */\n public replaceList(list: MSC3575List): void {\n list.filters = list.filters || {};\n list.ranges = list.ranges || [];\n this.list = JSON.parse(JSON.stringify(list));\n this.isModified = true;\n\n // reset values as the join count may be very different (if filters changed) including the rooms\n // (e.g. sort orders or sliding window ranges changed)\n\n // the constantly changing sliding window ranges. Not an array for performance reasons\n // E.g. tracking ranges 0-99, 500-599, we don't want to have a 600 element array\n this.roomIndexToRoomId = {};\n // the total number of joined rooms according to the server, always >= len(roomIndexToRoomId)\n this.joinedCount = 0;\n }\n\n /**\n * Return a copy of the list suitable for a request body.\n * @param forceIncludeAllParams - True to forcibly include all params even if the list\n * hasn't been modified. Callers may want to do this if they are modifying the list prior to calling\n * updateList.\n */\n public getList(forceIncludeAllParams: boolean): MSC3575List {\n let list = {\n ranges: JSON.parse(JSON.stringify(this.list.ranges)),\n };\n if (this.isModified || forceIncludeAllParams) {\n list = JSON.parse(JSON.stringify(this.list));\n }\n return list;\n }\n\n /**\n * Check if a given index is within the list range. This is required even though the /sync API\n * provides explicit updates with index positions because of the following situation:\n * 0 1 2 3 4 5 6 7 8 indexes\n * a b c d e f COMMANDS: SYNC 0 2 a b c; SYNC 6 8 d e f;\n * a b c d _ f COMMAND: DELETE 7;\n * e a b c d f COMMAND: INSERT 0 e;\n * c=3 is wrong as we are not tracking it, ergo we need to see if `i` is in range else drop it\n * @param i - The index to check\n * @returns True if the index is within a sliding window\n */\n public isIndexInRange(i: number): boolean {\n for (const r of this.list.ranges) {\n if (r[0] <= i && i <= r[1]) {\n return true;\n }\n }\n return false;\n }\n}\n\n/**\n * When onResponse extensions should be invoked: before or after processing the main response.\n */\nexport enum ExtensionState {\n // Call onResponse before processing the response body. This is useful when your extension is\n // preparing the ground for the response body e.g. processing to-device messages before the\n // encrypted event arrives.\n PreProcess = \"ExtState.PreProcess\",\n // Call onResponse after processing the response body. This is useful when your extension is\n // decorating data from the client, and you rely on MatrixClient.getRoom returning the Room object\n // e.g. room account data.\n PostProcess = \"ExtState.PostProcess\",\n}\n\n/**\n * An interface that must be satisfied to register extensions\n */\nexport interface Extension {\n /**\n * The extension name to go under 'extensions' in the request body.\n * @returns The JSON key.\n */\n name(): string;\n /**\n * A function which is called when the request JSON is being formed.\n * Returns the data to insert under this key.\n * @param isInitial - True when this is part of the initial request (send sticky params)\n * @returns The request JSON to send.\n */\n onRequest(isInitial: boolean): Req | undefined;\n /**\n * A function which is called when there is response JSON under this extension.\n * @param data - The response JSON under the extension name.\n */\n onResponse(data: Res): void;\n /**\n * Controls when onResponse should be called.\n * @returns The state when it should be called.\n */\n when(): ExtensionState;\n}\n\n/**\n * Events which can be fired by the SlidingSync class. These are designed to provide different levels\n * of information when processing sync responses.\n * - RoomData: concerns rooms, useful for SlidingSyncSdk to update its knowledge of rooms.\n * - Lifecycle: concerns callbacks at various well-defined points in the sync process.\n * - List: concerns lists, useful for UI layers to re-render room lists.\n * Specifically, the order of event invocation is:\n * - Lifecycle (state=RequestFinished)\n * - RoomData (N times)\n * - Lifecycle (state=Complete)\n * - List (at most once per list)\n */\nexport enum SlidingSyncEvent {\n /**\n * This event fires when there are updates for a room. Fired as and when rooms are encountered\n * in the response.\n */\n RoomData = \"SlidingSync.RoomData\",\n /**\n * This event fires at various points in the /sync loop lifecycle.\n * - SlidingSyncState.RequestFinished: Fires after we receive a valid response but before the\n * response has been processed. Perform any pre-process steps here. If there was a problem syncing,\n * `err` will be set (e.g network errors).\n * - SlidingSyncState.Complete: Fires after all SlidingSyncEvent.RoomData have been fired but before\n * SlidingSyncEvent.List.\n */\n Lifecycle = \"SlidingSync.Lifecycle\",\n /**\n * This event fires whenever there has been a change to this list index. It fires exactly once\n * per list, even if there were multiple operations for the list.\n * It fires AFTER Lifecycle and RoomData events.\n */\n List = \"SlidingSync.List\",\n}\n\nexport type SlidingSyncEventHandlerMap = {\n [SlidingSyncEvent.RoomData]: (roomId: string, roomData: MSC3575RoomData) => void;\n [SlidingSyncEvent.Lifecycle]: (\n state: SlidingSyncState,\n resp: MSC3575SlidingSyncResponse | null,\n err?: Error,\n ) => void;\n [SlidingSyncEvent.List]: (listKey: string, joinedCount: number, roomIndexToRoomId: Record) => void;\n};\n\n/**\n * SlidingSync is a high-level data structure which controls the majority of sliding sync.\n * It has no hooks into JS SDK except for needing a MatrixClient to perform the HTTP request.\n * This means this class (and everything it uses) can be used in isolation from JS SDK if needed.\n * To hook this up with the JS SDK, you need to use SlidingSyncSdk.\n */\nexport class SlidingSync extends TypedEventEmitter {\n private lists: Map;\n private listModifiedCount = 0;\n private terminated = false;\n // flag set when resend() is called because we cannot rely on detecting AbortError in JS SDK :(\n private needsResend = false;\n // the txn_id to send with the next request.\n private txnId: string | null = null;\n // a list (in chronological order of when they were sent) of objects containing the txn ID and\n // a defer to resolve/reject depending on whether they were successfully sent or not.\n private txnIdDefers: (IDeferred & { txnId: string })[] = [];\n // map of extension name to req/resp handler\n private extensions: Record> = {};\n\n private desiredRoomSubscriptions = new Set(); // the *desired* room subscriptions\n private confirmedRoomSubscriptions = new Set();\n\n // map of custom subscription name to the subscription\n private customSubscriptions: Map = new Map();\n // map of room ID to custom subscription name\n private roomIdToCustomSubscription: Map = new Map();\n\n private pendingReq?: Promise;\n private abortController?: AbortController;\n\n /**\n * Create a new sliding sync instance\n * @param proxyBaseUrl - The base URL of the sliding sync proxy\n * @param lists - The lists to use for sliding sync.\n * @param roomSubscriptionInfo - The params to use for room subscriptions.\n * @param client - The client to use for /sync calls.\n * @param timeoutMS - The number of milliseconds to wait for a response.\n */\n public constructor(\n private readonly proxyBaseUrl: string,\n lists: Map,\n private roomSubscriptionInfo: MSC3575RoomSubscription,\n private readonly client: MatrixClient,\n private readonly timeoutMS: number,\n ) {\n super();\n this.lists = new Map();\n lists.forEach((list, key) => {\n this.lists.set(key, new SlidingList(list));\n });\n }\n\n /**\n * Add a custom room subscription, referred to by an arbitrary name. If a subscription with this\n * name already exists, it is replaced. No requests are sent by calling this method.\n * @param name - The name of the subscription. Only used to reference this subscription in\n * useCustomSubscription.\n * @param sub - The subscription information.\n */\n public addCustomSubscription(name: string, sub: MSC3575RoomSubscription): void {\n if (this.customSubscriptions.has(name)) {\n logger.warn(`addCustomSubscription: ${name} already exists as a custom subscription, ignoring.`);\n return;\n }\n this.customSubscriptions.set(name, sub);\n }\n\n /**\n * Use a custom subscription previously added via addCustomSubscription. No requests are sent\n * by calling this method. Use modifyRoomSubscriptions to resend subscription information.\n * @param roomId - The room to use the subscription in.\n * @param name - The name of the subscription. If this name is unknown, the default subscription\n * will be used.\n */\n public useCustomSubscription(roomId: string, name: string): void {\n // We already know about this custom subscription, as it is immutable,\n // we don't need to unconfirm the subscription.\n if (this.roomIdToCustomSubscription.get(roomId) === name) {\n return;\n }\n this.roomIdToCustomSubscription.set(roomId, name);\n // unconfirm this subscription so a resend() will send it up afresh.\n this.confirmedRoomSubscriptions.delete(roomId);\n }\n\n /**\n * Get the room index data for a list.\n * @param key - The list key\n * @returns The list data which contains the rooms in this list\n */\n public getListData(key: string): { joinedCount: number; roomIndexToRoomId: Record } | null {\n const data = this.lists.get(key);\n if (!data) {\n return null;\n }\n return {\n joinedCount: data.joinedCount,\n roomIndexToRoomId: Object.assign({}, data.roomIndexToRoomId),\n };\n }\n\n /**\n * Get the full request list parameters for a list index. This function is provided for callers to use\n * in conjunction with setList to update fields on an existing list.\n * @param key - The list key to get the params for.\n * @returns A copy of the list params or undefined.\n */\n public getListParams(key: string): MSC3575List | null {\n const params = this.lists.get(key);\n if (!params) {\n return null;\n }\n return params.getList(true);\n }\n\n /**\n * Set new ranges for an existing list. Calling this function when _only_ the ranges have changed\n * is more efficient than calling setList(index,list) as this function won't resend sticky params,\n * whereas setList always will.\n * @param key - The list key to modify\n * @param ranges - The new ranges to apply.\n * @returns A promise which resolves to the transaction ID when it has been received down sync\n * (or rejects with the transaction ID if the action was not applied e.g the request was cancelled\n * immediately after sending, in which case the action will be applied in the subsequent request)\n */\n public setListRanges(key: string, ranges: number[][]): Promise {\n const list = this.lists.get(key);\n if (!list) {\n return Promise.reject(new Error(\"no list with key \" + key));\n }\n list.updateListRange(ranges);\n return this.resend();\n }\n\n /**\n * Add or replace a list. Calling this function will interrupt the /sync request to resend new\n * lists.\n * @param key - The key to modify\n * @param list - The new list parameters.\n * @returns A promise which resolves to the transaction ID when it has been received down sync\n * (or rejects with the transaction ID if the action was not applied e.g the request was cancelled\n * immediately after sending, in which case the action will be applied in the subsequent request)\n */\n public setList(key: string, list: MSC3575List): Promise {\n const existingList = this.lists.get(key);\n if (existingList) {\n existingList.replaceList(list);\n this.lists.set(key, existingList);\n } else {\n this.lists.set(key, new SlidingList(list));\n }\n this.listModifiedCount += 1;\n return this.resend();\n }\n\n /**\n * Get the room subscriptions for the sync API.\n * @returns A copy of the desired room subscriptions.\n */\n public getRoomSubscriptions(): Set {\n return new Set(Array.from(this.desiredRoomSubscriptions));\n }\n\n /**\n * Modify the room subscriptions for the sync API. Calling this function will interrupt the\n * /sync request to resend new subscriptions. If the /sync stream has not started, this will\n * prepare the room subscriptions for when start() is called.\n * @param s - The new desired room subscriptions.\n * @returns A promise which resolves to the transaction ID when it has been received down sync\n * (or rejects with the transaction ID if the action was not applied e.g the request was cancelled\n * immediately after sending, in which case the action will be applied in the subsequent request)\n */\n public modifyRoomSubscriptions(s: Set): Promise {\n this.desiredRoomSubscriptions = s;\n return this.resend();\n }\n\n /**\n * Modify which events to retrieve for room subscriptions. Invalidates all room subscriptions\n * such that they will be sent up afresh.\n * @param rs - The new room subscription fields to fetch.\n * @returns A promise which resolves to the transaction ID when it has been received down sync\n * (or rejects with the transaction ID if the action was not applied e.g the request was cancelled\n * immediately after sending, in which case the action will be applied in the subsequent request)\n */\n public modifyRoomSubscriptionInfo(rs: MSC3575RoomSubscription): Promise {\n this.roomSubscriptionInfo = rs;\n this.confirmedRoomSubscriptions = new Set();\n return this.resend();\n }\n\n /**\n * Register an extension to send with the /sync request.\n * @param ext - The extension to register.\n */\n public registerExtension(ext: Extension): void {\n if (this.extensions[ext.name()]) {\n throw new Error(`registerExtension: ${ext.name()} already exists as an extension`);\n }\n this.extensions[ext.name()] = ext;\n }\n\n private getExtensionRequest(isInitial: boolean): Record {\n const ext: Record = {};\n Object.keys(this.extensions).forEach((extName) => {\n ext[extName] = this.extensions[extName].onRequest(isInitial);\n });\n return ext;\n }\n\n private onPreExtensionsResponse(ext: Record): void {\n Object.keys(ext).forEach((extName) => {\n if (this.extensions[extName].when() == ExtensionState.PreProcess) {\n this.extensions[extName].onResponse(ext[extName]);\n }\n });\n }\n\n private onPostExtensionsResponse(ext: Record): void {\n Object.keys(ext).forEach((extName) => {\n if (this.extensions[extName].when() == ExtensionState.PostProcess) {\n this.extensions[extName].onResponse(ext[extName]);\n }\n });\n }\n\n /**\n * Invoke all attached room data listeners.\n * @param roomId - The room which received some data.\n * @param roomData - The raw sliding sync response JSON.\n */\n private invokeRoomDataListeners(roomId: string, roomData: MSC3575RoomData): void {\n if (!roomData.required_state) {\n roomData.required_state = [];\n }\n if (!roomData.timeline) {\n roomData.timeline = [];\n }\n this.emit(SlidingSyncEvent.RoomData, roomId, roomData);\n }\n\n /**\n * Invoke all attached lifecycle listeners.\n * @param state - The Lifecycle state\n * @param resp - The raw sync response JSON\n * @param err - Any error that occurred when making the request e.g. network errors.\n */\n private invokeLifecycleListeners(\n state: SlidingSyncState,\n resp: MSC3575SlidingSyncResponse | null,\n err?: Error,\n ): void {\n this.emit(SlidingSyncEvent.Lifecycle, state, resp, err);\n }\n\n private shiftRight(listKey: string, hi: number, low: number): void {\n const list = this.lists.get(listKey);\n if (!list) {\n return;\n }\n // l h\n // 0,1,2,3,4 <- before\n // 0,1,2,2,3 <- after, hi is deleted and low is duplicated\n for (let i = hi; i > low; i--) {\n if (list.isIndexInRange(i)) {\n list.roomIndexToRoomId[i] = list.roomIndexToRoomId[i - 1];\n }\n }\n }\n\n private shiftLeft(listKey: string, hi: number, low: number): void {\n const list = this.lists.get(listKey);\n if (!list) {\n return;\n }\n // l h\n // 0,1,2,3,4 <- before\n // 0,1,3,4,4 <- after, low is deleted and hi is duplicated\n for (let i = low; i < hi; i++) {\n if (list.isIndexInRange(i)) {\n list.roomIndexToRoomId[i] = list.roomIndexToRoomId[i + 1];\n }\n }\n }\n\n private removeEntry(listKey: string, index: number): void {\n const list = this.lists.get(listKey);\n if (!list) {\n return;\n }\n // work out the max index\n let max = -1;\n for (const n in list.roomIndexToRoomId) {\n if (Number(n) > max) {\n max = Number(n);\n }\n }\n if (max < 0 || index > max) {\n return;\n }\n // Everything higher than the gap needs to be shifted left.\n this.shiftLeft(listKey, max, index);\n delete list.roomIndexToRoomId[max];\n }\n\n private addEntry(listKey: string, index: number): void {\n const list = this.lists.get(listKey);\n if (!list) {\n return;\n }\n // work out the max index\n let max = -1;\n for (const n in list.roomIndexToRoomId) {\n if (Number(n) > max) {\n max = Number(n);\n }\n }\n if (max < 0 || index > max) {\n return;\n }\n // Everything higher than the gap needs to be shifted right, +1 so we don't delete the highest element\n this.shiftRight(listKey, max + 1, index);\n }\n\n private processListOps(list: ListResponse, listKey: string): void {\n let gapIndex = -1;\n const listData = this.lists.get(listKey);\n if (!listData) {\n return;\n }\n list.ops.forEach((op: Operation) => {\n if (!listData) {\n return;\n }\n switch (op.op) {\n case \"DELETE\": {\n logger.debug(\"DELETE\", listKey, op.index, \";\");\n delete listData.roomIndexToRoomId[op.index];\n if (gapIndex !== -1) {\n // we already have a DELETE operation to process, so process it.\n this.removeEntry(listKey, gapIndex);\n }\n gapIndex = op.index;\n break;\n }\n case \"INSERT\": {\n logger.debug(\"INSERT\", listKey, op.index, op.room_id, \";\");\n if (listData.roomIndexToRoomId[op.index]) {\n // something is in this space, shift items out of the way\n if (gapIndex < 0) {\n // we haven't been told where to shift from, so make way for a new room entry.\n this.addEntry(listKey, op.index);\n } else if (gapIndex > op.index) {\n // the gap is further down the list, shift every element to the right\n // starting at the gap so we can just shift each element in turn:\n // [A,B,C,_] gapIndex=3, op.index=0\n // [A,B,C,C] i=3\n // [A,B,B,C] i=2\n // [A,A,B,C] i=1\n // Terminate. We'll assign into op.index next.\n this.shiftRight(listKey, gapIndex, op.index);\n } else if (gapIndex < op.index) {\n // the gap is further up the list, shift every element to the left\n // starting at the gap so we can just shift each element in turn\n this.shiftLeft(listKey, op.index, gapIndex);\n }\n }\n // forget the gap, we don't need it anymore. This is outside the check for\n // a room being present in this index position because INSERTs always universally\n // forget the gap, not conditionally based on the presence of a room in the INSERT\n // position. Without this, DELETE 0; INSERT 0; would do the wrong thing.\n gapIndex = -1;\n listData.roomIndexToRoomId[op.index] = op.room_id;\n break;\n }\n case \"INVALIDATE\": {\n const startIndex = op.range[0];\n for (let i = startIndex; i <= op.range[1]; i++) {\n delete listData.roomIndexToRoomId[i];\n }\n logger.debug(\"INVALIDATE\", listKey, op.range[0], op.range[1], \";\");\n break;\n }\n case \"SYNC\": {\n const startIndex = op.range[0];\n for (let i = startIndex; i <= op.range[1]; i++) {\n const roomId = op.room_ids[i - startIndex];\n if (!roomId) {\n break; // we are at the end of list\n }\n listData.roomIndexToRoomId[i] = roomId;\n }\n logger.debug(\"SYNC\", listKey, op.range[0], op.range[1], (op.room_ids || []).join(\" \"), \";\");\n break;\n }\n }\n });\n if (gapIndex !== -1) {\n // we already have a DELETE operation to process, so process it\n // Everything higher than the gap needs to be shifted left.\n this.removeEntry(listKey, gapIndex);\n }\n }\n\n /**\n * Resend a Sliding Sync request. Used when something has changed in the request. Resolves with\n * the transaction ID of this request on success. Rejects with the transaction ID of this request\n * on failure.\n */\n public resend(): Promise {\n if (this.needsResend && this.txnIdDefers.length > 0) {\n // we already have a resend queued, so just return the same promise\n return this.txnIdDefers[this.txnIdDefers.length - 1].promise;\n }\n this.needsResend = true;\n this.txnId = this.client.makeTxnId();\n const d = defer();\n this.txnIdDefers.push({\n ...d,\n txnId: this.txnId,\n });\n this.abortController?.abort();\n this.abortController = new AbortController();\n return d.promise;\n }\n\n private resolveTransactionDefers(txnId?: string): void {\n if (!txnId) {\n return;\n }\n // find the matching index\n let txnIndex = -1;\n for (let i = 0; i < this.txnIdDefers.length; i++) {\n if (this.txnIdDefers[i].txnId === txnId) {\n txnIndex = i;\n break;\n }\n }\n if (txnIndex === -1) {\n // this shouldn't happen; we shouldn't be seeing txn_ids for things we don't know about,\n // whine about it.\n logger.warn(`resolveTransactionDefers: seen ${txnId} but it isn't a pending txn, ignoring.`);\n return;\n }\n // This list is sorted in time, so if the input txnId ACKs in the middle of this array,\n // then everything before it that hasn't been ACKed yet never will and we should reject them.\n for (let i = 0; i < txnIndex; i++) {\n this.txnIdDefers[i].reject(this.txnIdDefers[i].txnId);\n }\n this.txnIdDefers[txnIndex].resolve(txnId);\n // clear out settled promises, including the one we resolved.\n this.txnIdDefers = this.txnIdDefers.slice(txnIndex + 1);\n }\n\n /**\n * Stop syncing with the server.\n */\n public stop(): void {\n this.terminated = true;\n this.abortController?.abort();\n // remove all listeners so things can be GC'd\n this.removeAllListeners(SlidingSyncEvent.Lifecycle);\n this.removeAllListeners(SlidingSyncEvent.List);\n this.removeAllListeners(SlidingSyncEvent.RoomData);\n }\n\n /**\n * Re-setup this connection e.g in the event of an expired session.\n */\n private resetup(): void {\n logger.warn(\"SlidingSync: resetting connection info\");\n // any pending txn ID defers will be forgotten already by the server, so clear them out\n this.txnIdDefers.forEach((d) => {\n d.reject(d.txnId);\n });\n this.txnIdDefers = [];\n // resend sticky params and de-confirm all subscriptions\n this.lists.forEach((l) => {\n l.setModified(true);\n });\n this.confirmedRoomSubscriptions = new Set(); // leave desired ones alone though!\n // reset the connection as we might be wedged\n this.needsResend = true;\n this.abortController?.abort();\n this.abortController = new AbortController();\n }\n\n /**\n * Start syncing with the server. Blocks until stopped.\n */\n public async start(): Promise {\n this.abortController = new AbortController();\n\n let currentPos: string | undefined;\n while (!this.terminated) {\n this.needsResend = false;\n let doNotUpdateList = false;\n let resp: MSC3575SlidingSyncResponse | undefined;\n try {\n const listModifiedCount = this.listModifiedCount;\n const reqLists: Record = {};\n this.lists.forEach((l: SlidingList, key: string) => {\n reqLists[key] = l.getList(false);\n });\n const reqBody: MSC3575SlidingSyncRequest = {\n lists: reqLists,\n pos: currentPos,\n timeout: this.timeoutMS,\n clientTimeout: this.timeoutMS + BUFFER_PERIOD_MS,\n extensions: this.getExtensionRequest(currentPos === undefined),\n };\n // check if we are (un)subscribing to a room and modify request this one time for it\n const newSubscriptions = difference(this.desiredRoomSubscriptions, this.confirmedRoomSubscriptions);\n const unsubscriptions = difference(this.confirmedRoomSubscriptions, this.desiredRoomSubscriptions);\n if (unsubscriptions.size > 0) {\n reqBody.unsubscribe_rooms = Array.from(unsubscriptions);\n }\n if (newSubscriptions.size > 0) {\n reqBody.room_subscriptions = {};\n for (const roomId of newSubscriptions) {\n const customSubName = this.roomIdToCustomSubscription.get(roomId);\n let sub = this.roomSubscriptionInfo;\n if (customSubName && this.customSubscriptions.has(customSubName)) {\n sub = this.customSubscriptions.get(customSubName)!;\n }\n reqBody.room_subscriptions[roomId] = sub;\n }\n }\n if (this.txnId) {\n reqBody.txn_id = this.txnId;\n this.txnId = null;\n }\n this.pendingReq = this.client.slidingSync(reqBody, this.proxyBaseUrl, this.abortController.signal);\n resp = await this.pendingReq;\n currentPos = resp.pos;\n // update what we think we're subscribed to.\n for (const roomId of newSubscriptions) {\n this.confirmedRoomSubscriptions.add(roomId);\n }\n for (const roomId of unsubscriptions) {\n this.confirmedRoomSubscriptions.delete(roomId);\n }\n if (listModifiedCount !== this.listModifiedCount) {\n // the lists have been modified whilst we were waiting for 'await' to return, but the abort()\n // call did nothing. It is NOT SAFE to modify the list array now. We'll process the response but\n // not update list pointers.\n logger.debug(\"list modified during await call, not updating list\");\n doNotUpdateList = true;\n }\n // mark all these lists as having been sent as sticky so we don't keep sending sticky params\n this.lists.forEach((l) => {\n l.setModified(false);\n });\n // set default empty values so we don't need to null check\n resp.lists = resp.lists || {};\n resp.rooms = resp.rooms || {};\n resp.extensions = resp.extensions || {};\n Object.keys(resp.lists).forEach((key: string) => {\n const list = this.lists.get(key);\n if (!list || !resp) {\n return;\n }\n list.joinedCount = resp.lists[key].count;\n });\n this.invokeLifecycleListeners(SlidingSyncState.RequestFinished, resp);\n } catch (err) {\n if ((err).httpStatus) {\n this.invokeLifecycleListeners(SlidingSyncState.RequestFinished, null, err);\n if ((err).httpStatus === 400) {\n // session probably expired TODO: assign an errcode\n // so drop state and re-request\n this.resetup();\n currentPos = undefined;\n await sleep(50); // in case the 400 was for something else; don't tightloop\n continue;\n } // else fallthrough to generic error handling\n } else if (this.needsResend || (err).name === \"AbortError\") {\n continue; // don't sleep as we caused this error by abort()ing the request.\n }\n logger.error(err);\n await sleep(5000);\n }\n if (!resp) {\n continue;\n }\n this.onPreExtensionsResponse(resp.extensions);\n\n Object.keys(resp.rooms).forEach((roomId) => {\n this.invokeRoomDataListeners(roomId, resp!.rooms[roomId]);\n });\n\n const listKeysWithUpdates: Set = new Set();\n if (!doNotUpdateList) {\n for (const [key, list] of Object.entries(resp.lists)) {\n list.ops = list.ops || [];\n if (list.ops.length > 0) {\n listKeysWithUpdates.add(key);\n }\n this.processListOps(list, key);\n }\n }\n this.invokeLifecycleListeners(SlidingSyncState.Complete, resp);\n this.onPostExtensionsResponse(resp.extensions);\n listKeysWithUpdates.forEach((listKey: string) => {\n const list = this.lists.get(listKey);\n if (!list) {\n return;\n }\n this.emit(SlidingSyncEvent.List, listKey, list.joinedCount, Object.assign({}, list.roomIndexToRoomId));\n });\n\n this.resolveTransactionDefers(resp.txn_id);\n }\n }\n}\n\nconst difference = (setA: Set, setB: Set): Set => {\n const diff = new Set(setA);\n for (const elem of setB) {\n diff.delete(elem);\n }\n return diff;\n};\n", - "/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { IMinimalEvent, ISyncData, ISyncResponse, SyncAccumulator } from \"../sync-accumulator\";\nimport * as utils from \"../utils\";\nimport * as IndexedDBHelpers from \"../indexeddb-helpers\";\nimport { logger } from \"../logger\";\nimport { IStateEventWithRoomId, IStoredClientOpts } from \"../matrix\";\nimport { ISavedSync } from \"./index\";\nimport { IIndexedDBBackend, UserTuple } from \"./indexeddb-backend\";\nimport { IndexedToDeviceBatch, ToDeviceBatchWithTxnId } from \"../models/ToDeviceMessage\";\n\ntype DbMigration = (db: IDBDatabase) => void;\nconst DB_MIGRATIONS: DbMigration[] = [\n (db): void => {\n // Make user store, clobber based on user ID. (userId property of User objects)\n db.createObjectStore(\"users\", { keyPath: [\"userId\"] });\n\n // Make account data store, clobber based on event type.\n // (event.type property of MatrixEvent objects)\n db.createObjectStore(\"accountData\", { keyPath: [\"type\"] });\n\n // Make /sync store (sync tokens, room data, etc), always clobber (const key).\n db.createObjectStore(\"sync\", { keyPath: [\"clobber\"] });\n },\n (db): void => {\n const oobMembersStore = db.createObjectStore(\"oob_membership_events\", {\n keyPath: [\"room_id\", \"state_key\"],\n });\n oobMembersStore.createIndex(\"room\", \"room_id\");\n },\n (db): void => {\n db.createObjectStore(\"client_options\", { keyPath: [\"clobber\"] });\n },\n (db): void => {\n db.createObjectStore(\"to_device_queue\", { autoIncrement: true });\n },\n // Expand as needed.\n];\nconst VERSION = DB_MIGRATIONS.length;\n\n/**\n * Helper method to collect results from a Cursor and promiseify it.\n * @param store - The store to perform openCursor on.\n * @param keyRange - Optional key range to apply on the cursor.\n * @param resultMapper - A function which is repeatedly called with a\n * Cursor.\n * Return the data you want to keep.\n * @returns Promise which resolves to an array of whatever you returned from\n * resultMapper.\n */\nfunction selectQuery(\n store: IDBObjectStore,\n keyRange: IDBKeyRange | IDBValidKey | undefined,\n resultMapper: (cursor: IDBCursorWithValue) => T,\n): Promise {\n const query = store.openCursor(keyRange);\n return new Promise((resolve, reject) => {\n const results: T[] = [];\n query.onerror = (): void => {\n reject(new Error(\"Query failed: \" + query.error));\n };\n // collect results\n query.onsuccess = (): void => {\n const cursor = query.result;\n if (!cursor) {\n resolve(results);\n return; // end of results\n }\n results.push(resultMapper(cursor));\n cursor.continue();\n };\n });\n}\n\nfunction txnAsPromise(txn: IDBTransaction): Promise {\n return new Promise((resolve, reject) => {\n txn.oncomplete = function (event): void {\n resolve(event);\n };\n txn.onerror = function (): void {\n reject(txn.error);\n };\n });\n}\n\nfunction reqAsEventPromise(req: IDBRequest): Promise {\n return new Promise((resolve, reject) => {\n req.onsuccess = function (event): void {\n resolve(event);\n };\n req.onerror = function (): void {\n reject(req.error);\n };\n });\n}\n\nfunction reqAsPromise(req: IDBRequest): Promise {\n return new Promise((resolve, reject) => {\n req.onsuccess = (): void => resolve(req);\n req.onerror = (err): void => reject(err);\n });\n}\n\nfunction reqAsCursorPromise(req: IDBRequest): Promise {\n return reqAsEventPromise(req).then((event) => req.result);\n}\n\nexport class LocalIndexedDBStoreBackend implements IIndexedDBBackend {\n public static exists(indexedDB: IDBFactory, dbName: string): Promise {\n dbName = \"matrix-js-sdk:\" + (dbName || \"default\");\n return IndexedDBHelpers.exists(indexedDB, dbName);\n }\n\n private readonly dbName: string;\n private readonly syncAccumulator: SyncAccumulator;\n private db?: IDBDatabase;\n private disconnected = true;\n private _isNewlyCreated = false;\n private syncToDatabasePromise?: Promise;\n private pendingUserPresenceData: UserTuple[] = [];\n\n /**\n * Does the actual reading from and writing to the indexeddb\n *\n * Construct a new Indexed Database store backend. This requires a call to\n * `connect()` before this store can be used.\n * @param indexedDB - The Indexed DB interface e.g\n * `window.indexedDB`\n * @param dbName - Optional database name. The same name must be used\n * to open the same database.\n */\n public constructor(private readonly indexedDB: IDBFactory, dbName = \"default\") {\n this.dbName = \"matrix-js-sdk:\" + dbName;\n this.syncAccumulator = new SyncAccumulator();\n }\n\n /**\n * Attempt to connect to the database. This can fail if the user does not\n * grant permission.\n * @returns Promise which resolves if successfully connected.\n */\n public connect(onClose?: () => void): Promise {\n if (!this.disconnected) {\n logger.log(`LocalIndexedDBStoreBackend.connect: already connected or connecting`);\n return Promise.resolve();\n }\n\n this.disconnected = false;\n\n logger.log(`LocalIndexedDBStoreBackend.connect: connecting...`);\n const req = this.indexedDB.open(this.dbName, VERSION);\n req.onupgradeneeded = (ev): void => {\n const db = req.result;\n const oldVersion = ev.oldVersion;\n logger.log(`LocalIndexedDBStoreBackend.connect: upgrading from ${oldVersion}`);\n if (oldVersion < 1) {\n // The database did not previously exist\n this._isNewlyCreated = true;\n }\n DB_MIGRATIONS.forEach((migration, index) => {\n if (oldVersion <= index) migration(db);\n });\n };\n\n req.onblocked = (): void => {\n logger.log(`can't yet open LocalIndexedDBStoreBackend because it is open elsewhere`);\n };\n\n logger.log(`LocalIndexedDBStoreBackend.connect: awaiting connection...`);\n return reqAsEventPromise(req).then(async () => {\n logger.log(`LocalIndexedDBStoreBackend.connect: connected`);\n this.db = req.result;\n\n // add a poorly-named listener for when deleteDatabase is called\n // so we can close our db connections.\n this.db.onversionchange = (): void => {\n this.db?.close(); // this does not call onclose\n this.disconnected = true;\n this.db = undefined;\n onClose?.();\n };\n this.db.onclose = (): void => {\n this.disconnected = true;\n this.db = undefined;\n onClose?.();\n };\n\n await this.init();\n });\n }\n\n /** @returns whether or not the database was newly created in this session. */\n public isNewlyCreated(): Promise {\n return Promise.resolve(this._isNewlyCreated);\n }\n\n /**\n * Having connected, load initial data from the database and prepare for use\n * @returns Promise which resolves on success\n */\n private init(): Promise {\n return Promise.all([this.loadAccountData(), this.loadSyncData()]).then(([accountData, syncData]) => {\n logger.log(`LocalIndexedDBStoreBackend: loaded initial data`);\n this.syncAccumulator.accumulate(\n {\n next_batch: syncData.nextBatch,\n rooms: syncData.roomsData,\n account_data: {\n events: accountData,\n },\n },\n true,\n );\n });\n }\n\n /**\n * Returns the out-of-band membership events for this room that\n * were previously loaded.\n * @returns the events, potentially an empty array if OOB loading didn't yield any new members\n * @returns in case the members for this room haven't been stored yet\n */\n public getOutOfBandMembers(roomId: string): Promise {\n return new Promise((resolve, reject) => {\n const tx = this.db!.transaction([\"oob_membership_events\"], \"readonly\");\n const store = tx.objectStore(\"oob_membership_events\");\n const roomIndex = store.index(\"room\");\n const range = IDBKeyRange.only(roomId);\n const request = roomIndex.openCursor(range);\n\n const membershipEvents: IStateEventWithRoomId[] = [];\n // did we encounter the oob_written marker object\n // amongst the results? That means OOB member\n // loading already happened for this room\n // but there were no members to persist as they\n // were all known already\n let oobWritten = false;\n\n request.onsuccess = (): void => {\n const cursor = request.result;\n if (!cursor) {\n // Unknown room\n if (!membershipEvents.length && !oobWritten) {\n return resolve(null);\n }\n return resolve(membershipEvents);\n }\n const record = cursor.value;\n if (record.oob_written) {\n oobWritten = true;\n } else {\n membershipEvents.push(record);\n }\n cursor.continue();\n };\n request.onerror = (err): void => {\n reject(err);\n };\n }).then((events) => {\n logger.log(`LL: got ${events?.length} membershipEvents from storage for room ${roomId} ...`);\n return events;\n });\n }\n\n /**\n * Stores the out-of-band membership events for this room. Note that\n * it still makes sense to store an empty array as the OOB status for the room is\n * marked as fetched, and getOutOfBandMembers will return an empty array instead of null\n * @param membershipEvents - the membership events to store\n */\n public async setOutOfBandMembers(roomId: string, membershipEvents: IStateEventWithRoomId[]): Promise {\n logger.log(`LL: backend about to store ${membershipEvents.length}` + ` members for ${roomId}`);\n const tx = this.db!.transaction([\"oob_membership_events\"], \"readwrite\");\n const store = tx.objectStore(\"oob_membership_events\");\n membershipEvents.forEach((e) => {\n store.put(e);\n });\n // aside from all the events, we also write a marker object to the store\n // to mark the fact that OOB members have been written for this room.\n // It's possible that 0 members need to be written as all where previously know\n // but we still need to know whether to return null or [] from getOutOfBandMembers\n // where null means out of band members haven't been stored yet for this room\n const markerObject = {\n room_id: roomId,\n oob_written: true,\n state_key: 0,\n };\n store.put(markerObject);\n await txnAsPromise(tx);\n logger.log(`LL: backend done storing for ${roomId}!`);\n }\n\n public async clearOutOfBandMembers(roomId: string): Promise {\n // the approach to delete all members for a room\n // is to get the min and max state key from the index\n // for that room, and then delete between those\n // keys in the store.\n // this should be way faster than deleting every member\n // individually for a large room.\n const readTx = this.db!.transaction([\"oob_membership_events\"], \"readonly\");\n const store = readTx.objectStore(\"oob_membership_events\");\n const roomIndex = store.index(\"room\");\n const roomRange = IDBKeyRange.only(roomId);\n\n const minStateKeyProm = reqAsCursorPromise(roomIndex.openKeyCursor(roomRange, \"next\")).then(\n (cursor) => (cursor?.primaryKey)[1],\n );\n const maxStateKeyProm = reqAsCursorPromise(roomIndex.openKeyCursor(roomRange, \"prev\")).then(\n (cursor) => (cursor?.primaryKey)[1],\n );\n const [minStateKey, maxStateKey] = await Promise.all([minStateKeyProm, maxStateKeyProm]);\n\n const writeTx = this.db!.transaction([\"oob_membership_events\"], \"readwrite\");\n const writeStore = writeTx.objectStore(\"oob_membership_events\");\n const membersKeyRange = IDBKeyRange.bound([roomId, minStateKey], [roomId, maxStateKey]);\n\n logger.log(\n `LL: Deleting all users + marker in storage for room ${roomId}, with key range:`,\n [roomId, minStateKey],\n [roomId, maxStateKey],\n );\n await reqAsPromise(writeStore.delete(membersKeyRange));\n }\n\n /**\n * Clear the entire database. This should be used when logging out of a client\n * to prevent mixing data between accounts.\n * @returns Resolved when the database is cleared.\n */\n public clearDatabase(): Promise {\n return new Promise((resolve) => {\n logger.log(`Removing indexeddb instance: ${this.dbName}`);\n const req = this.indexedDB.deleteDatabase(this.dbName);\n\n req.onblocked = (): void => {\n logger.log(`can't yet delete indexeddb ${this.dbName} because it is open elsewhere`);\n };\n\n req.onerror = (): void => {\n // in firefox, with indexedDB disabled, this fails with a\n // DOMError. We treat this as non-fatal, so that we can still\n // use the app.\n logger.warn(`unable to delete js-sdk store indexeddb: ${req.error}`);\n resolve();\n };\n\n req.onsuccess = (): void => {\n logger.log(`Removed indexeddb instance: ${this.dbName}`);\n resolve();\n };\n });\n }\n\n /**\n * @param copy - If false, the data returned is from internal\n * buffers and must not be mutated. Otherwise, a copy is made before\n * returning such that the data can be safely mutated. Default: true.\n *\n * @returns Promise which resolves with a sync response to restore the\n * client state to where it was at the last save, or null if there\n * is no saved sync data.\n */\n public getSavedSync(copy = true): Promise {\n const data = this.syncAccumulator.getJSON();\n if (!data.nextBatch) return Promise.resolve(null);\n if (copy) {\n // We must deep copy the stored data so that the /sync processing code doesn't\n // corrupt the internal state of the sync accumulator (it adds non-clonable keys)\n return Promise.resolve(utils.deepCopy(data));\n } else {\n return Promise.resolve(data);\n }\n }\n\n public getNextBatchToken(): Promise {\n return Promise.resolve(this.syncAccumulator.getNextBatchToken());\n }\n\n public setSyncData(syncData: ISyncResponse): Promise {\n return Promise.resolve().then(() => {\n this.syncAccumulator.accumulate(syncData);\n });\n }\n\n /**\n * Sync users and all accumulated sync data to the database.\n * If a previous sync is in flight, the new data will be added to the\n * next sync and the current sync's promise will be returned.\n * @param userTuples - The user tuples\n * @returns Promise which resolves if the data was persisted.\n */\n public async syncToDatabase(userTuples: UserTuple[]): Promise {\n if (this.syncToDatabasePromise) {\n logger.warn(\"Skipping syncToDatabase() as persist already in flight\");\n this.pendingUserPresenceData.push(...userTuples);\n return this.syncToDatabasePromise;\n }\n userTuples.unshift(...this.pendingUserPresenceData);\n this.syncToDatabasePromise = this.doSyncToDatabase(userTuples);\n return this.syncToDatabasePromise;\n }\n\n private async doSyncToDatabase(userTuples: UserTuple[]): Promise {\n try {\n const syncData = this.syncAccumulator.getJSON(true);\n await Promise.all([\n this.persistUserPresenceEvents(userTuples),\n this.persistAccountData(syncData.accountData),\n this.persistSyncData(syncData.nextBatch, syncData.roomsData),\n ]);\n } finally {\n this.syncToDatabasePromise = undefined;\n }\n }\n\n /**\n * Persist rooms /sync data along with the next batch token.\n * @param nextBatch - The next_batch /sync value.\n * @param roomsData - The 'rooms' /sync data from a SyncAccumulator\n * @returns Promise which resolves if the data was persisted.\n */\n private persistSyncData(nextBatch: string, roomsData: ISyncResponse[\"rooms\"]): Promise {\n logger.log(\"Persisting sync data up to\", nextBatch);\n return utils.promiseTry(() => {\n const txn = this.db!.transaction([\"sync\"], \"readwrite\");\n const store = txn.objectStore(\"sync\");\n store.put({\n clobber: \"-\", // constant key so will always clobber\n nextBatch,\n roomsData,\n }); // put == UPSERT\n return txnAsPromise(txn).then(() => {\n logger.log(\"Persisted sync data up to\", nextBatch);\n });\n });\n }\n\n /**\n * Persist a list of account data events. Events with the same 'type' will\n * be replaced.\n * @param accountData - An array of raw user-scoped account data events\n * @returns Promise which resolves if the events were persisted.\n */\n private persistAccountData(accountData: IMinimalEvent[]): Promise {\n return utils.promiseTry(() => {\n const txn = this.db!.transaction([\"accountData\"], \"readwrite\");\n const store = txn.objectStore(\"accountData\");\n for (const event of accountData) {\n store.put(event); // put == UPSERT\n }\n return txnAsPromise(txn).then();\n });\n }\n\n /**\n * Persist a list of [user id, presence event] they are for.\n * Users with the same 'userId' will be replaced.\n * Presence events should be the event in its raw form (not the Event\n * object)\n * @param tuples - An array of [userid, event] tuples\n * @returns Promise which resolves if the users were persisted.\n */\n private persistUserPresenceEvents(tuples: UserTuple[]): Promise {\n return utils.promiseTry(() => {\n const txn = this.db!.transaction([\"users\"], \"readwrite\");\n const store = txn.objectStore(\"users\");\n for (const tuple of tuples) {\n store.put({\n userId: tuple[0],\n event: tuple[1],\n }); // put == UPSERT\n }\n return txnAsPromise(txn).then();\n });\n }\n\n /**\n * Load all user presence events from the database. This is not cached.\n * FIXME: It would probably be more sensible to store the events in the\n * sync.\n * @returns A list of presence events in their raw form.\n */\n public getUserPresenceEvents(): Promise {\n return utils.promiseTry(() => {\n const txn = this.db!.transaction([\"users\"], \"readonly\");\n const store = txn.objectStore(\"users\");\n return selectQuery(store, undefined, (cursor) => {\n return [cursor.value.userId, cursor.value.event];\n });\n });\n }\n\n /**\n * Load all the account data events from the database. This is not cached.\n * @returns A list of raw global account events.\n */\n private loadAccountData(): Promise {\n logger.log(`LocalIndexedDBStoreBackend: loading account data...`);\n return utils.promiseTry(() => {\n const txn = this.db!.transaction([\"accountData\"], \"readonly\");\n const store = txn.objectStore(\"accountData\");\n return selectQuery(store, undefined, (cursor) => {\n return cursor.value;\n }).then((result: IMinimalEvent[]) => {\n logger.log(`LocalIndexedDBStoreBackend: loaded account data`);\n return result;\n });\n });\n }\n\n /**\n * Load the sync data from the database.\n * @returns An object with \"roomsData\" and \"nextBatch\" keys.\n */\n private loadSyncData(): Promise {\n logger.log(`LocalIndexedDBStoreBackend: loading sync data...`);\n return utils.promiseTry(() => {\n const txn = this.db!.transaction([\"sync\"], \"readonly\");\n const store = txn.objectStore(\"sync\");\n return selectQuery(store, undefined, (cursor) => {\n return cursor.value;\n }).then((results: ISyncData[]) => {\n logger.log(`LocalIndexedDBStoreBackend: loaded sync data`);\n if (results.length > 1) {\n logger.warn(\"loadSyncData: More than 1 sync row found.\");\n }\n return results.length > 0 ? results[0] : ({} as ISyncData);\n });\n });\n }\n\n public getClientOptions(): Promise {\n return Promise.resolve().then(() => {\n const txn = this.db!.transaction([\"client_options\"], \"readonly\");\n const store = txn.objectStore(\"client_options\");\n return selectQuery(store, undefined, (cursor) => {\n return cursor.value?.options;\n }).then((results) => results[0]);\n });\n }\n\n public async storeClientOptions(options: IStoredClientOpts): Promise {\n const txn = this.db!.transaction([\"client_options\"], \"readwrite\");\n const store = txn.objectStore(\"client_options\");\n store.put({\n clobber: \"-\", // constant key so will always clobber\n options: options,\n }); // put == UPSERT\n await txnAsPromise(txn);\n }\n\n public async saveToDeviceBatches(batches: ToDeviceBatchWithTxnId[]): Promise {\n const txn = this.db!.transaction([\"to_device_queue\"], \"readwrite\");\n const store = txn.objectStore(\"to_device_queue\");\n for (const batch of batches) {\n store.add(batch);\n }\n await txnAsPromise(txn);\n }\n\n public async getOldestToDeviceBatch(): Promise {\n const txn = this.db!.transaction([\"to_device_queue\"], \"readonly\");\n const store = txn.objectStore(\"to_device_queue\");\n const cursor = await reqAsCursorPromise(store.openCursor());\n if (!cursor) return null;\n\n const resultBatch = cursor.value as ToDeviceBatchWithTxnId;\n\n return {\n id: cursor.key as number,\n txnId: resultBatch.txnId,\n eventType: resultBatch.eventType,\n batch: resultBatch.batch,\n };\n }\n\n public async removeToDeviceBatch(id: number): Promise {\n const txn = this.db!.transaction([\"to_device_queue\"], \"readwrite\");\n const store = txn.objectStore(\"to_device_queue\");\n store.delete(id);\n await txnAsPromise(txn);\n }\n}\n", - "/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { logger } from \"../logger\";\nimport { defer, IDeferred } from \"../utils\";\nimport { ISavedSync } from \"./index\";\nimport { IStoredClientOpts } from \"../client\";\nimport { IStateEventWithRoomId, ISyncResponse } from \"../matrix\";\nimport { IIndexedDBBackend, UserTuple } from \"./indexeddb-backend\";\nimport { IndexedToDeviceBatch, ToDeviceBatchWithTxnId } from \"../models/ToDeviceMessage\";\n\nexport class RemoteIndexedDBStoreBackend implements IIndexedDBBackend {\n private worker?: Worker;\n private nextSeq = 0;\n // The currently in-flight requests to the actual backend\n private inFlight: Record> = {}; // seq: promise\n // Once we start connecting, we keep the promise and re-use it\n // if we try to connect again\n private startPromise?: Promise;\n // Callback for when the IndexedDB gets closed unexpectedly\n private onClose?(): void;\n\n /**\n * An IndexedDB store backend where the actual backend sits in a web\n * worker.\n *\n * Construct a new Indexed Database store backend. This requires a call to\n * `connect()` before this store can be used.\n * @param workerFactory - Factory which produces a Worker\n * @param dbName - Optional database name. The same name must be used\n * to open the same database.\n */\n public constructor(private readonly workerFactory: () => Worker, private readonly dbName?: string) {}\n\n /**\n * Attempt to connect to the database. This can fail if the user does not\n * grant permission.\n * @returns Promise which resolves if successfully connected.\n */\n public connect(onClose?: () => void): Promise {\n this.onClose = onClose;\n return this.ensureStarted().then(() => this.doCmd(\"connect\"));\n }\n\n /**\n * Clear the entire database. This should be used when logging out of a client\n * to prevent mixing data between accounts.\n * @returns Resolved when the database is cleared.\n */\n public clearDatabase(): Promise {\n return this.ensureStarted().then(() => this.doCmd(\"clearDatabase\"));\n }\n\n /** @returns whether or not the database was newly created in this session. */\n public isNewlyCreated(): Promise {\n return this.doCmd(\"isNewlyCreated\");\n }\n\n /**\n * @returns Promise which resolves with a sync response to restore the\n * client state to where it was at the last save, or null if there\n * is no saved sync data.\n */\n public getSavedSync(): Promise {\n return this.doCmd(\"getSavedSync\");\n }\n\n public getNextBatchToken(): Promise {\n return this.doCmd(\"getNextBatchToken\");\n }\n\n public setSyncData(syncData: ISyncResponse): Promise {\n return this.doCmd(\"setSyncData\", [syncData]);\n }\n\n public syncToDatabase(userTuples: UserTuple[]): Promise {\n return this.doCmd(\"syncToDatabase\", [userTuples]);\n }\n\n /**\n * Returns the out-of-band membership events for this room that\n * were previously loaded.\n * @returns the events, potentially an empty array if OOB loading didn't yield any new members\n * @returns in case the members for this room haven't been stored yet\n */\n public getOutOfBandMembers(roomId: string): Promise {\n return this.doCmd(\"getOutOfBandMembers\", [roomId]);\n }\n\n /**\n * Stores the out-of-band membership events for this room. Note that\n * it still makes sense to store an empty array as the OOB status for the room is\n * marked as fetched, and getOutOfBandMembers will return an empty array instead of null\n * @param membershipEvents - the membership events to store\n * @returns when all members have been stored\n */\n public setOutOfBandMembers(roomId: string, membershipEvents: IStateEventWithRoomId[]): Promise {\n return this.doCmd(\"setOutOfBandMembers\", [roomId, membershipEvents]);\n }\n\n public clearOutOfBandMembers(roomId: string): Promise {\n return this.doCmd(\"clearOutOfBandMembers\", [roomId]);\n }\n\n public getClientOptions(): Promise {\n return this.doCmd(\"getClientOptions\");\n }\n\n public storeClientOptions(options: IStoredClientOpts): Promise {\n return this.doCmd(\"storeClientOptions\", [options]);\n }\n\n /**\n * Load all user presence events from the database. This is not cached.\n * @returns A list of presence events in their raw form.\n */\n public getUserPresenceEvents(): Promise {\n return this.doCmd(\"getUserPresenceEvents\");\n }\n\n public async saveToDeviceBatches(batches: ToDeviceBatchWithTxnId[]): Promise {\n return this.doCmd(\"saveToDeviceBatches\", [batches]);\n }\n\n public async getOldestToDeviceBatch(): Promise {\n return this.doCmd(\"getOldestToDeviceBatch\");\n }\n\n public async removeToDeviceBatch(id: number): Promise {\n return this.doCmd(\"removeToDeviceBatch\", [id]);\n }\n\n private ensureStarted(): Promise {\n if (!this.startPromise) {\n this.worker = this.workerFactory();\n this.worker.onmessage = this.onWorkerMessage;\n\n // tell the worker the db name.\n this.startPromise = this.doCmd(\"setupWorker\", [this.dbName]).then(() => {\n logger.log(\"IndexedDB worker is ready\");\n });\n }\n return this.startPromise;\n }\n\n private doCmd(command: string, args?: any): Promise {\n // wrap in a q so if the postMessage throws,\n // the promise automatically gets rejected\n return Promise.resolve().then(() => {\n const seq = this.nextSeq++;\n const def = defer();\n\n this.inFlight[seq] = def;\n\n this.worker?.postMessage({ command, seq, args });\n\n return def.promise;\n });\n }\n\n private onWorkerMessage = (ev: MessageEvent): void => {\n const msg = ev.data;\n\n if (msg.command == \"closed\") {\n this.onClose?.();\n } else if (msg.command == \"cmd_success\" || msg.command == \"cmd_fail\") {\n if (msg.seq === undefined) {\n logger.error(\"Got reply from worker with no seq\");\n return;\n }\n\n const def = this.inFlight[msg.seq];\n if (def === undefined) {\n logger.error(\"Got reply for unknown seq \" + msg.seq);\n return;\n }\n delete this.inFlight[msg.seq];\n\n if (msg.command == \"cmd_success\") {\n def.resolve(msg.result);\n } else {\n const error = new Error(msg.error.message);\n error.name = msg.error.name;\n def.reject(error);\n }\n } else {\n logger.warn(\"Unrecognised message from worker: \", msg);\n }\n };\n}\n", - "/*\nCopyright 2017 - 2021 Vector Creations Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/* eslint-disable @babel/no-invalid-this */\n\nimport { MemoryStore, IOpts as IBaseOpts } from \"./memory\";\nimport { LocalIndexedDBStoreBackend } from \"./indexeddb-local-backend\";\nimport { RemoteIndexedDBStoreBackend } from \"./indexeddb-remote-backend\";\nimport { User } from \"../models/user\";\nimport { IEvent, MatrixEvent } from \"../models/event\";\nimport { logger } from \"../logger\";\nimport { ISavedSync } from \"./index\";\nimport { IIndexedDBBackend } from \"./indexeddb-backend\";\nimport { ISyncResponse } from \"../sync-accumulator\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter\";\nimport { IStateEventWithRoomId } from \"../@types/search\";\nimport { IndexedToDeviceBatch, ToDeviceBatchWithTxnId } from \"../models/ToDeviceMessage\";\nimport { IStoredClientOpts } from \"../client\";\n\n/**\n * This is an internal module. See {@link IndexedDBStore} for the public class.\n */\n\n// If this value is too small we'll be writing very often which will cause\n// noticeable stop-the-world pauses. If this value is too big we'll be writing\n// so infrequently that the /sync size gets bigger on reload. Writing more\n// often does not affect the length of the pause since the entire /sync\n// response is persisted each time.\nconst WRITE_DELAY_MS = 1000 * 60 * 5; // once every 5 minutes\n\ninterface IOpts extends IBaseOpts {\n /** The Indexed DB interface e.g. `window.indexedDB` */\n indexedDB: IDBFactory;\n /** Optional database name. The same name must be used to open the same database. */\n dbName?: string;\n /** Optional factory to spin up a Worker to execute the IDB transactions within. */\n workerFactory?: () => Worker;\n}\n\ntype EventHandlerMap = {\n // Fired when an IDB command fails on a degradable path, and the store falls back to MemoryStore\n // This signals the potential for data volatility.\n degraded: (e: Error) => void;\n // Fired when the IndexedDB gets closed unexpectedly, for example, if the underlying storage is removed or\n // if the user clears the database in the browser's history preferences.\n closed: () => void;\n};\n\nexport class IndexedDBStore extends MemoryStore {\n public static exists(indexedDB: IDBFactory, dbName: string): Promise {\n return LocalIndexedDBStoreBackend.exists(indexedDB, dbName);\n }\n\n /**\n * The backend instance.\n * Call through to this API if you need to perform specific indexeddb actions like deleting the database.\n */\n public readonly backend: IIndexedDBBackend;\n\n private startedUp = false;\n private syncTs = 0;\n // Records the last-modified-time of each user at the last point we saved\n // the database, such that we can derive the set if users that have been\n // modified since we last saved.\n private userModifiedMap: Record = {}; // user_id : timestamp\n private emitter = new TypedEventEmitter();\n\n /**\n * Construct a new Indexed Database store, which extends MemoryStore.\n *\n * This store functions like a MemoryStore except it periodically persists\n * the contents of the store to an IndexedDB backend.\n *\n * All data is still kept in-memory but can be loaded from disk by calling\n * `startup()`. This can make startup times quicker as a complete\n * sync from the server is not required. This does not reduce memory usage as all\n * the data is eagerly fetched when `startup()` is called.\n * ```\n * let opts = { indexedDB: window.indexedDB, localStorage: window.localStorage };\n * let store = new IndexedDBStore(opts);\n * await store.startup(); // load from indexed db\n * let client = sdk.createClient({\n * store: store,\n * });\n * client.startClient();\n * client.on(\"sync\", function(state, prevState, data) {\n * if (state === \"PREPARED\") {\n * console.log(\"Started up, now with go faster stripes!\");\n * }\n * });\n * ```\n *\n * @param opts - Options object.\n */\n public constructor(opts: IOpts) {\n super(opts);\n\n if (!opts.indexedDB) {\n throw new Error(\"Missing required option: indexedDB\");\n }\n\n if (opts.workerFactory) {\n this.backend = new RemoteIndexedDBStoreBackend(opts.workerFactory, opts.dbName);\n } else {\n this.backend = new LocalIndexedDBStoreBackend(opts.indexedDB, opts.dbName);\n }\n }\n\n public on = this.emitter.on.bind(this.emitter);\n\n /**\n * @returns Resolved when loaded from indexed db.\n */\n public startup(): Promise {\n if (this.startedUp) {\n logger.log(`IndexedDBStore.startup: already started`);\n return Promise.resolve();\n }\n\n logger.log(`IndexedDBStore.startup: connecting to backend`);\n return this.backend\n .connect(this.onClose)\n .then(() => {\n logger.log(`IndexedDBStore.startup: loading presence events`);\n return this.backend.getUserPresenceEvents();\n })\n .then((userPresenceEvents) => {\n logger.log(`IndexedDBStore.startup: processing presence events`);\n userPresenceEvents.forEach(([userId, rawEvent]) => {\n const u = new User(userId);\n if (rawEvent) {\n u.setPresenceEvent(new MatrixEvent(rawEvent));\n }\n this.userModifiedMap[u.userId] = u.getLastModifiedTime();\n this.storeUser(u);\n });\n this.startedUp = true;\n });\n }\n\n private onClose = (): void => {\n this.emitter.emit(\"closed\");\n };\n\n /**\n * @returns Promise which resolves with a sync response to restore the\n * client state to where it was at the last save, or null if there\n * is no saved sync data.\n */\n public getSavedSync = this.degradable((): Promise => {\n return this.backend.getSavedSync();\n }, \"getSavedSync\");\n\n /** @returns whether or not the database was newly created in this session. */\n public isNewlyCreated = this.degradable((): Promise => {\n return this.backend.isNewlyCreated();\n }, \"isNewlyCreated\");\n\n /**\n * @returns If there is a saved sync, the nextBatch token\n * for this sync, otherwise null.\n */\n public getSavedSyncToken = this.degradable((): Promise => {\n return this.backend.getNextBatchToken();\n }, \"getSavedSyncToken\");\n\n /**\n * Delete all data from this store.\n * @returns Promise which resolves if the data was deleted from the database.\n */\n public deleteAllData = this.degradable((): Promise => {\n super.deleteAllData();\n return this.backend.clearDatabase().then(\n () => {\n logger.log(\"Deleted indexeddb data.\");\n },\n (err) => {\n logger.error(`Failed to delete indexeddb data: ${err}`);\n throw err;\n },\n );\n });\n\n /**\n * Whether this store would like to save its data\n * Note that obviously whether the store wants to save or\n * not could change between calling this function and calling\n * save().\n *\n * @returns True if calling save() will actually save\n * (at the time this function is called).\n */\n public wantsSave(): boolean {\n const now = Date.now();\n return now - this.syncTs > WRITE_DELAY_MS;\n }\n\n /**\n * Possibly write data to the database.\n *\n * @param force - True to force a save to happen\n * @returns Promise resolves after the write completes\n * (or immediately if no write is performed)\n */\n public save(force = false): Promise {\n if (force || this.wantsSave()) {\n return this.reallySave();\n }\n return Promise.resolve();\n }\n\n private reallySave = this.degradable((): Promise => {\n this.syncTs = Date.now(); // set now to guard against multi-writes\n\n // work out changed users (this doesn't handle deletions but you\n // can't 'delete' users as they are just presence events).\n const userTuples: [userId: string, presenceEvent: Partial][] = [];\n for (const u of this.getUsers()) {\n if (this.userModifiedMap[u.userId] === u.getLastModifiedTime()) continue;\n if (!u.events.presence) continue;\n\n userTuples.push([u.userId, u.events.presence.event]);\n\n // note that we've saved this version of the user\n this.userModifiedMap[u.userId] = u.getLastModifiedTime();\n }\n\n return this.backend.syncToDatabase(userTuples);\n });\n\n public setSyncData = this.degradable((syncData: ISyncResponse): Promise => {\n return this.backend.setSyncData(syncData);\n }, \"setSyncData\");\n\n /**\n * Returns the out-of-band membership events for this room that\n * were previously loaded.\n * @returns the events, potentially an empty array if OOB loading didn't yield any new members\n * @returns in case the members for this room haven't been stored yet\n */\n public getOutOfBandMembers = this.degradable((roomId: string): Promise => {\n return this.backend.getOutOfBandMembers(roomId);\n }, \"getOutOfBandMembers\");\n\n /**\n * Stores the out-of-band membership events for this room. Note that\n * it still makes sense to store an empty array as the OOB status for the room is\n * marked as fetched, and getOutOfBandMembers will return an empty array instead of null\n * @param membershipEvents - the membership events to store\n * @returns when all members have been stored\n */\n public setOutOfBandMembers = this.degradable(\n (roomId: string, membershipEvents: IStateEventWithRoomId[]): Promise => {\n super.setOutOfBandMembers(roomId, membershipEvents);\n return this.backend.setOutOfBandMembers(roomId, membershipEvents);\n },\n \"setOutOfBandMembers\",\n );\n\n public clearOutOfBandMembers = this.degradable((roomId: string) => {\n super.clearOutOfBandMembers(roomId);\n return this.backend.clearOutOfBandMembers(roomId);\n }, \"clearOutOfBandMembers\");\n\n public getClientOptions = this.degradable((): Promise => {\n return this.backend.getClientOptions();\n }, \"getClientOptions\");\n\n public storeClientOptions = this.degradable((options: IStoredClientOpts): Promise => {\n super.storeClientOptions(options);\n return this.backend.storeClientOptions(options);\n }, \"storeClientOptions\");\n\n /**\n * All member functions of `IndexedDBStore` that access the backend use this wrapper to\n * watch for failures after initial store startup, including `QuotaExceededError` as\n * free disk space changes, etc.\n *\n * When IndexedDB fails via any of these paths, we degrade this back to a `MemoryStore`\n * in place so that the current operation and all future ones are in-memory only.\n *\n * @param func - The degradable work to do.\n * @param fallback - The method name for fallback.\n * @returns A wrapped member function.\n */\n private degradable, R = void>(\n func: DegradableFn,\n fallback?: keyof MemoryStore,\n ): DegradableFn {\n const fallbackFn = fallback ? (super[fallback] as Function) : null;\n\n return async (...args) => {\n try {\n return await func.call(this, ...args);\n } catch (e) {\n logger.error(\"IndexedDBStore failure, degrading to MemoryStore\", e);\n this.emitter.emit(\"degraded\", e as Error);\n try {\n // We try to delete IndexedDB after degrading since this store is only a\n // cache (the app will still function correctly without the data).\n // It's possible that deleting repair IndexedDB for the next app load,\n // potentially by making a little more space available.\n logger.log(\"IndexedDBStore trying to delete degraded data\");\n await this.backend.clearDatabase();\n logger.log(\"IndexedDBStore delete after degrading succeeded\");\n } catch (e) {\n logger.warn(\"IndexedDBStore delete after degrading failed\", e);\n }\n // Degrade the store from being an instance of `IndexedDBStore` to instead be\n // an instance of `MemoryStore` so that future API calls use the memory path\n // directly and skip IndexedDB entirely. This should be safe as\n // `IndexedDBStore` already extends from `MemoryStore`, so we are making the\n // store become its parent type in a way. The mutator methods of\n // `IndexedDBStore` also maintain the state that `MemoryStore` uses (many are\n // not overridden at all).\n if (fallbackFn) {\n return fallbackFn.call(this, ...args);\n }\n }\n };\n }\n\n // XXX: ideally these would be stored in indexeddb as part of the room but,\n // we don't store rooms as such and instead accumulate entire sync responses atm.\n public async getPendingEvents(roomId: string): Promise[]> {\n if (!this.localStorage) return super.getPendingEvents(roomId);\n\n const serialized = this.localStorage.getItem(pendingEventsKey(roomId));\n if (serialized) {\n try {\n return JSON.parse(serialized);\n } catch (e) {\n logger.error(\"Could not parse persisted pending events\", e);\n }\n }\n return [];\n }\n\n public async setPendingEvents(roomId: string, events: Partial[]): Promise {\n if (!this.localStorage) return super.setPendingEvents(roomId, events);\n\n if (events.length > 0) {\n this.localStorage.setItem(pendingEventsKey(roomId), JSON.stringify(events));\n } else {\n this.localStorage.removeItem(pendingEventsKey(roomId));\n }\n }\n\n public saveToDeviceBatches(batches: ToDeviceBatchWithTxnId[]): Promise {\n return this.backend.saveToDeviceBatches(batches);\n }\n\n public getOldestToDeviceBatch(): Promise {\n return this.backend.getOldestToDeviceBatch();\n }\n\n public removeToDeviceBatch(id: number): Promise {\n return this.backend.removeToDeviceBatch(id);\n }\n}\n\n/**\n * @param roomId - ID of the current room\n * @returns Storage key to retrieve pending events\n */\nfunction pendingEventsKey(roomId: string): string {\n return `mx_pending_events_${roomId}`;\n}\n\ntype DegradableFn, T> = (...args: A) => Promise;\n", - "/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link MemoryStore} for the public class.\n */\n\nimport { EventType } from \"../@types/event\";\nimport { Room } from \"../models/room\";\nimport { User } from \"../models/user\";\nimport { IEvent, MatrixEvent } from \"../models/event\";\nimport { RoomState, RoomStateEvent } from \"../models/room-state\";\nimport { RoomMember } from \"../models/room-member\";\nimport { Filter } from \"../filter\";\nimport { ISavedSync, IStore } from \"./index\";\nimport { RoomSummary } from \"../models/room-summary\";\nimport { ISyncResponse } from \"../sync-accumulator\";\nimport { IStateEventWithRoomId } from \"../@types/search\";\nimport { IndexedToDeviceBatch, ToDeviceBatchWithTxnId } from \"../models/ToDeviceMessage\";\nimport { IStoredClientOpts } from \"../client\";\nimport { MapWithDefault } from \"../utils\";\n\nfunction isValidFilterId(filterId?: string | number | null): boolean {\n const isValidStr =\n typeof filterId === \"string\" &&\n !!filterId &&\n filterId !== \"undefined\" && // exclude these as we've serialized undefined in localStorage before\n filterId !== \"null\";\n\n return isValidStr || typeof filterId === \"number\";\n}\n\nexport interface IOpts {\n /** The local storage instance to persist some forms of data such as tokens. Rooms will NOT be stored. */\n localStorage?: Storage;\n}\n\nexport class MemoryStore implements IStore {\n private rooms: Record = {}; // roomId: Room\n private users: Record = {}; // userId: User\n private syncToken: string | null = null;\n // userId: {\n // filterId: Filter\n // }\n private filters: MapWithDefault> = new MapWithDefault(() => new Map());\n public accountData: Map = new Map(); // type: content\n protected readonly localStorage?: Storage;\n private oobMembers: Map = new Map(); // roomId: [member events]\n private pendingEvents: { [roomId: string]: Partial[] } = {};\n private clientOptions?: IStoredClientOpts;\n private pendingToDeviceBatches: IndexedToDeviceBatch[] = [];\n private nextToDeviceBatchId = 0;\n\n /**\n * Construct a new in-memory data store for the Matrix Client.\n * @param opts - Config options\n */\n public constructor(opts: IOpts = {}) {\n this.localStorage = opts.localStorage;\n }\n\n /**\n * Retrieve the token to stream from.\n * @returns The token or null.\n */\n public getSyncToken(): string | null {\n return this.syncToken;\n }\n\n /** @returns whether or not the database was newly created in this session. */\n public isNewlyCreated(): Promise {\n return Promise.resolve(true);\n }\n\n /**\n * Set the token to stream from.\n * @param token - The token to stream from.\n */\n public setSyncToken(token: string): void {\n this.syncToken = token;\n }\n\n /**\n * Store the given room.\n * @param room - The room to be stored. All properties must be stored.\n */\n public storeRoom(room: Room): void {\n this.rooms[room.roomId] = room;\n // add listeners for room member changes so we can keep the room member\n // map up-to-date.\n room.currentState.on(RoomStateEvent.Members, this.onRoomMember);\n // add existing members\n room.currentState.getMembers().forEach((m) => {\n this.onRoomMember(null, room.currentState, m);\n });\n }\n\n /**\n * Called when a room member in a room being tracked by this store has been\n * updated.\n */\n private onRoomMember = (event: MatrixEvent | null, state: RoomState, member: RoomMember): void => {\n if (member.membership === \"invite\") {\n // We do NOT add invited members because people love to typo user IDs\n // which would then show up in these lists (!)\n return;\n }\n\n const user = this.users[member.userId] || new User(member.userId);\n if (member.name) {\n user.setDisplayName(member.name);\n if (member.events.member) {\n user.setRawDisplayName(member.events.member.getDirectionalContent().displayname);\n }\n }\n if (member.events.member && member.events.member.getContent().avatar_url) {\n user.setAvatarUrl(member.events.member.getContent().avatar_url);\n }\n this.users[user.userId] = user;\n };\n\n /**\n * Retrieve a room by its' room ID.\n * @param roomId - The room ID.\n * @returns The room or null.\n */\n public getRoom(roomId: string): Room | null {\n return this.rooms[roomId] || null;\n }\n\n /**\n * Retrieve all known rooms.\n * @returns A list of rooms, which may be empty.\n */\n public getRooms(): Room[] {\n return Object.values(this.rooms);\n }\n\n /**\n * Permanently delete a room.\n */\n public removeRoom(roomId: string): void {\n if (this.rooms[roomId]) {\n this.rooms[roomId].currentState.removeListener(RoomStateEvent.Members, this.onRoomMember);\n }\n delete this.rooms[roomId];\n }\n\n /**\n * Retrieve a summary of all the rooms.\n * @returns A summary of each room.\n */\n public getRoomSummaries(): RoomSummary[] {\n return Object.values(this.rooms).map(function (room) {\n return room.summary!;\n });\n }\n\n /**\n * Store a User.\n * @param user - The user to store.\n */\n public storeUser(user: User): void {\n this.users[user.userId] = user;\n }\n\n /**\n * Retrieve a User by its' user ID.\n * @param userId - The user ID.\n * @returns The user or null.\n */\n public getUser(userId: string): User | null {\n return this.users[userId] || null;\n }\n\n /**\n * Retrieve all known users.\n * @returns A list of users, which may be empty.\n */\n public getUsers(): User[] {\n return Object.values(this.users);\n }\n\n /**\n * Retrieve scrollback for this room.\n * @param room - The matrix room\n * @param limit - The max number of old events to retrieve.\n * @returns An array of objects which will be at most 'limit'\n * length and at least 0. The objects are the raw event JSON.\n */\n public scrollback(room: Room, limit: number): MatrixEvent[] {\n return [];\n }\n\n /**\n * Store events for a room. The events have already been added to the timeline\n * @param room - The room to store events for.\n * @param events - The events to store.\n * @param token - The token associated with these events.\n * @param toStart - True if these are paginated results.\n */\n public storeEvents(room: Room, events: MatrixEvent[], token: string | null, toStart: boolean): void {\n // no-op because they've already been added to the room instance.\n }\n\n /**\n * Store a filter.\n */\n public storeFilter(filter: Filter): void {\n if (!filter?.userId || !filter?.filterId) return;\n this.filters.getOrCreate(filter.userId).set(filter.filterId, filter);\n }\n\n /**\n * Retrieve a filter.\n * @returns A filter or null.\n */\n public getFilter(userId: string, filterId: string): Filter | null {\n return this.filters.get(userId)?.get(filterId) || null;\n }\n\n /**\n * Retrieve a filter ID with the given name.\n * @param filterName - The filter name.\n * @returns The filter ID or null.\n */\n public getFilterIdByName(filterName: string): string | null {\n if (!this.localStorage) {\n return null;\n }\n const key = \"mxjssdk_memory_filter_\" + filterName;\n // XXX Storage.getItem doesn't throw ...\n // or are we using something different\n // than window.localStorage in some cases\n // that does throw?\n // that would be very naughty\n try {\n const value = this.localStorage.getItem(key);\n if (isValidFilterId(value)) {\n return value;\n }\n } catch (e) {}\n return null;\n }\n\n /**\n * Set a filter name to ID mapping.\n */\n public setFilterIdByName(filterName: string, filterId?: string): void {\n if (!this.localStorage) {\n return;\n }\n const key = \"mxjssdk_memory_filter_\" + filterName;\n try {\n if (isValidFilterId(filterId)) {\n this.localStorage.setItem(key, filterId!);\n } else {\n this.localStorage.removeItem(key);\n }\n } catch (e) {}\n }\n\n /**\n * Store user-scoped account data events.\n * N.B. that account data only allows a single event per type, so multiple\n * events with the same type will replace each other.\n * @param events - The events to store.\n */\n public storeAccountDataEvents(events: MatrixEvent[]): void {\n events.forEach((event) => {\n // MSC3391: an event with content of {} should be interpreted as deleted\n const isDeleted = !Object.keys(event.getContent()).length;\n if (isDeleted) {\n this.accountData.delete(event.getType());\n } else {\n this.accountData.set(event.getType(), event);\n }\n });\n }\n\n /**\n * Get account data event by event type\n * @param eventType - The event type being queried\n * @returns the user account_data event of given type, if any\n */\n public getAccountData(eventType: EventType | string): MatrixEvent | undefined {\n return this.accountData.get(eventType);\n }\n\n /**\n * setSyncData does nothing as there is no backing data store.\n *\n * @param syncData - The sync data\n * @returns An immediately resolved promise.\n */\n public setSyncData(syncData: ISyncResponse): Promise {\n return Promise.resolve();\n }\n\n /**\n * We never want to save becase we have nothing to save to.\n *\n * @returns If the store wants to save\n */\n public wantsSave(): boolean {\n return false;\n }\n\n /**\n * Save does nothing as there is no backing data store.\n * @param force - True to force a save (but the memory\n * store still can't save anything)\n */\n public save(force: boolean): void {}\n\n /**\n * Startup does nothing as this store doesn't require starting up.\n * @returns An immediately resolved promise.\n */\n public startup(): Promise {\n return Promise.resolve();\n }\n\n /**\n * @returns Promise which resolves with a sync response to restore the\n * client state to where it was at the last save, or null if there\n * is no saved sync data.\n */\n public getSavedSync(): Promise {\n return Promise.resolve(null);\n }\n\n /**\n * @returns If there is a saved sync, the nextBatch token\n * for this sync, otherwise null.\n */\n public getSavedSyncToken(): Promise {\n return Promise.resolve(null);\n }\n\n /**\n * Delete all data from this store.\n * @returns An immediately resolved promise.\n */\n public deleteAllData(): Promise {\n this.rooms = {\n // roomId: Room\n };\n this.users = {\n // userId: User\n };\n this.syncToken = null;\n this.filters = new MapWithDefault(() => new Map());\n this.accountData = new Map(); // type : content\n return Promise.resolve();\n }\n\n /**\n * Returns the out-of-band membership events for this room that\n * were previously loaded.\n * @returns the events, potentially an empty array if OOB loading didn't yield any new members\n * @returns in case the members for this room haven't been stored yet\n */\n public getOutOfBandMembers(roomId: string): Promise {\n return Promise.resolve(this.oobMembers.get(roomId) || null);\n }\n\n /**\n * Stores the out-of-band membership events for this room. Note that\n * it still makes sense to store an empty array as the OOB status for the room is\n * marked as fetched, and getOutOfBandMembers will return an empty array instead of null\n * @param membershipEvents - the membership events to store\n * @returns when all members have been stored\n */\n public setOutOfBandMembers(roomId: string, membershipEvents: IStateEventWithRoomId[]): Promise {\n this.oobMembers.set(roomId, membershipEvents);\n return Promise.resolve();\n }\n\n public clearOutOfBandMembers(roomId: string): Promise {\n this.oobMembers.delete(roomId);\n return Promise.resolve();\n }\n\n public getClientOptions(): Promise {\n return Promise.resolve(this.clientOptions);\n }\n\n public storeClientOptions(options: IStoredClientOpts): Promise {\n this.clientOptions = Object.assign({}, options);\n return Promise.resolve();\n }\n\n public async getPendingEvents(roomId: string): Promise[]> {\n return this.pendingEvents[roomId] ?? [];\n }\n\n public async setPendingEvents(roomId: string, events: Partial[]): Promise {\n this.pendingEvents[roomId] = events;\n }\n\n public saveToDeviceBatches(batches: ToDeviceBatchWithTxnId[]): Promise {\n for (const batch of batches) {\n this.pendingToDeviceBatches.push({\n id: this.nextToDeviceBatchId++,\n eventType: batch.eventType,\n txnId: batch.txnId,\n batch: batch.batch,\n });\n }\n return Promise.resolve();\n }\n\n public async getOldestToDeviceBatch(): Promise {\n if (this.pendingToDeviceBatches.length === 0) return null;\n return this.pendingToDeviceBatches[0];\n }\n\n public removeToDeviceBatch(id: number): Promise {\n this.pendingToDeviceBatches = this.pendingToDeviceBatches.filter((batch) => batch.id !== id);\n return Promise.resolve();\n }\n}\n", - "/*\nCopyright 2015 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module.\n */\n\nimport { EventType } from \"../@types/event\";\nimport { Room } from \"../models/room\";\nimport { User } from \"../models/user\";\nimport { IEvent, MatrixEvent } from \"../models/event\";\nimport { Filter } from \"../filter\";\nimport { ISavedSync, IStore } from \"./index\";\nimport { RoomSummary } from \"../models/room-summary\";\nimport { ISyncResponse } from \"../sync-accumulator\";\nimport { IStateEventWithRoomId } from \"../@types/search\";\nimport { IndexedToDeviceBatch, ToDeviceBatch } from \"../models/ToDeviceMessage\";\nimport { IStoredClientOpts } from \"../client\";\n\n/**\n * Construct a stub store. This does no-ops on most store methods.\n */\nexport class StubStore implements IStore {\n public readonly accountData = new Map(); // stub\n private fromToken: string | null = null;\n\n /** @returns whether or not the database was newly created in this session. */\n public isNewlyCreated(): Promise {\n return Promise.resolve(true);\n }\n\n /**\n * Get the sync token.\n */\n public getSyncToken(): string | null {\n return this.fromToken;\n }\n\n /**\n * Set the sync token.\n */\n public setSyncToken(token: string): void {\n this.fromToken = token;\n }\n\n /**\n * No-op.\n */\n public storeRoom(room: Room): void {}\n\n /**\n * No-op.\n */\n public getRoom(roomId: string): Room | null {\n return null;\n }\n\n /**\n * No-op.\n * @returns An empty array.\n */\n public getRooms(): Room[] {\n return [];\n }\n\n /**\n * Permanently delete a room.\n */\n public removeRoom(roomId: string): void {\n return;\n }\n\n /**\n * No-op.\n * @returns An empty array.\n */\n public getRoomSummaries(): RoomSummary[] {\n return [];\n }\n\n /**\n * No-op.\n */\n public storeUser(user: User): void {}\n\n /**\n * No-op.\n */\n public getUser(userId: string): User | null {\n return null;\n }\n\n /**\n * No-op.\n */\n public getUsers(): User[] {\n return [];\n }\n\n /**\n * No-op.\n */\n public scrollback(room: Room, limit: number): MatrixEvent[] {\n return [];\n }\n\n /**\n * Store events for a room.\n * @param room - The room to store events for.\n * @param events - The events to store.\n * @param token - The token associated with these events.\n * @param toStart - True if these are paginated results.\n */\n public storeEvents(room: Room, events: MatrixEvent[], token: string | null, toStart: boolean): void {}\n\n /**\n * Store a filter.\n */\n public storeFilter(filter: Filter): void {}\n\n /**\n * Retrieve a filter.\n * @returns A filter or null.\n */\n public getFilter(userId: string, filterId: string): Filter | null {\n return null;\n }\n\n /**\n * Retrieve a filter ID with the given name.\n * @param filterName - The filter name.\n * @returns The filter ID or null.\n */\n public getFilterIdByName(filterName: string): string | null {\n return null;\n }\n\n /**\n * Set a filter name to ID mapping.\n */\n public setFilterIdByName(filterName: string, filterId?: string): void {}\n\n /**\n * Store user-scoped account data events\n * @param events - The events to store.\n */\n public storeAccountDataEvents(events: MatrixEvent[]): void {}\n\n /**\n * Get account data event by event type\n * @param eventType - The event type being queried\n */\n public getAccountData(eventType: EventType | string): MatrixEvent | undefined {\n return undefined;\n }\n\n /**\n * setSyncData does nothing as there is no backing data store.\n *\n * @param syncData - The sync data\n * @returns An immediately resolved promise.\n */\n public setSyncData(syncData: ISyncResponse): Promise {\n return Promise.resolve();\n }\n\n /**\n * We never want to save because we have nothing to save to.\n *\n * @returns If the store wants to save\n */\n public wantsSave(): boolean {\n return false;\n }\n\n /**\n * Save does nothing as there is no backing data store.\n */\n public save(): void {}\n\n /**\n * Startup does nothing.\n * @returns An immediately resolved promise.\n */\n public startup(): Promise {\n return Promise.resolve();\n }\n\n /**\n * @returns Promise which resolves with a sync response to restore the\n * client state to where it was at the last save, or null if there\n * is no saved sync data.\n */\n public getSavedSync(): Promise {\n return Promise.resolve(null);\n }\n\n /**\n * @returns If there is a saved sync, the nextBatch token\n * for this sync, otherwise null.\n */\n public getSavedSyncToken(): Promise {\n return Promise.resolve(null);\n }\n\n /**\n * Delete all data from this store. Does nothing since this store\n * doesn't store anything.\n * @returns An immediately resolved promise.\n */\n public deleteAllData(): Promise {\n return Promise.resolve();\n }\n\n public getOutOfBandMembers(): Promise {\n return Promise.resolve(null);\n }\n\n public setOutOfBandMembers(roomId: string, membershipEvents: IStateEventWithRoomId[]): Promise {\n return Promise.resolve();\n }\n\n public clearOutOfBandMembers(): Promise {\n return Promise.resolve();\n }\n\n public getClientOptions(): Promise {\n return Promise.resolve(undefined);\n }\n\n public storeClientOptions(options: IStoredClientOpts): Promise {\n return Promise.resolve();\n }\n\n public async getPendingEvents(roomId: string): Promise[]> {\n return [];\n }\n\n public setPendingEvents(roomId: string, events: Partial[]): Promise {\n return Promise.resolve();\n }\n\n public async saveToDeviceBatches(batch: ToDeviceBatch[]): Promise {\n return Promise.resolve();\n }\n\n public getOldestToDeviceBatch(): Promise {\n return Promise.resolve(null);\n }\n\n public async removeToDeviceBatch(id: number): Promise {\n return Promise.resolve();\n }\n}\n", - "/*\nCopyright 2017 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link SyncAccumulator} for the public class.\n */\n\nimport { logger } from \"./logger\";\nimport { deepCopy, isSupportedReceiptType, MapWithDefault, recursiveMapToObject } from \"./utils\";\nimport { IContent, IUnsigned } from \"./models/event\";\nimport { IRoomSummary } from \"./models/room-summary\";\nimport { EventType } from \"./@types/event\";\nimport { MAIN_ROOM_TIMELINE, ReceiptContent, ReceiptType } from \"./@types/read_receipts\";\nimport { UNREAD_THREAD_NOTIFICATIONS } from \"./@types/sync\";\n\ninterface IOpts {\n /**\n * The ideal maximum number of timeline entries to keep in the sync response.\n * This is best-effort, as clients do not always have a back-pagination token for each event,\n * so it's possible there may be slightly *less* than this value. There will never be more.\n * This cannot be 0 or else it makes it impossible to scroll back in a room.\n * Default: 50.\n */\n maxTimelineEntries?: number;\n}\n\nexport interface IMinimalEvent {\n content: IContent;\n type: EventType | string;\n unsigned?: IUnsigned;\n}\n\nexport interface IEphemeral {\n events: IMinimalEvent[];\n}\n\n/* eslint-disable camelcase */\ninterface UnreadNotificationCounts {\n highlight_count?: number;\n notification_count?: number;\n}\n\nexport interface IRoomEvent extends IMinimalEvent {\n event_id: string;\n sender: string;\n origin_server_ts: number;\n /** @deprecated - legacy field */\n age?: number;\n}\n\nexport interface IStateEvent extends IRoomEvent {\n prev_content?: IContent;\n state_key: string;\n}\n\ninterface IState {\n events: IStateEvent[];\n}\n\nexport interface ITimeline {\n events: Array;\n limited?: boolean;\n prev_batch: string | null;\n}\n\nexport interface IJoinedRoom {\n \"summary\": IRoomSummary;\n \"state\": IState;\n \"timeline\": ITimeline;\n \"ephemeral\": IEphemeral;\n \"account_data\": IAccountData;\n \"unread_notifications\": UnreadNotificationCounts;\n \"unread_thread_notifications\"?: Record;\n \"org.matrix.msc3773.unread_thread_notifications\"?: Record;\n}\n\nexport interface IStrippedState {\n content: IContent;\n state_key: string;\n type: EventType | string;\n sender: string;\n}\n\nexport interface IInviteState {\n events: IStrippedState[];\n}\n\nexport interface IInvitedRoom {\n invite_state: IInviteState;\n}\n\nexport interface ILeftRoom {\n state: IState;\n timeline: ITimeline;\n account_data: IAccountData;\n}\n\nexport interface IRooms {\n [Category.Join]: Record;\n [Category.Invite]: Record;\n [Category.Leave]: Record;\n}\n\ninterface IPresence {\n events: IMinimalEvent[];\n}\n\ninterface IAccountData {\n events: IMinimalEvent[];\n}\n\nexport interface IToDeviceEvent {\n content: IContent;\n sender: string;\n type: string;\n}\n\ninterface IToDevice {\n events: IToDeviceEvent[];\n}\n\ninterface IDeviceLists {\n changed?: string[];\n left?: string[];\n}\n\nexport interface ISyncResponse {\n \"next_batch\": string;\n \"rooms\": IRooms;\n \"presence\"?: IPresence;\n \"account_data\": IAccountData;\n \"to_device\"?: IToDevice;\n \"device_lists\"?: IDeviceLists;\n \"device_one_time_keys_count\"?: Record;\n\n \"device_unused_fallback_key_types\"?: string[];\n \"org.matrix.msc2732.device_unused_fallback_key_types\"?: string[];\n}\n/* eslint-enable camelcase */\n\nexport enum Category {\n Invite = \"invite\",\n Leave = \"leave\",\n Join = \"join\",\n}\n\ninterface IRoom {\n _currentState: { [eventType: string]: { [stateKey: string]: IStateEvent } };\n _timeline: {\n event: IRoomEvent | IStateEvent;\n token: string | null;\n }[];\n _summary: Partial;\n _accountData: { [eventType: string]: IMinimalEvent };\n _unreadNotifications: Partial;\n _unreadThreadNotifications?: Record>;\n _readReceipts: {\n [userId: string]: {\n data: IMinimalEvent;\n type: ReceiptType;\n eventId: string;\n };\n };\n _threadReadReceipts: {\n [threadId: string]: {\n [userId: string]: {\n data: IMinimalEvent;\n type: ReceiptType;\n eventId: string;\n };\n };\n };\n}\n\nexport interface ISyncData {\n nextBatch: string;\n accountData: IMinimalEvent[];\n roomsData: IRooms;\n}\n\ntype TaggedEvent = IRoomEvent & { _localTs?: number };\n\nfunction isTaggedEvent(event: IRoomEvent): event is TaggedEvent {\n return \"_localTs\" in event && event[\"_localTs\"] !== undefined;\n}\n\n/**\n * The purpose of this class is to accumulate /sync responses such that a\n * complete \"initial\" JSON response can be returned which accurately represents\n * the sum total of the /sync responses accumulated to date. It only handles\n * room data: that is, everything under the \"rooms\" top-level key.\n *\n * This class is used when persisting room data so a complete /sync response can\n * be loaded from disk and incremental syncs can be performed on the server,\n * rather than asking the server to do an initial sync on startup.\n */\nexport class SyncAccumulator {\n private accountData: Record = {}; // $event_type: Object\n private inviteRooms: Record = {}; // $roomId: { ... sync 'invite' json data ... }\n private joinRooms: { [roomId: string]: IRoom } = {};\n // the /sync token which corresponds to the last time rooms were\n // accumulated. We remember this so that any caller can obtain a\n // coherent /sync response and know at what point they should be\n // streaming from without losing events.\n private nextBatch: string | null = null;\n\n public constructor(private readonly opts: IOpts = {}) {\n this.opts.maxTimelineEntries = this.opts.maxTimelineEntries || 50;\n }\n\n public accumulate(syncResponse: ISyncResponse, fromDatabase = false): void {\n this.accumulateRooms(syncResponse, fromDatabase);\n this.accumulateAccountData(syncResponse);\n this.nextBatch = syncResponse.next_batch;\n }\n\n private accumulateAccountData(syncResponse: ISyncResponse): void {\n if (!syncResponse.account_data || !syncResponse.account_data.events) {\n return;\n }\n // Clobbers based on event type.\n syncResponse.account_data.events.forEach((e) => {\n this.accountData[e.type] = e;\n });\n }\n\n /**\n * Accumulate incremental /sync room data.\n * @param syncResponse - the complete /sync JSON\n * @param fromDatabase - True if the sync response is one saved to the database\n */\n private accumulateRooms(syncResponse: ISyncResponse, fromDatabase = false): void {\n if (!syncResponse.rooms) {\n return;\n }\n if (syncResponse.rooms.invite) {\n Object.keys(syncResponse.rooms.invite).forEach((roomId) => {\n this.accumulateRoom(roomId, Category.Invite, syncResponse.rooms.invite[roomId], fromDatabase);\n });\n }\n if (syncResponse.rooms.join) {\n Object.keys(syncResponse.rooms.join).forEach((roomId) => {\n this.accumulateRoom(roomId, Category.Join, syncResponse.rooms.join[roomId], fromDatabase);\n });\n }\n if (syncResponse.rooms.leave) {\n Object.keys(syncResponse.rooms.leave).forEach((roomId) => {\n this.accumulateRoom(roomId, Category.Leave, syncResponse.rooms.leave[roomId], fromDatabase);\n });\n }\n }\n\n private accumulateRoom(roomId: string, category: Category.Invite, data: IInvitedRoom, fromDatabase: boolean): void;\n private accumulateRoom(roomId: string, category: Category.Join, data: IJoinedRoom, fromDatabase: boolean): void;\n private accumulateRoom(roomId: string, category: Category.Leave, data: ILeftRoom, fromDatabase: boolean): void;\n private accumulateRoom(roomId: string, category: Category, data: any, fromDatabase = false): void {\n // Valid /sync state transitions\n // +--------+ <======+ 1: Accept an invite\n // +== | INVITE | | (5) 2: Leave a room\n // | +--------+ =====+ | 3: Join a public room previously\n // |(1) (4) | | left (handle as if new room)\n // V (2) V | 4: Reject an invite\n // +------+ ========> +--------+ 5: Invite to a room previously\n // | JOIN | (3) | LEAVE* | left (handle as if new room)\n // +------+ <======== +--------+\n //\n // * equivalent to \"no state\"\n switch (category) {\n case Category.Invite: // (5)\n this.accumulateInviteState(roomId, data as IInvitedRoom);\n break;\n\n case Category.Join:\n if (this.inviteRooms[roomId]) {\n // (1)\n // was previously invite, now join. We expect /sync to give\n // the entire state and timeline on 'join', so delete previous\n // invite state\n delete this.inviteRooms[roomId];\n }\n // (3)\n this.accumulateJoinState(roomId, data as IJoinedRoom, fromDatabase);\n break;\n\n case Category.Leave:\n if (this.inviteRooms[roomId]) {\n // (4)\n delete this.inviteRooms[roomId];\n } else {\n // (2)\n delete this.joinRooms[roomId];\n }\n break;\n\n default:\n logger.error(\"Unknown cateogory: \", category);\n }\n }\n\n private accumulateInviteState(roomId: string, data: IInvitedRoom): void {\n if (!data.invite_state || !data.invite_state.events) {\n // no new data\n return;\n }\n if (!this.inviteRooms[roomId]) {\n this.inviteRooms[roomId] = {\n invite_state: data.invite_state,\n };\n return;\n }\n // accumulate extra keys for invite->invite transitions\n // clobber based on event type / state key\n // We expect invite_state to be small, so just loop over the events\n const currentData = this.inviteRooms[roomId];\n data.invite_state.events.forEach((e) => {\n let hasAdded = false;\n for (let i = 0; i < currentData.invite_state.events.length; i++) {\n const current = currentData.invite_state.events[i];\n if (current.type === e.type && current.state_key == e.state_key) {\n currentData.invite_state.events[i] = e; // update\n hasAdded = true;\n }\n }\n if (!hasAdded) {\n currentData.invite_state.events.push(e);\n }\n });\n }\n\n // Accumulate timeline and state events in a room.\n private accumulateJoinState(roomId: string, data: IJoinedRoom, fromDatabase = false): void {\n // We expect this function to be called a lot (every /sync) so we want\n // this to be fast. /sync stores events in an array but we often want\n // to clobber based on type/state_key. Rather than convert arrays to\n // maps all the time, just keep private maps which contain\n // the actual current accumulated sync state, and array-ify it when\n // getJSON() is called.\n\n // State resolution:\n // The 'state' key is the delta from the previous sync (or start of time\n // if no token was supplied), to the START of the timeline. To obtain\n // the current state, we need to \"roll forward\" state by reading the\n // timeline. We want to store the current state so we can drop events\n // out the end of the timeline based on opts.maxTimelineEntries.\n //\n // 'state' 'timeline' current state\n // |-------x<======================>x\n // T I M E\n //\n // When getJSON() is called, we 'roll back' the current state by the\n // number of entries in the timeline to work out what 'state' should be.\n\n // Back-pagination:\n // On an initial /sync, the server provides a back-pagination token for\n // the start of the timeline. When /sync deltas come down, they also\n // include back-pagination tokens for the start of the timeline. This\n // means not all events in the timeline have back-pagination tokens, as\n // it is only the ones at the START of the timeline which have them.\n // In order for us to have a valid timeline (and back-pagination token\n // to match), we need to make sure that when we remove old timeline\n // events, that we roll forward to an event which has a back-pagination\n // token. This means we can't keep a strict sliding-window based on\n // opts.maxTimelineEntries, and we may have a few less. We should never\n // have more though, provided that the /sync limit is less than or equal\n // to opts.maxTimelineEntries.\n\n if (!this.joinRooms[roomId]) {\n // Create truly empty objects so event types of 'hasOwnProperty' and co\n // don't cause this code to break.\n this.joinRooms[roomId] = {\n _currentState: Object.create(null),\n _timeline: [],\n _accountData: Object.create(null),\n _unreadNotifications: {},\n _unreadThreadNotifications: {},\n _summary: {},\n _readReceipts: {},\n _threadReadReceipts: {},\n };\n }\n const currentData = this.joinRooms[roomId];\n\n if (data.account_data && data.account_data.events) {\n // clobber based on type\n data.account_data.events.forEach((e) => {\n currentData._accountData[e.type] = e;\n });\n }\n\n // these probably clobber, spec is unclear.\n if (data.unread_notifications) {\n currentData._unreadNotifications = data.unread_notifications;\n }\n currentData._unreadThreadNotifications =\n data[UNREAD_THREAD_NOTIFICATIONS.stable!] ?? data[UNREAD_THREAD_NOTIFICATIONS.unstable!] ?? undefined;\n\n if (data.summary) {\n const HEROES_KEY = \"m.heroes\";\n const INVITED_COUNT_KEY = \"m.invited_member_count\";\n const JOINED_COUNT_KEY = \"m.joined_member_count\";\n\n const acc = currentData._summary;\n const sum = data.summary;\n acc[HEROES_KEY] = sum[HEROES_KEY] || acc[HEROES_KEY];\n acc[JOINED_COUNT_KEY] = sum[JOINED_COUNT_KEY] || acc[JOINED_COUNT_KEY];\n acc[INVITED_COUNT_KEY] = sum[INVITED_COUNT_KEY] || acc[INVITED_COUNT_KEY];\n }\n\n data.ephemeral?.events?.forEach((e) => {\n // We purposefully do not persist m.typing events.\n // Technically you could refresh a browser before the timer on a\n // typing event is up, so it'll look like you aren't typing when\n // you really still are. However, the alternative is worse. If\n // we do persist typing events, it will look like people are\n // typing forever until someone really does start typing (which\n // will prompt Synapse to send down an actual m.typing event to\n // clobber the one we persisted).\n if (e.type !== EventType.Receipt || !e.content) {\n // This means we'll drop unknown ephemeral events but that\n // seems okay.\n return;\n }\n // Handle m.receipt events. They clobber based on:\n // (user_id, receipt_type)\n // but they are keyed in the event as:\n // content:{ $event_id: { $receipt_type: { $user_id: {json} }}}\n // so store them in the former so we can accumulate receipt deltas\n // quickly and efficiently (we expect a lot of them). Fold the\n // receipt type into the key name since we only have 1 at the\n // moment (m.read) and nested JSON objects are slower and more\n // of a hassle to work with. We'll inflate this back out when\n // getJSON() is called.\n Object.keys(e.content).forEach((eventId) => {\n Object.entries(e.content[eventId]).forEach(([key, value]) => {\n if (!isSupportedReceiptType(key)) return;\n\n for (const userId of Object.keys(value)) {\n const data = e.content[eventId][key][userId];\n\n const receipt = {\n data: e.content[eventId][key][userId],\n type: key as ReceiptType,\n eventId: eventId,\n };\n\n if (!data.thread_id || data.thread_id === MAIN_ROOM_TIMELINE) {\n currentData._readReceipts[userId] = receipt;\n } else {\n currentData._threadReadReceipts = {\n ...currentData._threadReadReceipts,\n [data.thread_id]: {\n ...(currentData._threadReadReceipts[data.thread_id] ?? {}),\n [userId]: receipt,\n },\n };\n }\n }\n });\n });\n });\n\n // if we got a limited sync, we need to remove all timeline entries or else\n // we will have gaps in the timeline.\n if (data.timeline && data.timeline.limited) {\n currentData._timeline = [];\n }\n\n // Work out the current state. The deltas need to be applied in the order:\n // - existing state which didn't come down /sync.\n // - State events under the 'state' key.\n // - State events in the 'timeline'.\n data.state?.events?.forEach((e) => {\n setState(currentData._currentState, e);\n });\n data.timeline?.events?.forEach((e, index) => {\n // this nops if 'e' isn't a state event\n setState(currentData._currentState, e);\n // append the event to the timeline. The back-pagination token\n // corresponds to the first event in the timeline\n let transformedEvent: TaggedEvent;\n if (!fromDatabase) {\n transformedEvent = Object.assign({}, e);\n if (transformedEvent.unsigned !== undefined) {\n transformedEvent.unsigned = Object.assign({}, transformedEvent.unsigned);\n }\n const age = e.unsigned ? e.unsigned.age : e.age;\n if (age !== undefined) transformedEvent._localTs = Date.now() - age;\n } else {\n transformedEvent = e;\n }\n\n currentData._timeline.push({\n event: transformedEvent,\n token: index === 0 ? data.timeline.prev_batch ?? null : null,\n });\n });\n\n // attempt to prune the timeline by jumping between events which have\n // pagination tokens.\n if (currentData._timeline.length > this.opts.maxTimelineEntries!) {\n const startIndex = currentData._timeline.length - this.opts.maxTimelineEntries!;\n for (let i = startIndex; i < currentData._timeline.length; i++) {\n if (currentData._timeline[i].token) {\n // keep all events after this, including this one\n currentData._timeline = currentData._timeline.slice(i, currentData._timeline.length);\n break;\n }\n }\n }\n }\n\n /**\n * Return everything under the 'rooms' key from a /sync response which\n * represents all room data that should be stored. This should be paired\n * with the sync token which represents the most recent /sync response\n * provided to accumulate().\n * @param forDatabase - True to generate a sync to be saved to storage\n * @returns An object with a \"nextBatch\", \"roomsData\" and \"accountData\"\n * keys.\n * The \"nextBatch\" key is a string which represents at what point in the\n * /sync stream the accumulator reached. This token should be used when\n * restarting a /sync stream at startup. Failure to do so can lead to missing\n * events. The \"roomsData\" key is an Object which represents the entire\n * /sync response from the 'rooms' key onwards. The \"accountData\" key is\n * a list of raw events which represent global account data.\n */\n public getJSON(forDatabase = false): ISyncData {\n const data: IRooms = {\n join: {},\n invite: {},\n // always empty. This is set by /sync when a room was previously\n // in 'invite' or 'join'. On fresh startup, the client won't know\n // about any previous room being in 'invite' or 'join' so we can\n // just omit mentioning it at all, even if it has previously come\n // down /sync.\n // The notable exception is when a client is kicked or banned:\n // we may want to hold onto that room so the client can clearly see\n // why their room has disappeared. We don't persist it though because\n // it is unclear *when* we can safely remove the room from the DB.\n // Instead, we assume that if you're loading from the DB, you've\n // refreshed the page, which means you've seen the kick/ban already.\n leave: {},\n };\n Object.keys(this.inviteRooms).forEach((roomId) => {\n data.invite[roomId] = this.inviteRooms[roomId];\n });\n Object.keys(this.joinRooms).forEach((roomId) => {\n const roomData = this.joinRooms[roomId];\n const roomJson: IJoinedRoom = {\n ephemeral: { events: [] },\n account_data: { events: [] },\n state: { events: [] },\n timeline: {\n events: [],\n prev_batch: null,\n },\n unread_notifications: roomData._unreadNotifications,\n unread_thread_notifications: roomData._unreadThreadNotifications,\n summary: roomData._summary as IRoomSummary,\n };\n // Add account data\n Object.keys(roomData._accountData).forEach((evType) => {\n roomJson.account_data.events.push(roomData._accountData[evType]);\n });\n\n // Add receipt data\n const receiptEvent = {\n type: EventType.Receipt,\n room_id: roomId,\n content: {\n // $event_id: { \"m.read\": { $user_id: $json } }\n } as IContent,\n };\n\n const receiptEventContent: MapWithDefault<\n string,\n MapWithDefault>\n > = new MapWithDefault(() => new MapWithDefault(() => new Map()));\n\n for (const [userId, receiptData] of Object.entries(roomData._readReceipts)) {\n receiptEventContent\n .getOrCreate(receiptData.eventId)\n .getOrCreate(receiptData.type)\n .set(userId, receiptData.data);\n }\n\n for (const threadReceipts of Object.values(roomData._threadReadReceipts)) {\n for (const [userId, receiptData] of Object.entries(threadReceipts)) {\n receiptEventContent\n .getOrCreate(receiptData.eventId)\n .getOrCreate(receiptData.type)\n .set(userId, receiptData.data);\n }\n }\n\n receiptEvent.content = recursiveMapToObject(receiptEventContent);\n\n // add only if we have some receipt data\n if (receiptEventContent.size > 0) {\n roomJson.ephemeral.events.push(receiptEvent as IMinimalEvent);\n }\n\n // Add timeline data\n roomData._timeline.forEach((msgData) => {\n if (!roomJson.timeline.prev_batch) {\n // the first event we add to the timeline MUST match up to\n // the prev_batch token.\n if (!msgData.token) {\n return; // this shouldn't happen as we prune constantly.\n }\n roomJson.timeline.prev_batch = msgData.token;\n }\n\n let transformedEvent: (IRoomEvent | IStateEvent) & { _localTs?: number };\n if (!forDatabase && isTaggedEvent(msgData.event)) {\n // This means we have to copy each event, so we can fix it up to\n // set a correct 'age' parameter whilst keeping the local timestamp\n // on our stored event. If this turns out to be a bottleneck, it could\n // be optimised either by doing this in the main process after the data\n // has been structured-cloned to go between the worker & main process,\n // or special-casing data from saved syncs to read the local timestamp\n // directly rather than turning it into age to then immediately be\n // transformed back again into a local timestamp.\n transformedEvent = Object.assign({}, msgData.event);\n if (transformedEvent.unsigned !== undefined) {\n transformedEvent.unsigned = Object.assign({}, transformedEvent.unsigned);\n }\n delete transformedEvent._localTs;\n transformedEvent.unsigned = transformedEvent.unsigned || {};\n transformedEvent.unsigned.age = Date.now() - msgData.event._localTs!;\n } else {\n transformedEvent = msgData.event;\n }\n roomJson.timeline.events.push(transformedEvent);\n });\n\n // Add state data: roll back current state to the start of timeline,\n // by \"reverse clobbering\" from the end of the timeline to the start.\n // Convert maps back into arrays.\n const rollBackState = Object.create(null);\n for (let i = roomJson.timeline.events.length - 1; i >= 0; i--) {\n const timelineEvent = roomJson.timeline.events[i];\n if (\n (timelineEvent as IStateEvent).state_key === null ||\n (timelineEvent as IStateEvent).state_key === undefined\n ) {\n continue; // not a state event\n }\n // since we're going back in time, we need to use the previous\n // state value else we'll break causality. We don't have the\n // complete previous state event, so we need to create one.\n const prevStateEvent = deepCopy(timelineEvent);\n if (prevStateEvent.unsigned) {\n if (prevStateEvent.unsigned.prev_content) {\n prevStateEvent.content = prevStateEvent.unsigned.prev_content;\n }\n if (prevStateEvent.unsigned.prev_sender) {\n prevStateEvent.sender = prevStateEvent.unsigned.prev_sender;\n }\n }\n setState(rollBackState, prevStateEvent);\n }\n Object.keys(roomData._currentState).forEach((evType) => {\n Object.keys(roomData._currentState[evType]).forEach((stateKey) => {\n let ev = roomData._currentState[evType][stateKey];\n if (rollBackState[evType] && rollBackState[evType][stateKey]) {\n // use the reverse clobbered event instead.\n ev = rollBackState[evType][stateKey];\n }\n roomJson.state.events.push(ev);\n });\n });\n data.join[roomId] = roomJson;\n });\n\n // Add account data\n const accData: IMinimalEvent[] = [];\n Object.keys(this.accountData).forEach((evType) => {\n accData.push(this.accountData[evType]);\n });\n\n return {\n nextBatch: this.nextBatch!,\n roomsData: data,\n accountData: accData,\n };\n }\n\n public getNextBatchToken(): string {\n return this.nextBatch!;\n }\n}\n\nfunction setState(eventMap: Record>, event: IRoomEvent | IStateEvent): void {\n if ((event as IStateEvent).state_key === null || (event as IStateEvent).state_key === undefined || !event.type) {\n return;\n }\n if (!eventMap[event.type]) {\n eventMap[event.type] = Object.create(null);\n }\n eventMap[event.type][(event as IStateEvent).state_key] = event as IStateEvent;\n}\n", - "/*\nCopyright 2015 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\n * TODO:\n * This class mainly serves to take all the syncing logic out of client.js and\n * into a separate file. It's all very fluid, and this class gut wrenches a lot\n * of MatrixClient props (e.g. http). Given we want to support WebSockets as\n * an alternative syncing API, we may want to have a proper syncing interface\n * for HTTP and WS at some point.\n */\n\nimport { Optional } from \"matrix-events-sdk\";\n\nimport type { SyncCryptoCallbacks } from \"./common-crypto/CryptoBackend\";\nimport { User, UserEvent } from \"./models/user\";\nimport { NotificationCountType, Room, RoomEvent } from \"./models/room\";\nimport * as utils from \"./utils\";\nimport { IDeferred, noUnsafeEventProps, unsafeProp } from \"./utils\";\nimport { Filter } from \"./filter\";\nimport { EventTimeline } from \"./models/event-timeline\";\nimport { logger } from \"./logger\";\nimport { InvalidStoreError, InvalidStoreState } from \"./errors\";\nimport { ClientEvent, IStoredClientOpts, MatrixClient, PendingEventOrdering, ResetTimelineCallback } from \"./client\";\nimport {\n IEphemeral,\n IInvitedRoom,\n IInviteState,\n IJoinedRoom,\n ILeftRoom,\n IMinimalEvent,\n IRoomEvent,\n IStateEvent,\n IStrippedState,\n ISyncResponse,\n ITimeline,\n IToDeviceEvent,\n} from \"./sync-accumulator\";\nimport { MatrixEvent } from \"./models/event\";\nimport { MatrixError, Method } from \"./http-api\";\nimport { ISavedSync } from \"./store\";\nimport { EventType } from \"./@types/event\";\nimport { IPushRules } from \"./@types/PushRules\";\nimport { RoomStateEvent, IMarkerFoundOptions } from \"./models/room-state\";\nimport { RoomMemberEvent } from \"./models/room-member\";\nimport { BeaconEvent } from \"./models/beacon\";\nimport { IEventsResponse } from \"./@types/requests\";\nimport { UNREAD_THREAD_NOTIFICATIONS } from \"./@types/sync\";\nimport { Feature, ServerSupport } from \"./feature\";\nimport { Crypto } from \"./crypto\";\n\nconst DEBUG = true;\n\n// /sync requests allow you to set a timeout= but the request may continue\n// beyond that and wedge forever, so we need to track how long we are willing\n// to keep open the connection. This constant is *ADDED* to the timeout= value\n// to determine the max time we're willing to wait.\nconst BUFFER_PERIOD_MS = 80 * 1000;\n\n// Number of consecutive failed syncs that will lead to a syncState of ERROR as opposed\n// to RECONNECTING. This is needed to inform the client of server issues when the\n// keepAlive is successful but the server /sync fails.\nconst FAILED_SYNC_ERROR_THRESHOLD = 3;\n\nexport enum SyncState {\n /** Emitted after we try to sync more than `FAILED_SYNC_ERROR_THRESHOLD`\n * times and are still failing. Or when we enounter a hard error like the\n * token being invalid. */\n Error = \"ERROR\",\n /** Emitted after the first sync events are ready (this could even be sync\n * events from the cache) */\n Prepared = \"PREPARED\",\n /** Emitted when the sync loop is no longer running */\n Stopped = \"STOPPED\",\n /** Emitted after each sync request happens */\n Syncing = \"SYNCING\",\n /** Emitted after a connectivity error and we're ready to start syncing again */\n Catchup = \"CATCHUP\",\n /** Emitted for each time we try reconnecting. Will switch to `Error` after\n * we reach the `FAILED_SYNC_ERROR_THRESHOLD`\n */\n Reconnecting = \"RECONNECTING\",\n}\n\n// Room versions where \"insertion\", \"batch\", and \"marker\" events are controlled\n// by power-levels. MSC2716 is supported in existing room versions but they\n// should only have special meaning when the room creator sends them.\nconst MSC2716_ROOM_VERSIONS = [\"org.matrix.msc2716v3\"];\n\nfunction getFilterName(userId: string, suffix?: string): string {\n // scope this on the user ID because people may login on many accounts\n // and they all need to be stored!\n return `FILTER_SYNC_${userId}` + (suffix ? \"_\" + suffix : \"\");\n}\n\n/* istanbul ignore next */\nfunction debuglog(...params: any[]): void {\n if (!DEBUG) return;\n logger.log(...params);\n}\n\n/**\n * Options passed into the constructor of SyncApi by MatrixClient\n */\nexport interface SyncApiOptions {\n /**\n * Crypto manager\n *\n * @deprecated in favour of cryptoCallbacks\n */\n crypto?: Crypto;\n\n /**\n * If crypto is enabled on our client, callbacks into the crypto module\n */\n cryptoCallbacks?: SyncCryptoCallbacks;\n\n /**\n * A function which is called\n * with a room ID and returns a boolean. It should return 'true' if the SDK can\n * SAFELY remove events from this room. It may not be safe to remove events if\n * there are other references to the timelines for this room.\n */\n canResetEntireTimeline?: ResetTimelineCallback;\n}\n\ninterface ISyncOptions {\n filter?: string;\n hasSyncedBefore?: boolean;\n}\n\nexport interface ISyncStateData {\n /**\n * The matrix error if `state=ERROR`.\n */\n error?: Error;\n /**\n * The 'since' token passed to /sync.\n * `null` for the first successful sync since this client was\n * started. Only present if `state=PREPARED` or\n * `state=SYNCING`.\n */\n oldSyncToken?: string;\n /**\n * The 'next_batch' result from /sync, which\n * will become the 'since' token for the next call to /sync. Only present if\n * `state=PREPARED or state=SYNCING`.\n */\n nextSyncToken?: string;\n /**\n * True if we are working our way through a\n * backlog of events after connecting. Only present if `state=SYNCING`.\n */\n catchingUp?: boolean;\n fromCache?: boolean;\n}\n\nenum SetPresence {\n Offline = \"offline\",\n Online = \"online\",\n Unavailable = \"unavailable\",\n}\n\ninterface ISyncParams {\n filter?: string;\n timeout: number;\n since?: string;\n // eslint-disable-next-line camelcase\n full_state?: boolean;\n // eslint-disable-next-line camelcase\n set_presence?: SetPresence;\n _cacheBuster?: string | number; // not part of the API itself\n}\n\ntype WrappedRoom = T & {\n room: Room;\n isBrandNewRoom: boolean;\n};\n\n/** add default settings to an IStoredClientOpts */\nexport function defaultClientOpts(opts?: IStoredClientOpts): IStoredClientOpts {\n return {\n initialSyncLimit: 8,\n resolveInvitesToProfiles: false,\n pollTimeout: 30 * 1000,\n pendingEventOrdering: PendingEventOrdering.Chronological,\n threadSupport: false,\n ...opts,\n };\n}\n\nexport function defaultSyncApiOpts(syncOpts?: SyncApiOptions): SyncApiOptions {\n return {\n canResetEntireTimeline: (_roomId): boolean => false,\n ...syncOpts,\n };\n}\n\nexport class SyncApi {\n private readonly opts: IStoredClientOpts;\n private readonly syncOpts: SyncApiOptions;\n\n private _peekRoom: Optional = null;\n private currentSyncRequest?: Promise;\n private abortController?: AbortController;\n private syncState: SyncState | null = null;\n private syncStateData?: ISyncStateData; // additional data (eg. error object for failed sync)\n private catchingUp = false;\n private running = false;\n private keepAliveTimer?: ReturnType;\n private connectionReturnedDefer?: IDeferred;\n private notifEvents: MatrixEvent[] = []; // accumulator of sync events in the current sync response\n private failedSyncCount = 0; // Number of consecutive failed /sync requests\n private storeIsInvalid = false; // flag set if the store needs to be cleared before we can start\n\n /**\n * Construct an entity which is able to sync with a homeserver.\n * @param client - The matrix client instance to use.\n * @param opts - client config options\n * @param syncOpts - sync-specific options passed by the client\n * @internal\n */\n public constructor(private readonly client: MatrixClient, opts?: IStoredClientOpts, syncOpts?: SyncApiOptions) {\n this.opts = defaultClientOpts(opts);\n this.syncOpts = defaultSyncApiOpts(syncOpts);\n\n if (client.getNotifTimelineSet()) {\n client.reEmitter.reEmit(client.getNotifTimelineSet()!, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n }\n }\n\n public createRoom(roomId: string): Room {\n const room = _createAndReEmitRoom(this.client, roomId, this.opts);\n\n room.on(RoomStateEvent.Marker, (markerEvent, markerFoundOptions) => {\n this.onMarkerStateEvent(room, markerEvent, markerFoundOptions);\n });\n\n return room;\n }\n\n /** When we see the marker state change in the room, we know there is some\n * new historical messages imported by MSC2716 `/batch_send` somewhere in\n * the room and we need to throw away the timeline to make sure the\n * historical messages are shown when we paginate `/messages` again.\n * @param room - The room where the marker event was sent\n * @param markerEvent - The new marker event\n * @param setStateOptions - When `timelineWasEmpty` is set\n * as `true`, the given marker event will be ignored\n */\n private onMarkerStateEvent(\n room: Room,\n markerEvent: MatrixEvent,\n { timelineWasEmpty }: IMarkerFoundOptions = {},\n ): void {\n // We don't need to refresh the timeline if it was empty before the\n // marker arrived. This could be happen in a variety of cases:\n // 1. From the initial sync\n // 2. If it's from the first state we're seeing after joining the room\n // 3. Or whether it's coming from `syncFromCache`\n if (timelineWasEmpty) {\n logger.debug(\n `MarkerState: Ignoring markerEventId=${markerEvent.getId()} in roomId=${room.roomId} ` +\n `because the timeline was empty before the marker arrived which means there is nothing to refresh.`,\n );\n return;\n }\n\n const isValidMsc2716Event =\n // Check whether the room version directly supports MSC2716, in\n // which case, \"marker\" events are already auth'ed by\n // power_levels\n MSC2716_ROOM_VERSIONS.includes(room.getVersion()) ||\n // MSC2716 is also supported in all existing room versions but\n // special meaning should only be given to \"insertion\", \"batch\",\n // and \"marker\" events when they come from the room creator\n markerEvent.getSender() === room.getCreator();\n\n // It would be nice if we could also specifically tell whether the\n // historical messages actually affected the locally cached client\n // timeline or not. The problem is we can't see the prev_events of\n // the base insertion event that the marker was pointing to because\n // prev_events aren't available in the client API's. In most cases,\n // the history won't be in people's locally cached timelines in the\n // client, so we don't need to bother everyone about refreshing\n // their timeline. This works for a v1 though and there are use\n // cases like initially bootstrapping your bridged room where people\n // are likely to encounter the historical messages affecting their\n // current timeline (think someone signing up for Beeper and\n // importing their Whatsapp history).\n if (isValidMsc2716Event) {\n // Saw new marker event, let's let the clients know they should\n // refresh the timeline.\n logger.debug(\n `MarkerState: Timeline needs to be refreshed because ` +\n `a new markerEventId=${markerEvent.getId()} was sent in roomId=${room.roomId}`,\n );\n room.setTimelineNeedsRefresh(true);\n room.emit(RoomEvent.HistoryImportedWithinTimeline, markerEvent, room);\n } else {\n logger.debug(\n `MarkerState: Ignoring markerEventId=${markerEvent.getId()} in roomId=${room.roomId} because ` +\n `MSC2716 is not supported in the room version or for any room version, the marker wasn't sent ` +\n `by the room creator.`,\n );\n }\n }\n\n /**\n * Sync rooms the user has left.\n * @returns Resolved when they've been added to the store.\n */\n public async syncLeftRooms(): Promise {\n const client = this.client;\n\n // grab a filter with limit=1 and include_leave=true\n const filter = new Filter(this.client.credentials.userId);\n filter.setTimelineLimit(1);\n filter.setIncludeLeaveRooms(true);\n\n const localTimeoutMs = this.opts.pollTimeout! + BUFFER_PERIOD_MS;\n\n const filterId = await client.getOrCreateFilter(\n getFilterName(client.credentials.userId!, \"LEFT_ROOMS\"),\n filter,\n );\n\n const qps: ISyncParams = {\n timeout: 0, // don't want to block since this is a single isolated req\n filter: filterId,\n };\n\n const data = await client.http.authedRequest(Method.Get, \"/sync\", qps as any, undefined, {\n localTimeoutMs,\n });\n\n let leaveRooms: WrappedRoom[] = [];\n if (data.rooms?.leave) {\n leaveRooms = this.mapSyncResponseToRoomArray(data.rooms.leave);\n }\n\n const rooms = await Promise.all(\n leaveRooms.map(async (leaveObj) => {\n const room = leaveObj.room;\n if (!leaveObj.isBrandNewRoom) {\n // the intention behind syncLeftRooms is to add in rooms which were\n // *omitted* from the initial /sync. Rooms the user were joined to\n // but then left whilst the app is running will appear in this list\n // and we do not want to bother with them since they will have the\n // current state already (and may get dupe messages if we add\n // yet more timeline events!), so skip them.\n // NB: When we persist rooms to localStorage this will be more\n // complicated...\n return;\n }\n leaveObj.timeline = leaveObj.timeline || {\n prev_batch: null,\n events: [],\n };\n const events = this.mapSyncEventsFormat(leaveObj.timeline, room);\n\n const stateEvents = this.mapSyncEventsFormat(leaveObj.state, room);\n\n // set the back-pagination token. Do this *before* adding any\n // events so that clients can start back-paginating.\n room.getLiveTimeline().setPaginationToken(leaveObj.timeline.prev_batch, EventTimeline.BACKWARDS);\n\n await this.injectRoomEvents(room, stateEvents, events);\n\n room.recalculate();\n client.store.storeRoom(room);\n client.emit(ClientEvent.Room, room);\n\n this.processEventsForNotifs(room, events);\n return room;\n }),\n );\n\n return rooms.filter(Boolean) as Room[];\n }\n\n /**\n * Peek into a room. This will result in the room in question being synced so it\n * is accessible via getRooms(). Live updates for the room will be provided.\n * @param roomId - The room ID to peek into.\n * @returns A promise which resolves once the room has been added to the\n * store.\n */\n public peek(roomId: string): Promise {\n if (this._peekRoom?.roomId === roomId) {\n return Promise.resolve(this._peekRoom);\n }\n\n const client = this.client;\n this._peekRoom = this.createRoom(roomId);\n return this.client.roomInitialSync(roomId, 20).then((response) => {\n // make sure things are init'd\n response.messages = response.messages || { chunk: [] };\n response.messages.chunk = response.messages.chunk || [];\n response.state = response.state || [];\n\n // FIXME: Mostly duplicated from injectRoomEvents but not entirely\n // because \"state\" in this API is at the BEGINNING of the chunk\n const oldStateEvents = utils.deepCopy(response.state).map(client.getEventMapper());\n const stateEvents = response.state.map(client.getEventMapper());\n const messages = response.messages.chunk.map(client.getEventMapper());\n\n // XXX: copypasted from /sync until we kill off this minging v1 API stuff)\n // handle presence events (User objects)\n if (Array.isArray(response.presence)) {\n response.presence.map(client.getEventMapper()).forEach(function (presenceEvent) {\n let user = client.store.getUser(presenceEvent.getContent().user_id);\n if (user) {\n user.setPresenceEvent(presenceEvent);\n } else {\n user = createNewUser(client, presenceEvent.getContent().user_id);\n user.setPresenceEvent(presenceEvent);\n client.store.storeUser(user);\n }\n client.emit(ClientEvent.Event, presenceEvent);\n });\n }\n\n // set the pagination token before adding the events in case people\n // fire off pagination requests in response to the Room.timeline\n // events.\n if (response.messages.start) {\n this._peekRoom!.oldState.paginationToken = response.messages.start;\n }\n\n // set the state of the room to as it was after the timeline executes\n this._peekRoom!.oldState.setStateEvents(oldStateEvents);\n this._peekRoom!.currentState.setStateEvents(stateEvents);\n\n this.resolveInvites(this._peekRoom!);\n this._peekRoom!.recalculate();\n\n // roll backwards to diverge old state. addEventsToTimeline\n // will overwrite the pagination token, so make sure it overwrites\n // it with the right thing.\n this._peekRoom!.addEventsToTimeline(\n messages.reverse(),\n true,\n this._peekRoom!.getLiveTimeline(),\n response.messages.start,\n );\n\n client.store.storeRoom(this._peekRoom!);\n client.emit(ClientEvent.Room, this._peekRoom!);\n\n this.peekPoll(this._peekRoom!);\n return this._peekRoom!;\n });\n }\n\n /**\n * Stop polling for updates in the peeked room. NOPs if there is no room being\n * peeked.\n */\n public stopPeeking(): void {\n this._peekRoom = null;\n }\n\n /**\n * Do a peek room poll.\n * @param token - from= token\n */\n private peekPoll(peekRoom: Room, token?: string): void {\n if (this._peekRoom !== peekRoom) {\n debuglog(\"Stopped peeking in room %s\", peekRoom.roomId);\n return;\n }\n\n // FIXME: gut wrenching; hard-coded timeout values\n this.client.http\n .authedRequest(\n Method.Get,\n \"/events\",\n {\n room_id: peekRoom.roomId,\n timeout: String(30 * 1000),\n from: token,\n },\n undefined,\n {\n localTimeoutMs: 50 * 1000,\n abortSignal: this.abortController?.signal,\n },\n )\n .then(\n (res) => {\n if (this._peekRoom !== peekRoom) {\n debuglog(\"Stopped peeking in room %s\", peekRoom.roomId);\n return;\n }\n // We have a problem that we get presence both from /events and /sync\n // however, /sync only returns presence for users in rooms\n // you're actually joined to.\n // in order to be sure to get presence for all of the users in the\n // peeked room, we handle presence explicitly here. This may result\n // in duplicate presence events firing for some users, which is a\n // performance drain, but such is life.\n // XXX: copypasted from /sync until we can kill this minging v1 stuff.\n\n res.chunk\n .filter(function (e) {\n return e.type === \"m.presence\";\n })\n .map(this.client.getEventMapper())\n .forEach((presenceEvent) => {\n let user = this.client.store.getUser(presenceEvent.getContent().user_id);\n if (user) {\n user.setPresenceEvent(presenceEvent);\n } else {\n user = createNewUser(this.client, presenceEvent.getContent().user_id);\n user.setPresenceEvent(presenceEvent);\n this.client.store.storeUser(user);\n }\n this.client.emit(ClientEvent.Event, presenceEvent);\n });\n\n // strip out events which aren't for the given room_id (e.g presence)\n // and also ephemeral events (which we're assuming is anything without\n // and event ID because the /events API doesn't separate them).\n const events = res.chunk\n .filter(function (e) {\n return e.room_id === peekRoom.roomId && e.event_id;\n })\n .map(this.client.getEventMapper());\n\n peekRoom.addLiveEvents(events);\n this.peekPoll(peekRoom, res.end);\n },\n (err) => {\n logger.error(\"[%s] Peek poll failed: %s\", peekRoom.roomId, err);\n setTimeout(() => {\n this.peekPoll(peekRoom, token);\n }, 30 * 1000);\n },\n );\n }\n\n /**\n * Returns the current state of this sync object\n * @see MatrixClient#event:\"sync\"\n */\n public getSyncState(): SyncState | null {\n return this.syncState;\n }\n\n /**\n * Returns the additional data object associated with\n * the current sync state, or null if there is no\n * such data.\n * Sync errors, if available, are put in the 'error' key of\n * this object.\n */\n public getSyncStateData(): ISyncStateData | null {\n return this.syncStateData ?? null;\n }\n\n public async recoverFromSyncStartupError(savedSyncPromise: Promise | undefined, error: Error): Promise {\n // Wait for the saved sync to complete - we send the pushrules and filter requests\n // before the saved sync has finished so they can run in parallel, but only process\n // the results after the saved sync is done. Equivalently, we wait for it to finish\n // before reporting failures from these functions.\n await savedSyncPromise;\n const keepaliveProm = this.startKeepAlives();\n this.updateSyncState(SyncState.Error, { error });\n await keepaliveProm;\n }\n\n /**\n * Is the lazy loading option different than in previous session?\n * @param lazyLoadMembers - current options for lazy loading\n * @returns whether or not the option has changed compared to the previous session */\n private async wasLazyLoadingToggled(lazyLoadMembers = false): Promise {\n // assume it was turned off before\n // if we don't know any better\n let lazyLoadMembersBefore = false;\n const isStoreNewlyCreated = await this.client.store.isNewlyCreated();\n if (!isStoreNewlyCreated) {\n const prevClientOptions = await this.client.store.getClientOptions();\n if (prevClientOptions) {\n lazyLoadMembersBefore = !!prevClientOptions.lazyLoadMembers;\n }\n return lazyLoadMembersBefore !== lazyLoadMembers;\n }\n return false;\n }\n\n private shouldAbortSync(error: MatrixError): boolean {\n if (error.errcode === \"M_UNKNOWN_TOKEN\") {\n // The logout already happened, we just need to stop.\n logger.warn(\"Token no longer valid - assuming logout\");\n this.stop();\n this.updateSyncState(SyncState.Error, { error });\n return true;\n }\n return false;\n }\n\n private getPushRules = async (): Promise => {\n try {\n debuglog(\"Getting push rules...\");\n const result = await this.client.getPushRules();\n debuglog(\"Got push rules\");\n\n this.client.pushRules = result;\n } catch (err) {\n logger.error(\"Getting push rules failed\", err);\n if (this.shouldAbortSync(err)) return;\n // wait for saved sync to complete before doing anything else,\n // otherwise the sync state will end up being incorrect\n debuglog(\"Waiting for saved sync before retrying push rules...\");\n await this.recoverFromSyncStartupError(this.savedSyncPromise, err);\n return this.getPushRules(); // try again\n }\n };\n\n private buildDefaultFilter = (): Filter => {\n const filter = new Filter(this.client.credentials.userId);\n if (this.client.canSupport.get(Feature.ThreadUnreadNotifications) !== ServerSupport.Unsupported) {\n filter.setUnreadThreadNotifications(true);\n }\n return filter;\n };\n\n private checkLazyLoadStatus = async (): Promise => {\n debuglog(\"Checking lazy load status...\");\n if (this.opts.lazyLoadMembers && this.client.isGuest()) {\n this.opts.lazyLoadMembers = false;\n }\n if (this.opts.lazyLoadMembers) {\n debuglog(\"Checking server lazy load support...\");\n const supported = await this.client.doesServerSupportLazyLoading();\n if (supported) {\n debuglog(\"Enabling lazy load on sync filter...\");\n if (!this.opts.filter) {\n this.opts.filter = this.buildDefaultFilter();\n }\n this.opts.filter.setLazyLoadMembers(true);\n } else {\n debuglog(\"LL: lazy loading requested but not supported \" + \"by server, so disabling\");\n this.opts.lazyLoadMembers = false;\n }\n }\n // need to vape the store when enabling LL and wasn't enabled before\n debuglog(\"Checking whether lazy loading has changed in store...\");\n const shouldClear = await this.wasLazyLoadingToggled(this.opts.lazyLoadMembers);\n if (shouldClear) {\n this.storeIsInvalid = true;\n const error = new InvalidStoreError(InvalidStoreState.ToggledLazyLoading, !!this.opts.lazyLoadMembers);\n this.updateSyncState(SyncState.Error, { error });\n // bail out of the sync loop now: the app needs to respond to this error.\n // we leave the state as 'ERROR' which isn't great since this normally means\n // we're retrying. The client must be stopped before clearing the stores anyway\n // so the app should stop the client, clear the store and start it again.\n logger.warn(\"InvalidStoreError: store is not usable: stopping sync.\");\n return;\n }\n if (this.opts.lazyLoadMembers) {\n this.syncOpts.crypto?.enableLazyLoading();\n }\n try {\n debuglog(\"Storing client options...\");\n await this.client.storeClientOptions();\n debuglog(\"Stored client options\");\n } catch (err) {\n logger.error(\"Storing client options failed\", err);\n throw err;\n }\n };\n\n private getFilter = async (): Promise<{\n filterId?: string;\n filter?: Filter;\n }> => {\n debuglog(\"Getting filter...\");\n let filter: Filter;\n if (this.opts.filter) {\n filter = this.opts.filter;\n } else {\n filter = this.buildDefaultFilter();\n }\n\n let filterId: string;\n try {\n filterId = await this.client.getOrCreateFilter(getFilterName(this.client.credentials.userId!), filter);\n } catch (err) {\n logger.error(\"Getting filter failed\", err);\n if (this.shouldAbortSync(err)) return {};\n // wait for saved sync to complete before doing anything else,\n // otherwise the sync state will end up being incorrect\n debuglog(\"Waiting for saved sync before retrying filter...\");\n await this.recoverFromSyncStartupError(this.savedSyncPromise, err);\n return this.getFilter(); // try again\n }\n return { filter, filterId };\n };\n\n private savedSyncPromise?: Promise;\n\n /**\n * Main entry point\n */\n public async sync(): Promise {\n this.running = true;\n this.abortController = new AbortController();\n\n global.window?.addEventListener?.(\"online\", this.onOnline, false);\n\n if (this.client.isGuest()) {\n // no push rules for guests, no access to POST filter for guests.\n return this.doSync({});\n }\n\n // Pull the saved sync token out first, before the worker starts sending\n // all the sync data which could take a while. This will let us send our\n // first incremental sync request before we've processed our saved data.\n debuglog(\"Getting saved sync token...\");\n const savedSyncTokenPromise = this.client.store.getSavedSyncToken().then((tok) => {\n debuglog(\"Got saved sync token\");\n return tok;\n });\n\n this.savedSyncPromise = this.client.store\n .getSavedSync()\n .then((savedSync) => {\n debuglog(`Got reply from saved sync, exists? ${!!savedSync}`);\n if (savedSync) {\n return this.syncFromCache(savedSync);\n }\n })\n .catch((err) => {\n logger.error(\"Getting saved sync failed\", err);\n });\n\n // We need to do one-off checks before we can begin the /sync loop.\n // These are:\n // 1) We need to get push rules so we can check if events should bing as we get\n // them from /sync.\n // 2) We need to get/create a filter which we can use for /sync.\n // 3) We need to check the lazy loading option matches what was used in the\n // stored sync. If it doesn't, we can't use the stored sync.\n\n // Now start the first incremental sync request: this can also\n // take a while so if we set it going now, we can wait for it\n // to finish while we process our saved sync data.\n await this.getPushRules();\n await this.checkLazyLoadStatus();\n const { filterId, filter } = await this.getFilter();\n if (!filter) return; // bail, getFilter failed\n\n // reset the notifications timeline to prepare it to paginate from\n // the current point in time.\n // The right solution would be to tie /sync pagination tokens into\n // /notifications API somehow.\n this.client.resetNotifTimelineSet();\n\n if (!this.currentSyncRequest) {\n let firstSyncFilter = filterId;\n const savedSyncToken = await savedSyncTokenPromise;\n\n if (savedSyncToken) {\n debuglog(\"Sending first sync request...\");\n } else {\n debuglog(\"Sending initial sync request...\");\n const initialFilter = this.buildDefaultFilter();\n initialFilter.setDefinition(filter.getDefinition());\n initialFilter.setTimelineLimit(this.opts.initialSyncLimit!);\n // Use an inline filter, no point uploading it for a single usage\n firstSyncFilter = JSON.stringify(initialFilter.getDefinition());\n }\n\n // Send this first sync request here so we can then wait for the saved\n // sync data to finish processing before we process the results of this one.\n this.currentSyncRequest = this.doSyncRequest({ filter: firstSyncFilter }, savedSyncToken);\n }\n\n // Now wait for the saved sync to finish...\n debuglog(\"Waiting for saved sync before starting sync processing...\");\n await this.savedSyncPromise;\n // process the first sync request and continue syncing with the normal filterId\n return this.doSync({ filter: filterId });\n }\n\n /**\n * Stops the sync object from syncing.\n */\n public stop(): void {\n debuglog(\"SyncApi.stop\");\n // It is necessary to check for the existance of\n // global.window AND global.window.removeEventListener.\n // Some platforms (e.g. React Native) register global.window,\n // but do not have global.window.removeEventListener.\n global.window?.removeEventListener?.(\"online\", this.onOnline, false);\n this.running = false;\n this.abortController?.abort();\n if (this.keepAliveTimer) {\n clearTimeout(this.keepAliveTimer);\n this.keepAliveTimer = undefined;\n }\n }\n\n /**\n * Retry a backed off syncing request immediately. This should only be used when\n * the user explicitly attempts to retry their lost connection.\n * @returns True if this resulted in a request being retried.\n */\n public retryImmediately(): boolean {\n if (!this.connectionReturnedDefer) {\n return false;\n }\n this.startKeepAlives(0);\n return true;\n }\n /**\n * Process a single set of cached sync data.\n * @param savedSync - a saved sync that was persisted by a store. This\n * should have been acquired via client.store.getSavedSync().\n */\n private async syncFromCache(savedSync: ISavedSync): Promise {\n debuglog(\"sync(): not doing HTTP hit, instead returning stored /sync data\");\n\n const nextSyncToken = savedSync.nextBatch;\n\n // Set sync token for future incremental syncing\n this.client.store.setSyncToken(nextSyncToken);\n\n // No previous sync, set old token to null\n const syncEventData: ISyncStateData = {\n nextSyncToken,\n catchingUp: false,\n fromCache: true,\n };\n\n const data: ISyncResponse = {\n next_batch: nextSyncToken,\n rooms: savedSync.roomsData,\n account_data: {\n events: savedSync.accountData,\n },\n };\n\n try {\n await this.processSyncResponse(syncEventData, data);\n } catch (e) {\n logger.error(\"Error processing cached sync\", e);\n }\n\n // Don't emit a prepared if we've bailed because the store is invalid:\n // in this case the client will not be usable until stopped & restarted\n // so this would be useless and misleading.\n if (!this.storeIsInvalid) {\n this.updateSyncState(SyncState.Prepared, syncEventData);\n }\n }\n\n /**\n * Invoke me to do /sync calls\n */\n private async doSync(syncOptions: ISyncOptions): Promise {\n while (this.running) {\n const syncToken = this.client.store.getSyncToken();\n\n let data: ISyncResponse;\n try {\n if (!this.currentSyncRequest) {\n this.currentSyncRequest = this.doSyncRequest(syncOptions, syncToken);\n }\n data = await this.currentSyncRequest;\n } catch (e) {\n const abort = await this.onSyncError(e);\n if (abort) return;\n continue;\n } finally {\n this.currentSyncRequest = undefined;\n }\n\n // set the sync token NOW *before* processing the events. We do this so\n // if something barfs on an event we can skip it rather than constantly\n // polling with the same token.\n this.client.store.setSyncToken(data.next_batch);\n\n // Reset after a successful sync\n this.failedSyncCount = 0;\n\n await this.client.store.setSyncData(data);\n\n const syncEventData = {\n oldSyncToken: syncToken ?? undefined,\n nextSyncToken: data.next_batch,\n catchingUp: this.catchingUp,\n };\n\n if (this.syncOpts.crypto) {\n // tell the crypto module we're about to process a sync\n // response\n await this.syncOpts.crypto.onSyncWillProcess(syncEventData);\n }\n\n try {\n await this.processSyncResponse(syncEventData, data);\n } catch (e) {\n // log the exception with stack if we have it, else fall back\n // to the plain description\n logger.error(\"Caught /sync error\", e);\n\n // Emit the exception for client handling\n this.client.emit(ClientEvent.SyncUnexpectedError, e);\n }\n\n // update this as it may have changed\n syncEventData.catchingUp = this.catchingUp;\n\n // emit synced events\n if (!syncOptions.hasSyncedBefore) {\n this.updateSyncState(SyncState.Prepared, syncEventData);\n syncOptions.hasSyncedBefore = true;\n }\n\n // tell the crypto module to do its processing. It may block (to do a\n // /keys/changes request).\n if (this.syncOpts.cryptoCallbacks) {\n await this.syncOpts.cryptoCallbacks.onSyncCompleted(syncEventData);\n }\n\n // keep emitting SYNCING -> SYNCING for clients who want to do bulk updates\n this.updateSyncState(SyncState.Syncing, syncEventData);\n\n if (this.client.store.wantsSave()) {\n // We always save the device list (if it's dirty) before saving the sync data:\n // this means we know the saved device list data is at least as fresh as the\n // stored sync data which means we don't have to worry that we may have missed\n // device changes. We can also skip the delay since we're not calling this very\n // frequently (and we don't really want to delay the sync for it).\n if (this.syncOpts.crypto) {\n await this.syncOpts.crypto.saveDeviceList(0);\n }\n\n // tell databases that everything is now in a consistent state and can be saved.\n this.client.store.save();\n }\n }\n\n if (!this.running) {\n debuglog(\"Sync no longer running: exiting.\");\n if (this.connectionReturnedDefer) {\n this.connectionReturnedDefer.reject();\n this.connectionReturnedDefer = undefined;\n }\n this.updateSyncState(SyncState.Stopped);\n }\n }\n\n private doSyncRequest(syncOptions: ISyncOptions, syncToken: string | null): Promise {\n const qps = this.getSyncParams(syncOptions, syncToken);\n return this.client.http.authedRequest(Method.Get, \"/sync\", qps as any, undefined, {\n localTimeoutMs: qps.timeout + BUFFER_PERIOD_MS,\n abortSignal: this.abortController?.signal,\n });\n }\n\n private getSyncParams(syncOptions: ISyncOptions, syncToken: string | null): ISyncParams {\n let timeout = this.opts.pollTimeout!;\n\n if (this.getSyncState() !== SyncState.Syncing || this.catchingUp) {\n // unless we are happily syncing already, we want the server to return\n // as quickly as possible, even if there are no events queued. This\n // serves two purposes:\n //\n // * When the connection dies, we want to know asap when it comes back,\n // so that we can hide the error from the user. (We don't want to\n // have to wait for an event or a timeout).\n //\n // * We want to know if the server has any to_device messages queued up\n // for us. We do that by calling it with a zero timeout until it\n // doesn't give us any more to_device messages.\n this.catchingUp = true;\n timeout = 0;\n }\n\n let filter = syncOptions.filter;\n if (this.client.isGuest() && !filter) {\n filter = this.getGuestFilter();\n }\n\n const qps: ISyncParams = { filter, timeout };\n\n if (this.opts.disablePresence) {\n qps.set_presence = SetPresence.Offline;\n }\n\n if (syncToken) {\n qps.since = syncToken;\n } else {\n // use a cachebuster for initialsyncs, to make sure that\n // we don't get a stale sync\n // (https://github.com/vector-im/vector-web/issues/1354)\n qps._cacheBuster = Date.now();\n }\n\n if ([SyncState.Reconnecting, SyncState.Error].includes(this.getSyncState()!)) {\n // we think the connection is dead. If it comes back up, we won't know\n // about it till /sync returns. If the timeout= is high, this could\n // be a long time. Set it to 0 when doing retries so we don't have to wait\n // for an event or a timeout before emiting the SYNCING event.\n qps.timeout = 0;\n }\n\n return qps;\n }\n\n private async onSyncError(err: MatrixError): Promise {\n if (!this.running) {\n debuglog(\"Sync no longer running: exiting\");\n if (this.connectionReturnedDefer) {\n this.connectionReturnedDefer.reject();\n this.connectionReturnedDefer = undefined;\n }\n this.updateSyncState(SyncState.Stopped);\n return true; // abort\n }\n\n logger.error(\"/sync error %s\", err);\n\n if (this.shouldAbortSync(err)) {\n return true; // abort\n }\n\n this.failedSyncCount++;\n logger.log(\"Number of consecutive failed sync requests:\", this.failedSyncCount);\n\n debuglog(\"Starting keep-alive\");\n // Note that we do *not* mark the sync connection as\n // lost yet: we only do this if a keepalive poke\n // fails, since long lived HTTP connections will\n // go away sometimes and we shouldn't treat this as\n // erroneous. We set the state to 'reconnecting'\n // instead, so that clients can observe this state\n // if they wish.\n const keepAlivePromise = this.startKeepAlives();\n\n this.currentSyncRequest = undefined;\n // Transition from RECONNECTING to ERROR after a given number of failed syncs\n this.updateSyncState(\n this.failedSyncCount >= FAILED_SYNC_ERROR_THRESHOLD ? SyncState.Error : SyncState.Reconnecting,\n { error: err },\n );\n\n const connDidFail = await keepAlivePromise;\n\n // Only emit CATCHUP if we detected a connectivity error: if we didn't,\n // it's quite likely the sync will fail again for the same reason and we\n // want to stay in ERROR rather than keep flip-flopping between ERROR\n // and CATCHUP.\n if (connDidFail && this.getSyncState() === SyncState.Error) {\n this.updateSyncState(SyncState.Catchup, {\n catchingUp: true,\n });\n }\n return false;\n }\n\n /**\n * Process data returned from a sync response and propagate it\n * into the model objects\n *\n * @param syncEventData - Object containing sync tokens associated with this sync\n * @param data - The response from /sync\n */\n private async processSyncResponse(syncEventData: ISyncStateData, data: ISyncResponse): Promise {\n const client = this.client;\n\n // data looks like:\n // {\n // next_batch: $token,\n // presence: { events: [] },\n // account_data: { events: [] },\n // device_lists: { changed: [\"@user:server\", ... ]},\n // to_device: { events: [] },\n // device_one_time_keys_count: { signed_curve25519: 42 },\n // rooms: {\n // invite: {\n // $roomid: {\n // invite_state: { events: [] }\n // }\n // },\n // join: {\n // $roomid: {\n // state: { events: [] },\n // timeline: { events: [], prev_batch: $token, limited: true },\n // ephemeral: { events: [] },\n // summary: {\n // m.heroes: [ $user_id ],\n // m.joined_member_count: $count,\n // m.invited_member_count: $count\n // },\n // account_data: { events: [] },\n // unread_notifications: {\n // highlight_count: 0,\n // notification_count: 0,\n // }\n // }\n // },\n // leave: {\n // $roomid: {\n // state: { events: [] },\n // timeline: { events: [], prev_batch: $token }\n // }\n // }\n // }\n // }\n\n // TODO-arch:\n // - Each event we pass through needs to be emitted via 'event', can we\n // do this in one place?\n // - The isBrandNewRoom boilerplate is boilerplatey.\n\n // handle presence events (User objects)\n if (Array.isArray(data.presence?.events)) {\n data.presence!.events.filter(noUnsafeEventProps)\n .map(client.getEventMapper())\n .forEach(function (presenceEvent) {\n let user = client.store.getUser(presenceEvent.getSender()!);\n if (user) {\n user.setPresenceEvent(presenceEvent);\n } else {\n user = createNewUser(client, presenceEvent.getSender()!);\n user.setPresenceEvent(presenceEvent);\n client.store.storeUser(user);\n }\n client.emit(ClientEvent.Event, presenceEvent);\n });\n }\n\n // handle non-room account_data\n if (Array.isArray(data.account_data?.events)) {\n const events = data.account_data.events.filter(noUnsafeEventProps).map(client.getEventMapper());\n const prevEventsMap = events.reduce>((m, c) => {\n m[c.getType()!] = client.store.getAccountData(c.getType());\n return m;\n }, {});\n client.store.storeAccountDataEvents(events);\n events.forEach(function (accountDataEvent) {\n // Honour push rules that come down the sync stream but also\n // honour push rules that were previously cached. Base rules\n // will be updated when we receive push rules via getPushRules\n // (see sync) before syncing over the network.\n if (accountDataEvent.getType() === EventType.PushRules) {\n const rules = accountDataEvent.getContent();\n client.setPushRules(rules);\n }\n const prevEvent = prevEventsMap[accountDataEvent.getType()!];\n client.emit(ClientEvent.AccountData, accountDataEvent, prevEvent);\n return accountDataEvent;\n });\n }\n\n // handle to-device events\n if (data.to_device && Array.isArray(data.to_device.events) && data.to_device.events.length > 0) {\n let toDeviceMessages: IToDeviceEvent[] = data.to_device.events.filter(noUnsafeEventProps);\n\n if (this.syncOpts.cryptoCallbacks) {\n toDeviceMessages = await this.syncOpts.cryptoCallbacks.preprocessToDeviceMessages(toDeviceMessages);\n }\n\n const cancelledKeyVerificationTxns: string[] = [];\n toDeviceMessages\n .map(client.getEventMapper({ toDevice: true }))\n .map((toDeviceEvent) => {\n // map is a cheap inline forEach\n // We want to flag m.key.verification.start events as cancelled\n // if there's an accompanying m.key.verification.cancel event, so\n // we pull out the transaction IDs from the cancellation events\n // so we can flag the verification events as cancelled in the loop\n // below.\n if (toDeviceEvent.getType() === \"m.key.verification.cancel\") {\n const txnId: string = toDeviceEvent.getContent()[\"transaction_id\"];\n if (txnId) {\n cancelledKeyVerificationTxns.push(txnId);\n }\n }\n\n // as mentioned above, .map is a cheap inline forEach, so return\n // the unmodified event.\n return toDeviceEvent;\n })\n .forEach(function (toDeviceEvent) {\n const content = toDeviceEvent.getContent();\n if (toDeviceEvent.getType() == \"m.room.message\" && content.msgtype == \"m.bad.encrypted\") {\n // the mapper already logged a warning.\n logger.log(\"Ignoring undecryptable to-device event from \" + toDeviceEvent.getSender());\n return;\n }\n\n if (\n toDeviceEvent.getType() === \"m.key.verification.start\" ||\n toDeviceEvent.getType() === \"m.key.verification.request\"\n ) {\n const txnId = content[\"transaction_id\"];\n if (cancelledKeyVerificationTxns.includes(txnId)) {\n toDeviceEvent.flagCancelled();\n }\n }\n\n client.emit(ClientEvent.ToDeviceEvent, toDeviceEvent);\n });\n } else {\n // no more to-device events: we can stop polling with a short timeout.\n this.catchingUp = false;\n }\n\n // the returned json structure is a bit crap, so make it into a\n // nicer form (array) after applying sanity to make sure we don't fail\n // on missing keys (on the off chance)\n let inviteRooms: WrappedRoom[] = [];\n let joinRooms: WrappedRoom[] = [];\n let leaveRooms: WrappedRoom[] = [];\n\n if (data.rooms) {\n if (data.rooms.invite) {\n inviteRooms = this.mapSyncResponseToRoomArray(data.rooms.invite);\n }\n if (data.rooms.join) {\n joinRooms = this.mapSyncResponseToRoomArray(data.rooms.join);\n }\n if (data.rooms.leave) {\n leaveRooms = this.mapSyncResponseToRoomArray(data.rooms.leave);\n }\n }\n\n this.notifEvents = [];\n\n // Handle invites\n await utils.promiseMapSeries(inviteRooms, async (inviteObj) => {\n const room = inviteObj.room;\n const stateEvents = this.mapSyncEventsFormat(inviteObj.invite_state, room);\n\n await this.injectRoomEvents(room, stateEvents);\n\n const inviter = room.currentState.getStateEvents(EventType.RoomMember, client.getUserId()!)?.getSender();\n\n const crypto = client.crypto;\n if (crypto) {\n const parkedHistory = await crypto.cryptoStore.takeParkedSharedHistory(room.roomId);\n for (const parked of parkedHistory) {\n if (parked.senderId === inviter) {\n await crypto.olmDevice.addInboundGroupSession(\n room.roomId,\n parked.senderKey,\n parked.forwardingCurve25519KeyChain,\n parked.sessionId,\n parked.sessionKey,\n parked.keysClaimed,\n true,\n { sharedHistory: true, untrusted: true },\n );\n }\n }\n }\n\n if (inviteObj.isBrandNewRoom) {\n room.recalculate();\n client.store.storeRoom(room);\n client.emit(ClientEvent.Room, room);\n } else {\n // Update room state for invite->reject->invite cycles\n room.recalculate();\n }\n stateEvents.forEach(function (e) {\n client.emit(ClientEvent.Event, e);\n });\n });\n\n // Handle joins\n await utils.promiseMapSeries(joinRooms, async (joinObj) => {\n const room = joinObj.room;\n const stateEvents = this.mapSyncEventsFormat(joinObj.state, room);\n // Prevent events from being decrypted ahead of time\n // this helps large account to speed up faster\n // room::decryptCriticalEvent is in charge of decrypting all the events\n // required for a client to function properly\n const events = this.mapSyncEventsFormat(joinObj.timeline, room, false);\n const ephemeralEvents = this.mapSyncEventsFormat(joinObj.ephemeral);\n const accountDataEvents = this.mapSyncEventsFormat(joinObj.account_data);\n\n const encrypted = client.isRoomEncrypted(room.roomId);\n // We store the server-provided value first so it's correct when any of the events fire.\n if (joinObj.unread_notifications) {\n /**\n * We track unread notifications ourselves in encrypted rooms, so don't\n * bother setting it here. We trust our calculations better than the\n * server's for this case, and therefore will assume that our non-zero\n * count is accurate.\n *\n * @see import(\"./client\").fixNotificationCountOnDecryption\n */\n if (!encrypted || joinObj.unread_notifications.notification_count === 0) {\n // In an encrypted room, if the room has notifications enabled then it's typical for\n // the server to flag all new messages as notifying. However, some push rules calculate\n // events as ignored based on their event contents (e.g. ignoring msgtype=m.notice messages)\n // so we want to calculate this figure on the client in all cases.\n room.setUnreadNotificationCount(\n NotificationCountType.Total,\n joinObj.unread_notifications.notification_count ?? 0,\n );\n }\n\n if (!encrypted || room.getUnreadNotificationCount(NotificationCountType.Highlight) <= 0) {\n // If the locally stored highlight count is zero, use the server provided value.\n room.setUnreadNotificationCount(\n NotificationCountType.Highlight,\n joinObj.unread_notifications.highlight_count ?? 0,\n );\n }\n }\n\n const unreadThreadNotifications =\n joinObj[UNREAD_THREAD_NOTIFICATIONS.name] ?? joinObj[UNREAD_THREAD_NOTIFICATIONS.altName!];\n if (unreadThreadNotifications) {\n // Only partially reset unread notification\n // We want to keep the client-generated count. Particularly important\n // for encrypted room that refresh their notification count on event\n // decryption\n room.resetThreadUnreadNotificationCount(Object.keys(unreadThreadNotifications));\n for (const [threadId, unreadNotification] of Object.entries(unreadThreadNotifications)) {\n if (!encrypted || unreadNotification.notification_count === 0) {\n room.setThreadUnreadNotificationCount(\n threadId,\n NotificationCountType.Total,\n unreadNotification.notification_count ?? 0,\n );\n }\n\n const hasNoNotifications =\n room.getThreadUnreadNotificationCount(threadId, NotificationCountType.Highlight) <= 0;\n if (!encrypted || (encrypted && hasNoNotifications)) {\n room.setThreadUnreadNotificationCount(\n threadId,\n NotificationCountType.Highlight,\n unreadNotification.highlight_count ?? 0,\n );\n }\n }\n } else {\n room.resetThreadUnreadNotificationCount();\n }\n\n joinObj.timeline = joinObj.timeline || ({} as ITimeline);\n\n if (joinObj.isBrandNewRoom) {\n // set the back-pagination token. Do this *before* adding any\n // events so that clients can start back-paginating.\n if (joinObj.timeline.prev_batch !== null) {\n room.getLiveTimeline().setPaginationToken(joinObj.timeline.prev_batch, EventTimeline.BACKWARDS);\n }\n } else if (joinObj.timeline.limited) {\n let limited = true;\n\n // we've got a limited sync, so we *probably* have a gap in the\n // timeline, so should reset. But we might have been peeking or\n // paginating and already have some of the events, in which\n // case we just want to append any subsequent events to the end\n // of the existing timeline.\n //\n // This is particularly important in the case that we already have\n // *all* of the events in the timeline - in that case, if we reset\n // the timeline, we'll end up with an entirely empty timeline,\n // which we'll try to paginate but not get any new events (which\n // will stop us linking the empty timeline into the chain).\n //\n for (let i = events.length - 1; i >= 0; i--) {\n const eventId = events[i].getId()!;\n if (room.getTimelineForEvent(eventId)) {\n debuglog(`Already have event ${eventId} in limited sync - not resetting`);\n limited = false;\n\n // we might still be missing some of the events before i;\n // we don't want to be adding them to the end of the\n // timeline because that would put them out of order.\n events.splice(0, i);\n\n // XXX: there's a problem here if the skipped part of the\n // timeline modifies the state set in stateEvents, because\n // we'll end up using the state from stateEvents rather\n // than the later state from timelineEvents. We probably\n // need to wind stateEvents forward over the events we're\n // skipping.\n\n break;\n }\n }\n\n if (limited) {\n room.resetLiveTimeline(\n joinObj.timeline.prev_batch,\n this.syncOpts.canResetEntireTimeline!(room.roomId) ? null : syncEventData.oldSyncToken ?? null,\n );\n\n // We have to assume any gap in any timeline is\n // reason to stop incrementally tracking notifications and\n // reset the timeline.\n client.resetNotifTimelineSet();\n }\n }\n\n // process any crypto events *before* emitting the RoomStateEvent events. This\n // avoids a race condition if the application tries to send a message after the\n // state event is processed, but before crypto is enabled, which then causes the\n // crypto layer to complain.\n if (this.syncOpts.cryptoCallbacks) {\n for (const e of stateEvents.concat(events)) {\n if (e.isState() && e.getType() === EventType.RoomEncryption && e.getStateKey() === \"\") {\n await this.syncOpts.cryptoCallbacks.onCryptoEvent(room, e);\n }\n }\n }\n\n try {\n await this.injectRoomEvents(room, stateEvents, events, syncEventData.fromCache);\n } catch (e) {\n logger.error(`Failed to process events on room ${room.roomId}:`, e);\n }\n\n // set summary after processing events,\n // because it will trigger a name calculation\n // which needs the room state to be up to date\n if (joinObj.summary) {\n room.setSummary(joinObj.summary);\n }\n\n // we deliberately don't add ephemeral events to the timeline\n room.addEphemeralEvents(ephemeralEvents);\n\n // we deliberately don't add accountData to the timeline\n room.addAccountData(accountDataEvents);\n\n room.recalculate();\n if (joinObj.isBrandNewRoom) {\n client.store.storeRoom(room);\n client.emit(ClientEvent.Room, room);\n }\n\n this.processEventsForNotifs(room, events);\n\n const emitEvent = (e: MatrixEvent): boolean => client.emit(ClientEvent.Event, e);\n stateEvents.forEach(emitEvent);\n events.forEach(emitEvent);\n ephemeralEvents.forEach(emitEvent);\n accountDataEvents.forEach(emitEvent);\n\n // Decrypt only the last message in all rooms to make sure we can generate a preview\n // And decrypt all events after the recorded read receipt to ensure an accurate\n // notification count\n room.decryptCriticalEvents();\n });\n\n // Handle leaves (e.g. kicked rooms)\n await utils.promiseMapSeries(leaveRooms, async (leaveObj) => {\n const room = leaveObj.room;\n const stateEvents = this.mapSyncEventsFormat(leaveObj.state, room);\n const events = this.mapSyncEventsFormat(leaveObj.timeline, room);\n const accountDataEvents = this.mapSyncEventsFormat(leaveObj.account_data);\n\n await this.injectRoomEvents(room, stateEvents, events);\n room.addAccountData(accountDataEvents);\n\n room.recalculate();\n if (leaveObj.isBrandNewRoom) {\n client.store.storeRoom(room);\n client.emit(ClientEvent.Room, room);\n }\n\n this.processEventsForNotifs(room, events);\n\n stateEvents.forEach(function (e) {\n client.emit(ClientEvent.Event, e);\n });\n events.forEach(function (e) {\n client.emit(ClientEvent.Event, e);\n });\n accountDataEvents.forEach(function (e) {\n client.emit(ClientEvent.Event, e);\n });\n });\n\n // update the notification timeline, if appropriate.\n // we only do this for live events, as otherwise we can't order them sanely\n // in the timeline relative to ones paginated in by /notifications.\n // XXX: we could fix this by making EventTimeline support chronological\n // ordering... but it doesn't, right now.\n if (syncEventData.oldSyncToken && this.notifEvents.length) {\n this.notifEvents.sort(function (a, b) {\n return a.getTs() - b.getTs();\n });\n this.notifEvents.forEach(function (event) {\n client.getNotifTimelineSet()?.addLiveEvent(event);\n });\n }\n\n // Handle device list updates\n if (data.device_lists) {\n if (this.syncOpts.crypto) {\n await this.syncOpts.crypto.handleDeviceListChanges(syncEventData, data.device_lists);\n } else {\n // FIXME if we *don't* have a crypto module, we still need to\n // invalidate the device lists. But that would require a\n // substantial bit of rework :/.\n }\n }\n\n // Handle one_time_keys_count\n if (data.device_one_time_keys_count) {\n const map = new Map(Object.entries(data.device_one_time_keys_count));\n this.syncOpts.cryptoCallbacks?.preprocessOneTimeKeyCounts(map);\n }\n if (data.device_unused_fallback_key_types || data[\"org.matrix.msc2732.device_unused_fallback_key_types\"]) {\n // The presence of device_unused_fallback_key_types indicates that the\n // server supports fallback keys. If there's no unused\n // signed_curve25519 fallback key we need a new one.\n const unusedFallbackKeys =\n data.device_unused_fallback_key_types || data[\"org.matrix.msc2732.device_unused_fallback_key_types\"];\n this.syncOpts.cryptoCallbacks?.preprocessUnusedFallbackKeys(new Set(unusedFallbackKeys || null));\n }\n }\n\n /**\n * Starts polling the connectivity check endpoint\n * @param delay - How long to delay until the first poll.\n * defaults to a short, randomised interval (to prevent\n * tight-looping if /versions succeeds but /sync etc. fail).\n * @returns which resolves once the connection returns\n */\n private startKeepAlives(delay?: number): Promise {\n if (delay === undefined) {\n delay = 2000 + Math.floor(Math.random() * 5000);\n }\n\n if (this.keepAliveTimer !== null) {\n clearTimeout(this.keepAliveTimer);\n }\n if (delay > 0) {\n this.keepAliveTimer = setTimeout(this.pokeKeepAlive.bind(this), delay);\n } else {\n this.pokeKeepAlive();\n }\n if (!this.connectionReturnedDefer) {\n this.connectionReturnedDefer = utils.defer();\n }\n return this.connectionReturnedDefer.promise;\n }\n\n /**\n * Make a dummy call to /_matrix/client/versions, to see if the HS is\n * reachable.\n *\n * On failure, schedules a call back to itself. On success, resolves\n * this.connectionReturnedDefer.\n *\n * @param connDidFail - True if a connectivity failure has been detected. Optional.\n */\n private pokeKeepAlive(connDidFail = false): void {\n const success = (): void => {\n clearTimeout(this.keepAliveTimer);\n if (this.connectionReturnedDefer) {\n this.connectionReturnedDefer.resolve(connDidFail);\n this.connectionReturnedDefer = undefined;\n }\n };\n\n this.client.http\n .request(\n Method.Get,\n \"/_matrix/client/versions\",\n undefined, // queryParams\n undefined, // data\n {\n prefix: \"\",\n localTimeoutMs: 15 * 1000,\n abortSignal: this.abortController?.signal,\n },\n )\n .then(\n () => {\n success();\n },\n (err) => {\n if (err.httpStatus == 400 || err.httpStatus == 404) {\n // treat this as a success because the server probably just doesn't\n // support /versions: point is, we're getting a response.\n // We wait a short time though, just in case somehow the server\n // is in a mode where it 400s /versions responses and sync etc.\n // responses fail, this will mean we don't hammer in a loop.\n this.keepAliveTimer = setTimeout(success, 2000);\n } else {\n connDidFail = true;\n this.keepAliveTimer = setTimeout(\n this.pokeKeepAlive.bind(this, connDidFail),\n 5000 + Math.floor(Math.random() * 5000),\n );\n // A keepalive has failed, so we emit the\n // error state (whether or not this is the\n // first failure).\n // Note we do this after setting the timer:\n // this lets the unit tests advance the mock\n // clock when they get the error.\n this.updateSyncState(SyncState.Error, { error: err });\n }\n },\n );\n }\n\n private mapSyncResponseToRoomArray(\n obj: Record,\n ): Array> {\n // Maps { roomid: {stuff}, roomid: {stuff} }\n // to\n // [{stuff+Room+isBrandNewRoom}, {stuff+Room+isBrandNewRoom}]\n const client = this.client;\n return Object.keys(obj)\n .filter((k) => !unsafeProp(k))\n .map((roomId) => {\n const arrObj = obj[roomId] as T & { room: Room; isBrandNewRoom: boolean };\n let room = client.store.getRoom(roomId);\n let isBrandNewRoom = false;\n if (!room) {\n room = this.createRoom(roomId);\n isBrandNewRoom = true;\n }\n arrObj.room = room;\n arrObj.isBrandNewRoom = isBrandNewRoom;\n return arrObj;\n });\n }\n\n private mapSyncEventsFormat(\n obj: IInviteState | ITimeline | IEphemeral,\n room?: Room,\n decrypt = true,\n ): MatrixEvent[] {\n if (!obj || !Array.isArray(obj.events)) {\n return [];\n }\n const mapper = this.client.getEventMapper({ decrypt });\n type TaggedEvent = (IStrippedState | IRoomEvent | IStateEvent | IMinimalEvent) & { room_id?: string };\n return (obj.events as TaggedEvent[]).filter(noUnsafeEventProps).map(function (e) {\n if (room) {\n e.room_id = room.roomId;\n }\n return mapper(e);\n });\n }\n\n /**\n */\n private resolveInvites(room: Room): void {\n if (!room || !this.opts.resolveInvitesToProfiles) {\n return;\n }\n const client = this.client;\n // For each invited room member we want to give them a displayname/avatar url\n // if they have one (the m.room.member invites don't contain this).\n room.getMembersWithMembership(\"invite\").forEach(function (member) {\n if (member.requestedProfileInfo) return;\n member.requestedProfileInfo = true;\n // try to get a cached copy first.\n const user = client.getUser(member.userId);\n let promise;\n if (user) {\n promise = Promise.resolve({\n avatar_url: user.avatarUrl,\n displayname: user.displayName,\n });\n } else {\n promise = client.getProfileInfo(member.userId);\n }\n promise.then(\n function (info) {\n // slightly naughty by doctoring the invite event but this means all\n // the code paths remain the same between invite/join display name stuff\n // which is a worthy trade-off for some minor pollution.\n const inviteEvent = member.events.member;\n if (inviteEvent?.getContent().membership !== \"invite\") {\n // between resolving and now they have since joined, so don't clobber\n return;\n }\n inviteEvent.getContent().avatar_url = info.avatar_url;\n inviteEvent.getContent().displayname = info.displayname;\n // fire listeners\n member.setMembershipEvent(inviteEvent, room.currentState);\n },\n function (err) {\n // OH WELL.\n },\n );\n });\n }\n\n /**\n * Injects events into a room's model.\n * @param stateEventList - A list of state events. This is the state\n * at the *START* of the timeline list if it is supplied.\n * @param timelineEventList - A list of timeline events, including threaded. Lower index\n * is earlier in time. Higher index is later.\n * @param fromCache - whether the sync response came from cache\n */\n public async injectRoomEvents(\n room: Room,\n stateEventList: MatrixEvent[],\n timelineEventList?: MatrixEvent[],\n fromCache = false,\n ): Promise {\n // If there are no events in the timeline yet, initialise it with\n // the given state events\n const liveTimeline = room.getLiveTimeline();\n const timelineWasEmpty = liveTimeline.getEvents().length == 0;\n if (timelineWasEmpty) {\n // Passing these events into initialiseState will freeze them, so we need\n // to compute and cache the push actions for them now, otherwise sync dies\n // with an attempt to assign to read only property.\n // XXX: This is pretty horrible and is assuming all sorts of behaviour from\n // these functions that it shouldn't be. We should probably either store the\n // push actions cache elsewhere so we can freeze MatrixEvents, or otherwise\n // find some solution where MatrixEvents are immutable but allow for a cache\n // field.\n for (const ev of stateEventList) {\n this.client.getPushActionsForEvent(ev);\n }\n liveTimeline.initialiseState(stateEventList, {\n timelineWasEmpty,\n });\n }\n\n this.resolveInvites(room);\n\n // recalculate the room name at this point as adding events to the timeline\n // may make notifications appear which should have the right name.\n // XXX: This looks suspect: we'll end up recalculating the room once here\n // and then again after adding events (processSyncResponse calls it after\n // calling us) even if no state events were added. It also means that if\n // one of the room events in timelineEventList is something that needs\n // a recalculation (like m.room.name) we won't recalculate until we've\n // finished adding all the events, which will cause the notification to have\n // the old room name rather than the new one.\n room.recalculate();\n\n // If the timeline wasn't empty, we process the state events here: they're\n // defined as updates to the state before the start of the timeline, so this\n // starts to roll the state forward.\n // XXX: That's what we *should* do, but this can happen if we were previously\n // peeking in a room, in which case we obviously do *not* want to add the\n // state events here onto the end of the timeline. Historically, the js-sdk\n // has just set these new state events on the old and new state. This seems\n // very wrong because there could be events in the timeline that diverge the\n // state, in which case this is going to leave things out of sync. However,\n // for now I think it;s best to behave the same as the code has done previously.\n if (!timelineWasEmpty) {\n // XXX: As above, don't do this...\n //room.addLiveEvents(stateEventList || []);\n // Do this instead...\n room.oldState.setStateEvents(stateEventList || []);\n room.currentState.setStateEvents(stateEventList || []);\n }\n\n // Execute the timeline events. This will continue to diverge the current state\n // if the timeline has any state events in it.\n // This also needs to be done before running push rules on the events as they need\n // to be decorated with sender etc.\n room.addLiveEvents(timelineEventList || [], {\n fromCache,\n timelineWasEmpty,\n });\n this.client.processBeaconEvents(room, timelineEventList);\n }\n\n /**\n * Takes a list of timelineEvents and adds and adds to notifEvents\n * as appropriate.\n * This must be called after the room the events belong to has been stored.\n *\n * @param timelineEventList - A list of timeline events. Lower index\n * is earlier in time. Higher index is later.\n */\n private processEventsForNotifs(room: Room, timelineEventList: MatrixEvent[]): void {\n // gather our notifications into this.notifEvents\n if (this.client.getNotifTimelineSet()) {\n for (const event of timelineEventList) {\n const pushActions = this.client.getPushActionsForEvent(event);\n if (pushActions?.notify && pushActions.tweaks?.highlight) {\n this.notifEvents.push(event);\n }\n }\n }\n }\n\n private getGuestFilter(): string {\n // Dev note: This used to be conditional to return a filter of 20 events maximum, but\n // the condition never went to the other branch. This is now hardcoded.\n return \"{}\";\n }\n\n /**\n * Sets the sync state and emits an event to say so\n * @param newState - The new state string\n * @param data - Object of additional data to emit in the event\n */\n private updateSyncState(newState: SyncState, data?: ISyncStateData): void {\n const old = this.syncState;\n this.syncState = newState;\n this.syncStateData = data;\n this.client.emit(ClientEvent.Sync, this.syncState, old, data);\n }\n\n /**\n * Event handler for the 'online' event\n * This event is generally unreliable and precise behaviour\n * varies between browsers, so we poll for connectivity too,\n * but this might help us reconnect a little faster.\n */\n private onOnline = (): void => {\n debuglog(\"Browser thinks we are back online\");\n this.startKeepAlives(0);\n };\n}\n\nfunction createNewUser(client: MatrixClient, userId: string): User {\n const user = new User(userId);\n client.reEmitter.reEmit(user, [\n UserEvent.AvatarUrl,\n UserEvent.DisplayName,\n UserEvent.Presence,\n UserEvent.CurrentlyActive,\n UserEvent.LastPresenceTs,\n ]);\n return user;\n}\n\n// /!\\ This function is not intended for public use! It's only exported from\n// here in order to share some common logic with sliding-sync-sdk.ts.\nexport function _createAndReEmitRoom(client: MatrixClient, roomId: string, opts: Partial): Room {\n const { timelineSupport } = client;\n\n const room = new Room(roomId, client, client.getUserId()!, {\n lazyLoadMembers: opts.lazyLoadMembers,\n pendingEventOrdering: opts.pendingEventOrdering,\n timelineSupport,\n });\n\n client.reEmitter.reEmit(room, [\n RoomEvent.Name,\n RoomEvent.Redaction,\n RoomEvent.RedactionCancelled,\n RoomEvent.Receipt,\n RoomEvent.Tags,\n RoomEvent.LocalEchoUpdated,\n RoomEvent.AccountData,\n RoomEvent.MyMembership,\n RoomEvent.Timeline,\n RoomEvent.TimelineReset,\n RoomStateEvent.Events,\n RoomStateEvent.Members,\n RoomStateEvent.NewMember,\n RoomStateEvent.Update,\n BeaconEvent.New,\n BeaconEvent.Update,\n BeaconEvent.Destroy,\n BeaconEvent.LivenessChange,\n ]);\n\n // We need to add a listener for RoomState.members in order to hook them\n // correctly.\n room.on(RoomStateEvent.NewMember, (event, state, member) => {\n member.user = client.getUser(member.userId) ?? undefined;\n client.reEmitter.reEmit(member, [\n RoomMemberEvent.Name,\n RoomMemberEvent.Typing,\n RoomMemberEvent.PowerLevel,\n RoomMemberEvent.Membership,\n ]);\n });\n\n return room;\n}\n", - "/*\nCopyright 2016 - 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { Optional } from \"matrix-events-sdk\";\n\nimport { Direction, EventTimeline } from \"./models/event-timeline\";\nimport { logger } from \"./logger\";\nimport { MatrixClient } from \"./client\";\nimport { EventTimelineSet } from \"./models/event-timeline-set\";\nimport { MatrixEvent } from \"./models/event\";\n\n/**\n * @internal\n */\nconst DEBUG = false;\n\n/**\n * @internal\n */\n/* istanbul ignore next */\nconst debuglog = DEBUG ? logger.log.bind(logger) : function (): void {};\n\n/**\n * the number of times we ask the server for more events before giving up\n *\n * @internal\n */\nconst DEFAULT_PAGINATE_LOOP_LIMIT = 5;\n\ninterface IOpts {\n /**\n * Maximum number of events to keep in the window. If more events are retrieved via pagination requests,\n * excess events will be dropped from the other end of the window.\n */\n windowLimit?: number;\n}\n\nexport class TimelineWindow {\n private readonly windowLimit: number;\n // these will be TimelineIndex objects; they delineate the 'start' and\n // 'end' of the window.\n //\n // start.index is inclusive; end.index is exclusive.\n private start?: TimelineIndex;\n private end?: TimelineIndex;\n private eventCount = 0;\n\n /**\n * Construct a TimelineWindow.\n *\n *

This abstracts the separate timelines in a Matrix {@link Room} into a single iterable thing.\n * It keeps track of the start and endpoints of the window, which can be advanced with the help\n * of pagination requests.\n *\n *

Before the window is useful, it must be initialised by calling {@link TimelineWindow#load}.\n *\n *

Note that the window will not automatically extend itself when new events\n * are received from /sync; you should arrange to call {@link TimelineWindow#paginate}\n * on {@link RoomEvent.Timeline} events.\n *\n * @param client - MatrixClient to be used for context/pagination\n * requests.\n *\n * @param timelineSet - The timelineSet to track\n *\n * @param opts - Configuration options for this window\n */\n public constructor(\n private readonly client: MatrixClient,\n private readonly timelineSet: EventTimelineSet,\n opts: IOpts = {},\n ) {\n this.windowLimit = opts.windowLimit || 1000;\n }\n\n /**\n * Initialise the window to point at a given event, or the live timeline\n *\n * @param initialEventId - If given, the window will contain the\n * given event\n * @param initialWindowSize - Size of the initial window\n */\n public load(initialEventId?: string, initialWindowSize = 20): Promise {\n // given an EventTimeline, find the event we were looking for, and initialise our\n // fields so that the event in question is in the middle of the window.\n const initFields = (timeline: Optional): void => {\n if (!timeline) {\n throw new Error(\"No timeline given to initFields\");\n }\n\n let eventIndex: number;\n\n const events = timeline.getEvents();\n\n if (!initialEventId) {\n // we were looking for the live timeline: initialise to the end\n eventIndex = events.length;\n } else {\n eventIndex = events.findIndex((e) => e.getId() === initialEventId);\n\n if (eventIndex < 0) {\n throw new Error(\"getEventTimeline result didn't include requested event\");\n }\n }\n\n const endIndex = Math.min(events.length, eventIndex + Math.ceil(initialWindowSize / 2));\n const startIndex = Math.max(0, endIndex - initialWindowSize);\n this.start = new TimelineIndex(timeline, startIndex - timeline.getBaseIndex());\n this.end = new TimelineIndex(timeline, endIndex - timeline.getBaseIndex());\n this.eventCount = endIndex - startIndex;\n };\n\n // We avoid delaying the resolution of the promise by a reactor tick if we already have the data we need,\n // which is important to keep room-switching feeling snappy.\n if (this.timelineSet.getTimelineForEvent(initialEventId)) {\n initFields(this.timelineSet.getTimelineForEvent(initialEventId));\n return Promise.resolve();\n } else if (initialEventId) {\n return this.client.getEventTimeline(this.timelineSet, initialEventId).then(initFields);\n } else {\n initFields(this.timelineSet.getLiveTimeline());\n return Promise.resolve();\n }\n }\n\n /**\n * Get the TimelineIndex of the window in the given direction.\n *\n * @param direction - EventTimeline.BACKWARDS to get the TimelineIndex\n * at the start of the window; EventTimeline.FORWARDS to get the TimelineIndex at\n * the end.\n *\n * @returns The requested timeline index if one exists, null\n * otherwise.\n */\n public getTimelineIndex(direction: Direction): TimelineIndex | null {\n if (direction == EventTimeline.BACKWARDS) {\n return this.start ?? null;\n } else if (direction == EventTimeline.FORWARDS) {\n return this.end ?? null;\n } else {\n throw new Error(\"Invalid direction '\" + direction + \"'\");\n }\n }\n\n /**\n * Try to extend the window using events that are already in the underlying\n * TimelineIndex.\n *\n * @param direction - EventTimeline.BACKWARDS to try extending it\n * backwards; EventTimeline.FORWARDS to try extending it forwards.\n * @param size - number of events to try to extend by.\n *\n * @returns true if the window was extended, false otherwise.\n */\n public extend(direction: Direction, size: number): boolean {\n const tl = this.getTimelineIndex(direction);\n\n if (!tl) {\n debuglog(\"TimelineWindow: no timeline yet\");\n return false;\n }\n\n const count = direction == EventTimeline.BACKWARDS ? tl.retreat(size) : tl.advance(size);\n\n if (count) {\n this.eventCount += count;\n debuglog(\"TimelineWindow: increased cap by \" + count + \" (now \" + this.eventCount + \")\");\n // remove some events from the other end, if necessary\n const excess = this.eventCount - this.windowLimit;\n if (excess > 0) {\n this.unpaginate(excess, direction != EventTimeline.BACKWARDS);\n }\n return true;\n }\n\n return false;\n }\n\n /**\n * Check if this window can be extended\n *\n *

This returns true if we either have more events, or if we have a\n * pagination token which means we can paginate in that direction. It does not\n * necessarily mean that there are more events available in that direction at\n * this time.\n *\n * @param direction - EventTimeline.BACKWARDS to check if we can\n * paginate backwards; EventTimeline.FORWARDS to check if we can go forwards\n *\n * @returns true if we can paginate in the given direction\n */\n public canPaginate(direction: Direction): boolean {\n const tl = this.getTimelineIndex(direction);\n\n if (!tl) {\n debuglog(\"TimelineWindow: no timeline yet\");\n return false;\n }\n\n if (direction == EventTimeline.BACKWARDS) {\n if (tl.index > tl.minIndex()) {\n return true;\n }\n } else {\n if (tl.index < tl.maxIndex()) {\n return true;\n }\n }\n\n const hasNeighbouringTimeline = tl.timeline.getNeighbouringTimeline(direction);\n const paginationToken = tl.timeline.getPaginationToken(direction);\n return Boolean(hasNeighbouringTimeline) || Boolean(paginationToken);\n }\n\n /**\n * Attempt to extend the window\n *\n * @param direction - EventTimeline.BACKWARDS to extend the window\n * backwards (towards older events); EventTimeline.FORWARDS to go forwards.\n *\n * @param size - number of events to try to extend by. If fewer than this\n * number are immediately available, then we return immediately rather than\n * making an API call.\n *\n * @param makeRequest - whether we should make API calls to\n * fetch further events if we don't have any at all. (This has no effect if\n * the room already knows about additional events in the relevant direction,\n * even if there are fewer than 'size' of them, as we will just return those\n * we already know about.)\n *\n * @param requestLimit - limit for the number of API requests we\n * should make.\n *\n * @returns Promise which resolves to a boolean which is true if more events\n * were successfully retrieved.\n */\n public async paginate(\n direction: Direction,\n size: number,\n makeRequest = true,\n requestLimit = DEFAULT_PAGINATE_LOOP_LIMIT,\n ): Promise {\n // Either wind back the message cap (if there are enough events in the\n // timeline to do so), or fire off a pagination request.\n const tl = this.getTimelineIndex(direction);\n\n if (!tl) {\n debuglog(\"TimelineWindow: no timeline yet\");\n return false;\n }\n\n if (tl.pendingPaginate) {\n return tl.pendingPaginate;\n }\n\n // try moving the cap\n if (this.extend(direction, size)) {\n return true;\n }\n\n if (!makeRequest || requestLimit === 0) {\n // todo: should we return something different to indicate that there\n // might be more events out there, but we haven't found them yet?\n return false;\n }\n\n // try making a pagination request\n const token = tl.timeline.getPaginationToken(direction);\n if (!token) {\n debuglog(\"TimelineWindow: no token\");\n return false;\n }\n\n debuglog(\"TimelineWindow: starting request\");\n\n const prom = this.client\n .paginateEventTimeline(tl.timeline, {\n backwards: direction == EventTimeline.BACKWARDS,\n limit: size,\n })\n .finally(function () {\n tl.pendingPaginate = undefined;\n })\n .then((r) => {\n debuglog(\"TimelineWindow: request completed with result \" + r);\n if (!r) {\n return this.paginate(direction, size, false, 0);\n }\n\n // recurse to advance the index into the results.\n //\n // If we don't get any new events, we want to make sure we keep asking\n // the server for events for as long as we have a valid pagination\n // token. In particular, we want to know if we've actually hit the\n // start of the timeline, or if we just happened to know about all of\n // the events thanks to https://matrix.org/jira/browse/SYN-645.\n //\n // On the other hand, we necessarily want to wait forever for the\n // server to make its mind up about whether there are other events,\n // because it gives a bad user experience\n // (https://github.com/vector-im/vector-web/issues/1204).\n return this.paginate(direction, size, true, requestLimit - 1);\n });\n tl.pendingPaginate = prom;\n return prom;\n }\n\n /**\n * Remove `delta` events from the start or end of the timeline.\n *\n * @param delta - number of events to remove from the timeline\n * @param startOfTimeline - if events should be removed from the start\n * of the timeline.\n */\n public unpaginate(delta: number, startOfTimeline: boolean): void {\n const tl = startOfTimeline ? this.start : this.end;\n if (!tl) {\n throw new Error(\n `Attempting to unpaginate startOfTimeline=${startOfTimeline} but don't have this direction`,\n );\n }\n\n // sanity-check the delta\n if (delta > this.eventCount || delta < 0) {\n throw new Error(\n `Attemting to unpaginate ${delta} events, but only have ${this.eventCount} in the timeline`,\n );\n }\n\n while (delta > 0) {\n const count = startOfTimeline ? tl.advance(delta) : tl.retreat(delta);\n if (count <= 0) {\n // sadness. This shouldn't be possible.\n throw new Error(\"Unable to unpaginate any further, but still have \" + this.eventCount + \" events\");\n }\n\n delta -= count;\n this.eventCount -= count;\n debuglog(\"TimelineWindow.unpaginate: dropped \" + count + \" (now \" + this.eventCount + \")\");\n }\n }\n\n /**\n * Get a list of the events currently in the window\n *\n * @returns the events in the window\n */\n public getEvents(): MatrixEvent[] {\n if (!this.start) {\n // not yet loaded\n return [];\n }\n\n const result: MatrixEvent[] = [];\n\n // iterate through each timeline between this.start and this.end\n // (inclusive).\n let timeline = this.start.timeline;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const events = timeline.getEvents();\n\n // For the first timeline in the chain, we want to start at\n // this.start.index. For the last timeline in the chain, we want to\n // stop before this.end.index. Otherwise, we want to copy all of the\n // events in the timeline.\n //\n // (Note that both this.start.index and this.end.index are relative\n // to their respective timelines' BaseIndex).\n //\n let startIndex = 0;\n let endIndex = events.length;\n if (timeline === this.start.timeline) {\n startIndex = this.start.index + timeline.getBaseIndex();\n }\n if (timeline === this.end?.timeline) {\n endIndex = this.end.index + timeline.getBaseIndex();\n }\n\n for (let i = startIndex; i < endIndex; i++) {\n result.push(events[i]);\n }\n\n // if we're not done, iterate to the next timeline.\n if (timeline === this.end?.timeline) {\n break;\n } else {\n timeline = timeline.getNeighbouringTimeline(EventTimeline.FORWARDS)!;\n }\n }\n\n return result;\n }\n}\n\n/**\n * A thing which contains a timeline reference, and an index into it.\n * @internal\n */\nexport class TimelineIndex {\n public pendingPaginate?: Promise;\n\n // index: the indexes are relative to BaseIndex, so could well be negative.\n public constructor(public timeline: EventTimeline, public index: number) {}\n\n /**\n * @returns the minimum possible value for the index in the current\n * timeline\n */\n public minIndex(): number {\n return this.timeline.getBaseIndex() * -1;\n }\n\n /**\n * @returns the maximum possible value for the index in the current\n * timeline (exclusive - ie, it actually returns one more than the index\n * of the last element).\n */\n public maxIndex(): number {\n return this.timeline.getEvents().length - this.timeline.getBaseIndex();\n }\n\n /**\n * Try move the index forward, or into the neighbouring timeline\n *\n * @param delta - number of events to advance by\n * @returns number of events successfully advanced by\n */\n public advance(delta: number): number {\n if (!delta) {\n return 0;\n }\n\n // first try moving the index in the current timeline. See if there is room\n // to do so.\n let cappedDelta;\n if (delta < 0) {\n // we want to wind the index backwards.\n //\n // (this.minIndex() - this.index) is a negative number whose magnitude\n // is the amount of room we have to wind back the index in the current\n // timeline. We cap delta to this quantity.\n cappedDelta = Math.max(delta, this.minIndex() - this.index);\n if (cappedDelta < 0) {\n this.index += cappedDelta;\n return cappedDelta;\n }\n } else {\n // we want to wind the index forwards.\n //\n // (this.maxIndex() - this.index) is a (positive) number whose magnitude\n // is the amount of room we have to wind forward the index in the current\n // timeline. We cap delta to this quantity.\n cappedDelta = Math.min(delta, this.maxIndex() - this.index);\n if (cappedDelta > 0) {\n this.index += cappedDelta;\n return cappedDelta;\n }\n }\n\n // the index is already at the start/end of the current timeline.\n //\n // next see if there is a neighbouring timeline to switch to.\n const neighbour = this.timeline.getNeighbouringTimeline(\n delta < 0 ? EventTimeline.BACKWARDS : EventTimeline.FORWARDS,\n );\n if (neighbour) {\n this.timeline = neighbour;\n if (delta < 0) {\n this.index = this.maxIndex();\n } else {\n this.index = this.minIndex();\n }\n\n debuglog(\"paginate: switched to new neighbour\");\n\n // recurse, using the next timeline\n return this.advance(delta);\n }\n\n return 0;\n }\n\n /**\n * Try move the index backwards, or into the neighbouring timeline\n *\n * @param delta - number of events to retreat by\n * @returns number of events successfully retreated by\n */\n public retreat(delta: number): number {\n return this.advance(delta * -1) * -1;\n }\n}\n", - "/*\nCopyright 2015, 2016, 2019, 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module.\n */\n\nimport unhomoglyph from \"unhomoglyph\";\nimport promiseRetry from \"p-retry\";\nimport { Optional } from \"matrix-events-sdk\";\n\nimport { IEvent, MatrixEvent } from \"./models/event\";\nimport { M_TIMESTAMP } from \"./@types/location\";\nimport { ReceiptType } from \"./@types/read_receipts\";\n\nconst interns = new Map();\n\n/**\n * Internalises a string, reusing a known pointer or storing the pointer\n * if needed for future strings.\n * @param str - The string to internalise.\n * @returns The internalised string.\n */\nexport function internaliseString(str: string): string {\n // Unwrap strings before entering the map, if we somehow got a wrapped\n // string as our input. This should only happen from tests.\n if ((str as unknown) instanceof String) {\n str = str.toString();\n }\n\n // Check the map to see if we can store the value\n if (!interns.has(str)) {\n interns.set(str, str);\n }\n\n // Return any cached string reference\n return interns.get(str)!;\n}\n\n/**\n * Encode a dictionary of query parameters.\n * Omits any undefined/null values.\n * @param params - A dict of key/values to encode e.g.\n * `{\"foo\": \"bar\", \"baz\": \"taz\"}`\n * @returns The encoded string e.g. foo=bar&baz=taz\n */\nexport function encodeParams(params: QueryDict, urlSearchParams?: URLSearchParams): URLSearchParams {\n const searchParams = urlSearchParams ?? new URLSearchParams();\n for (const [key, val] of Object.entries(params)) {\n if (val !== undefined && val !== null) {\n if (Array.isArray(val)) {\n val.forEach((v) => {\n searchParams.append(key, String(v));\n });\n } else {\n searchParams.append(key, String(val));\n }\n }\n }\n return searchParams;\n}\n\nexport type QueryDict = Record;\n\n/**\n * Replace a stable parameter with the unstable naming for params\n */\nexport function replaceParam(stable: string, unstable: string, dict: QueryDict): QueryDict {\n const result = {\n ...dict,\n [unstable]: dict[stable],\n };\n delete result[stable];\n return result;\n}\n\n/**\n * Decode a query string in `application/x-www-form-urlencoded` format.\n * @param query - A query string to decode e.g.\n * foo=bar&via=server1&server2\n * @returns The decoded object, if any keys occurred multiple times\n * then the value will be an array of strings, else it will be an array.\n * This behaviour matches Node's qs.parse but is built on URLSearchParams\n * for native web compatibility\n */\nexport function decodeParams(query: string): Record {\n const o: Record = {};\n const params = new URLSearchParams(query);\n for (const key of params.keys()) {\n const val = params.getAll(key);\n o[key] = val.length === 1 ? val[0] : val;\n }\n return o;\n}\n\n/**\n * Encodes a URI according to a set of template variables. Variables will be\n * passed through encodeURIComponent.\n * @param pathTemplate - The path with template variables e.g. '/foo/$bar'.\n * @param variables - The key/value pairs to replace the template\n * variables with. E.g. `{ \"$bar\": \"baz\" }`.\n * @returns The result of replacing all template variables e.g. '/foo/baz'.\n */\nexport function encodeUri(pathTemplate: string, variables: Record>): string {\n for (const key in variables) {\n if (!variables.hasOwnProperty(key)) {\n continue;\n }\n const value = variables[key];\n if (value === undefined || value === null) {\n continue;\n }\n pathTemplate = pathTemplate.replace(key, encodeURIComponent(value));\n }\n return pathTemplate;\n}\n\n/**\n * The removeElement() method removes the first element in the array that\n * satisfies (returns true) the provided testing function.\n * @param array - The array.\n * @param fn - Function to execute on each value in the array, with the\n * function signature `fn(element, index, array)`. Return true to\n * remove this element and break.\n * @param reverse - True to search in reverse order.\n * @returns True if an element was removed.\n */\nexport function removeElement(array: T[], fn: (t: T, i?: number, a?: T[]) => boolean, reverse?: boolean): boolean {\n let i: number;\n if (reverse) {\n for (i = array.length - 1; i >= 0; i--) {\n if (fn(array[i], i, array)) {\n array.splice(i, 1);\n return true;\n }\n }\n } else {\n for (i = 0; i < array.length; i++) {\n if (fn(array[i], i, array)) {\n array.splice(i, 1);\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Checks if the given thing is a function.\n * @param value - The thing to check.\n * @returns True if it is a function.\n */\nexport function isFunction(value: any): boolean {\n return Object.prototype.toString.call(value) === \"[object Function]\";\n}\n\n/**\n * Checks that the given object has the specified keys.\n * @param obj - The object to check.\n * @param keys - The list of keys that 'obj' must have.\n * @throws If the object is missing keys.\n */\n// note using 'keys' here would shadow the 'keys' function defined above\nexport function checkObjectHasKeys(obj: object, keys: string[]): void {\n for (const key of keys) {\n if (!obj.hasOwnProperty(key)) {\n throw new Error(\"Missing required key: \" + key);\n }\n }\n}\n\n/**\n * Deep copy the given object. The object MUST NOT have circular references and\n * MUST NOT have functions.\n * @param obj - The object to deep copy.\n * @returns A copy of the object without any references to the original.\n */\nexport function deepCopy(obj: T): T {\n return JSON.parse(JSON.stringify(obj));\n}\n\n/**\n * Compare two objects for equality. The objects MUST NOT have circular references.\n *\n * @param x - The first object to compare.\n * @param y - The second object to compare.\n *\n * @returns true if the two objects are equal\n */\nexport function deepCompare(x: any, y: any): boolean {\n // Inspired by\n // http://stackoverflow.com/questions/1068834/object-comparison-in-javascript#1144249\n\n // Compare primitives and functions.\n // Also check if both arguments link to the same object.\n if (x === y) {\n return true;\n }\n\n if (typeof x !== typeof y) {\n return false;\n }\n\n // special-case NaN (since NaN !== NaN)\n if (typeof x === \"number\" && isNaN(x) && isNaN(y)) {\n return true;\n }\n\n // special-case null (since typeof null == 'object', but null.constructor\n // throws)\n if (x === null || y === null) {\n return x === y;\n }\n\n // everything else is either an unequal primitive, or an object\n if (!(x instanceof Object)) {\n return false;\n }\n\n // check they are the same type of object\n if (x.constructor !== y.constructor || x.prototype !== y.prototype) {\n return false;\n }\n\n // special-casing for some special types of object\n if (x instanceof RegExp || x instanceof Date) {\n return x.toString() === y.toString();\n }\n\n // the object algorithm works for Array, but it's sub-optimal.\n if (Array.isArray(x)) {\n if (x.length !== y.length) {\n return false;\n }\n\n for (let i = 0; i < x.length; i++) {\n if (!deepCompare(x[i], y[i])) {\n return false;\n }\n }\n } else {\n // check that all of y's direct keys are in x\n for (const p in y) {\n if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {\n return false;\n }\n }\n\n // finally, compare each of x's keys with y\n for (const p in x) {\n if (y.hasOwnProperty(p) !== x.hasOwnProperty(p) || !deepCompare(x[p], y[p])) {\n return false;\n }\n }\n }\n return true;\n}\n\n// Dev note: This returns an array of tuples, but jsdoc doesn't like that. https://github.com/jsdoc/jsdoc/issues/1703\n/**\n * Creates an array of object properties/values (entries) then\n * sorts the result by key, recursively. The input object must\n * ensure it does not have loops. If the input is not an object\n * then it will be returned as-is.\n * @param obj - The object to get entries of\n * @returns The entries, sorted by key.\n */\nexport function deepSortedObjectEntries(obj: any): [string, any][] {\n if (typeof obj !== \"object\") return obj;\n\n // Apparently these are object types...\n if (obj === null || obj === undefined || Array.isArray(obj)) return obj;\n\n const pairs: [string, any][] = [];\n for (const [k, v] of Object.entries(obj)) {\n pairs.push([k, deepSortedObjectEntries(v)]);\n }\n\n // lexicographicCompare is faster than localeCompare, so let's use that.\n pairs.sort((a, b) => lexicographicCompare(a[0], b[0]));\n\n return pairs;\n}\n\n/**\n * Returns whether the given value is a finite number without type-coercion\n *\n * @param value - the value to test\n * @returns whether or not value is a finite number without type-coercion\n */\nexport function isNumber(value: any): value is number {\n return typeof value === \"number\" && isFinite(value);\n}\n\n/**\n * Removes zero width chars, diacritics and whitespace from the string\n * Also applies an unhomoglyph on the string, to prevent similar looking chars\n * @param str - the string to remove hidden characters from\n * @returns a string with the hidden characters removed\n */\nexport function removeHiddenChars(str: string): string {\n if (typeof str === \"string\") {\n return unhomoglyph(str.normalize(\"NFD\").replace(removeHiddenCharsRegex, \"\"));\n }\n return \"\";\n}\n\n/**\n * Removes the direction override characters from a string\n * @returns string with chars removed\n */\nexport function removeDirectionOverrideChars(str: string): string {\n if (typeof str === \"string\") {\n return str.replace(/[\\u202d-\\u202e]/g, \"\");\n }\n return \"\";\n}\n\nexport function normalize(str: string): string {\n // Note: we have to match the filter with the removeHiddenChars() because the\n // function strips spaces and other characters (M becomes RN for example, in lowercase).\n return (\n removeHiddenChars(str.toLowerCase())\n // Strip all punctuation\n .replace(/[\\\\'!\"#$%&()*+,\\-./:;<=>?@[\\]^_`{|}~\\u2000-\\u206f\\u2e00-\\u2e7f]/g, \"\")\n // We also doubly convert to lowercase to work around oddities of the library.\n .toLowerCase()\n );\n}\n\n// Regex matching bunch of unicode control characters and otherwise misleading/invisible characters.\n// Includes:\n// various width spaces U+2000 - U+200D\n// LTR and RTL marks U+200E and U+200F\n// LTR/RTL and other directional formatting marks U+202A - U+202F\n// Arabic Letter RTL mark U+061C\n// Combining characters U+0300 - U+036F\n// Zero width no-break space (BOM) U+FEFF\n// Blank/invisible characters (U2800, U2062-U2063)\n// eslint-disable-next-line no-misleading-character-class\nconst removeHiddenCharsRegex = /[\\u2000-\\u200F\\u202A-\\u202F\\u0300-\\u036F\\uFEFF\\u061C\\u2800\\u2062-\\u2063\\s]/g;\n\nexport function escapeRegExp(string: string): string {\n return string.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nexport function globToRegexp(glob: string, extended = false): string {\n // From\n // https://github.com/matrix-org/synapse/blob/abbee6b29be80a77e05730707602f3bbfc3f38cb/synapse/push/__init__.py#L132\n // Because micromatch is about 130KB with dependencies,\n // and minimatch is not much better.\n const replacements: [RegExp, string | ((substring: string, ...args: any[]) => string)][] = [\n [/\\\\\\*/g, \".*\"],\n [/\\?/g, \".\"],\n ];\n if (!extended) {\n replacements.push([\n /\\\\\\[(!|)(.*)\\\\]/g,\n (_match: string, neg: string, pat: string): string =>\n [\"[\", neg ? \"^\" : \"\", pat.replace(/\\\\-/, \"-\"), \"]\"].join(\"\"),\n ]);\n }\n return replacements.reduce(\n // https://github.com/microsoft/TypeScript/issues/30134\n (pat, args) => (args ? pat.replace(args[0], args[1] as any) : pat),\n escapeRegExp(glob),\n );\n}\n\nexport function ensureNoTrailingSlash(url: string): string;\nexport function ensureNoTrailingSlash(url: undefined): undefined;\nexport function ensureNoTrailingSlash(url?: string): string | undefined;\nexport function ensureNoTrailingSlash(url?: string): string | undefined {\n if (url?.endsWith(\"/\")) {\n return url.slice(0, -1);\n } else {\n return url;\n }\n}\n\n/**\n * Returns a promise which resolves with a given value after the given number of ms\n */\nexport function sleep(ms: number, value?: T): Promise {\n return new Promise((resolve) => {\n setTimeout(resolve, ms, value);\n });\n}\n\n/**\n * Promise/async version of {@link setImmediate}.\n */\nexport function immediate(): Promise {\n return new Promise(setImmediate);\n}\n\nexport function isNullOrUndefined(val: any): boolean {\n return val === null || val === undefined;\n}\n\nexport interface IDeferred {\n resolve: (value: T | Promise) => void;\n reject: (reason?: any) => void;\n promise: Promise;\n}\n\n// Returns a Deferred\nexport function defer(): IDeferred {\n let resolve!: IDeferred[\"resolve\"];\n let reject!: IDeferred[\"reject\"];\n\n const promise = new Promise((_resolve, _reject) => {\n resolve = _resolve;\n reject = _reject;\n });\n\n return { resolve, reject, promise };\n}\n\nexport async function promiseMapSeries(\n promises: Array>,\n fn: (t: T) => Promise | undefined, // if async we don't care about the type as we only await resolution\n): Promise {\n for (const o of promises) {\n await fn(await o);\n }\n}\n\nexport function promiseTry(fn: () => T | Promise): Promise {\n return Promise.resolve(fn());\n}\n\n// Creates and awaits all promises, running no more than `chunkSize` at the same time\nexport async function chunkPromises(fns: (() => Promise)[], chunkSize: number): Promise {\n const results: T[] = [];\n for (let i = 0; i < fns.length; i += chunkSize) {\n results.push(...(await Promise.all(fns.slice(i, i + chunkSize).map((fn) => fn()))));\n }\n return results;\n}\n\n/**\n * Retries the function until it succeeds or is interrupted. The given function must return\n * a promise which throws/rejects on error, otherwise the retry will assume the request\n * succeeded. The promise chain returned will contain the successful promise. The given function\n * should always return a new promise.\n * @param promiseFn - The function to call to get a fresh promise instance. Takes an\n * attempt count as an argument, for logging/debugging purposes.\n * @returns The promise for the retried operation.\n */\nexport function simpleRetryOperation(promiseFn: (attempt: number) => Promise): Promise {\n return promiseRetry(\n (attempt: number) => {\n return promiseFn(attempt);\n },\n {\n forever: true,\n factor: 2,\n minTimeout: 3000, // ms\n maxTimeout: 15000, // ms\n },\n );\n}\n\n// String averaging inspired by https://stackoverflow.com/a/2510816\n// Dev note: We make the alphabet a string because it's easier to write syntactically\n// than arrays. Thankfully, strings implement the useful parts of the Array interface\n// anyhow.\n\n/**\n * The default alphabet used by string averaging in this SDK. This matches\n * all usefully printable ASCII characters (0x20-0x7E, inclusive).\n */\nexport const DEFAULT_ALPHABET = ((): string => {\n let str = \"\";\n for (let c = 0x20; c <= 0x7e; c++) {\n str += String.fromCharCode(c);\n }\n return str;\n})();\n\n/**\n * Pads a string using the given alphabet as a base. The returned string will be\n * padded at the end with the first character in the alphabet.\n *\n * This is intended for use with string averaging.\n * @param s - The string to pad.\n * @param n - The length to pad to.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The padded string.\n */\nexport function alphabetPad(s: string, n: number, alphabet = DEFAULT_ALPHABET): string {\n return s.padEnd(n, alphabet[0]);\n}\n\n/**\n * Converts a baseN number to a string, where N is the alphabet's length.\n *\n * This is intended for use with string averaging.\n * @param n - The baseN number.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The baseN number encoded as a string from the alphabet.\n */\nexport function baseToString(n: bigint, alphabet = DEFAULT_ALPHABET): string {\n // Developer note: the stringToBase() function offsets the character set by 1 so that repeated\n // characters (ie: \"aaaaaa\" in a..z) don't come out as zero. We have to reverse this here as\n // otherwise we'll be wrong in our conversion. Undoing a +1 before an exponent isn't very fun\n // though, so we rely on a lengthy amount of `x - 1` and integer division rules to reach a\n // sane state. This also means we have to do rollover detection: see below.\n\n const len = BigInt(alphabet.length);\n if (n <= len) {\n return alphabet[Number(n) - 1] ?? \"\";\n }\n\n let d = n / len;\n let r = Number(n % len) - 1;\n\n // Rollover detection: if the remainder is negative, it means that the string needs\n // to roll over by 1 character downwards (ie: in a..z, the previous to \"aaa\" would be\n // \"zz\").\n if (r < 0) {\n d -= BigInt(Math.abs(r)); // abs() is just to be clear what we're doing. Could also `+= r`.\n r = Number(len) - 1;\n }\n\n return baseToString(d, alphabet) + alphabet[r];\n}\n\n/**\n * Converts a string to a baseN number, where N is the alphabet's length.\n *\n * This is intended for use with string averaging.\n * @param s - The string to convert to a number.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The baseN number.\n */\nexport function stringToBase(s: string, alphabet = DEFAULT_ALPHABET): bigint {\n const len = BigInt(alphabet.length);\n\n // In our conversion to baseN we do a couple performance optimizations to avoid using\n // excess CPU and such. To create baseN numbers, the input string needs to be reversed\n // so the exponents stack up appropriately, as the last character in the unreversed\n // string has less impact than the first character (in \"abc\" the A is a lot more important\n // for lexicographic sorts). We also do a trick with the character codes to optimize the\n // alphabet lookup, avoiding an index scan of `alphabet.indexOf(reversedStr[i])` - we know\n // that the alphabet and (theoretically) the input string are constrained on character sets\n // and thus can do simple subtraction to end up with the same result.\n\n // Developer caution: we carefully cast to BigInt here to avoid losing precision. We cannot\n // rely on Math.pow() (for example) to be capable of handling our insane numbers.\n\n let result = BigInt(0);\n for (let i = s.length - 1, j = BigInt(0); i >= 0; i--, j++) {\n const charIndex = s.charCodeAt(i) - alphabet.charCodeAt(0);\n\n // We add 1 to the char index to offset the whole numbering scheme. We unpack this in\n // the baseToString() function.\n result += BigInt(1 + charIndex) * len ** j;\n }\n return result;\n}\n\n/**\n * Averages two strings, returning the midpoint between them. This is accomplished by\n * converting both to baseN numbers (where N is the alphabet's length) then averaging\n * those before re-encoding as a string.\n * @param a - The first string.\n * @param b - The second string.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The midpoint between the strings, as a string.\n */\nexport function averageBetweenStrings(a: string, b: string, alphabet = DEFAULT_ALPHABET): string {\n const padN = Math.max(a.length, b.length);\n const baseA = stringToBase(alphabetPad(a, padN, alphabet), alphabet);\n const baseB = stringToBase(alphabetPad(b, padN, alphabet), alphabet);\n const avg = (baseA + baseB) / BigInt(2);\n\n // Detect integer division conflicts. This happens when two numbers are divided too close so\n // we lose a .5 precision. We need to add a padding character in these cases.\n if (avg === baseA || avg == baseB) {\n return baseToString(avg, alphabet) + alphabet[0];\n }\n\n return baseToString(avg, alphabet);\n}\n\n/**\n * Finds the next string using the alphabet provided. This is done by converting the\n * string to a baseN number, where N is the alphabet's length, then adding 1 before\n * converting back to a string.\n * @param s - The string to start at.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The string which follows the input string.\n */\nexport function nextString(s: string, alphabet = DEFAULT_ALPHABET): string {\n return baseToString(stringToBase(s, alphabet) + BigInt(1), alphabet);\n}\n\n/**\n * Finds the previous string using the alphabet provided. This is done by converting the\n * string to a baseN number, where N is the alphabet's length, then subtracting 1 before\n * converting back to a string.\n * @param s - The string to start at.\n * @param alphabet - The alphabet to use as a single string.\n * @returns The string which precedes the input string.\n */\nexport function prevString(s: string, alphabet = DEFAULT_ALPHABET): string {\n return baseToString(stringToBase(s, alphabet) - BigInt(1), alphabet);\n}\n\n/**\n * Compares strings lexicographically as a sort-safe function.\n * @param a - The first (reference) string.\n * @param b - The second (compare) string.\n * @returns Negative if the reference string is before the compare string;\n * positive if the reference string is after; and zero if equal.\n */\nexport function lexicographicCompare(a: string, b: string): number {\n // Dev note: this exists because I'm sad that you can use math operators on strings, so I've\n // hidden the operation in this function.\n if (a < b) {\n return -1;\n } else if (a > b) {\n return 1;\n } else {\n return 0;\n }\n}\n\nconst collator = new Intl.Collator();\n/**\n * Performant language-sensitive string comparison\n * @param a - the first string to compare\n * @param b - the second string to compare\n */\nexport function compare(a: string, b: string): number {\n return collator.compare(a, b);\n}\n\n/**\n * This function is similar to Object.assign() but it assigns recursively and\n * allows you to ignore nullish values from the source\n *\n * @returns the target object\n */\nexport function recursivelyAssign>(\n target: T1,\n source: T2,\n ignoreNullish = false,\n): T1 & T2 {\n for (const [sourceKey, sourceValue] of Object.entries(source)) {\n if (target[sourceKey] instanceof Object && sourceValue) {\n recursivelyAssign(target[sourceKey], sourceValue);\n continue;\n }\n if ((sourceValue !== null && sourceValue !== undefined) || !ignoreNullish) {\n target[sourceKey as keyof T1] = sourceValue;\n continue;\n }\n }\n return target as T1 & T2;\n}\n\nfunction getContentTimestampWithFallback(event: MatrixEvent): number {\n return M_TIMESTAMP.findIn(event.getContent()) ?? -1;\n}\n\n/**\n * Sort events by their content m.ts property\n * Latest timestamp first\n */\nexport function sortEventsByLatestContentTimestamp(left: MatrixEvent, right: MatrixEvent): number {\n return getContentTimestampWithFallback(right) - getContentTimestampWithFallback(left);\n}\n\nexport function isSupportedReceiptType(receiptType: string): boolean {\n return [ReceiptType.Read, ReceiptType.ReadPrivate].includes(receiptType as ReceiptType);\n}\n\n/**\n * Determines whether two maps are equal.\n * @param eq - The equivalence relation to compare values by. Defaults to strict equality.\n */\nexport function mapsEqual(x: Map, y: Map, eq = (v1: V, v2: V): boolean => v1 === v2): boolean {\n if (x.size !== y.size) return false;\n for (const [k, v1] of x) {\n const v2 = y.get(k);\n if (v2 === undefined || !eq(v1, v2)) return false;\n }\n return true;\n}\n\nfunction processMapToObjectValue(value: any): any {\n if (value instanceof Map) {\n // Value is a Map. Recursively map it to an object.\n return recursiveMapToObject(value);\n } else if (Array.isArray(value)) {\n // Value is an Array. Recursively map the value (e.g. to cover Array of Arrays).\n return value.map((v) => processMapToObjectValue(v));\n } else {\n return value;\n }\n}\n\n/**\n * Recursively converts Maps to plain objects.\n * Also supports sub-lists of Maps.\n */\nexport function recursiveMapToObject(map: Map): any {\n const targetMap = new Map();\n\n for (const [key, value] of map) {\n targetMap.set(key, processMapToObjectValue(value));\n }\n\n return Object.fromEntries(targetMap.entries());\n}\n\nexport function unsafeProp(prop: K): boolean {\n return prop === \"__proto__\" || prop === \"prototype\" || prop === \"constructor\";\n}\n\nexport function safeSet(obj: Record, prop: K, value: any): void {\n if (unsafeProp(prop)) {\n throw new Error(\"Trying to modify prototype or constructor\");\n }\n\n obj[prop] = value;\n}\n\nexport function noUnsafeEventProps(event: Partial): boolean {\n return !(\n unsafeProp(event.room_id) ||\n unsafeProp(event.sender) ||\n unsafeProp(event.user_id) ||\n unsafeProp(event.event_id)\n );\n}\n\nexport class MapWithDefault extends Map {\n public constructor(private createDefault: () => V) {\n super();\n }\n\n /**\n * Returns the value if the key already exists.\n * If not, it creates a new value under that key using the ctor callback and returns it.\n */\n public getOrCreate(key: K): V {\n if (!this.has(key)) {\n this.set(key, this.createDefault());\n }\n\n return this.get(key)!;\n }\n}\n", - "/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nlet audioContext: AudioContext | null = null;\nlet refCount = 0;\n\n/**\n * Acquires a reference to the shared AudioContext.\n * It's highly recommended to reuse this AudioContext rather than creating your\n * own, because multiple AudioContexts can be problematic in some browsers.\n * Make sure to call releaseContext when you're done using it.\n * @returns The shared AudioContext\n */\nexport const acquireContext = (): AudioContext => {\n if (audioContext === null) audioContext = new AudioContext();\n refCount++;\n return audioContext;\n};\n\n/**\n * Signals that one of the references to the shared AudioContext has been\n * released, allowing the context and associated hardware resources to be\n * cleaned up if nothing else is using it.\n */\nexport const releaseContext = (): void => {\n refCount--;\n if (refCount === 0) {\n audioContext?.close();\n audioContext = null;\n }\n};\n", - "/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 New Vector Ltd\nCopyright 2019, 2020 The Matrix.org Foundation C.I.C.\nCopyright 2021 - 2022 Šimon Brandner \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * This is an internal module. See {@link createNewMatrixCall} for the public API.\n */\n\nimport { v4 as uuidv4 } from \"uuid\";\nimport { parse as parseSdp, write as writeSdp } from \"sdp-transform\";\n\nimport { logger } from \"../logger\";\nimport * as utils from \"../utils\";\nimport { IContent, MatrixEvent } from \"../models/event\";\nimport { EventType, ToDeviceMessageId } from \"../@types/event\";\nimport { RoomMember } from \"../models/room-member\";\nimport { randomString } from \"../randomstring\";\nimport {\n MCallReplacesEvent,\n MCallAnswer,\n MCallInviteNegotiate,\n CallCapabilities,\n SDPStreamMetadataPurpose,\n SDPStreamMetadata,\n SDPStreamMetadataKey,\n MCallSDPStreamMetadataChanged,\n MCallSelectAnswer,\n MCAllAssertedIdentity,\n MCallCandidates,\n MCallBase,\n MCallHangupReject,\n} from \"./callEventTypes\";\nimport { CallFeed } from \"./callFeed\";\nimport { MatrixClient } from \"../client\";\nimport { EventEmitterEvents, TypedEventEmitter } from \"../models/typed-event-emitter\";\nimport { DeviceInfo } from \"../crypto/deviceinfo\";\nimport { GroupCallUnknownDeviceError } from \"./groupCall\";\nimport { IScreensharingOpts } from \"./mediaHandler\";\nimport { MatrixError } from \"../http-api\";\nimport { GroupCallStats } from \"./stats/groupCallStats\";\n\ninterface CallOpts {\n // The room ID for this call.\n roomId: string;\n invitee?: string;\n // The Matrix Client instance to send events to.\n client: MatrixClient;\n /**\n * Whether relay through TURN should be forced.\n * @deprecated use opts.forceTURN when creating the matrix client\n * since it's only possible to set this option on outbound calls.\n */\n forceTURN?: boolean;\n // A list of TURN servers.\n turnServers?: Array;\n opponentDeviceId?: string;\n opponentSessionId?: string;\n groupCallId?: string;\n}\n\ninterface TurnServer {\n urls: Array;\n username?: string;\n password?: string;\n ttl?: number;\n}\n\ninterface AssertedIdentity {\n id: string;\n displayName: string;\n}\n\nenum MediaType {\n AUDIO = \"audio\",\n VIDEO = \"video\",\n}\n\nenum CodecName {\n OPUS = \"opus\",\n // add more as needed\n}\n\n// Used internally to specify modifications to codec parameters in SDP\ninterface CodecParamsMod {\n mediaType: MediaType;\n codec: CodecName;\n enableDtx?: boolean; // true to enable discontinuous transmission, false to disable, undefined to leave as-is\n maxAverageBitrate?: number; // sets the max average bitrate, or undefined to leave as-is\n}\n\nexport enum CallState {\n Fledgling = \"fledgling\",\n InviteSent = \"invite_sent\",\n WaitLocalMedia = \"wait_local_media\",\n CreateOffer = \"create_offer\",\n CreateAnswer = \"create_answer\",\n Connecting = \"connecting\",\n Connected = \"connected\",\n Ringing = \"ringing\",\n Ended = \"ended\",\n}\n\nexport enum CallType {\n Voice = \"voice\",\n Video = \"video\",\n}\n\nexport enum CallDirection {\n Inbound = \"inbound\",\n Outbound = \"outbound\",\n}\n\nexport enum CallParty {\n Local = \"local\",\n Remote = \"remote\",\n}\n\nexport enum CallEvent {\n Hangup = \"hangup\",\n State = \"state\",\n Error = \"error\",\n Replaced = \"replaced\",\n\n // The value of isLocalOnHold() has changed\n LocalHoldUnhold = \"local_hold_unhold\",\n // The value of isRemoteOnHold() has changed\n RemoteHoldUnhold = \"remote_hold_unhold\",\n // backwards compat alias for LocalHoldUnhold: remove in a major version bump\n HoldUnhold = \"hold_unhold\",\n // Feeds have changed\n FeedsChanged = \"feeds_changed\",\n\n AssertedIdentityChanged = \"asserted_identity_changed\",\n\n LengthChanged = \"length_changed\",\n\n DataChannel = \"datachannel\",\n\n SendVoipEvent = \"send_voip_event\",\n}\n\nexport enum CallErrorCode {\n /** The user chose to end the call */\n UserHangup = \"user_hangup\",\n\n /** An error code when the local client failed to create an offer. */\n LocalOfferFailed = \"local_offer_failed\",\n /**\n * An error code when there is no local mic/camera to use. This may be because\n * the hardware isn't plugged in, or the user has explicitly denied access.\n */\n NoUserMedia = \"no_user_media\",\n\n /**\n * Error code used when a call event failed to send\n * because unknown devices were present in the room\n */\n UnknownDevices = \"unknown_devices\",\n\n /**\n * Error code used when we fail to send the invite\n * for some reason other than there being unknown devices\n */\n SendInvite = \"send_invite\",\n\n /**\n * An answer could not be created\n */\n CreateAnswer = \"create_answer\",\n\n /**\n * An offer could not be created\n */\n CreateOffer = \"create_offer\",\n\n /**\n * Error code used when we fail to send the answer\n * for some reason other than there being unknown devices\n */\n SendAnswer = \"send_answer\",\n\n /**\n * The session description from the other side could not be set\n */\n SetRemoteDescription = \"set_remote_description\",\n\n /**\n * The session description from this side could not be set\n */\n SetLocalDescription = \"set_local_description\",\n\n /**\n * A different device answered the call\n */\n AnsweredElsewhere = \"answered_elsewhere\",\n\n /**\n * No media connection could be established to the other party\n */\n IceFailed = \"ice_failed\",\n\n /**\n * The invite timed out whilst waiting for an answer\n */\n InviteTimeout = \"invite_timeout\",\n\n /**\n * The call was replaced by another call\n */\n Replaced = \"replaced\",\n\n /**\n * Signalling for the call could not be sent (other than the initial invite)\n */\n SignallingFailed = \"signalling_timeout\",\n\n /**\n * The remote party is busy\n */\n UserBusy = \"user_busy\",\n\n /**\n * We transferred the call off to somewhere else\n */\n Transferred = \"transferred\",\n\n /**\n * A call from the same user was found with a new session id\n */\n NewSession = \"new_session\",\n}\n\n/**\n * The version field that we set in m.call.* events\n */\nconst VOIP_PROTO_VERSION = \"1\";\n\n/** The fallback ICE server to use for STUN or TURN protocols. */\nconst FALLBACK_ICE_SERVER = \"stun:turn.matrix.org\";\n\n/** The length of time a call can be ringing for. */\nconst CALL_TIMEOUT_MS = 60 * 1000; // ms\n/** The time after which we increment callLength */\nconst CALL_LENGTH_INTERVAL = 1000; // ms\n/** The time after which we end the call, if ICE got disconnected */\nconst ICE_DISCONNECTED_TIMEOUT = 30 * 1000; // ms\n\nexport class CallError extends Error {\n public readonly code: string;\n\n public constructor(code: CallErrorCode, msg: string, err: Error) {\n // Still don't think there's any way to have proper nested errors\n super(msg + \": \" + err);\n\n this.code = code;\n }\n}\n\nexport function genCallID(): string {\n return Date.now().toString() + randomString(16);\n}\n\nfunction getCodecParamMods(isPtt: boolean): CodecParamsMod[] {\n const mods = [\n {\n mediaType: \"audio\",\n codec: \"opus\",\n enableDtx: true,\n maxAverageBitrate: isPtt ? 12000 : undefined,\n },\n ] as CodecParamsMod[];\n\n return mods;\n}\n\nexport interface VoipEvent {\n type: \"toDevice\" | \"sendEvent\";\n eventType: string;\n userId?: string;\n opponentDeviceId?: string;\n roomId?: string;\n content: Record;\n}\n\n/**\n * These now all have the call object as an argument. Why? Well, to know which call a given event is\n * about you have three options:\n * 1. Use a closure as the callback that remembers what call it's listening to. This can be\n * a pain because you need to pass the listener function again when you remove the listener,\n * which might be somewhere else.\n * 2. Use not-very-well-known fact that EventEmitter sets 'this' to the emitter object in the\n * callback. This doesn't really play well with modern Typescript and eslint and doesn't work\n * with our pattern of re-emitting events.\n * 3. Pass the object in question as an argument to the callback.\n *\n * Now that we have group calls which have to deal with multiple call objects, this will\n * become more important, and I think methods 1 and 2 are just going to cause issues.\n */\nexport type CallEventHandlerMap = {\n [CallEvent.DataChannel]: (channel: RTCDataChannel, call: MatrixCall) => void;\n [CallEvent.FeedsChanged]: (feeds: CallFeed[], call: MatrixCall) => void;\n [CallEvent.Replaced]: (newCall: MatrixCall, oldCall: MatrixCall) => void;\n [CallEvent.Error]: (error: CallError, call: MatrixCall) => void;\n [CallEvent.RemoteHoldUnhold]: (onHold: boolean, call: MatrixCall) => void;\n [CallEvent.LocalHoldUnhold]: (onHold: boolean, call: MatrixCall) => void;\n [CallEvent.LengthChanged]: (length: number, call: MatrixCall) => void;\n [CallEvent.State]: (state: CallState, oldState: CallState, call: MatrixCall) => void;\n [CallEvent.Hangup]: (call: MatrixCall) => void;\n [CallEvent.AssertedIdentityChanged]: (call: MatrixCall) => void;\n /* @deprecated */\n [CallEvent.HoldUnhold]: (onHold: boolean) => void;\n [CallEvent.SendVoipEvent]: (event: VoipEvent, call: MatrixCall) => void;\n};\n\n// The key of the transceiver map (purpose + media type, separated by ':')\ntype TransceiverKey = string;\n\n// generates keys for the map of transceivers\n// kind is unfortunately a string rather than MediaType as this is the type of\n// track.kind\nfunction getTransceiverKey(purpose: SDPStreamMetadataPurpose, kind: TransceiverKey): string {\n return purpose + \":\" + kind;\n}\n\nexport class MatrixCall extends TypedEventEmitter {\n public roomId: string;\n public callId: string;\n public invitee?: string;\n public hangupParty?: CallParty;\n public hangupReason?: string;\n public direction?: CallDirection;\n public ourPartyId: string;\n public peerConn?: RTCPeerConnection;\n public toDeviceSeq = 0;\n\n // whether this call should have push-to-talk semantics\n // This should be set by the consumer on incoming & outgoing calls.\n public isPtt = false;\n\n private _state = CallState.Fledgling;\n private readonly client: MatrixClient;\n private readonly forceTURN?: boolean;\n private readonly turnServers: Array;\n // A queue for candidates waiting to go out.\n // We try to amalgamate candidates into a single candidate message where\n // possible\n private candidateSendQueue: Array = [];\n private candidateSendTries = 0;\n private candidatesEnded = false;\n private feeds: Array = [];\n\n // our transceivers for each purpose and type of media\n private transceivers = new Map();\n\n private inviteOrAnswerSent = false;\n private waitForLocalAVStream = false;\n private successor?: MatrixCall;\n private opponentMember?: RoomMember;\n private opponentVersion?: number | string;\n // The party ID of the other side: undefined if we haven't chosen a partner\n // yet, null if we have but they didn't send a party ID.\n private opponentPartyId: string | null | undefined;\n private opponentCaps?: CallCapabilities;\n private iceDisconnectedTimeout?: ReturnType;\n private inviteTimeout?: ReturnType;\n private readonly removeTrackListeners = new Map void>();\n\n // The logic of when & if a call is on hold is nontrivial and explained in is*OnHold\n // This flag represents whether we want the other party to be on hold\n private remoteOnHold = false;\n\n // the stats for the call at the point it ended. We can't get these after we\n // tear the call down, so we just grab a snapshot before we stop the call.\n // The typescript definitions have this type as 'any' :(\n private callStatsAtEnd?: any[];\n\n // Perfect negotiation state: https://www.w3.org/TR/webrtc/#perfect-negotiation-example\n private makingOffer = false;\n private ignoreOffer = false;\n\n private responsePromiseChain?: Promise;\n\n // If candidates arrive before we've picked an opponent (which, in particular,\n // will happen if the opponent sends candidates eagerly before the user answers\n // the call) we buffer them up here so we can then add the ones from the party we pick\n private remoteCandidateBuffer = new Map();\n\n private remoteAssertedIdentity?: AssertedIdentity;\n private remoteSDPStreamMetadata?: SDPStreamMetadata;\n\n private callLengthInterval?: ReturnType;\n private callStartTime?: number;\n\n private opponentDeviceId?: string;\n private opponentDeviceInfo?: DeviceInfo;\n private opponentSessionId?: string;\n public groupCallId?: string;\n\n // Used to keep the timer for the delay before actually stopping our\n // video track after muting (see setLocalVideoMuted)\n private stopVideoTrackTimer?: ReturnType;\n // Used to allow connection without Video and Audio. To establish a webrtc connection without media a Data channel is\n // needed At the moment this property is true if we allow MatrixClient with isVoipWithNoMediaAllowed = true\n private readonly isOnlyDataChannelAllowed: boolean;\n private stats: GroupCallStats | undefined;\n\n /**\n * Construct a new Matrix Call.\n * @param opts - Config options.\n */\n public constructor(opts: CallOpts) {\n super();\n\n this.roomId = opts.roomId;\n this.invitee = opts.invitee;\n this.client = opts.client;\n\n if (!this.client.deviceId) throw new Error(\"Client must have a device ID to start calls\");\n\n this.forceTURN = opts.forceTURN ?? false;\n this.ourPartyId = this.client.deviceId;\n this.opponentDeviceId = opts.opponentDeviceId;\n this.opponentSessionId = opts.opponentSessionId;\n this.groupCallId = opts.groupCallId;\n // Array of Objects with urls, username, credential keys\n this.turnServers = opts.turnServers || [];\n if (this.turnServers.length === 0 && this.client.isFallbackICEServerAllowed()) {\n this.turnServers.push({\n urls: [FALLBACK_ICE_SERVER],\n });\n }\n for (const server of this.turnServers) {\n utils.checkObjectHasKeys(server, [\"urls\"]);\n }\n this.callId = genCallID();\n // If the Client provides calls without audio and video we need a datachannel for a webrtc connection\n this.isOnlyDataChannelAllowed = this.client.isVoipWithNoMediaAllowed;\n }\n\n /**\n * Place a voice call to this room.\n * @throws If you have not specified a listener for 'error' events.\n */\n public async placeVoiceCall(): Promise {\n await this.placeCall(true, false);\n }\n\n /**\n * Place a video call to this room.\n * @throws If you have not specified a listener for 'error' events.\n */\n public async placeVideoCall(): Promise {\n await this.placeCall(true, true);\n }\n\n /**\n * Create a datachannel using this call's peer connection.\n * @param label - A human readable label for this datachannel\n * @param options - An object providing configuration options for the data channel.\n */\n public createDataChannel(label: string, options: RTCDataChannelInit | undefined): RTCDataChannel {\n const dataChannel = this.peerConn!.createDataChannel(label, options);\n this.emit(CallEvent.DataChannel, dataChannel, this);\n return dataChannel;\n }\n\n public getOpponentMember(): RoomMember | undefined {\n return this.opponentMember;\n }\n\n public getOpponentDeviceId(): string | undefined {\n return this.opponentDeviceId;\n }\n\n public getOpponentSessionId(): string | undefined {\n return this.opponentSessionId;\n }\n\n public opponentCanBeTransferred(): boolean {\n return Boolean(this.opponentCaps && this.opponentCaps[\"m.call.transferee\"]);\n }\n\n public opponentSupportsDTMF(): boolean {\n return Boolean(this.opponentCaps && this.opponentCaps[\"m.call.dtmf\"]);\n }\n\n public getRemoteAssertedIdentity(): AssertedIdentity | undefined {\n return this.remoteAssertedIdentity;\n }\n\n public get state(): CallState {\n return this._state;\n }\n\n private set state(state: CallState) {\n const oldState = this._state;\n this._state = state;\n this.emit(CallEvent.State, state, oldState, this);\n }\n\n public get type(): CallType {\n // we may want to look for a video receiver here rather than a track to match the\n // sender behaviour, although in practice they should be the same thing\n return this.hasUserMediaVideoSender || this.hasRemoteUserMediaVideoTrack ? CallType.Video : CallType.Voice;\n }\n\n public get hasLocalUserMediaVideoTrack(): boolean {\n return !!this.localUsermediaStream?.getVideoTracks().length;\n }\n\n public get hasRemoteUserMediaVideoTrack(): boolean {\n return this.getRemoteFeeds().some((feed) => {\n return feed.purpose === SDPStreamMetadataPurpose.Usermedia && feed.stream?.getVideoTracks().length;\n });\n }\n\n public get hasLocalUserMediaAudioTrack(): boolean {\n return !!this.localUsermediaStream?.getAudioTracks().length;\n }\n\n public get hasRemoteUserMediaAudioTrack(): boolean {\n return this.getRemoteFeeds().some((feed) => {\n return feed.purpose === SDPStreamMetadataPurpose.Usermedia && !!feed.stream?.getAudioTracks().length;\n });\n }\n\n private get hasUserMediaAudioSender(): boolean {\n return Boolean(this.transceivers.get(getTransceiverKey(SDPStreamMetadataPurpose.Usermedia, \"audio\"))?.sender);\n }\n\n private get hasUserMediaVideoSender(): boolean {\n return Boolean(this.transceivers.get(getTransceiverKey(SDPStreamMetadataPurpose.Usermedia, \"video\"))?.sender);\n }\n\n public get localUsermediaFeed(): CallFeed | undefined {\n return this.getLocalFeeds().find((feed) => feed.purpose === SDPStreamMetadataPurpose.Usermedia);\n }\n\n public get localScreensharingFeed(): CallFeed | undefined {\n return this.getLocalFeeds().find((feed) => feed.purpose === SDPStreamMetadataPurpose.Screenshare);\n }\n\n public get localUsermediaStream(): MediaStream | undefined {\n return this.localUsermediaFeed?.stream;\n }\n\n public get localScreensharingStream(): MediaStream | undefined {\n return this.localScreensharingFeed?.stream;\n }\n\n public get remoteUsermediaFeed(): CallFeed | undefined {\n return this.getRemoteFeeds().find((feed) => feed.purpose === SDPStreamMetadataPurpose.Usermedia);\n }\n\n public get remoteScreensharingFeed(): CallFeed | undefined {\n return this.getRemoteFeeds().find((feed) => feed.purpose === SDPStreamMetadataPurpose.Screenshare);\n }\n\n public get remoteUsermediaStream(): MediaStream | undefined {\n return this.remoteUsermediaFeed?.stream;\n }\n\n public get remoteScreensharingStream(): MediaStream | undefined {\n return this.remoteScreensharingFeed?.stream;\n }\n\n private getFeedByStreamId(streamId: string): CallFeed | undefined {\n return this.getFeeds().find((feed) => feed.stream.id === streamId);\n }\n\n /**\n * Returns an array of all CallFeeds\n * @returns CallFeeds\n */\n public getFeeds(): Array {\n return this.feeds;\n }\n\n /**\n * Returns an array of all local CallFeeds\n * @returns local CallFeeds\n */\n public getLocalFeeds(): Array {\n return this.feeds.filter((feed) => feed.isLocal());\n }\n\n /**\n * Returns an array of all remote CallFeeds\n * @returns remote CallFeeds\n */\n public getRemoteFeeds(): Array {\n return this.feeds.filter((feed) => !feed.isLocal());\n }\n\n private async initOpponentCrypto(): Promise {\n if (!this.opponentDeviceId) return;\n if (!this.client.getUseE2eForGroupCall()) return;\n // It's possible to want E2EE and yet not have the means to manage E2EE\n // ourselves (for example if the client is a RoomWidgetClient)\n if (!this.client.isCryptoEnabled()) {\n // All we know is the device ID\n this.opponentDeviceInfo = new DeviceInfo(this.opponentDeviceId);\n return;\n }\n // if we've got to this point, we do want to init crypto, so throw if we can't\n if (!this.client.crypto) throw new Error(\"Crypto is not initialised.\");\n\n const userId = this.invitee || this.getOpponentMember()?.userId;\n\n if (!userId) throw new Error(\"Couldn't find opponent user ID to init crypto\");\n\n const deviceInfoMap = await this.client.crypto.deviceList.downloadKeys([userId], false);\n this.opponentDeviceInfo = deviceInfoMap.get(userId)?.get(this.opponentDeviceId);\n if (this.opponentDeviceInfo === undefined) {\n throw new GroupCallUnknownDeviceError(userId);\n }\n }\n\n /**\n * Generates and returns localSDPStreamMetadata\n * @returns localSDPStreamMetadata\n */\n private getLocalSDPStreamMetadata(updateStreamIds = false): SDPStreamMetadata {\n const metadata: SDPStreamMetadata = {};\n for (const localFeed of this.getLocalFeeds()) {\n if (updateStreamIds) {\n localFeed.sdpMetadataStreamId = localFeed.stream.id;\n }\n\n metadata[localFeed.sdpMetadataStreamId] = {\n purpose: localFeed.purpose,\n audio_muted: localFeed.isAudioMuted(),\n video_muted: localFeed.isVideoMuted(),\n };\n }\n return metadata;\n }\n\n /**\n * Returns true if there are no incoming feeds,\n * otherwise returns false\n * @returns no incoming feeds\n */\n public noIncomingFeeds(): boolean {\n return !this.feeds.some((feed) => !feed.isLocal());\n }\n\n private pushRemoteFeed(stream: MediaStream): void {\n // Fallback to old behavior if the other side doesn't support SDPStreamMetadata\n if (!this.opponentSupportsSDPStreamMetadata()) {\n this.pushRemoteFeedWithoutMetadata(stream);\n return;\n }\n\n const userId = this.getOpponentMember()!.userId;\n const purpose = this.remoteSDPStreamMetadata![stream.id].purpose;\n const audioMuted = this.remoteSDPStreamMetadata![stream.id].audio_muted;\n const videoMuted = this.remoteSDPStreamMetadata![stream.id].video_muted;\n\n if (!purpose) {\n logger.warn(\n `Call ${this.callId} pushRemoteFeed() ignoring stream because we didn't get any metadata about it (streamId=${stream.id})`,\n );\n return;\n }\n\n if (this.getFeedByStreamId(stream.id)) {\n logger.warn(\n `Call ${this.callId} pushRemoteFeed() ignoring stream because we already have a feed for it (streamId=${stream.id})`,\n );\n return;\n }\n\n this.feeds.push(\n new CallFeed({\n client: this.client,\n call: this,\n roomId: this.roomId,\n userId,\n deviceId: this.getOpponentDeviceId(),\n stream,\n purpose,\n audioMuted,\n videoMuted,\n }),\n );\n\n this.emit(CallEvent.FeedsChanged, this.feeds, this);\n\n logger.info(\n `Call ${this.callId} pushRemoteFeed() pushed stream (streamId=${stream.id}, active=${stream.active}, purpose=${purpose})`,\n );\n }\n\n /**\n * This method is used ONLY if the other client doesn't support sending SDPStreamMetadata\n */\n private pushRemoteFeedWithoutMetadata(stream: MediaStream): void {\n const userId = this.getOpponentMember()!.userId;\n // We can guess the purpose here since the other client can only send one stream\n const purpose = SDPStreamMetadataPurpose.Usermedia;\n const oldRemoteStream = this.feeds.find((feed) => !feed.isLocal())?.stream;\n\n // Note that we check by ID and always set the remote stream: Chrome appears\n // to make new stream objects when transceiver directionality is changed and the 'active'\n // status of streams change - Dave\n // If we already have a stream, check this stream has the same id\n if (oldRemoteStream && stream.id !== oldRemoteStream.id) {\n logger.warn(\n `Call ${this.callId} pushRemoteFeedWithoutMetadata() ignoring new stream because we already have stream (streamId=${stream.id})`,\n );\n return;\n }\n\n if (this.getFeedByStreamId(stream.id)) {\n logger.warn(\n `Call ${this.callId} pushRemoteFeedWithoutMetadata() ignoring stream because we already have a feed for it (streamId=${stream.id})`,\n );\n return;\n }\n\n this.feeds.push(\n new CallFeed({\n client: this.client,\n call: this,\n roomId: this.roomId,\n audioMuted: false,\n videoMuted: false,\n userId,\n deviceId: this.getOpponentDeviceId(),\n stream,\n purpose,\n }),\n );\n\n this.emit(CallEvent.FeedsChanged, this.feeds, this);\n\n logger.info(\n `Call ${this.callId} pushRemoteFeedWithoutMetadata() pushed stream (streamId=${stream.id}, active=${stream.active})`,\n );\n }\n\n private pushNewLocalFeed(stream: MediaStream, purpose: SDPStreamMetadataPurpose, addToPeerConnection = true): void {\n const userId = this.client.getUserId()!;\n\n // Tracks don't always start off enabled, eg. chrome will give a disabled\n // audio track if you ask for user media audio and already had one that\n // you'd set to disabled (presumably because it clones them internally).\n setTracksEnabled(stream.getAudioTracks(), true);\n setTracksEnabled(stream.getVideoTracks(), true);\n\n if (this.getFeedByStreamId(stream.id)) {\n logger.warn(\n `Call ${this.callId} pushNewLocalFeed() ignoring stream because we already have a feed for it (streamId=${stream.id})`,\n );\n return;\n }\n\n this.pushLocalFeed(\n new CallFeed({\n client: this.client,\n roomId: this.roomId,\n audioMuted: false,\n videoMuted: false,\n userId,\n deviceId: this.getOpponentDeviceId(),\n stream,\n purpose,\n }),\n addToPeerConnection,\n );\n }\n\n /**\n * Pushes supplied feed to the call\n * @param callFeed - to push\n * @param addToPeerConnection - whether to add the tracks to the peer connection\n */\n public pushLocalFeed(callFeed: CallFeed, addToPeerConnection = true): void {\n if (this.feeds.some((feed) => callFeed.stream.id === feed.stream.id)) {\n logger.info(\n `Call ${this.callId} pushLocalFeed() ignoring duplicate local stream (streamId=${callFeed.stream.id})`,\n );\n return;\n }\n\n this.feeds.push(callFeed);\n\n if (addToPeerConnection) {\n for (const track of callFeed.stream.getTracks()) {\n logger.info(\n `Call ${this.callId} pushLocalFeed() adding track to peer connection (id=${track.id}, kind=${track.kind}, streamId=${callFeed.stream.id}, streamPurpose=${callFeed.purpose}, enabled=${track.enabled})`,\n );\n\n const tKey = getTransceiverKey(callFeed.purpose, track.kind);\n if (this.transceivers.has(tKey)) {\n // we already have a sender, so we re-use it. We try to re-use transceivers as much\n // as possible because they can't be removed once added, so otherwise they just\n // accumulate which makes the SDP very large very quickly: in fact it only takes\n // about 6 video tracks to exceed the maximum size of an Olm-encrypted\n // Matrix event.\n const transceiver = this.transceivers.get(tKey)!;\n\n transceiver.sender.replaceTrack(track);\n // set the direction to indicate we're going to start sending again\n // (this will trigger the re-negotiation)\n transceiver.direction = transceiver.direction === \"inactive\" ? \"sendonly\" : \"sendrecv\";\n } else {\n // create a new one. We need to use addTrack rather addTransceiver for this because firefox\n // doesn't yet implement RTCRTPSender.setStreams()\n // (https://bugzilla.mozilla.org/show_bug.cgi?id=1510802) so we'd have no way to group the\n // two tracks together into a stream.\n const newSender = this.peerConn!.addTrack(track, callFeed.stream);\n\n // now go & fish for the new transceiver\n const newTransceiver = this.peerConn!.getTransceivers().find((t) => t.sender === newSender);\n if (newTransceiver) {\n this.transceivers.set(tKey, newTransceiver);\n } else {\n logger.warn(\n `Call ${this.callId} pushLocalFeed() didn't find a matching transceiver after adding track!`,\n );\n }\n }\n }\n }\n\n logger.info(\n `Call ${this.callId} pushLocalFeed() pushed stream (id=${callFeed.stream.id}, active=${callFeed.stream.active}, purpose=${callFeed.purpose})`,\n );\n\n this.emit(CallEvent.FeedsChanged, this.feeds, this);\n }\n\n /**\n * Removes local call feed from the call and its tracks from the peer\n * connection\n * @param callFeed - to remove\n */\n public removeLocalFeed(callFeed: CallFeed): void {\n const audioTransceiverKey = getTransceiverKey(callFeed.purpose, \"audio\");\n const videoTransceiverKey = getTransceiverKey(callFeed.purpose, \"video\");\n\n for (const transceiverKey of [audioTransceiverKey, videoTransceiverKey]) {\n // this is slightly mixing the track and transceiver API but is basically just shorthand.\n // There is no way to actually remove a transceiver, so this just sets it to inactive\n // (or recvonly) and replaces the source with nothing.\n if (this.transceivers.has(transceiverKey)) {\n const transceiver = this.transceivers.get(transceiverKey)!;\n if (transceiver.sender) this.peerConn!.removeTrack(transceiver.sender);\n }\n }\n\n if (callFeed.purpose === SDPStreamMetadataPurpose.Screenshare) {\n this.client.getMediaHandler().stopScreensharingStream(callFeed.stream);\n }\n\n this.deleteFeed(callFeed);\n }\n\n private deleteAllFeeds(): void {\n for (const feed of this.feeds) {\n if (!feed.isLocal() || !this.groupCallId) {\n feed.dispose();\n }\n }\n\n this.feeds = [];\n this.emit(CallEvent.FeedsChanged, this.feeds, this);\n }\n\n private deleteFeedByStream(stream: MediaStream): void {\n const feed = this.getFeedByStreamId(stream.id);\n if (!feed) {\n logger.warn(\n `Call ${this.callId} deleteFeedByStream() didn't find the feed to delete (streamId=${stream.id})`,\n );\n return;\n }\n this.deleteFeed(feed);\n }\n\n private deleteFeed(feed: CallFeed): void {\n feed.dispose();\n this.feeds.splice(this.feeds.indexOf(feed), 1);\n this.emit(CallEvent.FeedsChanged, this.feeds, this);\n }\n\n // The typescript definitions have this type as 'any' :(\n public async getCurrentCallStats(): Promise {\n if (this.callHasEnded()) {\n return this.callStatsAtEnd;\n }\n\n return this.collectCallStats();\n }\n\n private async collectCallStats(): Promise {\n // This happens when the call fails before it starts.\n // For example when we fail to get capture sources\n if (!this.peerConn) return;\n\n const statsReport = await this.peerConn.getStats();\n const stats: any[] = [];\n statsReport.forEach((item) => {\n stats.push(item);\n });\n\n return stats;\n }\n\n /**\n * Configure this call from an invite event. Used by MatrixClient.\n * @param event - The m.call.invite event\n */\n public async initWithInvite(event: MatrixEvent): Promise {\n const invite = event.getContent();\n this.direction = CallDirection.Inbound;\n\n // make sure we have valid turn creds. Unless something's gone wrong, it should\n // poll and keep the credentials valid so this should be instant.\n const haveTurnCreds = await this.client.checkTurnServers();\n if (!haveTurnCreds) {\n logger.warn(\n `Call ${this.callId} initWithInvite() failed to get TURN credentials! Proceeding with call anyway...`,\n );\n }\n\n const sdpStreamMetadata = invite[SDPStreamMetadataKey];\n if (sdpStreamMetadata) {\n this.updateRemoteSDPStreamMetadata(sdpStreamMetadata);\n } else {\n logger.debug(\n `Call ${this.callId} initWithInvite() did not get any SDPStreamMetadata! Can not send/receive multiple streams`,\n );\n }\n\n this.peerConn = this.createPeerConnection();\n // we must set the party ID before await-ing on anything: the call event\n // handler will start giving us more call events (eg. candidates) so if\n // we haven't set the party ID, we'll ignore them.\n this.chooseOpponent(event);\n await this.initOpponentCrypto();\n try {\n await this.peerConn.setRemoteDescription(invite.offer);\n await this.addBufferedIceCandidates();\n } catch (e) {\n logger.debug(`Call ${this.callId} initWithInvite() failed to set remote description`, e);\n this.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false);\n return;\n }\n\n const remoteStream = this.feeds.find((feed) => !feed.isLocal())?.stream;\n\n // According to previous comments in this file, firefox at some point did not\n // add streams until media started arriving on them. Testing latest firefox\n // (81 at time of writing), this is no longer a problem, so let's do it the correct way.\n //\n // For example in case of no media webrtc connections like screen share only call we have to allow webrtc\n // connections without remote media. In this case we always use a data channel. At the moment we allow as well\n // only data channel as media in the WebRTC connection with this setup here.\n if (!this.isOnlyDataChannelAllowed && (!remoteStream || remoteStream.getTracks().length === 0)) {\n logger.error(\n `Call ${this.callId} initWithInvite() no remote stream or no tracks after setting remote description!`,\n );\n this.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false);\n return;\n }\n\n this.state = CallState.Ringing;\n\n if (event.getLocalAge()) {\n // Time out the call if it's ringing for too long\n const ringingTimer = setTimeout(() => {\n if (this.state == CallState.Ringing) {\n logger.debug(`Call ${this.callId} initWithInvite() invite has expired. Hanging up.`);\n this.hangupParty = CallParty.Remote; // effectively\n this.state = CallState.Ended;\n this.stopAllMedia();\n if (this.peerConn!.signalingState != \"closed\") {\n this.peerConn!.close();\n }\n this.stats?.removeStatsReportGatherer(this.callId);\n this.emit(CallEvent.Hangup, this);\n }\n }, invite.lifetime - event.getLocalAge());\n\n const onState = (state: CallState): void => {\n if (state !== CallState.Ringing) {\n clearTimeout(ringingTimer);\n this.off(CallEvent.State, onState);\n }\n };\n this.on(CallEvent.State, onState);\n }\n }\n\n /**\n * Configure this call from a hangup or reject event. Used by MatrixClient.\n * @param event - The m.call.hangup event\n */\n public initWithHangup(event: MatrixEvent): void {\n // perverse as it may seem, sometimes we want to instantiate a call with a\n // hangup message (because when getting the state of the room on load, events\n // come in reverse order and we want to remember that a call has been hung up)\n this.state = CallState.Ended;\n }\n\n private shouldAnswerWithMediaType(\n wantedValue: boolean | undefined,\n valueOfTheOtherSide: boolean,\n type: \"audio\" | \"video\",\n ): boolean {\n if (wantedValue && !valueOfTheOtherSide) {\n // TODO: Figure out how to do this\n logger.warn(\n `Call ${this.callId} shouldAnswerWithMediaType() unable to answer with ${type} because the other side isn't sending it either.`,\n );\n return false;\n } else if (\n !utils.isNullOrUndefined(wantedValue) &&\n wantedValue !== valueOfTheOtherSide &&\n !this.opponentSupportsSDPStreamMetadata()\n ) {\n logger.warn(\n `Call ${this.callId} shouldAnswerWithMediaType() unable to answer with ${type}=${wantedValue} because the other side doesn't support it. Answering with ${type}=${valueOfTheOtherSide}.`,\n );\n return valueOfTheOtherSide!;\n }\n return wantedValue ?? valueOfTheOtherSide!;\n }\n\n /**\n * Answer a call.\n */\n public async answer(audio?: boolean, video?: boolean): Promise {\n if (this.inviteOrAnswerSent) return;\n // TODO: Figure out how to do this\n if (audio === false && video === false) throw new Error(\"You CANNOT answer a call without media\");\n\n if (!this.localUsermediaStream && !this.waitForLocalAVStream) {\n const prevState = this.state;\n const answerWithAudio = this.shouldAnswerWithMediaType(audio, this.hasRemoteUserMediaAudioTrack, \"audio\");\n const answerWithVideo = this.shouldAnswerWithMediaType(video, this.hasRemoteUserMediaVideoTrack, \"video\");\n\n this.state = CallState.WaitLocalMedia;\n this.waitForLocalAVStream = true;\n\n try {\n const stream = await this.client.getMediaHandler().getUserMediaStream(answerWithAudio, answerWithVideo);\n this.waitForLocalAVStream = false;\n const usermediaFeed = new CallFeed({\n client: this.client,\n roomId: this.roomId,\n userId: this.client.getUserId()!,\n deviceId: this.client.getDeviceId() ?? undefined,\n stream,\n purpose: SDPStreamMetadataPurpose.Usermedia,\n audioMuted: false,\n videoMuted: false,\n });\n\n const feeds = [usermediaFeed];\n\n if (this.localScreensharingFeed) {\n feeds.push(this.localScreensharingFeed);\n }\n\n this.answerWithCallFeeds(feeds);\n } catch (e) {\n if (answerWithVideo) {\n // Try to answer without video\n logger.warn(\n `Call ${this.callId} answer() failed to getUserMedia(), trying to getUserMedia() without video`,\n );\n this.state = prevState;\n this.waitForLocalAVStream = false;\n await this.answer(answerWithAudio, false);\n } else {\n this.getUserMediaFailed(e);\n return;\n }\n }\n } else if (this.waitForLocalAVStream) {\n this.state = CallState.WaitLocalMedia;\n }\n }\n\n public answerWithCallFeeds(callFeeds: CallFeed[]): void {\n if (this.inviteOrAnswerSent) return;\n\n this.queueGotCallFeedsForAnswer(callFeeds);\n }\n\n /**\n * Replace this call with a new call, e.g. for glare resolution. Used by\n * MatrixClient.\n * @param newCall - The new call.\n */\n public replacedBy(newCall: MatrixCall): void {\n logger.debug(`Call ${this.callId} replacedBy() running (newCallId=${newCall.callId})`);\n if (this.state === CallState.WaitLocalMedia) {\n logger.debug(\n `Call ${this.callId} replacedBy() telling new call to wait for local media (newCallId=${newCall.callId})`,\n );\n newCall.waitForLocalAVStream = true;\n } else if ([CallState.CreateOffer, CallState.InviteSent].includes(this.state)) {\n if (newCall.direction === CallDirection.Outbound) {\n newCall.queueGotCallFeedsForAnswer([]);\n } else {\n logger.debug(\n `Call ${this.callId} replacedBy() handing local stream to new call(newCallId=${newCall.callId})`,\n );\n newCall.queueGotCallFeedsForAnswer(this.getLocalFeeds().map((feed) => feed.clone()));\n }\n }\n this.successor = newCall;\n this.emit(CallEvent.Replaced, newCall, this);\n this.hangup(CallErrorCode.Replaced, true);\n }\n\n /**\n * Hangup a call.\n * @param reason - The reason why the call is being hung up.\n * @param suppressEvent - True to suppress emitting an event.\n */\n public hangup(reason: CallErrorCode, suppressEvent: boolean): void {\n if (this.callHasEnded()) return;\n\n logger.debug(`Call ${this.callId} hangup() ending call (reason=${reason})`);\n this.terminate(CallParty.Local, reason, !suppressEvent);\n // We don't want to send hangup here if we didn't even get to sending an invite\n if ([CallState.Fledgling, CallState.WaitLocalMedia].includes(this.state)) return;\n const content: IContent = {};\n // Don't send UserHangup reason to older clients\n if ((this.opponentVersion && this.opponentVersion !== 0) || reason !== CallErrorCode.UserHangup) {\n content[\"reason\"] = reason;\n }\n this.sendVoipEvent(EventType.CallHangup, content);\n }\n\n /**\n * Reject a call\n * This used to be done by calling hangup, but is a separate method and protocol\n * event as of MSC2746.\n */\n public reject(): void {\n if (this.state !== CallState.Ringing) {\n throw Error(\"Call must be in 'ringing' state to reject!\");\n }\n\n if (this.opponentVersion === 0) {\n logger.info(\n `Call ${this.callId} reject() opponent version is less than 1: sending hangup instead of reject (opponentVersion=${this.opponentVersion})`,\n );\n this.hangup(CallErrorCode.UserHangup, true);\n return;\n }\n\n logger.debug(\"Rejecting call: \" + this.callId);\n this.terminate(CallParty.Local, CallErrorCode.UserHangup, true);\n this.sendVoipEvent(EventType.CallReject, {});\n }\n\n /**\n * Adds an audio and/or video track - upgrades the call\n * @param audio - should add an audio track\n * @param video - should add an video track\n */\n private async upgradeCall(audio: boolean, video: boolean): Promise {\n // We don't do call downgrades\n if (!audio && !video) return;\n if (!this.opponentSupportsSDPStreamMetadata()) return;\n\n try {\n logger.debug(`Call ${this.callId} upgradeCall() upgrading call (audio=${audio}, video=${video})`);\n const getAudio = audio || this.hasLocalUserMediaAudioTrack;\n const getVideo = video || this.hasLocalUserMediaVideoTrack;\n\n // updateLocalUsermediaStream() will take the tracks, use them as\n // replacement and throw the stream away, so it isn't reusable\n const stream = await this.client.getMediaHandler().getUserMediaStream(getAudio, getVideo, false);\n await this.updateLocalUsermediaStream(stream, audio, video);\n } catch (error) {\n logger.error(`Call ${this.callId} upgradeCall() failed to upgrade the call`, error);\n this.emit(\n CallEvent.Error,\n new CallError(CallErrorCode.NoUserMedia, \"Failed to get camera access: \", error),\n this,\n );\n }\n }\n\n /**\n * Returns true if this.remoteSDPStreamMetadata is defined, otherwise returns false\n * @returns can screenshare\n */\n public opponentSupportsSDPStreamMetadata(): boolean {\n return Boolean(this.remoteSDPStreamMetadata);\n }\n\n /**\n * If there is a screensharing stream returns true, otherwise returns false\n * @returns is screensharing\n */\n public isScreensharing(): boolean {\n return Boolean(this.localScreensharingStream);\n }\n\n /**\n * Starts/stops screensharing\n * @param enabled - the desired screensharing state\n * @param desktopCapturerSourceId - optional id of the desktop capturer source to use\n * @returns new screensharing state\n */\n public async setScreensharingEnabled(enabled: boolean, opts?: IScreensharingOpts): Promise {\n // Skip if there is nothing to do\n if (enabled && this.isScreensharing()) {\n logger.warn(\n `Call ${this.callId} setScreensharingEnabled() there is already a screensharing stream - there is nothing to do!`,\n );\n return true;\n } else if (!enabled && !this.isScreensharing()) {\n logger.warn(\n `Call ${this.callId} setScreensharingEnabled() there already isn't a screensharing stream - there is nothing to do!`,\n );\n return false;\n }\n\n // Fallback to replaceTrack()\n if (!this.opponentSupportsSDPStreamMetadata()) {\n return this.setScreensharingEnabledWithoutMetadataSupport(enabled, opts);\n }\n\n logger.debug(`Call ${this.callId} setScreensharingEnabled() running (enabled=${enabled})`);\n if (enabled) {\n try {\n const stream = await this.client.getMediaHandler().getScreensharingStream(opts);\n if (!stream) return false;\n this.pushNewLocalFeed(stream, SDPStreamMetadataPurpose.Screenshare);\n return true;\n } catch (err) {\n logger.error(`Call ${this.callId} setScreensharingEnabled() failed to get screen-sharing stream:`, err);\n return false;\n }\n } else {\n const audioTransceiver = this.transceivers.get(\n getTransceiverKey(SDPStreamMetadataPurpose.Screenshare, \"audio\"),\n );\n const videoTransceiver = this.transceivers.get(\n getTransceiverKey(SDPStreamMetadataPurpose.Screenshare, \"video\"),\n );\n\n for (const transceiver of [audioTransceiver, videoTransceiver]) {\n // this is slightly mixing the track and transceiver API but is basically just shorthand\n // for removing the sender.\n if (transceiver && transceiver.sender) this.peerConn!.removeTrack(transceiver.sender);\n }\n\n this.client.getMediaHandler().stopScreensharingStream(this.localScreensharingStream!);\n this.deleteFeedByStream(this.localScreensharingStream!);\n return false;\n }\n }\n\n /**\n * Starts/stops screensharing\n * Should be used ONLY if the opponent doesn't support SDPStreamMetadata\n * @param enabled - the desired screensharing state\n * @param desktopCapturerSourceId - optional id of the desktop capturer source to use\n * @returns new screensharing state\n */\n private async setScreensharingEnabledWithoutMetadataSupport(\n enabled: boolean,\n opts?: IScreensharingOpts,\n ): Promise {\n logger.debug(\n `Call ${this.callId} setScreensharingEnabledWithoutMetadataSupport() running (enabled=${enabled})`,\n );\n if (enabled) {\n try {\n const stream = await this.client.getMediaHandler().getScreensharingStream(opts);\n if (!stream) return false;\n\n const track = stream.getTracks().find((track) => track.kind === \"video\");\n\n const sender = this.transceivers.get(\n getTransceiverKey(SDPStreamMetadataPurpose.Usermedia, \"video\"),\n )?.sender;\n\n sender?.replaceTrack(track ?? null);\n\n this.pushNewLocalFeed(stream, SDPStreamMetadataPurpose.Screenshare, false);\n\n return true;\n } catch (err) {\n logger.error(\n `Call ${this.callId} setScreensharingEnabledWithoutMetadataSupport() failed to get screen-sharing stream:`,\n err,\n );\n return false;\n }\n } else {\n const track = this.localUsermediaStream?.getTracks().find((track) => track.kind === \"video\");\n const sender = this.transceivers.get(\n getTransceiverKey(SDPStreamMetadataPurpose.Usermedia, \"video\"),\n )?.sender;\n sender?.replaceTrack(track ?? null);\n\n this.client.getMediaHandler().stopScreensharingStream(this.localScreensharingStream!);\n this.deleteFeedByStream(this.localScreensharingStream!);\n\n return false;\n }\n }\n\n /**\n * Replaces/adds the tracks from the passed stream to the localUsermediaStream\n * @param stream - to use a replacement for the local usermedia stream\n */\n public async updateLocalUsermediaStream(\n stream: MediaStream,\n forceAudio = false,\n forceVideo = false,\n ): Promise {\n const callFeed = this.localUsermediaFeed!;\n const audioEnabled = forceAudio || (!callFeed.isAudioMuted() && !this.remoteOnHold);\n const videoEnabled = forceVideo || (!callFeed.isVideoMuted() && !this.remoteOnHold);\n logger.log(\n `Call ${this.callId} updateLocalUsermediaStream() running (streamId=${stream.id}, audio=${audioEnabled}, video=${videoEnabled})`,\n );\n setTracksEnabled(stream.getAudioTracks(), audioEnabled);\n setTracksEnabled(stream.getVideoTracks(), videoEnabled);\n\n // We want to keep the same stream id, so we replace the tracks rather\n // than the whole stream.\n\n // Firstly, we replace the tracks in our localUsermediaStream.\n for (const track of this.localUsermediaStream!.getTracks()) {\n this.localUsermediaStream!.removeTrack(track);\n track.stop();\n }\n for (const track of stream.getTracks()) {\n this.localUsermediaStream!.addTrack(track);\n }\n\n // Then replace the old tracks, if possible.\n for (const track of stream.getTracks()) {\n const tKey = getTransceiverKey(SDPStreamMetadataPurpose.Usermedia, track.kind);\n\n const transceiver = this.transceivers.get(tKey);\n const oldSender = transceiver?.sender;\n let added = false;\n if (oldSender) {\n try {\n logger.info(\n `Call ${this.callId} updateLocalUsermediaStream() replacing track (id=${track.id}, kind=${track.kind}, streamId=${stream.id}, streamPurpose=${callFeed.purpose})`,\n );\n await oldSender.replaceTrack(track);\n // Set the direction to indicate we're going to be sending.\n // This is only necessary in the cases where we're upgrading\n // the call to video after downgrading it.\n transceiver.direction = transceiver.direction === \"inactive\" ? \"sendonly\" : \"sendrecv\";\n added = true;\n } catch (error) {\n logger.warn(\n `Call ${this.callId} updateLocalUsermediaStream() replaceTrack failed: adding new transceiver instead`,\n error,\n );\n }\n }\n\n if (!added) {\n logger.info(\n `Call ${this.callId} updateLocalUsermediaStream() adding track to peer connection (id=${track.id}, kind=${track.kind}, streamId=${stream.id}, streamPurpose=${callFeed.purpose})`,\n );\n\n const newSender = this.peerConn!.addTrack(track, this.localUsermediaStream!);\n const newTransceiver = this.peerConn!.getTransceivers().find((t) => t.sender === newSender);\n if (newTransceiver) {\n this.transceivers.set(tKey, newTransceiver);\n } else {\n logger.warn(\n `Call ${this.callId} updateLocalUsermediaStream() couldn't find matching transceiver for newly added track!`,\n );\n }\n }\n }\n }\n\n /**\n * Set whether our outbound video should be muted or not.\n * @param muted - True to mute the outbound video.\n * @returns the new mute state\n */\n public async setLocalVideoMuted(muted: boolean): Promise {\n logger.log(`Call ${this.callId} setLocalVideoMuted() running ${muted}`);\n\n // if we were still thinking about stopping and removing the video\n // track: don't, because we want it back.\n if (!muted && this.stopVideoTrackTimer !== undefined) {\n clearTimeout(this.stopVideoTrackTimer);\n this.stopVideoTrackTimer = undefined;\n }\n\n if (!(await this.client.getMediaHandler().hasVideoDevice())) {\n return this.isLocalVideoMuted();\n }\n\n if (!this.hasUserMediaVideoSender && !muted) {\n this.localUsermediaFeed?.setAudioVideoMuted(null, muted);\n await this.upgradeCall(false, true);\n return this.isLocalVideoMuted();\n }\n\n // we may not have a video track - if not, re-request usermedia\n if (!muted && this.localUsermediaStream!.getVideoTracks().length === 0) {\n const stream = await this.client.getMediaHandler().getUserMediaStream(true, true);\n await this.updateLocalUsermediaStream(stream);\n }\n\n this.localUsermediaFeed?.setAudioVideoMuted(null, muted);\n\n this.updateMuteStatus();\n await this.sendMetadataUpdate();\n\n // if we're muting video, set a timeout to stop & remove the video track so we release\n // the camera. We wait a short time to do this because when we disable a track, WebRTC\n // will send black video for it. If we just stop and remove it straight away, the video\n // will just freeze which means that when we unmute video, the other side will briefly\n // get a static frame of us from before we muted. This way, the still frame is just black.\n // A very small delay is not always enough so the theory here is that it needs to be long\n // enough for WebRTC to encode a frame: 120ms should be long enough even if we're only\n // doing 10fps.\n if (muted) {\n this.stopVideoTrackTimer = setTimeout(() => {\n for (const t of this.localUsermediaStream!.getVideoTracks()) {\n t.stop();\n this.localUsermediaStream!.removeTrack(t);\n }\n }, 120);\n }\n\n return this.isLocalVideoMuted();\n }\n\n /**\n * Check if local video is muted.\n *\n * If there are multiple video tracks, all of the tracks need to be muted\n * for this to return true. This means if there are no video tracks, this will\n * return true.\n * @returns True if the local preview video is muted, else false\n * (including if the call is not set up yet).\n */\n public isLocalVideoMuted(): boolean {\n return this.localUsermediaFeed?.isVideoMuted() ?? false;\n }\n\n /**\n * Set whether the microphone should be muted or not.\n * @param muted - True to mute the mic.\n * @returns the new mute state\n */\n public async setMicrophoneMuted(muted: boolean): Promise {\n logger.log(`Call ${this.callId} setMicrophoneMuted() running ${muted}`);\n if (!(await this.client.getMediaHandler().hasAudioDevice())) {\n return this.isMicrophoneMuted();\n }\n\n if (!muted && (!this.hasUserMediaAudioSender || !this.hasLocalUserMediaAudioTrack)) {\n await this.upgradeCall(true, false);\n return this.isMicrophoneMuted();\n }\n this.localUsermediaFeed?.setAudioVideoMuted(muted, null);\n this.updateMuteStatus();\n await this.sendMetadataUpdate();\n return this.isMicrophoneMuted();\n }\n\n /**\n * Check if the microphone is muted.\n *\n * If there are multiple audio tracks, all of the tracks need to be muted\n * for this to return true. This means if there are no audio tracks, this will\n * return true.\n * @returns True if the mic is muted, else false (including if the call\n * is not set up yet).\n */\n public isMicrophoneMuted(): boolean {\n return this.localUsermediaFeed?.isAudioMuted() ?? false;\n }\n\n /**\n * @returns true if we have put the party on the other side of the call on hold\n * (that is, we are signalling to them that we are not listening)\n */\n public isRemoteOnHold(): boolean {\n return this.remoteOnHold;\n }\n\n public setRemoteOnHold(onHold: boolean): void {\n if (this.isRemoteOnHold() === onHold) return;\n this.remoteOnHold = onHold;\n\n for (const transceiver of this.peerConn!.getTransceivers()) {\n // We don't send hold music or anything so we're not actually\n // sending anything, but sendrecv is fairly standard for hold and\n // it makes it a lot easier to figure out who's put who on hold.\n transceiver.direction = onHold ? \"sendonly\" : \"sendrecv\";\n }\n this.updateMuteStatus();\n this.sendMetadataUpdate();\n\n this.emit(CallEvent.RemoteHoldUnhold, this.remoteOnHold, this);\n }\n\n /**\n * Indicates whether we are 'on hold' to the remote party (ie. if true,\n * they cannot hear us).\n * @returns true if the other party has put us on hold\n */\n public isLocalOnHold(): boolean {\n if (this.state !== CallState.Connected) return false;\n\n let callOnHold = true;\n\n // We consider a call to be on hold only if *all* the tracks are on hold\n // (is this the right thing to do?)\n for (const transceiver of this.peerConn!.getTransceivers()) {\n const trackOnHold = [\"inactive\", \"recvonly\"].includes(transceiver.currentDirection!);\n\n if (!trackOnHold) callOnHold = false;\n }\n\n return callOnHold;\n }\n\n /**\n * Sends a DTMF digit to the other party\n * @param digit - The digit (nb. string - '#' and '*' are dtmf too)\n */\n public sendDtmfDigit(digit: string): void {\n for (const sender of this.peerConn!.getSenders()) {\n if (sender.track?.kind === \"audio\" && sender.dtmf) {\n sender.dtmf.insertDTMF(digit);\n return;\n }\n }\n\n throw new Error(\"Unable to find a track to send DTMF on\");\n }\n\n private updateMuteStatus(): void {\n const micShouldBeMuted = this.isMicrophoneMuted() || this.remoteOnHold;\n const vidShouldBeMuted = this.isLocalVideoMuted() || this.remoteOnHold;\n\n logger.log(\n `Call ${this.callId} updateMuteStatus stream ${\n this.localUsermediaStream!.id\n } micShouldBeMuted ${micShouldBeMuted} vidShouldBeMuted ${vidShouldBeMuted}`,\n );\n\n setTracksEnabled(this.localUsermediaStream!.getAudioTracks(), !micShouldBeMuted);\n setTracksEnabled(this.localUsermediaStream!.getVideoTracks(), !vidShouldBeMuted);\n }\n\n public async sendMetadataUpdate(): Promise {\n await this.sendVoipEvent(EventType.CallSDPStreamMetadataChangedPrefix, {\n [SDPStreamMetadataKey]: this.getLocalSDPStreamMetadata(),\n });\n }\n\n private gotCallFeedsForInvite(callFeeds: CallFeed[], requestScreenshareFeed = false): void {\n if (this.successor) {\n this.successor.queueGotCallFeedsForAnswer(callFeeds);\n return;\n }\n if (this.callHasEnded()) {\n this.stopAllMedia();\n return;\n }\n\n for (const feed of callFeeds) {\n this.pushLocalFeed(feed);\n }\n\n if (requestScreenshareFeed) {\n this.peerConn!.addTransceiver(\"video\", {\n direction: \"recvonly\",\n });\n }\n\n this.state = CallState.CreateOffer;\n\n logger.debug(`Call ${this.callId} gotUserMediaForInvite() run`);\n // Now we wait for the negotiationneeded event\n }\n\n private async sendAnswer(): Promise {\n const answerContent = {\n answer: {\n sdp: this.peerConn!.localDescription!.sdp,\n // type is now deprecated as of Matrix VoIP v1, but\n // required to still be sent for backwards compat\n type: this.peerConn!.localDescription!.type,\n },\n [SDPStreamMetadataKey]: this.getLocalSDPStreamMetadata(true),\n } as MCallAnswer;\n\n answerContent.capabilities = {\n \"m.call.transferee\": this.client.supportsCallTransfer,\n \"m.call.dtmf\": false,\n };\n\n // We have just taken the local description from the peerConn which will\n // contain all the local candidates added so far, so we can discard any candidates\n // we had queued up because they'll be in the answer.\n const discardCount = this.discardDuplicateCandidates();\n logger.info(\n `Call ${this.callId} sendAnswer() discarding ${discardCount} candidates that will be sent in answer`,\n );\n\n try {\n await this.sendVoipEvent(EventType.CallAnswer, answerContent);\n // If this isn't the first time we've tried to send the answer,\n // we may have candidates queued up, so send them now.\n this.inviteOrAnswerSent = true;\n } catch (error) {\n // We've failed to answer: back to the ringing state\n this.state = CallState.Ringing;\n if (error instanceof MatrixError && error.event) this.client.cancelPendingEvent(error.event);\n\n let code = CallErrorCode.SendAnswer;\n let message = \"Failed to send answer\";\n if ((error).name == \"UnknownDeviceError\") {\n code = CallErrorCode.UnknownDevices;\n message = \"Unknown devices present in the room\";\n }\n this.emit(CallEvent.Error, new CallError(code, message, error), this);\n throw error;\n }\n\n // error handler re-throws so this won't happen on error, but\n // we don't want the same error handling on the candidate queue\n this.sendCandidateQueue();\n }\n\n private queueGotCallFeedsForAnswer(callFeeds: CallFeed[]): void {\n // Ensure only one negotiate/answer event is being processed at a time.\n if (this.responsePromiseChain) {\n this.responsePromiseChain = this.responsePromiseChain.then(() => this.gotCallFeedsForAnswer(callFeeds));\n } else {\n this.responsePromiseChain = this.gotCallFeedsForAnswer(callFeeds);\n }\n }\n\n // Enables DTX (discontinuous transmission) on the given session to reduce\n // bandwidth when transmitting silence\n private mungeSdp(description: RTCSessionDescriptionInit, mods: CodecParamsMod[]): void {\n // The only way to enable DTX at this time is through SDP munging\n const sdp = parseSdp(description.sdp!);\n\n sdp.media.forEach((media) => {\n const payloadTypeToCodecMap = new Map();\n const codecToPayloadTypeMap = new Map();\n for (const rtp of media.rtp) {\n payloadTypeToCodecMap.set(rtp.payload, rtp.codec);\n codecToPayloadTypeMap.set(rtp.codec, rtp.payload);\n }\n\n for (const mod of mods) {\n if (mod.mediaType !== media.type) continue;\n\n if (!codecToPayloadTypeMap.has(mod.codec)) {\n logger.info(\n `Call ${this.callId} mungeSdp() ignoring SDP modifications for ${mod.codec} as it's not present.`,\n );\n continue;\n }\n\n const extraConfig: string[] = [];\n if (mod.enableDtx !== undefined) {\n extraConfig.push(`usedtx=${mod.enableDtx ? \"1\" : \"0\"}`);\n }\n if (mod.maxAverageBitrate !== undefined) {\n extraConfig.push(`maxaveragebitrate=${mod.maxAverageBitrate}`);\n }\n\n let found = false;\n for (const fmtp of media.fmtp) {\n if (payloadTypeToCodecMap.get(fmtp.payload) === mod.codec) {\n found = true;\n fmtp.config += \";\" + extraConfig.join(\";\");\n }\n }\n if (!found) {\n media.fmtp.push({\n payload: codecToPayloadTypeMap.get(mod.codec)!,\n config: extraConfig.join(\";\"),\n });\n }\n }\n });\n description.sdp = writeSdp(sdp);\n }\n\n private async createOffer(): Promise {\n const offer = await this.peerConn!.createOffer();\n this.mungeSdp(offer, getCodecParamMods(this.isPtt));\n return offer;\n }\n\n private async createAnswer(): Promise {\n const answer = await this.peerConn!.createAnswer();\n this.mungeSdp(answer, getCodecParamMods(this.isPtt));\n return answer;\n }\n\n private async gotCallFeedsForAnswer(callFeeds: CallFeed[]): Promise {\n if (this.callHasEnded()) return;\n\n this.waitForLocalAVStream = false;\n\n for (const feed of callFeeds) {\n this.pushLocalFeed(feed);\n }\n\n this.state = CallState.CreateAnswer;\n\n let answer: RTCSessionDescriptionInit;\n try {\n this.getRidOfRTXCodecs();\n answer = await this.createAnswer();\n } catch (err) {\n logger.debug(`Call ${this.callId} gotCallFeedsForAnswer() failed to create answer: `, err);\n this.terminate(CallParty.Local, CallErrorCode.CreateAnswer, true);\n return;\n }\n\n try {\n await this.peerConn!.setLocalDescription(answer);\n\n // make sure we're still going\n if (this.callHasEnded()) return;\n\n this.state = CallState.Connecting;\n\n // Allow a short time for initial candidates to be gathered\n await new Promise((resolve) => {\n setTimeout(resolve, 200);\n });\n\n // make sure the call hasn't ended before we continue\n if (this.callHasEnded()) return;\n\n this.sendAnswer();\n } catch (err) {\n logger.debug(`Call ${this.callId} gotCallFeedsForAnswer() error setting local description!`, err);\n this.terminate(CallParty.Local, CallErrorCode.SetLocalDescription, true);\n return;\n }\n }\n\n /**\n * Internal\n */\n private gotLocalIceCandidate = (event: RTCPeerConnectionIceEvent): void => {\n if (event.candidate) {\n if (this.candidatesEnded) {\n logger.warn(\n `Call ${this.callId} gotLocalIceCandidate() got candidate after candidates have ended - ignoring!`,\n );\n return;\n }\n\n logger.debug(`Call ${this.callId} got local ICE ${event.candidate.sdpMid} ${event.candidate.candidate}`);\n\n if (this.callHasEnded()) return;\n\n // As with the offer, note we need to make a copy of this object, not\n // pass the original: that broke in Chrome ~m43.\n if (event.candidate.candidate === \"\") {\n this.queueCandidate(null);\n } else {\n this.queueCandidate(event.candidate);\n }\n }\n };\n\n private onIceGatheringStateChange = (event: Event): void => {\n logger.debug(\n `Call ${this.callId} onIceGatheringStateChange() ice gathering state changed to ${\n this.peerConn!.iceGatheringState\n }`,\n );\n if (this.peerConn?.iceGatheringState === \"complete\") {\n this.queueCandidate(null);\n }\n };\n\n public async onRemoteIceCandidatesReceived(ev: MatrixEvent): Promise {\n if (this.callHasEnded()) {\n //debuglog(\"Ignoring remote ICE candidate because call has ended\");\n return;\n }\n\n const content = ev.getContent();\n const candidates = content.candidates;\n if (!candidates) {\n logger.info(\n `Call ${this.callId} onRemoteIceCandidatesReceived() ignoring candidates event with no candidates!`,\n );\n return;\n }\n\n const fromPartyId = content.version === 0 ? null : content.party_id || null;\n\n if (this.opponentPartyId === undefined) {\n // we haven't picked an opponent yet so save the candidates\n if (fromPartyId) {\n logger.info(\n `Call ${this.callId} onRemoteIceCandidatesReceived() buffering ${candidates.length} candidates until we pick an opponent`,\n );\n const bufferedCandidates = this.remoteCandidateBuffer.get(fromPartyId) || [];\n bufferedCandidates.push(...candidates);\n this.remoteCandidateBuffer.set(fromPartyId, bufferedCandidates);\n }\n return;\n }\n\n if (!this.partyIdMatches(content)) {\n logger.info(\n `Call ${this.callId} onRemoteIceCandidatesReceived() ignoring candidates from party ID ${content.party_id}: we have chosen party ID ${this.opponentPartyId}`,\n );\n\n return;\n }\n\n await this.addIceCandidates(candidates);\n }\n\n /**\n * Used by MatrixClient.\n */\n public async onAnswerReceived(event: MatrixEvent): Promise {\n const content = event.getContent();\n logger.debug(`Call ${this.callId} onAnswerReceived() running (hangupParty=${content.party_id})`);\n\n if (this.callHasEnded()) {\n logger.debug(`Call ${this.callId} onAnswerReceived() ignoring answer because call has ended`);\n return;\n }\n\n if (this.opponentPartyId !== undefined) {\n logger.info(\n `Call ${this.callId} onAnswerReceived() ignoring answer from party ID ${content.party_id}: we already have an answer/reject from ${this.opponentPartyId}`,\n );\n return;\n }\n\n this.chooseOpponent(event);\n await this.addBufferedIceCandidates();\n\n this.state = CallState.Connecting;\n\n const sdpStreamMetadata = content[SDPStreamMetadataKey];\n if (sdpStreamMetadata) {\n this.updateRemoteSDPStreamMetadata(sdpStreamMetadata);\n } else {\n logger.warn(\n `Call ${this.callId} onAnswerReceived() did not get any SDPStreamMetadata! Can not send/receive multiple streams`,\n );\n }\n\n try {\n await this.peerConn!.setRemoteDescription(content.answer);\n } catch (e) {\n logger.debug(`Call ${this.callId} onAnswerReceived() failed to set remote description`, e);\n this.terminate(CallParty.Local, CallErrorCode.SetRemoteDescription, false);\n return;\n }\n\n // If the answer we selected has a party_id, send a select_answer event\n // We do this after setting the remote description since otherwise we'd block\n // call setup on it\n if (this.opponentPartyId !== null) {\n try {\n await this.sendVoipEvent(EventType.CallSelectAnswer, {\n selected_party_id: this.opponentPartyId,\n });\n } catch (err) {\n // This isn't fatal, and will just mean that if another party has raced to answer\n // the call, they won't know they got rejected, so we carry on & don't retry.\n logger.warn(`Call ${this.callId} onAnswerReceived() failed to send select_answer event`, err);\n }\n }\n }\n\n public async onSelectAnswerReceived(event: MatrixEvent): Promise {\n if (this.direction !== CallDirection.Inbound) {\n logger.warn(\n `Call ${this.callId} onSelectAnswerReceived() got select_answer for an outbound call: ignoring`,\n );\n return;\n }\n\n const selectedPartyId = event.getContent().selected_party_id;\n\n if (selectedPartyId === undefined || selectedPartyId === null) {\n logger.warn(\n `Call ${this.callId} onSelectAnswerReceived() got nonsensical select_answer with null/undefined selected_party_id: ignoring`,\n );\n return;\n }\n\n if (selectedPartyId !== this.ourPartyId) {\n logger.info(\n `Call ${this.callId} onSelectAnswerReceived() got select_answer for party ID ${selectedPartyId}: we are party ID ${this.ourPartyId}.`,\n );\n // The other party has picked somebody else's answer\n await this.terminate(CallParty.Remote, CallErrorCode.AnsweredElsewhere, true);\n }\n }\n\n public async onNegotiateReceived(event: MatrixEvent): Promise {\n const content = event.getContent();\n const description = content.description;\n if (!description || !description.sdp || !description.type) {\n logger.info(`Call ${this.callId} onNegotiateReceived() ignoring invalid m.call.negotiate event`);\n return;\n }\n // Politeness always follows the direction of the call: in a glare situation,\n // we pick either the inbound or outbound call, so one side will always be\n // inbound and one outbound\n const polite = this.direction === CallDirection.Inbound;\n\n // Here we follow the perfect negotiation logic from\n // https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Perfect_negotiation\n const offerCollision =\n description.type === \"offer\" && (this.makingOffer || this.peerConn!.signalingState !== \"stable\");\n\n this.ignoreOffer = !polite && offerCollision;\n if (this.ignoreOffer) {\n logger.info(\n `Call ${this.callId} onNegotiateReceived() ignoring colliding negotiate event because we're impolite`,\n );\n return;\n }\n\n const prevLocalOnHold = this.isLocalOnHold();\n\n const sdpStreamMetadata = content[SDPStreamMetadataKey];\n if (sdpStreamMetadata) {\n this.updateRemoteSDPStreamMetadata(sdpStreamMetadata);\n } else {\n logger.warn(\n `Call ${this.callId} onNegotiateReceived() received negotiation event without SDPStreamMetadata!`,\n );\n }\n\n try {\n await this.peerConn!.setRemoteDescription(description);\n\n if (description.type === \"offer\") {\n let answer: RTCSessionDescriptionInit;\n try {\n this.getRidOfRTXCodecs();\n answer = await this.createAnswer();\n } catch (err) {\n logger.debug(`Call ${this.callId} onNegotiateReceived() failed to create answer: `, err);\n this.terminate(CallParty.Local, CallErrorCode.CreateAnswer, true);\n return;\n }\n\n await this.peerConn!.setLocalDescription(answer);\n\n this.sendVoipEvent(EventType.CallNegotiate, {\n description: this.peerConn!.localDescription?.toJSON(),\n [SDPStreamMetadataKey]: this.getLocalSDPStreamMetadata(true),\n });\n }\n } catch (err) {\n logger.warn(`Call ${this.callId} onNegotiateReceived() failed to complete negotiation`, err);\n }\n\n const newLocalOnHold = this.isLocalOnHold();\n if (prevLocalOnHold !== newLocalOnHold) {\n this.emit(CallEvent.LocalHoldUnhold, newLocalOnHold, this);\n // also this one for backwards compat\n this.emit(CallEvent.HoldUnhold, newLocalOnHold);\n }\n }\n\n private updateRemoteSDPStreamMetadata(metadata: SDPStreamMetadata): void {\n this.remoteSDPStreamMetadata = utils.recursivelyAssign(this.remoteSDPStreamMetadata || {}, metadata, true);\n for (const feed of this.getRemoteFeeds()) {\n const streamId = feed.stream.id;\n const metadata = this.remoteSDPStreamMetadata![streamId];\n\n feed.setAudioVideoMuted(metadata?.audio_muted, metadata?.video_muted);\n feed.purpose = this.remoteSDPStreamMetadata![streamId]?.purpose;\n }\n }\n\n public onSDPStreamMetadataChangedReceived(event: MatrixEvent): void {\n const content = event.getContent();\n const metadata = content[SDPStreamMetadataKey];\n this.updateRemoteSDPStreamMetadata(metadata);\n }\n\n public async onAssertedIdentityReceived(event: MatrixEvent): Promise {\n const content = event.getContent();\n if (!content.asserted_identity) return;\n\n this.remoteAssertedIdentity = {\n id: content.asserted_identity.id,\n displayName: content.asserted_identity.display_name,\n };\n this.emit(CallEvent.AssertedIdentityChanged, this);\n }\n\n public callHasEnded(): boolean {\n // This exists as workaround to typescript trying to be clever and erroring\n // when putting if (this.state === CallState.Ended) return; twice in the same\n // function, even though that function is async.\n return this.state === CallState.Ended;\n }\n\n private queueGotLocalOffer(): void {\n // Ensure only one negotiate/answer event is being processed at a time.\n if (this.responsePromiseChain) {\n this.responsePromiseChain = this.responsePromiseChain.then(() => this.wrappedGotLocalOffer());\n } else {\n this.responsePromiseChain = this.wrappedGotLocalOffer();\n }\n }\n\n private async wrappedGotLocalOffer(): Promise {\n this.makingOffer = true;\n try {\n // XXX: in what situations do we believe gotLocalOffer actually throws? It appears\n // to handle most of its exceptions itself and terminate the call. I'm not entirely\n // sure it would ever throw, so I can't add a test for these lines.\n // Also the tense is different between \"gotLocalOffer\" and \"getLocalOfferFailed\" so\n // it's not entirely clear whether getLocalOfferFailed is just misnamed or whether\n // they've been cross-polinated somehow at some point.\n await this.gotLocalOffer();\n } catch (e) {\n this.getLocalOfferFailed(e as Error);\n return;\n } finally {\n this.makingOffer = false;\n }\n }\n\n private async gotLocalOffer(): Promise {\n logger.debug(`Call ${this.callId} gotLocalOffer() running`);\n\n if (this.callHasEnded()) {\n logger.debug(\n `Call ${this.callId} gotLocalOffer() ignoring newly created offer because the call has ended\"`,\n );\n return;\n }\n\n let offer: RTCSessionDescriptionInit;\n try {\n this.getRidOfRTXCodecs();\n offer = await this.createOffer();\n } catch (err) {\n logger.debug(`Call ${this.callId} gotLocalOffer() failed to create offer: `, err);\n this.terminate(CallParty.Local, CallErrorCode.CreateOffer, true);\n return;\n }\n\n try {\n await this.peerConn!.setLocalDescription(offer);\n } catch (err) {\n logger.debug(`Call ${this.callId} gotLocalOffer() error setting local description!`, err);\n this.terminate(CallParty.Local, CallErrorCode.SetLocalDescription, true);\n return;\n }\n\n if (this.peerConn!.iceGatheringState === \"gathering\") {\n // Allow a short time for initial candidates to be gathered\n await new Promise((resolve) => {\n setTimeout(resolve, 200);\n });\n }\n\n if (this.callHasEnded()) return;\n\n const eventType = this.state === CallState.CreateOffer ? EventType.CallInvite : EventType.CallNegotiate;\n\n const content = {\n lifetime: CALL_TIMEOUT_MS,\n } as MCallInviteNegotiate;\n\n if (eventType === EventType.CallInvite && this.invitee) {\n content.invitee = this.invitee;\n }\n\n // clunky because TypeScript can't follow the types through if we use an expression as the key\n if (this.state === CallState.CreateOffer) {\n content.offer = this.peerConn!.localDescription?.toJSON();\n } else {\n content.description = this.peerConn!.localDescription?.toJSON();\n }\n\n content.capabilities = {\n \"m.call.transferee\": this.client.supportsCallTransfer,\n \"m.call.dtmf\": false,\n };\n\n content[SDPStreamMetadataKey] = this.getLocalSDPStreamMetadata(true);\n\n // Get rid of any candidates waiting to be sent: they'll be included in the local\n // description we just got and will send in the offer.\n const discardCount = this.discardDuplicateCandidates();\n logger.info(\n `Call ${this.callId} gotLocalOffer() discarding ${discardCount} candidates that will be sent in offer`,\n );\n\n try {\n await this.sendVoipEvent(eventType, content);\n } catch (error) {\n logger.error(`Call ${this.callId} gotLocalOffer() failed to send invite`, error);\n if (error instanceof MatrixError && error.event) this.client.cancelPendingEvent(error.event);\n\n let code = CallErrorCode.SignallingFailed;\n let message = \"Signalling failed\";\n if (this.state === CallState.CreateOffer) {\n code = CallErrorCode.SendInvite;\n message = \"Failed to send invite\";\n }\n if ((error).name == \"UnknownDeviceError\") {\n code = CallErrorCode.UnknownDevices;\n message = \"Unknown devices present in the room\";\n }\n\n this.emit(CallEvent.Error, new CallError(code, message, error), this);\n this.terminate(CallParty.Local, code, false);\n\n // no need to carry on & send the candidate queue, but we also\n // don't want to rethrow the error\n return;\n }\n\n this.sendCandidateQueue();\n if (this.state === CallState.CreateOffer) {\n this.inviteOrAnswerSent = true;\n this.state = CallState.InviteSent;\n this.inviteTimeout = setTimeout(() => {\n this.inviteTimeout = undefined;\n if (this.state === CallState.InviteSent) {\n this.hangup(CallErrorCode.InviteTimeout, false);\n }\n }, CALL_TIMEOUT_MS);\n }\n }\n\n private getLocalOfferFailed = (err: Error): void => {\n logger.error(`Call ${this.callId} getLocalOfferFailed() running`, err);\n\n this.emit(\n CallEvent.Error,\n new CallError(CallErrorCode.LocalOfferFailed, \"Failed to get local offer!\", err),\n this,\n );\n this.terminate(CallParty.Local, CallErrorCode.LocalOfferFailed, false);\n };\n\n private getUserMediaFailed = (err: Error): void => {\n if (this.successor) {\n this.successor.getUserMediaFailed(err);\n return;\n }\n\n logger.warn(`Call ${this.callId} getUserMediaFailed() failed to get user media - ending call`, err);\n\n this.emit(\n CallEvent.Error,\n new CallError(\n CallErrorCode.NoUserMedia,\n \"Couldn't start capturing media! Is your microphone set up and \" + \"does this app have permission?\",\n err,\n ),\n this,\n );\n this.terminate(CallParty.Local, CallErrorCode.NoUserMedia, false);\n };\n\n private onIceConnectionStateChanged = (): void => {\n if (this.callHasEnded()) {\n return; // because ICE can still complete as we're ending the call\n }\n logger.debug(\n `Call ${this.callId} onIceConnectionStateChanged() running (state=${this.peerConn?.iceConnectionState})`,\n );\n\n // ideally we'd consider the call to be connected when we get media but\n // chrome doesn't implement any of the 'onstarted' events yet\n if ([\"connected\", \"completed\"].includes(this.peerConn?.iceConnectionState ?? \"\")) {\n clearTimeout(this.iceDisconnectedTimeout);\n this.iceDisconnectedTimeout = undefined;\n this.state = CallState.Connected;\n\n if (!this.callLengthInterval && !this.callStartTime) {\n this.callStartTime = Date.now();\n\n this.callLengthInterval = setInterval(() => {\n this.emit(CallEvent.LengthChanged, Math.round((Date.now() - this.callStartTime!) / 1000), this);\n }, CALL_LENGTH_INTERVAL);\n }\n } else if (this.peerConn?.iceConnectionState == \"failed\") {\n // Firefox for Android does not yet have support for restartIce()\n // (the types say it's always defined though, so we have to cast\n // to prevent typescript from warning).\n if (this.peerConn?.restartIce as (() => void) | null) {\n this.candidatesEnded = false;\n this.peerConn!.restartIce();\n } else {\n logger.info(\n `Call ${this.callId} onIceConnectionStateChanged() hanging up call (ICE failed and no ICE restart method)`,\n );\n this.hangup(CallErrorCode.IceFailed, false);\n }\n } else if (this.peerConn?.iceConnectionState == \"disconnected\") {\n this.iceDisconnectedTimeout = setTimeout(() => {\n logger.info(\n `Call ${this.callId} onIceConnectionStateChanged() hanging up call (ICE disconnected for too long)`,\n );\n this.hangup(CallErrorCode.IceFailed, false);\n }, ICE_DISCONNECTED_TIMEOUT);\n this.state = CallState.Connecting;\n }\n\n // In PTT mode, override feed status to muted when we lose connection to\n // the peer, since we don't want to block the line if they're not saying anything.\n // Experimenting in Chrome, this happens after 5 or 6 seconds, which is probably\n // fast enough.\n if (this.isPtt && [\"failed\", \"disconnected\"].includes(this.peerConn!.iceConnectionState)) {\n for (const feed of this.getRemoteFeeds()) {\n feed.setAudioVideoMuted(true, true);\n }\n }\n };\n\n private onSignallingStateChanged = (): void => {\n logger.debug(`Call ${this.callId} onSignallingStateChanged() running (state=${this.peerConn?.signalingState})`);\n };\n\n private onTrack = (ev: RTCTrackEvent): void => {\n if (ev.streams.length === 0) {\n logger.warn(\n `Call ${this.callId} onTrack() called with streamless track streamless (kind=${ev.track.kind})`,\n );\n return;\n }\n\n const stream = ev.streams[0];\n this.pushRemoteFeed(stream);\n\n if (!this.removeTrackListeners.has(stream)) {\n const onRemoveTrack = (): void => {\n if (stream.getTracks().length === 0) {\n logger.info(`Call ${this.callId} onTrack() removing track (streamId=${stream.id})`);\n this.deleteFeedByStream(stream);\n stream.removeEventListener(\"removetrack\", onRemoveTrack);\n this.removeTrackListeners.delete(stream);\n }\n };\n stream.addEventListener(\"removetrack\", onRemoveTrack);\n this.removeTrackListeners.set(stream, onRemoveTrack);\n }\n };\n\n private onDataChannel = (ev: RTCDataChannelEvent): void => {\n this.emit(CallEvent.DataChannel, ev.channel, this);\n };\n\n /**\n * This method removes all video/rtx codecs from screensharing video\n * transceivers. This is necessary since they can cause problems. Without\n * this the following steps should produce an error:\n * Chromium calls Firefox\n * Firefox answers\n * Firefox starts screen-sharing\n * Chromium starts screen-sharing\n * Call crashes for Chromium with:\n * [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.\n * [96685:23:0518/162603.933377:ERROR:webrtc_video_engine.cc(1171)] GetChangedRecvParameters called without any video codecs.\n * [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)\n */\n private getRidOfRTXCodecs(): void {\n // RTCRtpReceiver.getCapabilities and RTCRtpSender.getCapabilities don't seem to be supported on FF\n if (!RTCRtpReceiver.getCapabilities || !RTCRtpSender.getCapabilities) return;\n\n const recvCodecs = RTCRtpReceiver.getCapabilities(\"video\")!.codecs;\n const sendCodecs = RTCRtpSender.getCapabilities(\"video\")!.codecs;\n const codecs = [...sendCodecs, ...recvCodecs];\n\n for (const codec of codecs) {\n if (codec.mimeType === \"video/rtx\") {\n const rtxCodecIndex = codecs.indexOf(codec);\n codecs.splice(rtxCodecIndex, 1);\n }\n }\n\n const screenshareVideoTransceiver = this.transceivers.get(\n getTransceiverKey(SDPStreamMetadataPurpose.Screenshare, \"video\"),\n );\n if (screenshareVideoTransceiver) screenshareVideoTransceiver.setCodecPreferences(codecs);\n }\n\n private onNegotiationNeeded = async (): Promise => {\n logger.info(`Call ${this.callId} onNegotiationNeeded() negotiation is needed!`);\n\n if (this.state !== CallState.CreateOffer && this.opponentVersion === 0) {\n logger.info(\n `Call ${this.callId} onNegotiationNeeded() opponent does not support renegotiation: ignoring negotiationneeded event`,\n );\n return;\n }\n\n this.queueGotLocalOffer();\n };\n\n public onHangupReceived = (msg: MCallHangupReject): void => {\n logger.debug(`Call ${this.callId} onHangupReceived() running`);\n\n // party ID must match (our chosen partner hanging up the call) or be undefined (we haven't chosen\n // a partner yet but we're treating the hangup as a reject as per VoIP v0)\n if (this.partyIdMatches(msg) || this.state === CallState.Ringing) {\n // default reason is user_hangup\n this.terminate(CallParty.Remote, msg.reason || CallErrorCode.UserHangup, true);\n } else {\n logger.info(\n `Call ${this.callId} onHangupReceived() ignoring message from party ID ${msg.party_id}: our partner is ${this.opponentPartyId}`,\n );\n }\n };\n\n public onRejectReceived = (msg: MCallHangupReject): void => {\n logger.debug(`Call ${this.callId} onRejectReceived() running`);\n\n // No need to check party_id for reject because if we'd received either\n // an answer or reject, we wouldn't be in state InviteSent\n\n const shouldTerminate =\n // reject events also end the call if it's ringing: it's another of\n // our devices rejecting the call.\n [CallState.InviteSent, CallState.Ringing].includes(this.state) ||\n // also if we're in the init state and it's an inbound call, since\n // this means we just haven't entered the ringing state yet\n (this.state === CallState.Fledgling && this.direction === CallDirection.Inbound);\n\n if (shouldTerminate) {\n this.terminate(CallParty.Remote, msg.reason || CallErrorCode.UserHangup, true);\n } else {\n logger.debug(`Call ${this.callId} onRejectReceived() called in wrong state (state=${this.state})`);\n }\n };\n\n public onAnsweredElsewhere = (msg: MCallAnswer): void => {\n logger.debug(`Call ${this.callId} onAnsweredElsewhere() running`);\n this.terminate(CallParty.Remote, CallErrorCode.AnsweredElsewhere, true);\n };\n\n /**\n * @internal\n */\n private async sendVoipEvent(eventType: string, content: object): Promise {\n const realContent = Object.assign({}, content, {\n version: VOIP_PROTO_VERSION,\n call_id: this.callId,\n party_id: this.ourPartyId,\n conf_id: this.groupCallId,\n });\n\n if (this.opponentDeviceId) {\n const toDeviceSeq = this.toDeviceSeq++;\n const content = {\n ...realContent,\n device_id: this.client.deviceId,\n sender_session_id: this.client.getSessionId(),\n dest_session_id: this.opponentSessionId,\n seq: toDeviceSeq,\n [ToDeviceMessageId]: uuidv4(),\n };\n\n this.emit(\n CallEvent.SendVoipEvent,\n {\n type: \"toDevice\",\n eventType,\n userId: this.invitee || this.getOpponentMember()?.userId,\n opponentDeviceId: this.opponentDeviceId,\n content,\n },\n this,\n );\n\n const userId = this.invitee || this.getOpponentMember()!.userId;\n if (this.client.getUseE2eForGroupCall()) {\n if (!this.opponentDeviceInfo) {\n logger.warn(`Call ${this.callId} sendVoipEvent() failed: we do not have opponentDeviceInfo`);\n return;\n }\n\n await this.client.encryptAndSendToDevices(\n [\n {\n userId,\n deviceInfo: this.opponentDeviceInfo,\n },\n ],\n {\n type: eventType,\n content,\n },\n );\n } else {\n await this.client.sendToDevice(\n eventType,\n new Map([[userId, new Map([[this.opponentDeviceId, content]])]]),\n );\n }\n } else {\n this.emit(\n CallEvent.SendVoipEvent,\n {\n type: \"sendEvent\",\n eventType,\n roomId: this.roomId,\n content: realContent,\n userId: this.invitee || this.getOpponentMember()?.userId,\n },\n this,\n );\n\n await this.client.sendEvent(this.roomId!, eventType, realContent);\n }\n }\n\n /**\n * Queue a candidate to be sent\n * @param content - The candidate to queue up, or null if candidates have finished being generated\n * and end-of-candidates should be signalled\n */\n private queueCandidate(content: RTCIceCandidate | null): void {\n // We partially de-trickle candidates by waiting for `delay` before sending them\n // amalgamated, in order to avoid sending too many m.call.candidates events and hitting\n // rate limits in Matrix.\n // In practice, it'd be better to remove rate limits for m.call.*\n\n // N.B. this deliberately lets you queue and send blank candidates, which MSC2746\n // currently proposes as the way to indicate that candidate gathering is complete.\n // This will hopefully be changed to an explicit rather than implicit notification\n // shortly.\n if (content) {\n this.candidateSendQueue.push(content);\n } else {\n this.candidatesEnded = true;\n }\n\n // Don't send the ICE candidates yet if the call is in the ringing state: this\n // means we tried to pick (ie. started generating candidates) and then failed to\n // send the answer and went back to the ringing state. Queue up the candidates\n // to send if we successfully send the answer.\n // Equally don't send if we haven't yet sent the answer because we can send the\n // first batch of candidates along with the answer\n if (this.state === CallState.Ringing || !this.inviteOrAnswerSent) return;\n\n // MSC2746 recommends these values (can be quite long when calling because the\n // callee will need a while to answer the call)\n const delay = this.direction === CallDirection.Inbound ? 500 : 2000;\n\n if (this.candidateSendTries === 0) {\n setTimeout(() => {\n this.sendCandidateQueue();\n }, delay);\n }\n }\n\n // Discard all non-end-of-candidates messages\n // Return the number of candidate messages that were discarded.\n // Call this method before sending an invite or answer message\n private discardDuplicateCandidates(): number {\n let discardCount = 0;\n const newQueue: RTCIceCandidate[] = [];\n\n for (let i = 0; i < this.candidateSendQueue.length; i++) {\n const candidate = this.candidateSendQueue[i];\n if (candidate.candidate === \"\") {\n newQueue.push(candidate);\n } else {\n discardCount++;\n }\n }\n\n this.candidateSendQueue = newQueue;\n\n return discardCount;\n }\n\n /*\n * Transfers this call to another user\n */\n public async transfer(targetUserId: string): Promise {\n // Fetch the target user's global profile info: their room avatar / displayname\n // could be different in whatever room we share with them.\n const profileInfo = await this.client.getProfileInfo(targetUserId);\n\n const replacementId = genCallID();\n\n const body = {\n replacement_id: genCallID(),\n target_user: {\n id: targetUserId,\n display_name: profileInfo.displayname,\n avatar_url: profileInfo.avatar_url,\n },\n create_call: replacementId,\n } as MCallReplacesEvent;\n\n await this.sendVoipEvent(EventType.CallReplaces, body);\n\n await this.terminate(CallParty.Local, CallErrorCode.Transferred, true);\n }\n\n /*\n * Transfers this call to the target call, effectively 'joining' the\n * two calls (so the remote parties on each call are connected together).\n */\n public async transferToCall(transferTargetCall: MatrixCall): Promise {\n const targetUserId = transferTargetCall.getOpponentMember()?.userId;\n const targetProfileInfo = targetUserId ? await this.client.getProfileInfo(targetUserId) : undefined;\n const opponentUserId = this.getOpponentMember()?.userId;\n const transfereeProfileInfo = opponentUserId ? await this.client.getProfileInfo(opponentUserId) : undefined;\n\n const newCallId = genCallID();\n\n const bodyToTransferTarget = {\n // the replacements on each side have their own ID, and it's distinct from the\n // ID of the new call (but we can use the same function to generate it)\n replacement_id: genCallID(),\n target_user: {\n id: opponentUserId,\n display_name: transfereeProfileInfo?.displayname,\n avatar_url: transfereeProfileInfo?.avatar_url,\n },\n await_call: newCallId,\n } as MCallReplacesEvent;\n\n await transferTargetCall.sendVoipEvent(EventType.CallReplaces, bodyToTransferTarget);\n\n const bodyToTransferee = {\n replacement_id: genCallID(),\n target_user: {\n id: targetUserId,\n display_name: targetProfileInfo?.displayname,\n avatar_url: targetProfileInfo?.avatar_url,\n },\n create_call: newCallId,\n } as MCallReplacesEvent;\n\n await this.sendVoipEvent(EventType.CallReplaces, bodyToTransferee);\n\n await this.terminate(CallParty.Local, CallErrorCode.Transferred, true);\n await transferTargetCall.terminate(CallParty.Local, CallErrorCode.Transferred, true);\n }\n\n private async terminate(hangupParty: CallParty, hangupReason: CallErrorCode, shouldEmit: boolean): Promise {\n if (this.callHasEnded()) return;\n\n this.hangupParty = hangupParty;\n this.hangupReason = hangupReason;\n this.state = CallState.Ended;\n\n if (this.inviteTimeout) {\n clearTimeout(this.inviteTimeout);\n this.inviteTimeout = undefined;\n }\n if (this.iceDisconnectedTimeout !== undefined) {\n clearTimeout(this.iceDisconnectedTimeout);\n this.iceDisconnectedTimeout = undefined;\n }\n if (this.callLengthInterval) {\n clearInterval(this.callLengthInterval);\n this.callLengthInterval = undefined;\n }\n if (this.stopVideoTrackTimer !== undefined) {\n clearTimeout(this.stopVideoTrackTimer);\n this.stopVideoTrackTimer = undefined;\n }\n\n for (const [stream, listener] of this.removeTrackListeners) {\n stream.removeEventListener(\"removetrack\", listener);\n }\n this.removeTrackListeners.clear();\n\n this.callStatsAtEnd = await this.collectCallStats();\n\n // Order is important here: first we stopAllMedia() and only then we can deleteAllFeeds()\n this.stopAllMedia();\n this.deleteAllFeeds();\n\n if (this.peerConn && this.peerConn.signalingState !== \"closed\") {\n this.peerConn.close();\n }\n this.stats?.removeStatsReportGatherer(this.callId);\n\n if (shouldEmit) {\n this.emit(CallEvent.Hangup, this);\n }\n\n this.client.callEventHandler!.calls.delete(this.callId);\n }\n\n private stopAllMedia(): void {\n logger.debug(`Call ${this.callId} stopAllMedia() running`);\n\n for (const feed of this.feeds) {\n // Slightly awkward as local feed need to go via the correct method on\n // the MediaHandler so they get removed from MediaHandler (remote tracks\n // don't)\n // NB. We clone local streams when passing them to individual calls in a group\n // call, so we can (and should) stop the clones once we no longer need them:\n // the other clones will continue fine.\n if (feed.isLocal() && feed.purpose === SDPStreamMetadataPurpose.Usermedia) {\n this.client.getMediaHandler().stopUserMediaStream(feed.stream);\n } else if (feed.isLocal() && feed.purpose === SDPStreamMetadataPurpose.Screenshare) {\n this.client.getMediaHandler().stopScreensharingStream(feed.stream);\n } else if (!feed.isLocal()) {\n logger.debug(`Call ${this.callId} stopAllMedia() stopping stream (streamId=${feed.stream.id})`);\n for (const track of feed.stream.getTracks()) {\n track.stop();\n }\n }\n }\n }\n\n private checkForErrorListener(): void {\n if (this.listeners(EventEmitterEvents.Error).length === 0) {\n throw new Error(\"You MUST attach an error listener using call.on('error', function() {})\");\n }\n }\n\n private async sendCandidateQueue(): Promise {\n if (this.candidateSendQueue.length === 0 || this.callHasEnded()) {\n return;\n }\n\n const candidates = this.candidateSendQueue;\n this.candidateSendQueue = [];\n ++this.candidateSendTries;\n const content = { candidates: candidates.map((candidate) => candidate.toJSON()) };\n if (this.candidatesEnded) {\n // If there are no more candidates, signal this by adding an empty string candidate\n content.candidates.push({\n candidate: \"\",\n });\n }\n logger.debug(`Call ${this.callId} sendCandidateQueue() attempting to send ${candidates.length} candidates`);\n try {\n await this.sendVoipEvent(EventType.CallCandidates, content);\n // reset our retry count if we have successfully sent our candidates\n // otherwise queueCandidate() will refuse to try to flush the queue\n this.candidateSendTries = 0;\n\n // Try to send candidates again just in case we received more candidates while sending.\n this.sendCandidateQueue();\n } catch (error) {\n // don't retry this event: we'll send another one later as we might\n // have more candidates by then.\n if (error instanceof MatrixError && error.event) this.client.cancelPendingEvent(error.event);\n\n // put all the candidates we failed to send back in the queue\n this.candidateSendQueue.push(...candidates);\n\n if (this.candidateSendTries > 5) {\n logger.debug(\n `Call ${this.callId} sendCandidateQueue() failed to send candidates on attempt ${this.candidateSendTries}. Giving up on this call.`,\n error,\n );\n\n const code = CallErrorCode.SignallingFailed;\n const message = \"Signalling failed\";\n\n this.emit(CallEvent.Error, new CallError(code, message, error), this);\n this.hangup(code, false);\n\n return;\n }\n\n const delayMs = 500 * Math.pow(2, this.candidateSendTries);\n ++this.candidateSendTries;\n logger.debug(\n `Call ${this.callId} sendCandidateQueue() failed to send candidates. Retrying in ${delayMs}ms`,\n error,\n );\n setTimeout(() => {\n this.sendCandidateQueue();\n }, delayMs);\n }\n }\n\n /**\n * Place a call to this room.\n * @throws if you have not specified a listener for 'error' events.\n * @throws if have passed audio=false.\n */\n public async placeCall(audio: boolean, video: boolean): Promise {\n if (!audio) {\n throw new Error(\"You CANNOT start a call without audio\");\n }\n this.state = CallState.WaitLocalMedia;\n\n try {\n const stream = await this.client.getMediaHandler().getUserMediaStream(audio, video);\n\n // make sure all the tracks are enabled (same as pushNewLocalFeed -\n // we probably ought to just have one code path for adding streams)\n setTracksEnabled(stream.getAudioTracks(), true);\n setTracksEnabled(stream.getVideoTracks(), true);\n\n const callFeed = new CallFeed({\n client: this.client,\n roomId: this.roomId,\n userId: this.client.getUserId()!,\n deviceId: this.client.getDeviceId() ?? undefined,\n stream,\n purpose: SDPStreamMetadataPurpose.Usermedia,\n audioMuted: false,\n videoMuted: false,\n });\n await this.placeCallWithCallFeeds([callFeed]);\n } catch (e) {\n this.getUserMediaFailed(e);\n return;\n }\n }\n\n /**\n * Place a call to this room with call feed.\n * @param callFeeds - to use\n * @throws if you have not specified a listener for 'error' events.\n * @throws if have passed audio=false.\n */\n public async placeCallWithCallFeeds(callFeeds: CallFeed[], requestScreenshareFeed = false): Promise {\n this.checkForErrorListener();\n this.direction = CallDirection.Outbound;\n\n await this.initOpponentCrypto();\n\n // XXX Find a better way to do this\n this.client.callEventHandler!.calls.set(this.callId, this);\n\n // make sure we have valid turn creds. Unless something's gone wrong, it should\n // poll and keep the credentials valid so this should be instant.\n const haveTurnCreds = await this.client.checkTurnServers();\n if (!haveTurnCreds) {\n logger.warn(\n `Call ${this.callId} placeCallWithCallFeeds() failed to get TURN credentials! Proceeding with call anyway...`,\n );\n }\n\n // create the peer connection now so it can be gathering candidates while we get user\n // media (assuming a candidate pool size is configured)\n this.peerConn = this.createPeerConnection();\n this.gotCallFeedsForInvite(callFeeds, requestScreenshareFeed);\n }\n\n private createPeerConnection(): RTCPeerConnection {\n const pc = new window.RTCPeerConnection({\n iceTransportPolicy: this.forceTURN ? \"relay\" : undefined,\n iceServers: this.turnServers,\n iceCandidatePoolSize: this.client.iceCandidatePoolSize,\n bundlePolicy: \"max-bundle\",\n });\n\n // 'connectionstatechange' would be better, but firefox doesn't implement that.\n pc.addEventListener(\"iceconnectionstatechange\", this.onIceConnectionStateChanged);\n pc.addEventListener(\"signalingstatechange\", this.onSignallingStateChanged);\n pc.addEventListener(\"icecandidate\", this.gotLocalIceCandidate);\n pc.addEventListener(\"icegatheringstatechange\", this.onIceGatheringStateChange);\n pc.addEventListener(\"track\", this.onTrack);\n pc.addEventListener(\"negotiationneeded\", this.onNegotiationNeeded);\n pc.addEventListener(\"datachannel\", this.onDataChannel);\n\n this.stats?.addStatsReportGatherer(this.callId, \"unknown\", pc);\n return pc;\n }\n\n private partyIdMatches(msg: MCallBase): boolean {\n // They must either match or both be absent (in which case opponentPartyId will be null)\n // Also we ignore party IDs on the invite/offer if the version is 0, so we must do the same\n // here and use null if the version is 0 (woe betide any opponent sending messages in the\n // same call with different versions)\n const msgPartyId = msg.version === 0 ? null : msg.party_id || null;\n return msgPartyId === this.opponentPartyId;\n }\n\n // Commits to an opponent for the call\n // ev: An invite or answer event\n private chooseOpponent(ev: MatrixEvent): void {\n // I choo-choo-choose you\n const msg = ev.getContent();\n\n logger.debug(`Call ${this.callId} chooseOpponent() running (partyId=${msg.party_id})`);\n\n this.opponentVersion = msg.version;\n if (this.opponentVersion === 0) {\n // set to null to indicate that we've chosen an opponent, but because\n // they're v0 they have no party ID (even if they sent one, we're ignoring it)\n this.opponentPartyId = null;\n } else {\n // set to their party ID, or if they're naughty and didn't send one despite\n // not being v0, set it to null to indicate we picked an opponent with no\n // party ID\n this.opponentPartyId = msg.party_id || null;\n }\n this.opponentCaps = msg.capabilities || ({} as CallCapabilities);\n this.opponentMember = this.client.getRoom(this.roomId)!.getMember(ev.getSender()!) ?? undefined;\n }\n\n private async addBufferedIceCandidates(): Promise {\n const bufferedCandidates = this.remoteCandidateBuffer.get(this.opponentPartyId!);\n if (bufferedCandidates) {\n logger.info(\n `Call ${this.callId} addBufferedIceCandidates() adding ${bufferedCandidates.length} buffered candidates for opponent ${this.opponentPartyId}`,\n );\n await this.addIceCandidates(bufferedCandidates);\n }\n this.remoteCandidateBuffer.clear();\n }\n\n private async addIceCandidates(candidates: RTCIceCandidate[]): Promise {\n for (const candidate of candidates) {\n if (\n (candidate.sdpMid === null || candidate.sdpMid === undefined) &&\n (candidate.sdpMLineIndex === null || candidate.sdpMLineIndex === undefined)\n ) {\n logger.debug(`Call ${this.callId} addIceCandidates() got remote ICE end-of-candidates`);\n } else {\n logger.debug(\n `Call ${this.callId} addIceCandidates() got remote ICE candidate (sdpMid=${candidate.sdpMid}, candidate=${candidate.candidate})`,\n );\n }\n\n try {\n await this.peerConn!.addIceCandidate(candidate);\n } catch (err) {\n if (!this.ignoreOffer) {\n logger.info(`Call ${this.callId} addIceCandidates() failed to add remote ICE candidate`, err);\n }\n }\n }\n }\n\n public get hasPeerConnection(): boolean {\n return Boolean(this.peerConn);\n }\n\n public initStats(stats: GroupCallStats, peerId = \"unknown\"): void {\n this.stats = stats;\n this.stats.start();\n }\n}\n\nexport function setTracksEnabled(tracks: Array, enabled: boolean): void {\n for (const track of tracks) {\n track.enabled = enabled;\n }\n}\n\nexport function supportsMatrixCall(): boolean {\n // typeof prevents Node from erroring on an undefined reference\n if (typeof window === \"undefined\" || typeof document === \"undefined\") {\n // NB. We don't log here as apps try to create a call object as a test for\n // whether calls are supported, so we shouldn't fill the logs up.\n return false;\n }\n\n // Firefox throws on so little as accessing the RTCPeerConnection when operating in a secure mode.\n // There's some information at https://bugzilla.mozilla.org/show_bug.cgi?id=1542616 though the concern\n // is that the browser throwing a SecurityError will brick the client creation process.\n try {\n const supported = Boolean(\n window.RTCPeerConnection ||\n window.RTCSessionDescription ||\n window.RTCIceCandidate ||\n navigator.mediaDevices,\n );\n if (!supported) {\n /* istanbul ignore if */ // Adds a lot of noise to test runs, so disable logging there.\n if (process.env.NODE_ENV !== \"test\") {\n logger.error(\"WebRTC is not supported in this browser / environment\");\n }\n return false;\n }\n } catch (e) {\n logger.error(\"Exception thrown when trying to access WebRTC\", e);\n return false;\n }\n\n return true;\n}\n\n/**\n * DEPRECATED\n * Use client.createCall()\n *\n * Create a new Matrix call for the browser.\n * @param client - The client instance to use.\n * @param roomId - The room the call is in.\n * @param options - DEPRECATED optional options map.\n * @returns the call or null if the browser doesn't support calling.\n */\nexport function createNewMatrixCall(\n client: MatrixClient,\n roomId: string,\n options?: Pick,\n): MatrixCall | null {\n if (!supportsMatrixCall()) return null;\n\n const optionsForceTURN = options ? options.forceTURN : false;\n\n const opts: CallOpts = {\n client: client,\n roomId: roomId,\n invitee: options?.invitee,\n turnServers: client.getTurnServers(),\n // call level options\n forceTURN: client.forceTURN || optionsForceTURN,\n opponentDeviceId: options?.opponentDeviceId,\n opponentSessionId: options?.opponentSessionId,\n groupCallId: options?.groupCallId,\n };\n const call = new MatrixCall(opts);\n\n client.reEmitter.reEmit(call, Object.values(CallEvent));\n\n return call;\n}\n", - "/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixEvent } from \"../models/event\";\nimport { logger } from \"../logger\";\nimport { CallDirection, CallError, CallErrorCode, CallState, createNewMatrixCall, MatrixCall } from \"./call\";\nimport { EventType } from \"../@types/event\";\nimport { ClientEvent, MatrixClient } from \"../client\";\nimport { MCallAnswer, MCallHangupReject } from \"./callEventTypes\";\nimport { GroupCall, GroupCallErrorCode, GroupCallEvent, GroupCallUnknownDeviceError } from \"./groupCall\";\nimport { RoomEvent } from \"../models/room\";\n\n// Don't ring unless we'd be ringing for at least 3 seconds: the user needs some\n// time to press the 'accept' button\nconst RING_GRACE_PERIOD = 3000;\n\nexport enum CallEventHandlerEvent {\n Incoming = \"Call.incoming\",\n}\n\nexport type CallEventHandlerEventHandlerMap = {\n /**\n * Fires whenever an incoming call arrives.\n * @param call - The incoming call.\n * @example\n * ```\n * matrixClient.on(\"Call.incoming\", function(call){\n * call.answer(); // auto-answer\n * });\n * ```\n */\n [CallEventHandlerEvent.Incoming]: (call: MatrixCall) => void;\n};\n\nexport class CallEventHandler {\n // XXX: Most of these are only public because of the tests\n public calls: Map;\n public callEventBuffer: MatrixEvent[];\n public nextSeqByCall: Map = new Map();\n public toDeviceEventBuffers: Map> = new Map();\n\n private client: MatrixClient;\n private candidateEventsByCall: Map>;\n private eventBufferPromiseChain?: Promise;\n\n public constructor(client: MatrixClient) {\n this.client = client;\n this.calls = new Map();\n // The sync code always emits one event at a time, so it will patiently\n // wait for us to finish processing a call invite before delivering the\n // next event, even if that next event is a hangup. We therefore accumulate\n // all our call events and then process them on the 'sync' event, ie.\n // each time a sync has completed. This way, we can avoid emitting incoming\n // call events if we get both the invite and answer/hangup in the same sync.\n // This happens quite often, eg. replaying sync from storage, catchup sync\n // after loading and after we've been offline for a bit.\n this.callEventBuffer = [];\n this.candidateEventsByCall = new Map>();\n }\n\n public start(): void {\n this.client.on(ClientEvent.Sync, this.onSync);\n this.client.on(RoomEvent.Timeline, this.onRoomTimeline);\n this.client.on(ClientEvent.ToDeviceEvent, this.onToDeviceEvent);\n }\n\n public stop(): void {\n this.client.removeListener(ClientEvent.Sync, this.onSync);\n this.client.removeListener(RoomEvent.Timeline, this.onRoomTimeline);\n this.client.removeListener(ClientEvent.ToDeviceEvent, this.onToDeviceEvent);\n }\n\n private onSync = (): void => {\n // Process the current event buffer and start queuing into a new one.\n const currentEventBuffer = this.callEventBuffer;\n this.callEventBuffer = [];\n\n // Ensure correct ordering by only processing this queue after the previous one has finished processing\n if (this.eventBufferPromiseChain) {\n this.eventBufferPromiseChain = this.eventBufferPromiseChain.then(() =>\n this.evaluateEventBuffer(currentEventBuffer),\n );\n } else {\n this.eventBufferPromiseChain = this.evaluateEventBuffer(currentEventBuffer);\n }\n };\n\n private async evaluateEventBuffer(eventBuffer: MatrixEvent[]): Promise {\n await Promise.all(eventBuffer.map((event) => this.client.decryptEventIfNeeded(event)));\n\n const callEvents = eventBuffer.filter((event) => {\n const eventType = event.getType();\n return eventType.startsWith(\"m.call.\") || eventType.startsWith(\"org.matrix.call.\");\n });\n\n const ignoreCallIds = new Set();\n\n // inspect the buffer and mark all calls which have been answered\n // or hung up before passing them to the call event handler.\n for (const event of callEvents) {\n const eventType = event.getType();\n\n if (eventType === EventType.CallAnswer || eventType === EventType.CallHangup) {\n ignoreCallIds.add(event.getContent().call_id);\n }\n }\n\n // Process call events in the order that they were received\n for (const event of callEvents) {\n const eventType = event.getType();\n const callId = event.getContent().call_id;\n\n if (eventType === EventType.CallInvite && ignoreCallIds.has(callId)) {\n // This call has previously been answered or hung up: ignore it\n continue;\n }\n\n try {\n await this.handleCallEvent(event);\n } catch (e) {\n logger.error(\"CallEventHandler evaluateEventBuffer() caught exception handling call event\", e);\n }\n }\n }\n\n private onRoomTimeline = (event: MatrixEvent): void => {\n this.callEventBuffer.push(event);\n };\n\n private onToDeviceEvent = (event: MatrixEvent): void => {\n const content = event.getContent();\n\n if (!content.call_id) {\n this.callEventBuffer.push(event);\n return;\n }\n\n if (!this.nextSeqByCall.has(content.call_id)) {\n this.nextSeqByCall.set(content.call_id, 0);\n }\n\n if (content.seq === undefined) {\n this.callEventBuffer.push(event);\n return;\n }\n\n const nextSeq = this.nextSeqByCall.get(content.call_id) || 0;\n\n if (content.seq !== nextSeq) {\n if (!this.toDeviceEventBuffers.has(content.call_id)) {\n this.toDeviceEventBuffers.set(content.call_id, []);\n }\n\n const buffer = this.toDeviceEventBuffers.get(content.call_id)!;\n const index = buffer.findIndex((e) => e.getContent().seq > content.seq);\n\n if (index === -1) {\n buffer.push(event);\n } else {\n buffer.splice(index, 0, event);\n }\n } else {\n const callId = content.call_id;\n this.callEventBuffer.push(event);\n this.nextSeqByCall.set(callId, content.seq + 1);\n\n const buffer = this.toDeviceEventBuffers.get(callId);\n\n let nextEvent = buffer && buffer.shift();\n\n while (nextEvent && nextEvent.getContent().seq === this.nextSeqByCall.get(callId)) {\n this.callEventBuffer.push(nextEvent);\n this.nextSeqByCall.set(callId, nextEvent.getContent().seq + 1);\n nextEvent = buffer!.shift();\n }\n }\n };\n\n private async handleCallEvent(event: MatrixEvent): Promise {\n this.client.emit(ClientEvent.ReceivedVoipEvent, event);\n\n const content = event.getContent();\n const callRoomId =\n event.getRoomId() || this.client.groupCallEventHandler!.getGroupCallById(content.conf_id)?.room?.roomId;\n const groupCallId = content.conf_id;\n const type = event.getType() as EventType;\n const senderId = event.getSender()!;\n let call = content.call_id ? this.calls.get(content.call_id) : undefined;\n\n let opponentDeviceId: string | undefined;\n\n let groupCall: GroupCall | undefined;\n if (groupCallId) {\n groupCall = this.client.groupCallEventHandler!.getGroupCallById(groupCallId);\n\n if (!groupCall) {\n logger.warn(\n `CallEventHandler handleCallEvent() could not find a group call - ignoring event (groupCallId=${groupCallId}, type=${type})`,\n );\n return;\n }\n\n opponentDeviceId = content.device_id;\n\n if (!opponentDeviceId) {\n logger.warn(\n `CallEventHandler handleCallEvent() could not find a device id - ignoring event (senderId=${senderId})`,\n );\n groupCall.emit(GroupCallEvent.Error, new GroupCallUnknownDeviceError(senderId));\n return;\n }\n\n if (content.dest_session_id !== this.client.getSessionId()) {\n logger.warn(\n \"CallEventHandler handleCallEvent() call event does not match current session id - ignoring\",\n );\n return;\n }\n }\n\n const weSentTheEvent =\n senderId === this.client.credentials.userId &&\n (opponentDeviceId === undefined || opponentDeviceId === this.client.getDeviceId()!);\n\n if (!callRoomId) return;\n\n if (type === EventType.CallInvite) {\n // ignore invites you send\n if (weSentTheEvent) return;\n // expired call\n if (event.getLocalAge() > content.lifetime - RING_GRACE_PERIOD) return;\n // stale/old invite event\n if (call && call.state === CallState.Ended) return;\n\n if (call) {\n logger.warn(\n `CallEventHandler handleCallEvent() already has a call but got an invite - clobbering (callId=${content.call_id})`,\n );\n }\n\n if (content.invitee && content.invitee !== this.client.getUserId()) {\n return; // This invite was meant for another user in the room\n }\n\n const timeUntilTurnCresExpire = (this.client.getTurnServersExpiry() ?? 0) - Date.now();\n logger.info(\n \"CallEventHandler handleCallEvent() current turn creds expire in \" + timeUntilTurnCresExpire + \" ms\",\n );\n call =\n createNewMatrixCall(this.client, callRoomId, {\n forceTURN: this.client.forceTURN,\n opponentDeviceId,\n groupCallId,\n opponentSessionId: content.sender_session_id,\n }) ?? undefined;\n if (!call) {\n logger.log(\n `CallEventHandler handleCallEvent() this client does not support WebRTC (callId=${content.call_id})`,\n );\n // don't hang up the call: there could be other clients\n // connected that do support WebRTC and declining the\n // the call on their behalf would be really annoying.\n return;\n }\n\n call.callId = content.call_id;\n const stats = groupCall?.getGroupCallStats();\n if (stats) {\n call.initStats(stats);\n }\n\n try {\n await call.initWithInvite(event);\n } catch (e) {\n if (e instanceof CallError) {\n if (e.code === GroupCallErrorCode.UnknownDevice) {\n groupCall?.emit(GroupCallEvent.Error, e);\n } else {\n logger.error(e);\n }\n }\n }\n this.calls.set(call.callId, call);\n\n // if we stashed candidate events for that call ID, play them back now\n if (this.candidateEventsByCall.get(call.callId)) {\n for (const ev of this.candidateEventsByCall.get(call.callId)!) {\n call.onRemoteIceCandidatesReceived(ev);\n }\n }\n\n // Were we trying to call that user (room)?\n let existingCall: MatrixCall | undefined;\n for (const thisCall of this.calls.values()) {\n const isCalling = [CallState.WaitLocalMedia, CallState.CreateOffer, CallState.InviteSent].includes(\n thisCall.state,\n );\n\n if (\n call.roomId === thisCall.roomId &&\n thisCall.direction === CallDirection.Outbound &&\n call.getOpponentMember()?.userId === thisCall.invitee &&\n isCalling\n ) {\n existingCall = thisCall;\n break;\n }\n }\n\n if (existingCall) {\n if (existingCall.callId > call.callId) {\n logger.log(\n `CallEventHandler handleCallEvent() detected glare - answering incoming call and canceling outgoing call (incomingId=${call.callId}, outgoingId=${existingCall.callId})`,\n );\n existingCall.replacedBy(call);\n } else {\n logger.log(\n `CallEventHandler handleCallEvent() detected glare - hanging up incoming call (incomingId=${call.callId}, outgoingId=${existingCall.callId})`,\n );\n call.hangup(CallErrorCode.Replaced, true);\n }\n } else {\n this.client.emit(CallEventHandlerEvent.Incoming, call);\n }\n return;\n } else if (type === EventType.CallCandidates) {\n if (weSentTheEvent) return;\n\n if (!call) {\n // store the candidates; we may get a call eventually.\n if (!this.candidateEventsByCall.has(content.call_id)) {\n this.candidateEventsByCall.set(content.call_id, []);\n }\n this.candidateEventsByCall.get(content.call_id)!.push(event);\n } else {\n call.onRemoteIceCandidatesReceived(event);\n }\n return;\n } else if ([EventType.CallHangup, EventType.CallReject].includes(type)) {\n // Note that we also observe our own hangups here so we can see\n // if we've already rejected a call that would otherwise be valid\n if (!call) {\n // if not live, store the fact that the call has ended because\n // we're probably getting events backwards so\n // the hangup will come before the invite\n call =\n createNewMatrixCall(this.client, callRoomId, {\n opponentDeviceId,\n opponentSessionId: content.sender_session_id,\n }) ?? undefined;\n if (call) {\n call.callId = content.call_id;\n call.initWithHangup(event);\n this.calls.set(content.call_id, call);\n }\n } else {\n if (call.state !== CallState.Ended) {\n if (type === EventType.CallHangup) {\n call.onHangupReceived(content as MCallHangupReject);\n } else {\n call.onRejectReceived(content as MCallHangupReject);\n }\n\n // @ts-expect-error typescript thinks the state can't be 'ended' because we're\n // inside the if block where it wasn't, but it could have changed because\n // on[Hangup|Reject]Received are side-effecty.\n if (call.state === CallState.Ended) this.calls.delete(content.call_id);\n }\n }\n return;\n }\n\n // The following events need a call and a peer connection\n if (!call || !call.hasPeerConnection) {\n logger.info(\n `CallEventHandler handleCallEvent() discarding possible call event as we don't have a call (type=${type})`,\n );\n return;\n }\n // Ignore remote echo\n if (event.getContent().party_id === call.ourPartyId) return;\n\n switch (type) {\n case EventType.CallAnswer:\n if (weSentTheEvent) {\n if (call.state === CallState.Ringing) {\n call.onAnsweredElsewhere(content as MCallAnswer);\n }\n } else {\n call.onAnswerReceived(event);\n }\n break;\n case EventType.CallSelectAnswer:\n call.onSelectAnswerReceived(event);\n break;\n\n case EventType.CallNegotiate:\n call.onNegotiateReceived(event);\n break;\n\n case EventType.CallAssertedIdentity:\n case EventType.CallAssertedIdentityPrefix:\n call.onAssertedIdentityReceived(event);\n break;\n\n case EventType.CallSDPStreamMetadataChanged:\n case EventType.CallSDPStreamMetadataChangedPrefix:\n call.onSDPStreamMetadataChangedReceived(event);\n break;\n }\n }\n}\n", - "// allow non-camelcase as these are events type that go onto the wire\n/* eslint-disable camelcase */\n\nimport { CallErrorCode } from \"./call\";\n\n// TODO: Change to \"sdp_stream_metadata\" when MSC3077 is merged\nexport const SDPStreamMetadataKey = \"org.matrix.msc3077.sdp_stream_metadata\";\n\nexport enum SDPStreamMetadataPurpose {\n Usermedia = \"m.usermedia\",\n Screenshare = \"m.screenshare\",\n}\n\nexport interface SDPStreamMetadataObject {\n purpose: SDPStreamMetadataPurpose;\n audio_muted: boolean;\n video_muted: boolean;\n}\n\nexport interface SDPStreamMetadata {\n [key: string]: SDPStreamMetadataObject;\n}\n\nexport interface CallCapabilities {\n \"m.call.transferee\": boolean;\n \"m.call.dtmf\": boolean;\n}\n\nexport interface CallReplacesTarget {\n id: string;\n display_name: string;\n avatar_url: string;\n}\n\nexport interface MCallBase {\n call_id: string;\n version: string | number;\n party_id?: string;\n sender_session_id?: string;\n dest_session_id?: string;\n}\n\nexport interface MCallAnswer extends MCallBase {\n answer: RTCSessionDescription;\n capabilities?: CallCapabilities;\n [SDPStreamMetadataKey]: SDPStreamMetadata;\n}\n\nexport interface MCallSelectAnswer extends MCallBase {\n selected_party_id: string;\n}\n\nexport interface MCallInviteNegotiate extends MCallBase {\n offer: RTCSessionDescription;\n description: RTCSessionDescription;\n lifetime: number;\n capabilities?: CallCapabilities;\n invitee?: string;\n sender_session_id?: string;\n dest_session_id?: string;\n [SDPStreamMetadataKey]: SDPStreamMetadata;\n}\n\nexport interface MCallSDPStreamMetadataChanged extends MCallBase {\n [SDPStreamMetadataKey]: SDPStreamMetadata;\n}\n\nexport interface MCallReplacesEvent extends MCallBase {\n replacement_id: string;\n target_user: CallReplacesTarget;\n create_call: string;\n await_call: string;\n target_room: string;\n}\n\nexport interface MCAllAssertedIdentity extends MCallBase {\n asserted_identity: {\n id: string;\n display_name: string;\n avatar_url: string;\n };\n}\n\nexport interface MCallCandidates extends MCallBase {\n candidates: RTCIceCandidate[];\n}\n\nexport interface MCallHangupReject extends MCallBase {\n reason?: CallErrorCode;\n}\n\n/* eslint-enable camelcase */\n", - "/*\nCopyright 2021 Šimon Brandner \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { SDPStreamMetadataPurpose } from \"./callEventTypes\";\nimport { acquireContext, releaseContext } from \"./audioContext\";\nimport { MatrixClient } from \"../client\";\nimport { RoomMember } from \"../models/room-member\";\nimport { logger } from \"../logger\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter\";\nimport { CallEvent, CallState, MatrixCall } from \"./call\";\n\nconst POLLING_INTERVAL = 200; // ms\nexport const SPEAKING_THRESHOLD = -60; // dB\nconst SPEAKING_SAMPLE_COUNT = 8; // samples\n\nexport interface ICallFeedOpts {\n client: MatrixClient;\n roomId?: string;\n userId: string;\n deviceId: string | undefined;\n stream: MediaStream;\n purpose: SDPStreamMetadataPurpose;\n /**\n * Whether or not the remote SDPStreamMetadata says audio is muted\n */\n audioMuted: boolean;\n /**\n * Whether or not the remote SDPStreamMetadata says video is muted\n */\n videoMuted: boolean;\n /**\n * The MatrixCall which is the source of this CallFeed\n */\n call?: MatrixCall;\n}\n\nexport enum CallFeedEvent {\n NewStream = \"new_stream\",\n MuteStateChanged = \"mute_state_changed\",\n LocalVolumeChanged = \"local_volume_changed\",\n VolumeChanged = \"volume_changed\",\n ConnectedChanged = \"connected_changed\",\n Speaking = \"speaking\",\n Disposed = \"disposed\",\n}\n\ntype EventHandlerMap = {\n [CallFeedEvent.NewStream]: (stream: MediaStream) => void;\n [CallFeedEvent.MuteStateChanged]: (audioMuted: boolean, videoMuted: boolean) => void;\n [CallFeedEvent.LocalVolumeChanged]: (localVolume: number) => void;\n [CallFeedEvent.VolumeChanged]: (volume: number) => void;\n [CallFeedEvent.ConnectedChanged]: (connected: boolean) => void;\n [CallFeedEvent.Speaking]: (speaking: boolean) => void;\n [CallFeedEvent.Disposed]: () => void;\n};\n\nexport class CallFeed extends TypedEventEmitter {\n public stream: MediaStream;\n public sdpMetadataStreamId: string;\n public userId: string;\n public readonly deviceId: string | undefined;\n public purpose: SDPStreamMetadataPurpose;\n public speakingVolumeSamples: number[];\n\n private client: MatrixClient;\n private call?: MatrixCall;\n private roomId?: string;\n private audioMuted: boolean;\n private videoMuted: boolean;\n private localVolume = 1;\n private measuringVolumeActivity = false;\n private audioContext?: AudioContext;\n private analyser?: AnalyserNode;\n private frequencyBinCount?: Float32Array;\n private speakingThreshold = SPEAKING_THRESHOLD;\n private speaking = false;\n private volumeLooperTimeout?: ReturnType;\n private _disposed = false;\n private _connected = false;\n\n public constructor(opts: ICallFeedOpts) {\n super();\n\n this.client = opts.client;\n this.call = opts.call;\n this.roomId = opts.roomId;\n this.userId = opts.userId;\n this.deviceId = opts.deviceId;\n this.purpose = opts.purpose;\n this.audioMuted = opts.audioMuted;\n this.videoMuted = opts.videoMuted;\n this.speakingVolumeSamples = new Array(SPEAKING_SAMPLE_COUNT).fill(-Infinity);\n this.sdpMetadataStreamId = opts.stream.id;\n\n this.updateStream(null, opts.stream);\n this.stream = opts.stream; // updateStream does this, but this makes TS happier\n\n if (this.hasAudioTrack) {\n this.initVolumeMeasuring();\n }\n\n if (opts.call) {\n opts.call.addListener(CallEvent.State, this.onCallState);\n this.onCallState(opts.call.state);\n }\n }\n\n public get connected(): boolean {\n // Local feeds are always considered connected\n return this.isLocal() || this._connected;\n }\n\n private set connected(connected: boolean) {\n this._connected = connected;\n this.emit(CallFeedEvent.ConnectedChanged, this.connected);\n }\n\n private get hasAudioTrack(): boolean {\n return this.stream.getAudioTracks().length > 0;\n }\n\n private updateStream(oldStream: MediaStream | null, newStream: MediaStream): void {\n if (newStream === oldStream) return;\n\n if (oldStream) {\n oldStream.removeEventListener(\"addtrack\", this.onAddTrack);\n this.measureVolumeActivity(false);\n }\n\n this.stream = newStream;\n newStream.addEventListener(\"addtrack\", this.onAddTrack);\n\n if (this.hasAudioTrack) {\n this.initVolumeMeasuring();\n } else {\n this.measureVolumeActivity(false);\n }\n\n this.emit(CallFeedEvent.NewStream, this.stream);\n }\n\n private initVolumeMeasuring(): void {\n if (!this.hasAudioTrack) return;\n if (!this.audioContext) this.audioContext = acquireContext();\n\n this.analyser = this.audioContext.createAnalyser();\n this.analyser.fftSize = 512;\n this.analyser.smoothingTimeConstant = 0.1;\n\n const mediaStreamAudioSourceNode = this.audioContext.createMediaStreamSource(this.stream);\n mediaStreamAudioSourceNode.connect(this.analyser);\n\n this.frequencyBinCount = new Float32Array(this.analyser.frequencyBinCount);\n }\n\n private onAddTrack = (): void => {\n this.emit(CallFeedEvent.NewStream, this.stream);\n };\n\n private onCallState = (state: CallState): void => {\n if (state === CallState.Connected) {\n this.connected = true;\n } else if (state === CallState.Connecting) {\n this.connected = false;\n }\n };\n\n /**\n * Returns callRoom member\n * @returns member of the callRoom\n */\n public getMember(): RoomMember | null {\n const callRoom = this.client.getRoom(this.roomId);\n return callRoom?.getMember(this.userId) ?? null;\n }\n\n /**\n * Returns true if CallFeed is local, otherwise returns false\n * @returns is local?\n */\n public isLocal(): boolean {\n return (\n this.userId === this.client.getUserId() &&\n (this.deviceId === undefined || this.deviceId === this.client.getDeviceId())\n );\n }\n\n /**\n * Returns true if audio is muted or if there are no audio\n * tracks, otherwise returns false\n * @returns is audio muted?\n */\n public isAudioMuted(): boolean {\n return this.stream.getAudioTracks().length === 0 || this.audioMuted;\n }\n\n /**\n * Returns true video is muted or if there are no video\n * tracks, otherwise returns false\n * @returns is video muted?\n */\n public isVideoMuted(): boolean {\n // We assume only one video track\n return this.stream.getVideoTracks().length === 0 || this.videoMuted;\n }\n\n public isSpeaking(): boolean {\n return this.speaking;\n }\n\n /**\n * Replaces the current MediaStream with a new one.\n * The stream will be different and new stream as remote parties are\n * concerned, but this can be used for convenience locally to set up\n * volume listeners automatically on the new stream etc.\n * @param newStream - new stream with which to replace the current one\n */\n public setNewStream(newStream: MediaStream): void {\n this.updateStream(this.stream, newStream);\n }\n\n /**\n * Set one or both of feed's internal audio and video video mute state\n * Either value may be null to leave it as-is\n * @param audioMuted - is the feed's audio muted?\n * @param videoMuted - is the feed's video muted?\n */\n public setAudioVideoMuted(audioMuted: boolean | null, videoMuted: boolean | null): void {\n if (audioMuted !== null) {\n if (this.audioMuted !== audioMuted) {\n this.speakingVolumeSamples.fill(-Infinity);\n }\n this.audioMuted = audioMuted;\n }\n if (videoMuted !== null) this.videoMuted = videoMuted;\n this.emit(CallFeedEvent.MuteStateChanged, this.audioMuted, this.videoMuted);\n }\n\n /**\n * Starts emitting volume_changed events where the emitter value is in decibels\n * @param enabled - emit volume changes\n */\n public measureVolumeActivity(enabled: boolean): void {\n if (enabled) {\n if (!this.analyser || !this.frequencyBinCount || !this.hasAudioTrack) return;\n\n this.measuringVolumeActivity = true;\n this.volumeLooper();\n } else {\n this.measuringVolumeActivity = false;\n this.speakingVolumeSamples.fill(-Infinity);\n this.emit(CallFeedEvent.VolumeChanged, -Infinity);\n }\n }\n\n public setSpeakingThreshold(threshold: number): void {\n this.speakingThreshold = threshold;\n }\n\n private volumeLooper = (): void => {\n if (!this.analyser) return;\n\n if (!this.measuringVolumeActivity) return;\n\n this.analyser.getFloatFrequencyData(this.frequencyBinCount!);\n\n let maxVolume = -Infinity;\n for (const volume of this.frequencyBinCount!) {\n if (volume > maxVolume) {\n maxVolume = volume;\n }\n }\n\n this.speakingVolumeSamples.shift();\n this.speakingVolumeSamples.push(maxVolume);\n\n this.emit(CallFeedEvent.VolumeChanged, maxVolume);\n\n let newSpeaking = false;\n\n for (const volume of this.speakingVolumeSamples) {\n if (volume > this.speakingThreshold) {\n newSpeaking = true;\n break;\n }\n }\n\n if (this.speaking !== newSpeaking) {\n this.speaking = newSpeaking;\n this.emit(CallFeedEvent.Speaking, this.speaking);\n }\n\n this.volumeLooperTimeout = setTimeout(this.volumeLooper, POLLING_INTERVAL);\n };\n\n public clone(): CallFeed {\n const mediaHandler = this.client.getMediaHandler();\n const stream = this.stream.clone();\n logger.log(`CallFeed clone() cloning stream (originalStreamId=${this.stream.id}, newStreamId${stream.id})`);\n\n if (this.purpose === SDPStreamMetadataPurpose.Usermedia) {\n mediaHandler.userMediaStreams.push(stream);\n } else {\n mediaHandler.screensharingStreams.push(stream);\n }\n\n return new CallFeed({\n client: this.client,\n roomId: this.roomId,\n userId: this.userId,\n deviceId: this.deviceId,\n stream,\n purpose: this.purpose,\n audioMuted: this.audioMuted,\n videoMuted: this.videoMuted,\n });\n }\n\n public dispose(): void {\n clearTimeout(this.volumeLooperTimeout);\n this.stream?.removeEventListener(\"addtrack\", this.onAddTrack);\n this.call?.removeListener(CallEvent.State, this.onCallState);\n if (this.audioContext) {\n this.audioContext = undefined;\n this.analyser = undefined;\n releaseContext();\n }\n this._disposed = true;\n this.emit(CallFeedEvent.Disposed);\n }\n\n public get disposed(): boolean {\n return this._disposed;\n }\n\n private set disposed(value: boolean) {\n this._disposed = value;\n }\n\n public getLocalVolume(): number {\n return this.localVolume;\n }\n\n public setLocalVolume(localVolume: number): void {\n this.localVolume = localVolume;\n this.emit(CallFeedEvent.LocalVolumeChanged, localVolume);\n }\n}\n", - "import { TypedEventEmitter } from \"../models/typed-event-emitter\";\nimport { CallFeed, SPEAKING_THRESHOLD } from \"./callFeed\";\nimport { MatrixClient, IMyDevice } from \"../client\";\nimport {\n CallErrorCode,\n CallEvent,\n CallEventHandlerMap,\n CallState,\n genCallID,\n MatrixCall,\n setTracksEnabled,\n createNewMatrixCall,\n CallError,\n} from \"./call\";\nimport { RoomMember } from \"../models/room-member\";\nimport { Room } from \"../models/room\";\nimport { RoomStateEvent } from \"../models/room-state\";\nimport { logger } from \"../logger\";\nimport { ReEmitter } from \"../ReEmitter\";\nimport { SDPStreamMetadataPurpose } from \"./callEventTypes\";\nimport { MatrixEvent } from \"../models/event\";\nimport { EventType } from \"../@types/event\";\nimport { CallEventHandlerEvent } from \"./callEventHandler\";\nimport { GroupCallEventHandlerEvent } from \"./groupCallEventHandler\";\nimport { IScreensharingOpts } from \"./mediaHandler\";\nimport { mapsEqual } from \"../utils\";\nimport { GroupCallStats } from \"./stats/groupCallStats\";\nimport { ByteSentStatsReport, ConnectionStatsReport, StatsReport } from \"./stats/statsReport\";\n\nexport enum GroupCallIntent {\n Ring = \"m.ring\",\n Prompt = \"m.prompt\",\n Room = \"m.room\",\n}\n\nexport enum GroupCallType {\n Video = \"m.video\",\n Voice = \"m.voice\",\n}\n\nexport enum GroupCallTerminationReason {\n CallEnded = \"call_ended\",\n}\n\nexport type CallsByUserAndDevice = Map>;\n\n/**\n * Because event names are just strings, they do need\n * to be unique over all event types of event emitter.\n * Some objects could emit more then one set of events.\n */\nexport enum GroupCallEvent {\n GroupCallStateChanged = \"group_call_state_changed\",\n ActiveSpeakerChanged = \"active_speaker_changed\",\n CallsChanged = \"calls_changed\",\n UserMediaFeedsChanged = \"user_media_feeds_changed\",\n ScreenshareFeedsChanged = \"screenshare_feeds_changed\",\n LocalScreenshareStateChanged = \"local_screenshare_state_changed\",\n LocalMuteStateChanged = \"local_mute_state_changed\",\n ParticipantsChanged = \"participants_changed\",\n Error = \"group_call_error\",\n}\n\nexport type GroupCallEventHandlerMap = {\n [GroupCallEvent.GroupCallStateChanged]: (newState: GroupCallState, oldState: GroupCallState) => void;\n [GroupCallEvent.ActiveSpeakerChanged]: (activeSpeaker: CallFeed | undefined) => void;\n [GroupCallEvent.CallsChanged]: (calls: CallsByUserAndDevice) => void;\n [GroupCallEvent.UserMediaFeedsChanged]: (feeds: CallFeed[]) => void;\n [GroupCallEvent.ScreenshareFeedsChanged]: (feeds: CallFeed[]) => void;\n [GroupCallEvent.LocalScreenshareStateChanged]: (\n isScreensharing: boolean,\n feed?: CallFeed,\n sourceId?: string,\n ) => void;\n [GroupCallEvent.LocalMuteStateChanged]: (audioMuted: boolean, videoMuted: boolean) => void;\n [GroupCallEvent.ParticipantsChanged]: (participants: Map>) => void;\n /**\n * Fires whenever an error occurs when call.js encounters an issue with setting up the call.\n *

\n * The error given will have a code equal to either `MatrixCall.ERR_LOCAL_OFFER_FAILED` or\n * `MatrixCall.ERR_NO_USER_MEDIA`. `ERR_LOCAL_OFFER_FAILED` is emitted when the local client\n * fails to create an offer. `ERR_NO_USER_MEDIA` is emitted when the user has denied access\n * to their audio/video hardware.\n * @param err - The error raised by MatrixCall.\n * @example\n * ```\n * matrixCall.on(\"error\", function(err){\n * console.error(err.code, err);\n * });\n * ```\n */\n [GroupCallEvent.Error]: (error: GroupCallError) => void;\n};\n\nexport enum GroupCallStatsReportEvent {\n ConnectionStats = \"GroupCall.connection_stats\",\n ByteSentStats = \"GroupCall.byte_sent_stats\",\n}\n\nexport type GroupCallStatsReportEventHandlerMap = {\n [GroupCallStatsReportEvent.ConnectionStats]: (report: GroupCallStatsReport) => void;\n [GroupCallStatsReportEvent.ByteSentStats]: (report: GroupCallStatsReport) => void;\n};\n\nexport enum GroupCallErrorCode {\n NoUserMedia = \"no_user_media\",\n UnknownDevice = \"unknown_device\",\n PlaceCallFailed = \"place_call_failed\",\n}\n\nexport interface GroupCallStatsReport {\n report: T;\n}\n\nexport class GroupCallError extends Error {\n public code: string;\n\n public constructor(code: GroupCallErrorCode, msg: string, err?: Error) {\n // Still don't think there's any way to have proper nested errors\n if (err) {\n super(msg + \": \" + err);\n } else {\n super(msg);\n }\n\n this.code = code;\n }\n}\n\nexport class GroupCallUnknownDeviceError extends GroupCallError {\n public constructor(public userId: string) {\n super(GroupCallErrorCode.UnknownDevice, \"No device found for \" + userId);\n }\n}\n\nexport class OtherUserSpeakingError extends Error {\n public constructor() {\n super(\"Cannot unmute: another user is speaking\");\n }\n}\n\nexport interface IGroupCallDataChannelOptions {\n ordered: boolean;\n maxPacketLifeTime: number;\n maxRetransmits: number;\n protocol: string;\n}\n\nexport interface IGroupCallRoomState {\n \"m.intent\": GroupCallIntent;\n \"m.type\": GroupCallType;\n \"io.element.ptt\"?: boolean;\n // TODO: Specify data-channels\n \"dataChannelsEnabled\"?: boolean;\n \"dataChannelOptions\"?: IGroupCallDataChannelOptions;\n}\n\nexport interface IGroupCallRoomMemberFeed {\n purpose: SDPStreamMetadataPurpose;\n}\n\nexport interface IGroupCallRoomMemberDevice {\n device_id: string;\n session_id: string;\n expires_ts: number;\n feeds: IGroupCallRoomMemberFeed[];\n}\n\nexport interface IGroupCallRoomMemberCallState {\n \"m.call_id\": string;\n \"m.foci\"?: string[];\n \"m.devices\": IGroupCallRoomMemberDevice[];\n}\n\nexport interface IGroupCallRoomMemberState {\n \"m.calls\": IGroupCallRoomMemberCallState[];\n}\n\nexport enum GroupCallState {\n LocalCallFeedUninitialized = \"local_call_feed_uninitialized\",\n InitializingLocalCallFeed = \"initializing_local_call_feed\",\n LocalCallFeedInitialized = \"local_call_feed_initialized\",\n Entered = \"entered\",\n Ended = \"ended\",\n}\n\nexport interface ParticipantState {\n sessionId: string;\n screensharing: boolean;\n}\n\ninterface ICallHandlers {\n onCallFeedsChanged: (feeds: CallFeed[]) => void;\n onCallStateChanged: (state: CallState, oldState: CallState | undefined) => void;\n onCallHangup: (call: MatrixCall) => void;\n onCallReplaced: (newCall: MatrixCall) => void;\n}\n\nconst DEVICE_TIMEOUT = 1000 * 60 * 60; // 1 hour\n\nfunction getCallUserId(call: MatrixCall): string | null {\n return call.getOpponentMember()?.userId || call.invitee || null;\n}\n\nexport class GroupCall extends TypedEventEmitter<\n GroupCallEvent | CallEvent | GroupCallStatsReportEvent,\n GroupCallEventHandlerMap & CallEventHandlerMap & GroupCallStatsReportEventHandlerMap\n> {\n // Config\n public activeSpeakerInterval = 1000;\n public retryCallInterval = 5000;\n public participantTimeout = 1000 * 15;\n public pttMaxTransmitTime = 1000 * 20;\n\n public activeSpeaker?: CallFeed;\n public localCallFeed?: CallFeed;\n public localScreenshareFeed?: CallFeed;\n public localDesktopCapturerSourceId?: string;\n public readonly userMediaFeeds: CallFeed[] = [];\n public readonly screenshareFeeds: CallFeed[] = [];\n public groupCallId: string;\n public readonly allowCallWithoutVideoAndAudio: boolean;\n\n private readonly calls = new Map>(); // user_id -> device_id -> MatrixCall\n private callHandlers = new Map>(); // user_id -> device_id -> ICallHandlers\n private activeSpeakerLoopInterval?: ReturnType;\n private retryCallLoopInterval?: ReturnType;\n private retryCallCounts: Map> = new Map(); // user_id -> device_id -> count\n private reEmitter: ReEmitter;\n private transmitTimer: ReturnType | null = null;\n private participantsExpirationTimer: ReturnType | null = null;\n private resendMemberStateTimer: ReturnType | null = null;\n private initWithAudioMuted = false;\n private initWithVideoMuted = false;\n private initCallFeedPromise?: Promise;\n\n private readonly stats: GroupCallStats;\n\n public constructor(\n private client: MatrixClient,\n public room: Room,\n public type: GroupCallType,\n public isPtt: boolean,\n public intent: GroupCallIntent,\n groupCallId?: string,\n private dataChannelsEnabled?: boolean,\n private dataChannelOptions?: IGroupCallDataChannelOptions,\n isCallWithoutVideoAndAudio?: boolean,\n ) {\n super();\n this.reEmitter = new ReEmitter(this);\n this.groupCallId = groupCallId ?? genCallID();\n this.creationTs =\n room.currentState.getStateEvents(EventType.GroupCallPrefix, this.groupCallId)?.getTs() ?? null;\n this.updateParticipants();\n\n room.on(RoomStateEvent.Update, this.onRoomState);\n this.on(GroupCallEvent.ParticipantsChanged, this.onParticipantsChanged);\n this.on(GroupCallEvent.GroupCallStateChanged, this.onStateChanged);\n this.on(GroupCallEvent.LocalScreenshareStateChanged, this.onLocalFeedsChanged);\n this.allowCallWithoutVideoAndAudio = !!isCallWithoutVideoAndAudio;\n\n const userID = this.client.getUserId() || \"unknown\";\n this.stats = new GroupCallStats(this.groupCallId, userID);\n this.stats.reports.on(StatsReport.CONNECTION_STATS, this.onConnectionStats);\n this.stats.reports.on(StatsReport.BYTE_SENT_STATS, this.onByteSentStats);\n }\n\n private onConnectionStats = (report: ConnectionStatsReport): void => {\n // @TODO: Implement data argumentation\n this.emit(GroupCallStatsReportEvent.ConnectionStats, { report });\n };\n\n private onByteSentStats = (report: ByteSentStatsReport): void => {\n // @TODO: Implement data argumentation\n this.emit(GroupCallStatsReportEvent.ByteSentStats, { report });\n };\n\n public async create(): Promise {\n this.creationTs = Date.now();\n this.client.groupCallEventHandler!.groupCalls.set(this.room.roomId, this);\n this.client.emit(GroupCallEventHandlerEvent.Outgoing, this);\n\n const groupCallState: IGroupCallRoomState = {\n \"m.intent\": this.intent,\n \"m.type\": this.type,\n \"io.element.ptt\": this.isPtt,\n // TODO: Specify data-channels better\n \"dataChannelsEnabled\": this.dataChannelsEnabled,\n \"dataChannelOptions\": this.dataChannelsEnabled ? this.dataChannelOptions : undefined,\n };\n\n await this.client.sendStateEvent(this.room.roomId, EventType.GroupCallPrefix, groupCallState, this.groupCallId);\n\n return this;\n }\n\n private _state = GroupCallState.LocalCallFeedUninitialized;\n\n /**\n * The group call's state.\n */\n public get state(): GroupCallState {\n return this._state;\n }\n\n private set state(value: GroupCallState) {\n const prevValue = this._state;\n if (value !== prevValue) {\n this._state = value;\n this.emit(GroupCallEvent.GroupCallStateChanged, value, prevValue);\n }\n }\n\n private _participants = new Map>();\n\n /**\n * The current participants in the call, as a map from members to device IDs\n * to participant info.\n */\n public get participants(): Map> {\n return this._participants;\n }\n\n private set participants(value: Map>) {\n const prevValue = this._participants;\n const participantStateEqual = (x: ParticipantState, y: ParticipantState): boolean =>\n x.sessionId === y.sessionId && x.screensharing === y.screensharing;\n const deviceMapsEqual = (x: Map, y: Map): boolean =>\n mapsEqual(x, y, participantStateEqual);\n\n // Only update if the map actually changed\n if (!mapsEqual(value, prevValue, deviceMapsEqual)) {\n this._participants = value;\n this.emit(GroupCallEvent.ParticipantsChanged, value);\n }\n }\n\n private _creationTs: number | null = null;\n\n /**\n * The timestamp at which the call was created, or null if it has not yet\n * been created.\n */\n public get creationTs(): number | null {\n return this._creationTs;\n }\n\n private set creationTs(value: number | null) {\n this._creationTs = value;\n }\n\n private _enteredViaAnotherSession = false;\n\n /**\n * Whether the local device has entered this call via another session, such\n * as a widget.\n */\n public get enteredViaAnotherSession(): boolean {\n return this._enteredViaAnotherSession;\n }\n\n public set enteredViaAnotherSession(value: boolean) {\n this._enteredViaAnotherSession = value;\n this.updateParticipants();\n }\n\n /**\n * Executes the given callback on all calls in this group call.\n * @param f - The callback.\n */\n public forEachCall(f: (call: MatrixCall) => void): void {\n for (const deviceMap of this.calls.values()) {\n for (const call of deviceMap.values()) f(call);\n }\n }\n\n public getLocalFeeds(): CallFeed[] {\n const feeds: CallFeed[] = [];\n\n if (this.localCallFeed) feeds.push(this.localCallFeed);\n if (this.localScreenshareFeed) feeds.push(this.localScreenshareFeed);\n\n return feeds;\n }\n\n public hasLocalParticipant(): boolean {\n return (\n this.participants.get(this.room.getMember(this.client.getUserId()!)!)?.has(this.client.getDeviceId()!) ??\n false\n );\n }\n\n /**\n * Determines whether the given call is one that we were expecting to exist\n * given our knowledge of who is participating in the group call.\n */\n private callExpected(call: MatrixCall): boolean {\n const userId = getCallUserId(call);\n const member = userId === null ? null : this.room.getMember(userId);\n const deviceId = call.getOpponentDeviceId();\n return member !== null && deviceId !== undefined && this.participants.get(member)?.get(deviceId) !== undefined;\n }\n\n public async initLocalCallFeed(): Promise {\n if (this.state !== GroupCallState.LocalCallFeedUninitialized) {\n throw new Error(`Cannot initialize local call feed in the \"${this.state}\" state.`);\n }\n this.state = GroupCallState.InitializingLocalCallFeed;\n\n // wraps the real method to serialise calls, because we don't want to try starting\n // multiple call feeds at once\n if (this.initCallFeedPromise) return this.initCallFeedPromise;\n\n try {\n this.initCallFeedPromise = this.initLocalCallFeedInternal();\n await this.initCallFeedPromise;\n } finally {\n this.initCallFeedPromise = undefined;\n }\n }\n\n private async initLocalCallFeedInternal(): Promise {\n logger.log(`GroupCall ${this.groupCallId} initLocalCallFeedInternal() running`);\n\n let stream: MediaStream;\n\n try {\n stream = await this.client.getMediaHandler().getUserMediaStream(true, this.type === GroupCallType.Video);\n } catch (error) {\n // If is allowed to join a call without a media stream, then we\n // don't throw an error here. But we need an empty Local Feed to establish\n // a connection later.\n if (this.allowCallWithoutVideoAndAudio) {\n stream = new MediaStream();\n } else {\n this.state = GroupCallState.LocalCallFeedUninitialized;\n throw error;\n }\n }\n\n // The call could've been disposed while we were waiting, and could\n // also have been started back up again (hello, React 18) so if we're\n // still in this 'initializing' state, carry on, otherwise bail.\n if (this._state !== GroupCallState.InitializingLocalCallFeed) {\n this.client.getMediaHandler().stopUserMediaStream(stream);\n throw new Error(\"Group call disposed while gathering media stream\");\n }\n\n const callFeed = new CallFeed({\n client: this.client,\n roomId: this.room.roomId,\n userId: this.client.getUserId()!,\n deviceId: this.client.getDeviceId()!,\n stream,\n purpose: SDPStreamMetadataPurpose.Usermedia,\n audioMuted: this.initWithAudioMuted || stream.getAudioTracks().length === 0 || this.isPtt,\n videoMuted: this.initWithVideoMuted || stream.getVideoTracks().length === 0,\n });\n\n setTracksEnabled(stream.getAudioTracks(), !callFeed.isAudioMuted());\n setTracksEnabled(stream.getVideoTracks(), !callFeed.isVideoMuted());\n\n this.localCallFeed = callFeed;\n this.addUserMediaFeed(callFeed);\n\n this.state = GroupCallState.LocalCallFeedInitialized;\n }\n\n public async updateLocalUsermediaStream(stream: MediaStream): Promise {\n if (this.localCallFeed) {\n const oldStream = this.localCallFeed.stream;\n this.localCallFeed.setNewStream(stream);\n const micShouldBeMuted = this.localCallFeed.isAudioMuted();\n const vidShouldBeMuted = this.localCallFeed.isVideoMuted();\n logger.log(\n `GroupCall ${this.groupCallId} updateLocalUsermediaStream() (oldStreamId=${oldStream.id}, newStreamId=${stream.id}, micShouldBeMuted=${micShouldBeMuted}, vidShouldBeMuted=${vidShouldBeMuted})`,\n );\n setTracksEnabled(stream.getAudioTracks(), !micShouldBeMuted);\n setTracksEnabled(stream.getVideoTracks(), !vidShouldBeMuted);\n this.client.getMediaHandler().stopUserMediaStream(oldStream);\n }\n }\n\n public async enter(): Promise {\n if (this.state === GroupCallState.LocalCallFeedUninitialized) {\n await this.initLocalCallFeed();\n } else if (this.state !== GroupCallState.LocalCallFeedInitialized) {\n throw new Error(`Cannot enter call in the \"${this.state}\" state`);\n }\n\n logger.log(`GroupCall ${this.groupCallId} enter() running`);\n this.state = GroupCallState.Entered;\n\n this.client.on(CallEventHandlerEvent.Incoming, this.onIncomingCall);\n\n for (const call of this.client.callEventHandler!.calls.values()) {\n this.onIncomingCall(call);\n }\n\n this.retryCallLoopInterval = setInterval(this.onRetryCallLoop, this.retryCallInterval);\n\n this.activeSpeaker = undefined;\n this.onActiveSpeakerLoop();\n this.activeSpeakerLoopInterval = setInterval(this.onActiveSpeakerLoop, this.activeSpeakerInterval);\n }\n\n private dispose(): void {\n if (this.localCallFeed) {\n this.removeUserMediaFeed(this.localCallFeed);\n this.localCallFeed = undefined;\n }\n\n if (this.localScreenshareFeed) {\n this.client.getMediaHandler().stopScreensharingStream(this.localScreenshareFeed.stream);\n this.removeScreenshareFeed(this.localScreenshareFeed);\n this.localScreenshareFeed = undefined;\n this.localDesktopCapturerSourceId = undefined;\n }\n\n this.client.getMediaHandler().stopAllStreams();\n\n if (this.transmitTimer !== null) {\n clearTimeout(this.transmitTimer);\n this.transmitTimer = null;\n }\n\n if (this.retryCallLoopInterval !== undefined) {\n clearInterval(this.retryCallLoopInterval);\n this.retryCallLoopInterval = undefined;\n }\n\n if (this.participantsExpirationTimer !== null) {\n clearTimeout(this.participantsExpirationTimer);\n this.participantsExpirationTimer = null;\n }\n\n if (this.state !== GroupCallState.Entered) {\n return;\n }\n\n this.forEachCall((call) => call.hangup(CallErrorCode.UserHangup, false));\n\n this.activeSpeaker = undefined;\n clearInterval(this.activeSpeakerLoopInterval);\n\n this.retryCallCounts.clear();\n clearInterval(this.retryCallLoopInterval);\n\n this.client.removeListener(CallEventHandlerEvent.Incoming, this.onIncomingCall);\n this.stats.stop();\n }\n\n public leave(): void {\n this.dispose();\n this.state = GroupCallState.LocalCallFeedUninitialized;\n }\n\n public async terminate(emitStateEvent = true): Promise {\n this.dispose();\n\n this.room.off(RoomStateEvent.Update, this.onRoomState);\n this.client.groupCallEventHandler!.groupCalls.delete(this.room.roomId);\n this.client.emit(GroupCallEventHandlerEvent.Ended, this);\n this.state = GroupCallState.Ended;\n\n if (emitStateEvent) {\n const existingStateEvent = this.room.currentState.getStateEvents(\n EventType.GroupCallPrefix,\n this.groupCallId,\n )!;\n\n await this.client.sendStateEvent(\n this.room.roomId,\n EventType.GroupCallPrefix,\n {\n ...existingStateEvent.getContent(),\n \"m.terminated\": GroupCallTerminationReason.CallEnded,\n },\n this.groupCallId,\n );\n }\n }\n\n /*\n * Local Usermedia\n */\n\n public isLocalVideoMuted(): boolean {\n if (this.localCallFeed) {\n return this.localCallFeed.isVideoMuted();\n }\n\n return true;\n }\n\n public isMicrophoneMuted(): boolean {\n if (this.localCallFeed) {\n return this.localCallFeed.isAudioMuted();\n }\n\n return true;\n }\n\n /**\n * Sets the mute state of the local participants's microphone.\n * @param muted - Whether to mute the microphone\n * @returns Whether muting/unmuting was successful\n */\n public async setMicrophoneMuted(muted: boolean): Promise {\n // hasAudioDevice can block indefinitely if the window has lost focus,\n // and it doesn't make much sense to keep a device from being muted, so\n // we always allow muted = true changes to go through\n if (!muted && !(await this.client.getMediaHandler().hasAudioDevice())) {\n return false;\n }\n\n const sendUpdatesBefore = !muted && this.isPtt;\n\n // set a timer for the maximum transmit time on PTT calls\n if (this.isPtt) {\n // Set or clear the max transmit timer\n if (!muted && this.isMicrophoneMuted()) {\n this.transmitTimer = setTimeout(() => {\n this.setMicrophoneMuted(true);\n }, this.pttMaxTransmitTime);\n } else if (muted && !this.isMicrophoneMuted()) {\n if (this.transmitTimer !== null) clearTimeout(this.transmitTimer);\n this.transmitTimer = null;\n }\n }\n\n this.forEachCall((call) => call.localUsermediaFeed?.setAudioVideoMuted(muted, null));\n\n const sendUpdates = async (): Promise => {\n const updates: Promise[] = [];\n this.forEachCall((call) => updates.push(call.sendMetadataUpdate()));\n\n await Promise.all(updates).catch((e) =>\n logger.info(\n `GroupCall ${this.groupCallId} setMicrophoneMuted() failed to send some metadata updates`,\n e,\n ),\n );\n };\n\n if (sendUpdatesBefore) await sendUpdates();\n\n if (this.localCallFeed) {\n logger.log(\n `GroupCall ${this.groupCallId} setMicrophoneMuted() (streamId=${this.localCallFeed.stream.id}, muted=${muted})`,\n );\n\n // We needed this here to avoid an error in case user join a call without a device.\n // I can not use .then .catch functions because linter :-(\n try {\n if (!muted) {\n const stream = await this.client\n .getMediaHandler()\n .getUserMediaStream(true, !this.localCallFeed.isVideoMuted());\n if (stream === null) {\n // if case permission denied to get a stream stop this here\n /* istanbul ignore next */\n logger.log(\n `GroupCall ${this.groupCallId} setMicrophoneMuted() no device to receive local stream, muted=${muted}`,\n );\n return false;\n }\n }\n } catch (e) {\n /* istanbul ignore next */\n logger.log(\n `GroupCall ${this.groupCallId} setMicrophoneMuted() no device or permission to receive local stream, muted=${muted}`,\n );\n return false;\n }\n\n this.localCallFeed.setAudioVideoMuted(muted, null);\n // I don't believe its actually necessary to enable these tracks: they\n // are the one on the GroupCall's own CallFeed and are cloned before being\n // given to any of the actual calls, so these tracks don't actually go\n // anywhere. Let's do it anyway to avoid confusion.\n setTracksEnabled(this.localCallFeed.stream.getAudioTracks(), !muted);\n } else {\n logger.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() no stream muted (muted=${muted})`);\n this.initWithAudioMuted = muted;\n }\n\n this.forEachCall((call) =>\n setTracksEnabled(call.localUsermediaFeed!.stream.getAudioTracks(), !muted && this.callExpected(call)),\n );\n this.emit(GroupCallEvent.LocalMuteStateChanged, muted, this.isLocalVideoMuted());\n\n if (!sendUpdatesBefore) await sendUpdates();\n\n return true;\n }\n\n /**\n * Sets the mute state of the local participants's video.\n * @param muted - Whether to mute the video\n * @returns Whether muting/unmuting was successful\n */\n public async setLocalVideoMuted(muted: boolean): Promise {\n // hasAudioDevice can block indefinitely if the window has lost focus,\n // and it doesn't make much sense to keep a device from being muted, so\n // we always allow muted = true changes to go through\n if (!muted && !(await this.client.getMediaHandler().hasVideoDevice())) {\n return false;\n }\n\n if (this.localCallFeed) {\n /* istanbul ignore next */\n logger.log(\n `GroupCall ${this.groupCallId} setLocalVideoMuted() (stream=${this.localCallFeed.stream.id}, muted=${muted})`,\n );\n\n try {\n const stream = await this.client.getMediaHandler().getUserMediaStream(true, !muted);\n await this.updateLocalUsermediaStream(stream);\n this.localCallFeed.setAudioVideoMuted(null, muted);\n setTracksEnabled(this.localCallFeed.stream.getVideoTracks(), !muted);\n } catch (_) {\n // No permission to video device\n /* istanbul ignore next */\n logger.log(\n `GroupCall ${this.groupCallId} setLocalVideoMuted() no device or permission to receive local stream, muted=${muted}`,\n );\n return false;\n }\n } else {\n logger.log(`GroupCall ${this.groupCallId} setLocalVideoMuted() no stream muted (muted=${muted})`);\n this.initWithVideoMuted = muted;\n }\n\n const updates: Promise[] = [];\n this.forEachCall((call) => updates.push(call.setLocalVideoMuted(muted)));\n await Promise.all(updates);\n\n // We setTracksEnabled again, independently from the call doing it\n // internally, since we might not be expecting the call\n this.forEachCall((call) =>\n setTracksEnabled(call.localUsermediaFeed!.stream.getVideoTracks(), !muted && this.callExpected(call)),\n );\n\n this.emit(GroupCallEvent.LocalMuteStateChanged, this.isMicrophoneMuted(), muted);\n\n return true;\n }\n\n public async setScreensharingEnabled(enabled: boolean, opts: IScreensharingOpts = {}): Promise {\n if (enabled === this.isScreensharing()) {\n return enabled;\n }\n\n if (enabled) {\n try {\n logger.log(\n `GroupCall ${this.groupCallId} setScreensharingEnabled() is asking for screensharing permissions`,\n );\n const stream = await this.client.getMediaHandler().getScreensharingStream(opts);\n\n for (const track of stream.getTracks()) {\n const onTrackEnded = (): void => {\n this.setScreensharingEnabled(false);\n track.removeEventListener(\"ended\", onTrackEnded);\n };\n\n track.addEventListener(\"ended\", onTrackEnded);\n }\n\n logger.log(\n `GroupCall ${this.groupCallId} setScreensharingEnabled() granted screensharing permissions. Setting screensharing enabled on all calls`,\n );\n\n this.localDesktopCapturerSourceId = opts.desktopCapturerSourceId;\n this.localScreenshareFeed = new CallFeed({\n client: this.client,\n roomId: this.room.roomId,\n userId: this.client.getUserId()!,\n deviceId: this.client.getDeviceId()!,\n stream,\n purpose: SDPStreamMetadataPurpose.Screenshare,\n audioMuted: false,\n videoMuted: false,\n });\n this.addScreenshareFeed(this.localScreenshareFeed);\n\n this.emit(\n GroupCallEvent.LocalScreenshareStateChanged,\n true,\n this.localScreenshareFeed,\n this.localDesktopCapturerSourceId,\n );\n\n // TODO: handle errors\n this.forEachCall((call) => call.pushLocalFeed(this.localScreenshareFeed!.clone()));\n\n return true;\n } catch (error) {\n if (opts.throwOnFail) throw error;\n logger.error(\n `GroupCall ${this.groupCallId} setScreensharingEnabled() enabling screensharing error`,\n error,\n );\n this.emit(\n GroupCallEvent.Error,\n new GroupCallError(\n GroupCallErrorCode.NoUserMedia,\n \"Failed to get screen-sharing stream: \",\n error as Error,\n ),\n );\n return false;\n }\n } else {\n this.forEachCall((call) => {\n if (call.localScreensharingFeed) call.removeLocalFeed(call.localScreensharingFeed);\n });\n this.client.getMediaHandler().stopScreensharingStream(this.localScreenshareFeed!.stream);\n this.removeScreenshareFeed(this.localScreenshareFeed!);\n this.localScreenshareFeed = undefined;\n this.localDesktopCapturerSourceId = undefined;\n this.emit(GroupCallEvent.LocalScreenshareStateChanged, false, undefined, undefined);\n return false;\n }\n }\n\n public isScreensharing(): boolean {\n return !!this.localScreenshareFeed;\n }\n\n /*\n * Call Setup\n *\n * There are two different paths for calls to be created:\n * 1. Incoming calls triggered by the Call.incoming event.\n * 2. Outgoing calls to the initial members of a room or new members\n * as they are observed by the RoomState.members event.\n */\n\n private onIncomingCall = (newCall: MatrixCall): void => {\n // The incoming calls may be for another room, which we will ignore.\n if (newCall.roomId !== this.room.roomId) {\n return;\n }\n\n if (newCall.state !== CallState.Ringing) {\n logger.warn(\n `GroupCall ${this.groupCallId} onIncomingCall() incoming call no longer in ringing state - ignoring`,\n );\n return;\n }\n\n if (!newCall.groupCallId || newCall.groupCallId !== this.groupCallId) {\n logger.log(\n `GroupCall ${this.groupCallId} onIncomingCall() ignored because it doesn't match the current group call`,\n );\n newCall.reject();\n return;\n }\n\n const opponentUserId = newCall.getOpponentMember()?.userId;\n if (opponentUserId === undefined) {\n logger.warn(`GroupCall ${this.groupCallId} onIncomingCall() incoming call with no member - ignoring`);\n return;\n }\n\n const deviceMap = this.calls.get(opponentUserId) ?? new Map();\n const prevCall = deviceMap.get(newCall.getOpponentDeviceId()!);\n\n if (prevCall?.callId === newCall.callId) return;\n\n logger.log(\n `GroupCall ${this.groupCallId} onIncomingCall() incoming call (userId=${opponentUserId}, callId=${newCall.callId})`,\n );\n\n if (prevCall) prevCall.hangup(CallErrorCode.Replaced, false);\n\n this.initCall(newCall);\n\n const feeds = this.getLocalFeeds().map((feed) => feed.clone());\n if (!this.callExpected(newCall)) {\n // Disable our tracks for users not explicitly participating in the\n // call but trying to receive the feeds\n for (const feed of feeds) {\n setTracksEnabled(feed.stream.getAudioTracks(), false);\n setTracksEnabled(feed.stream.getVideoTracks(), false);\n }\n }\n newCall.answerWithCallFeeds(feeds);\n\n deviceMap.set(newCall.getOpponentDeviceId()!, newCall);\n this.calls.set(opponentUserId, deviceMap);\n this.emit(GroupCallEvent.CallsChanged, this.calls);\n };\n\n /**\n * Determines whether a given participant expects us to call them (versus\n * them calling us).\n * @param userId - The participant's user ID.\n * @param deviceId - The participant's device ID.\n * @returns Whether we need to place an outgoing call to the participant.\n */\n private wantsOutgoingCall(userId: string, deviceId: string): boolean {\n const localUserId = this.client.getUserId()!;\n const localDeviceId = this.client.getDeviceId()!;\n return (\n // If a user's ID is less than our own, they'll call us\n userId >= localUserId &&\n // If this is another one of our devices, compare device IDs to tell whether it'll call us\n (userId !== localUserId || deviceId > localDeviceId)\n );\n }\n\n /**\n * Places calls to all participants that we're responsible for calling.\n */\n private placeOutgoingCalls(): void {\n let callsChanged = false;\n\n for (const [{ userId }, participantMap] of this.participants) {\n const callMap = this.calls.get(userId) ?? new Map();\n\n for (const [deviceId, participant] of participantMap) {\n const prevCall = callMap.get(deviceId);\n\n if (\n prevCall?.getOpponentSessionId() !== participant.sessionId &&\n this.wantsOutgoingCall(userId, deviceId)\n ) {\n callsChanged = true;\n\n if (prevCall !== undefined) {\n logger.debug(\n `GroupCall ${this.groupCallId} placeOutgoingCalls() replacing call (userId=${userId}, deviceId=${deviceId}, callId=${prevCall.callId})`,\n );\n prevCall.hangup(CallErrorCode.NewSession, false);\n }\n\n const newCall = createNewMatrixCall(this.client, this.room.roomId, {\n invitee: userId,\n opponentDeviceId: deviceId,\n opponentSessionId: participant.sessionId,\n groupCallId: this.groupCallId,\n });\n\n if (newCall === null) {\n logger.error(\n `GroupCall ${this.groupCallId} placeOutgoingCalls() failed to create call (userId=${userId}, device=${deviceId})`,\n );\n callMap.delete(deviceId);\n } else {\n this.initCall(newCall);\n callMap.set(deviceId, newCall);\n\n logger.debug(\n `GroupCall ${this.groupCallId} placeOutgoingCalls() placing call (userId=${userId}, deviceId=${deviceId}, sessionId=${participant.sessionId})`,\n );\n\n newCall\n .placeCallWithCallFeeds(\n this.getLocalFeeds().map((feed) => feed.clone()),\n participant.screensharing,\n )\n .then(() => {\n if (this.dataChannelsEnabled) {\n newCall.createDataChannel(\"datachannel\", this.dataChannelOptions);\n }\n })\n .catch((e) => {\n logger.warn(\n `GroupCall ${this.groupCallId} placeOutgoingCalls() failed to place call (userId=${userId})`,\n e,\n );\n\n if (e instanceof CallError && e.code === GroupCallErrorCode.UnknownDevice) {\n this.emit(GroupCallEvent.Error, e);\n } else {\n this.emit(\n GroupCallEvent.Error,\n new GroupCallError(\n GroupCallErrorCode.PlaceCallFailed,\n `Failed to place call to ${userId}`,\n ),\n );\n }\n\n newCall.hangup(CallErrorCode.SignallingFailed, false);\n if (callMap.get(deviceId) === newCall) callMap.delete(deviceId);\n });\n }\n }\n }\n\n if (callMap.size > 0) {\n this.calls.set(userId, callMap);\n } else {\n this.calls.delete(userId);\n }\n }\n\n if (callsChanged) this.emit(GroupCallEvent.CallsChanged, this.calls);\n }\n\n /*\n * Room Member State\n */\n\n private getMemberStateEvents(): MatrixEvent[];\n private getMemberStateEvents(userId: string): MatrixEvent | null;\n private getMemberStateEvents(userId?: string): MatrixEvent[] | MatrixEvent | null {\n return userId === undefined\n ? this.room.currentState.getStateEvents(EventType.GroupCallMemberPrefix)\n : this.room.currentState.getStateEvents(EventType.GroupCallMemberPrefix, userId);\n }\n\n private onRetryCallLoop = (): void => {\n let needsRetry = false;\n\n for (const [{ userId }, participantMap] of this.participants) {\n const callMap = this.calls.get(userId);\n let retriesMap = this.retryCallCounts.get(userId);\n\n for (const [deviceId, participant] of participantMap) {\n const call = callMap?.get(deviceId);\n const retries = retriesMap?.get(deviceId) ?? 0;\n\n if (\n call?.getOpponentSessionId() !== participant.sessionId &&\n this.wantsOutgoingCall(userId, deviceId) &&\n retries < 3\n ) {\n if (retriesMap === undefined) {\n retriesMap = new Map();\n this.retryCallCounts.set(userId, retriesMap);\n }\n retriesMap.set(deviceId, retries + 1);\n needsRetry = true;\n }\n }\n }\n\n if (needsRetry) this.placeOutgoingCalls();\n };\n\n private initCall(call: MatrixCall): void {\n const opponentMemberId = getCallUserId(call);\n\n if (!opponentMemberId) {\n throw new Error(\"Cannot init call without user id\");\n }\n\n const onCallFeedsChanged = (): void => this.onCallFeedsChanged(call);\n const onCallStateChanged = (state: CallState, oldState?: CallState): void =>\n this.onCallStateChanged(call, state, oldState);\n const onCallHangup = this.onCallHangup;\n const onCallReplaced = (newCall: MatrixCall): void => this.onCallReplaced(call, newCall);\n\n let deviceMap = this.callHandlers.get(opponentMemberId);\n if (deviceMap === undefined) {\n deviceMap = new Map();\n this.callHandlers.set(opponentMemberId, deviceMap);\n }\n\n deviceMap.set(call.getOpponentDeviceId()!, {\n onCallFeedsChanged,\n onCallStateChanged,\n onCallHangup,\n onCallReplaced,\n });\n\n call.on(CallEvent.FeedsChanged, onCallFeedsChanged);\n call.on(CallEvent.State, onCallStateChanged);\n call.on(CallEvent.Hangup, onCallHangup);\n call.on(CallEvent.Replaced, onCallReplaced);\n\n call.isPtt = this.isPtt;\n\n this.reEmitter.reEmit(call, Object.values(CallEvent));\n\n call.initStats(this.stats);\n\n onCallFeedsChanged();\n }\n\n private disposeCall(call: MatrixCall, hangupReason: CallErrorCode): void {\n const opponentMemberId = getCallUserId(call);\n const opponentDeviceId = call.getOpponentDeviceId()!;\n\n if (!opponentMemberId) {\n throw new Error(\"Cannot dispose call without user id\");\n }\n\n const deviceMap = this.callHandlers.get(opponentMemberId)!;\n const { onCallFeedsChanged, onCallStateChanged, onCallHangup, onCallReplaced } =\n deviceMap.get(opponentDeviceId)!;\n\n call.removeListener(CallEvent.FeedsChanged, onCallFeedsChanged);\n call.removeListener(CallEvent.State, onCallStateChanged);\n call.removeListener(CallEvent.Hangup, onCallHangup);\n call.removeListener(CallEvent.Replaced, onCallReplaced);\n\n deviceMap.delete(opponentMemberId);\n if (deviceMap.size === 0) this.callHandlers.delete(opponentMemberId);\n\n if (call.hangupReason === CallErrorCode.Replaced) {\n return;\n }\n\n const usermediaFeed = this.getUserMediaFeed(opponentMemberId, opponentDeviceId);\n\n if (usermediaFeed) {\n this.removeUserMediaFeed(usermediaFeed);\n }\n\n const screenshareFeed = this.getScreenshareFeed(opponentMemberId, opponentDeviceId);\n\n if (screenshareFeed) {\n this.removeScreenshareFeed(screenshareFeed);\n }\n }\n\n private onCallFeedsChanged = (call: MatrixCall): void => {\n const opponentMemberId = getCallUserId(call);\n const opponentDeviceId = call.getOpponentDeviceId()!;\n\n if (!opponentMemberId) {\n throw new Error(\"Cannot change call feeds without user id\");\n }\n\n const currentUserMediaFeed = this.getUserMediaFeed(opponentMemberId, opponentDeviceId);\n const remoteUsermediaFeed = call.remoteUsermediaFeed;\n const remoteFeedChanged = remoteUsermediaFeed !== currentUserMediaFeed;\n\n if (remoteFeedChanged) {\n if (!currentUserMediaFeed && remoteUsermediaFeed) {\n this.addUserMediaFeed(remoteUsermediaFeed);\n } else if (currentUserMediaFeed && remoteUsermediaFeed) {\n this.replaceUserMediaFeed(currentUserMediaFeed, remoteUsermediaFeed);\n } else if (currentUserMediaFeed && !remoteUsermediaFeed) {\n this.removeUserMediaFeed(currentUserMediaFeed);\n }\n }\n\n const currentScreenshareFeed = this.getScreenshareFeed(opponentMemberId, opponentDeviceId);\n const remoteScreensharingFeed = call.remoteScreensharingFeed;\n const remoteScreenshareFeedChanged = remoteScreensharingFeed !== currentScreenshareFeed;\n\n if (remoteScreenshareFeedChanged) {\n if (!currentScreenshareFeed && remoteScreensharingFeed) {\n this.addScreenshareFeed(remoteScreensharingFeed);\n } else if (currentScreenshareFeed && remoteScreensharingFeed) {\n this.replaceScreenshareFeed(currentScreenshareFeed, remoteScreensharingFeed);\n } else if (currentScreenshareFeed && !remoteScreensharingFeed) {\n this.removeScreenshareFeed(currentScreenshareFeed);\n }\n }\n };\n\n private onCallStateChanged = (call: MatrixCall, state: CallState, _oldState: CallState | undefined): void => {\n if (state === CallState.Ended) return;\n\n const audioMuted = this.localCallFeed!.isAudioMuted();\n\n if (call.localUsermediaStream && call.isMicrophoneMuted() !== audioMuted) {\n call.setMicrophoneMuted(audioMuted);\n }\n\n const videoMuted = this.localCallFeed!.isVideoMuted();\n\n if (call.localUsermediaStream && call.isLocalVideoMuted() !== videoMuted) {\n call.setLocalVideoMuted(videoMuted);\n }\n\n const opponentUserId = call.getOpponentMember()?.userId;\n if (state === CallState.Connected && opponentUserId) {\n const retriesMap = this.retryCallCounts.get(opponentUserId);\n retriesMap?.delete(call.getOpponentDeviceId()!);\n if (retriesMap?.size === 0) this.retryCallCounts.delete(opponentUserId);\n }\n };\n\n private onCallHangup = (call: MatrixCall): void => {\n if (call.hangupReason === CallErrorCode.Replaced) return;\n\n const opponentUserId = call.getOpponentMember()?.userId ?? this.room.getMember(call.invitee!)!.userId;\n const deviceMap = this.calls.get(opponentUserId);\n\n // Sanity check that this call is in fact in the map\n if (deviceMap?.get(call.getOpponentDeviceId()!) === call) {\n this.disposeCall(call, call.hangupReason as CallErrorCode);\n deviceMap.delete(call.getOpponentDeviceId()!);\n if (deviceMap.size === 0) this.calls.delete(opponentUserId);\n this.emit(GroupCallEvent.CallsChanged, this.calls);\n }\n };\n\n private onCallReplaced = (prevCall: MatrixCall, newCall: MatrixCall): void => {\n const opponentUserId = prevCall.getOpponentMember()!.userId;\n\n let deviceMap = this.calls.get(opponentUserId);\n if (deviceMap === undefined) {\n deviceMap = new Map();\n this.calls.set(opponentUserId, deviceMap);\n }\n\n prevCall.hangup(CallErrorCode.Replaced, false);\n this.initCall(newCall);\n deviceMap.set(prevCall.getOpponentDeviceId()!, newCall);\n this.emit(GroupCallEvent.CallsChanged, this.calls);\n };\n\n /*\n * UserMedia CallFeed Event Handlers\n */\n\n public getUserMediaFeed(userId: string, deviceId: string): CallFeed | undefined {\n return this.userMediaFeeds.find((f) => f.userId === userId && f.deviceId! === deviceId);\n }\n\n private addUserMediaFeed(callFeed: CallFeed): void {\n this.userMediaFeeds.push(callFeed);\n callFeed.measureVolumeActivity(true);\n this.emit(GroupCallEvent.UserMediaFeedsChanged, this.userMediaFeeds);\n }\n\n private replaceUserMediaFeed(existingFeed: CallFeed, replacementFeed: CallFeed): void {\n const feedIndex = this.userMediaFeeds.findIndex(\n (f) => f.userId === existingFeed.userId && f.deviceId! === existingFeed.deviceId,\n );\n\n if (feedIndex === -1) {\n throw new Error(\"Couldn't find user media feed to replace\");\n }\n\n this.userMediaFeeds.splice(feedIndex, 1, replacementFeed);\n\n existingFeed.dispose();\n replacementFeed.measureVolumeActivity(true);\n this.emit(GroupCallEvent.UserMediaFeedsChanged, this.userMediaFeeds);\n }\n\n private removeUserMediaFeed(callFeed: CallFeed): void {\n const feedIndex = this.userMediaFeeds.findIndex(\n (f) => f.userId === callFeed.userId && f.deviceId! === callFeed.deviceId,\n );\n\n if (feedIndex === -1) {\n throw new Error(\"Couldn't find user media feed to remove\");\n }\n\n this.userMediaFeeds.splice(feedIndex, 1);\n\n callFeed.dispose();\n this.emit(GroupCallEvent.UserMediaFeedsChanged, this.userMediaFeeds);\n\n if (this.activeSpeaker === callFeed) {\n this.activeSpeaker = this.userMediaFeeds[0];\n this.emit(GroupCallEvent.ActiveSpeakerChanged, this.activeSpeaker);\n }\n }\n\n private onActiveSpeakerLoop = (): void => {\n let topAvg: number | undefined = undefined;\n let nextActiveSpeaker: CallFeed | undefined = undefined;\n\n for (const callFeed of this.userMediaFeeds) {\n if (callFeed.isLocal() && this.userMediaFeeds.length > 1) continue;\n\n const total = callFeed.speakingVolumeSamples.reduce(\n (acc, volume) => acc + Math.max(volume, SPEAKING_THRESHOLD),\n );\n const avg = total / callFeed.speakingVolumeSamples.length;\n\n if (!topAvg || avg > topAvg) {\n topAvg = avg;\n nextActiveSpeaker = callFeed;\n }\n }\n\n if (nextActiveSpeaker && this.activeSpeaker !== nextActiveSpeaker && topAvg && topAvg > SPEAKING_THRESHOLD) {\n this.activeSpeaker = nextActiveSpeaker;\n this.emit(GroupCallEvent.ActiveSpeakerChanged, this.activeSpeaker);\n }\n };\n\n /*\n * Screenshare Call Feed Event Handlers\n */\n\n public getScreenshareFeed(userId: string, deviceId: string): CallFeed | undefined {\n return this.screenshareFeeds.find((f) => f.userId === userId && f.deviceId! === deviceId);\n }\n\n private addScreenshareFeed(callFeed: CallFeed): void {\n this.screenshareFeeds.push(callFeed);\n this.emit(GroupCallEvent.ScreenshareFeedsChanged, this.screenshareFeeds);\n }\n\n private replaceScreenshareFeed(existingFeed: CallFeed, replacementFeed: CallFeed): void {\n const feedIndex = this.screenshareFeeds.findIndex(\n (f) => f.userId === existingFeed.userId && f.deviceId! === existingFeed.deviceId,\n );\n\n if (feedIndex === -1) {\n throw new Error(\"Couldn't find screenshare feed to replace\");\n }\n\n this.screenshareFeeds.splice(feedIndex, 1, replacementFeed);\n\n existingFeed.dispose();\n this.emit(GroupCallEvent.ScreenshareFeedsChanged, this.screenshareFeeds);\n }\n\n private removeScreenshareFeed(callFeed: CallFeed): void {\n const feedIndex = this.screenshareFeeds.findIndex(\n (f) => f.userId === callFeed.userId && f.deviceId! === callFeed.deviceId,\n );\n\n if (feedIndex === -1) {\n throw new Error(\"Couldn't find screenshare feed to remove\");\n }\n\n this.screenshareFeeds.splice(feedIndex, 1);\n\n callFeed.dispose();\n this.emit(GroupCallEvent.ScreenshareFeedsChanged, this.screenshareFeeds);\n }\n\n /**\n * Recalculates and updates the participant map to match the room state.\n */\n private updateParticipants(): void {\n const localMember = this.room.getMember(this.client.getUserId()!)!;\n if (!localMember) {\n // The client hasn't fetched enough of the room state to get our own member\n // event. This probably shouldn't happen, but sanity check & exit for now.\n logger.warn(\n `GroupCall ${this.groupCallId} updateParticipants() tried to update participants before local room member is available`,\n );\n return;\n }\n\n if (this.participantsExpirationTimer !== null) {\n clearTimeout(this.participantsExpirationTimer);\n this.participantsExpirationTimer = null;\n }\n\n if (this.state === GroupCallState.Ended) {\n this.participants = new Map();\n return;\n }\n\n const participants = new Map>();\n const now = Date.now();\n const entered = this.state === GroupCallState.Entered || this.enteredViaAnotherSession;\n let nextExpiration = Infinity;\n\n for (const e of this.getMemberStateEvents()) {\n const member = this.room.getMember(e.getStateKey()!);\n const content = e.getContent>();\n const calls: Record[] = Array.isArray(content[\"m.calls\"]) ? content[\"m.calls\"] : [];\n const call = calls.find((call) => call[\"m.call_id\"] === this.groupCallId);\n const devices: Record[] = Array.isArray(call?.[\"m.devices\"]) ? call![\"m.devices\"] : [];\n\n // Filter out invalid and expired devices\n let validDevices = devices.filter(\n (d) =>\n typeof d.device_id === \"string\" &&\n typeof d.session_id === \"string\" &&\n typeof d.expires_ts === \"number\" &&\n d.expires_ts > now &&\n Array.isArray(d.feeds),\n ) as unknown as IGroupCallRoomMemberDevice[];\n\n // Apply local echo for the unentered case\n if (!entered && member?.userId === this.client.getUserId()!) {\n validDevices = validDevices.filter((d) => d.device_id !== this.client.getDeviceId()!);\n }\n\n // Must have a connected device and be joined to the room\n if (validDevices.length > 0 && member?.membership === \"join\") {\n const deviceMap = new Map();\n participants.set(member, deviceMap);\n\n for (const d of validDevices) {\n deviceMap.set(d.device_id, {\n sessionId: d.session_id,\n screensharing: d.feeds.some((f) => f.purpose === SDPStreamMetadataPurpose.Screenshare),\n });\n if (d.expires_ts < nextExpiration) nextExpiration = d.expires_ts;\n }\n }\n }\n\n // Apply local echo for the entered case\n if (entered) {\n let deviceMap = participants.get(localMember);\n if (deviceMap === undefined) {\n deviceMap = new Map();\n participants.set(localMember, deviceMap);\n }\n\n if (!deviceMap.has(this.client.getDeviceId()!)) {\n deviceMap.set(this.client.getDeviceId()!, {\n sessionId: this.client.getSessionId(),\n screensharing: this.getLocalFeeds().some((f) => f.purpose === SDPStreamMetadataPurpose.Screenshare),\n });\n }\n }\n\n this.participants = participants;\n if (nextExpiration < Infinity) {\n this.participantsExpirationTimer = setTimeout(() => this.updateParticipants(), nextExpiration - now);\n }\n }\n\n /**\n * Updates the local user's member state with the devices returned by the given function.\n * @param fn - A function from the current devices to the new devices. If it\n * returns null, the update will be skipped.\n * @param keepAlive - Whether the request should outlive the window.\n */\n private async updateDevices(\n fn: (devices: IGroupCallRoomMemberDevice[]) => IGroupCallRoomMemberDevice[] | null,\n keepAlive = false,\n ): Promise {\n const now = Date.now();\n const localUserId = this.client.getUserId()!;\n\n const event = this.getMemberStateEvents(localUserId);\n const content = event?.getContent>() ?? {};\n const calls: Record[] = Array.isArray(content[\"m.calls\"]) ? content[\"m.calls\"] : [];\n\n let call: Record | null = null;\n const otherCalls: Record[] = [];\n for (const c of calls) {\n if (c[\"m.call_id\"] === this.groupCallId) {\n call = c;\n } else {\n otherCalls.push(c);\n }\n }\n if (call === null) call = {};\n\n const devices: Record[] = Array.isArray(call[\"m.devices\"]) ? call[\"m.devices\"] : [];\n\n // Filter out invalid and expired devices\n const validDevices = devices.filter(\n (d) =>\n typeof d.device_id === \"string\" &&\n typeof d.session_id === \"string\" &&\n typeof d.expires_ts === \"number\" &&\n d.expires_ts > now &&\n Array.isArray(d.feeds),\n ) as unknown as IGroupCallRoomMemberDevice[];\n\n const newDevices = fn(validDevices);\n if (newDevices === null) return;\n\n const newCalls = [...(otherCalls as unknown as IGroupCallRoomMemberCallState[])];\n if (newDevices.length > 0) {\n newCalls.push({\n ...call,\n \"m.call_id\": this.groupCallId,\n \"m.devices\": newDevices,\n });\n }\n\n const newContent: IGroupCallRoomMemberState = { \"m.calls\": newCalls };\n\n await this.client.sendStateEvent(this.room.roomId, EventType.GroupCallMemberPrefix, newContent, localUserId, {\n keepAlive,\n });\n }\n\n private async addDeviceToMemberState(): Promise {\n await this.updateDevices((devices) => [\n ...devices.filter((d) => d.device_id !== this.client.getDeviceId()!),\n {\n device_id: this.client.getDeviceId()!,\n session_id: this.client.getSessionId(),\n expires_ts: Date.now() + DEVICE_TIMEOUT,\n feeds: this.getLocalFeeds().map((feed) => ({ purpose: feed.purpose })),\n // TODO: Add data channels\n },\n ]);\n }\n\n private async updateMemberState(): Promise {\n // Clear the old update interval before proceeding\n if (this.resendMemberStateTimer !== null) {\n clearInterval(this.resendMemberStateTimer);\n this.resendMemberStateTimer = null;\n }\n\n if (this.state === GroupCallState.Entered) {\n // Add the local device\n await this.addDeviceToMemberState();\n\n // Resend the state event every so often so it doesn't become stale\n this.resendMemberStateTimer = setInterval(async () => {\n logger.log(`GroupCall ${this.groupCallId} updateMemberState() resending call member state\"`);\n try {\n await this.addDeviceToMemberState();\n } catch (e) {\n logger.error(\n `GroupCall ${this.groupCallId} updateMemberState() failed to resend call member state`,\n e,\n );\n }\n }, (DEVICE_TIMEOUT * 3) / 4);\n } else {\n // Remove the local device\n await this.updateDevices(\n (devices) => devices.filter((d) => d.device_id !== this.client.getDeviceId()!),\n true,\n );\n }\n }\n\n /**\n * Cleans up our member state by filtering out logged out devices, inactive\n * devices, and our own device (if we know we haven't entered).\n */\n public async cleanMemberState(): Promise {\n const { devices: myDevices } = await this.client.getDevices();\n const deviceMap = new Map(myDevices.map((d) => [d.device_id, d]));\n\n // updateDevices takes care of filtering out inactive devices for us\n await this.updateDevices((devices) => {\n const newDevices = devices.filter((d) => {\n const device = deviceMap.get(d.device_id);\n return (\n device?.last_seen_ts !== undefined &&\n !(\n d.device_id === this.client.getDeviceId()! &&\n this.state !== GroupCallState.Entered &&\n !this.enteredViaAnotherSession\n )\n );\n });\n\n // Skip the update if the devices are unchanged\n return newDevices.length === devices.length ? null : newDevices;\n });\n }\n\n private onRoomState = (): void => this.updateParticipants();\n\n private onParticipantsChanged = (): void => {\n // Re-run setTracksEnabled on all calls, so that participants that just\n // left get denied access to our media, and participants that just\n // joined get granted access\n this.forEachCall((call) => {\n const expected = this.callExpected(call);\n for (const feed of call.getLocalFeeds()) {\n setTracksEnabled(feed.stream.getAudioTracks(), !feed.isAudioMuted() && expected);\n setTracksEnabled(feed.stream.getVideoTracks(), !feed.isVideoMuted() && expected);\n }\n });\n\n if (this.state === GroupCallState.Entered) this.placeOutgoingCalls();\n };\n\n private onStateChanged = (newState: GroupCallState, oldState: GroupCallState): void => {\n if (\n newState === GroupCallState.Entered ||\n oldState === GroupCallState.Entered ||\n newState === GroupCallState.Ended\n ) {\n // We either entered, left, or ended the call\n this.updateParticipants();\n this.updateMemberState().catch((e) =>\n logger.error(\n `GroupCall ${this.groupCallId} onStateChanged() failed to update member state devices\"`,\n e,\n ),\n );\n }\n };\n\n private onLocalFeedsChanged = (): void => {\n if (this.state === GroupCallState.Entered) {\n this.updateMemberState().catch((e) =>\n logger.error(\n `GroupCall ${this.groupCallId} onLocalFeedsChanged() failed to update member state feeds`,\n e,\n ),\n );\n }\n };\n\n public getGroupCallStats(): GroupCallStats {\n return this.stats;\n }\n}\n", - "/*\nCopyright 2021 Šimon Brandner \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MatrixEvent } from \"../models/event\";\nimport { MatrixClient, ClientEvent } from \"../client\";\nimport { GroupCall, GroupCallIntent, GroupCallType, IGroupCallDataChannelOptions } from \"./groupCall\";\nimport { Room } from \"../models/room\";\nimport { RoomState, RoomStateEvent } from \"../models/room-state\";\nimport { RoomMember } from \"../models/room-member\";\nimport { logger } from \"../logger\";\nimport { EventType } from \"../@types/event\";\nimport { SyncState } from \"../sync\";\n\nexport enum GroupCallEventHandlerEvent {\n Incoming = \"GroupCall.incoming\",\n Outgoing = \"GroupCall.outgoing\",\n Ended = \"GroupCall.ended\",\n Participants = \"GroupCall.participants\",\n}\n\nexport type GroupCallEventHandlerEventHandlerMap = {\n [GroupCallEventHandlerEvent.Incoming]: (call: GroupCall) => void;\n [GroupCallEventHandlerEvent.Outgoing]: (call: GroupCall) => void;\n [GroupCallEventHandlerEvent.Ended]: (call: GroupCall) => void;\n [GroupCallEventHandlerEvent.Participants]: (participants: RoomMember[], call: GroupCall) => void;\n};\n\ninterface RoomDeferred {\n prom: Promise;\n resolve?: () => void;\n}\n\nexport class GroupCallEventHandler {\n public groupCalls = new Map(); // roomId -> GroupCall\n\n // All rooms we know about and whether we've seen a 'Room' event\n // for them. The promise will be fulfilled once we've processed that\n // event which means we're \"up to date\" on what calls are in a room\n // and get\n private roomDeferreds = new Map();\n\n public constructor(private client: MatrixClient) {}\n\n public async start(): Promise {\n // We wait until the client has started syncing for real.\n // This is because we only support one call at a time, and want\n // the latest. We therefore want the latest state of the room before\n // we create a group call for the room so we can be fairly sure that\n // the group call we create is really the latest one.\n if (this.client.getSyncState() !== SyncState.Syncing) {\n logger.debug(\"GroupCallEventHandler start() waiting for client to start syncing\");\n await new Promise((resolve) => {\n const onSync = (): void => {\n if (this.client.getSyncState() === SyncState.Syncing) {\n this.client.off(ClientEvent.Sync, onSync);\n return resolve();\n }\n };\n this.client.on(ClientEvent.Sync, onSync);\n });\n }\n\n const rooms = this.client.getRooms();\n\n for (const room of rooms) {\n this.createGroupCallForRoom(room);\n }\n\n this.client.on(ClientEvent.Room, this.onRoomsChanged);\n this.client.on(RoomStateEvent.Events, this.onRoomStateChanged);\n }\n\n public stop(): void {\n this.client.removeListener(RoomStateEvent.Events, this.onRoomStateChanged);\n }\n\n private getRoomDeferred(roomId: string): RoomDeferred {\n let deferred = this.roomDeferreds.get(roomId);\n if (deferred === undefined) {\n let resolveFunc: () => void;\n deferred = {\n prom: new Promise((resolve) => {\n resolveFunc = resolve;\n }),\n };\n deferred.resolve = resolveFunc!;\n this.roomDeferreds.set(roomId, deferred);\n }\n\n return deferred;\n }\n\n public waitUntilRoomReadyForGroupCalls(roomId: string): Promise {\n return this.getRoomDeferred(roomId).prom;\n }\n\n public getGroupCallById(groupCallId: string): GroupCall | undefined {\n return [...this.groupCalls.values()].find((groupCall) => groupCall.groupCallId === groupCallId);\n }\n\n private createGroupCallForRoom(room: Room): void {\n const callEvents = room.currentState.getStateEvents(EventType.GroupCallPrefix);\n const sortedCallEvents = callEvents.sort((a, b) => b.getTs() - a.getTs());\n\n for (const callEvent of sortedCallEvents) {\n const content = callEvent.getContent();\n\n if (content[\"m.terminated\"] || callEvent.isRedacted()) {\n continue;\n }\n\n logger.debug(\n `GroupCallEventHandler createGroupCallForRoom() choosing group call from possible calls (stateKey=${callEvent.getStateKey()}, ts=${callEvent.getTs()}, roomId=${\n room.roomId\n }, numOfPossibleCalls=${callEvents.length})`,\n );\n\n this.createGroupCallFromRoomStateEvent(callEvent);\n break;\n }\n\n logger.info(`GroupCallEventHandler createGroupCallForRoom() processed room (roomId=${room.roomId})`);\n this.getRoomDeferred(room.roomId).resolve!();\n }\n\n private createGroupCallFromRoomStateEvent(event: MatrixEvent): GroupCall | undefined {\n const roomId = event.getRoomId();\n const content = event.getContent();\n\n const room = this.client.getRoom(roomId);\n\n if (!room) {\n logger.warn(\n `GroupCallEventHandler createGroupCallFromRoomStateEvent() couldn't find room for call (roomId=${roomId})`,\n );\n return;\n }\n\n const groupCallId = event.getStateKey();\n\n const callType = content[\"m.type\"];\n\n if (!Object.values(GroupCallType).includes(callType)) {\n logger.warn(\n `GroupCallEventHandler createGroupCallFromRoomStateEvent() received invalid call type (type=${callType}, roomId=${roomId})`,\n );\n return;\n }\n\n const callIntent = content[\"m.intent\"];\n\n if (!Object.values(GroupCallIntent).includes(callIntent)) {\n logger.warn(`Received invalid group call intent (type=${callType}, roomId=${roomId})`);\n return;\n }\n\n const isPtt = Boolean(content[\"io.element.ptt\"]);\n\n let dataChannelOptions: IGroupCallDataChannelOptions | undefined;\n\n if (content?.dataChannelsEnabled && content?.dataChannelOptions) {\n // Pull out just the dataChannelOptions we want to support.\n const { ordered, maxPacketLifeTime, maxRetransmits, protocol } = content.dataChannelOptions;\n dataChannelOptions = { ordered, maxPacketLifeTime, maxRetransmits, protocol };\n }\n\n const groupCall = new GroupCall(\n this.client,\n room,\n callType,\n isPtt,\n callIntent,\n groupCallId,\n // Because without Media section a WebRTC connection is not possible, so need a RTCDataChannel to set up a\n // no media WebRTC connection anyway.\n content?.dataChannelsEnabled || this.client.isVoipWithNoMediaAllowed,\n dataChannelOptions,\n this.client.isVoipWithNoMediaAllowed,\n );\n\n this.groupCalls.set(room.roomId, groupCall);\n this.client.emit(GroupCallEventHandlerEvent.Incoming, groupCall);\n\n return groupCall;\n }\n\n private onRoomsChanged = (room: Room): void => {\n this.createGroupCallForRoom(room);\n };\n\n private onRoomStateChanged = (event: MatrixEvent, state: RoomState): void => {\n const eventType = event.getType();\n\n if (eventType === EventType.GroupCallPrefix) {\n const groupCallId = event.getStateKey();\n const content = event.getContent();\n\n const currentGroupCall = this.groupCalls.get(state.roomId);\n\n if (!currentGroupCall && !content[\"m.terminated\"] && !event.isRedacted()) {\n this.createGroupCallFromRoomStateEvent(event);\n } else if (currentGroupCall && currentGroupCall.groupCallId === groupCallId) {\n if (content[\"m.terminated\"] || event.isRedacted()) {\n currentGroupCall.terminate(false);\n } else if (content[\"m.type\"] !== currentGroupCall.type) {\n // TODO: Handle the callType changing when the room state changes\n logger.warn(\n `GroupCallEventHandler onRoomStateChanged() currently does not support changing type (roomId=${state.roomId})`,\n );\n }\n } else if (currentGroupCall && currentGroupCall.groupCallId !== groupCallId) {\n // TODO: Handle new group calls and multiple group calls\n logger.warn(\n `GroupCallEventHandler onRoomStateChanged() currently does not support multiple calls (roomId=${state.roomId})`,\n );\n }\n }\n };\n}\n", - "/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 New Vector Ltd\nCopyright 2019, 2020 The Matrix.org Foundation C.I.C.\nCopyright 2021 - 2022 Šimon Brandner \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { TypedEventEmitter } from \"../models/typed-event-emitter\";\nimport { GroupCallType, GroupCallState } from \"../webrtc/groupCall\";\nimport { logger } from \"../logger\";\nimport { MatrixClient } from \"../client\";\n\nexport enum MediaHandlerEvent {\n LocalStreamsChanged = \"local_streams_changed\",\n}\n\nexport type MediaHandlerEventHandlerMap = {\n [MediaHandlerEvent.LocalStreamsChanged]: () => void;\n};\n\nexport interface IScreensharingOpts {\n desktopCapturerSourceId?: string;\n audio?: boolean;\n // For electron screen capture, there are very few options for detecting electron\n // apart from inspecting the user agent or just trying getDisplayMedia() and\n // catching the failure, so we do the latter - this flag tells the function to just\n // throw an error so we can catch it in this case, rather than logging and emitting.\n throwOnFail?: boolean;\n}\n\nexport interface AudioSettings {\n autoGainControl: boolean;\n echoCancellation: boolean;\n noiseSuppression: boolean;\n}\n\nexport class MediaHandler extends TypedEventEmitter<\n MediaHandlerEvent.LocalStreamsChanged,\n MediaHandlerEventHandlerMap\n> {\n private audioInput?: string;\n private audioSettings?: AudioSettings;\n private videoInput?: string;\n private localUserMediaStream?: MediaStream;\n public userMediaStreams: MediaStream[] = [];\n public screensharingStreams: MediaStream[] = [];\n\n // Promise chain to serialise calls to getMediaStream\n private getMediaStreamPromise?: Promise;\n\n public constructor(private client: MatrixClient) {\n super();\n }\n\n public restoreMediaSettings(audioInput: string, videoInput: string): void {\n this.audioInput = audioInput;\n this.videoInput = videoInput;\n }\n\n /**\n * Set an audio input device to use for MatrixCalls\n * @param deviceId - the identifier for the device\n * undefined treated as unset\n */\n public async setAudioInput(deviceId: string): Promise {\n logger.info(`MediaHandler setAudioInput() running (deviceId=${deviceId})`);\n\n if (this.audioInput === deviceId) return;\n\n this.audioInput = deviceId;\n await this.updateLocalUsermediaStreams();\n }\n\n /**\n * Set audio settings for MatrixCalls\n * @param opts - audio options to set\n */\n public async setAudioSettings(opts: AudioSettings): Promise {\n logger.info(`MediaHandler setAudioSettings() running (opts=${JSON.stringify(opts)})`);\n\n this.audioSettings = Object.assign({}, opts) as AudioSettings;\n await this.updateLocalUsermediaStreams();\n }\n\n /**\n * Set a video input device to use for MatrixCalls\n * @param deviceId - the identifier for the device\n * undefined treated as unset\n */\n public async setVideoInput(deviceId: string): Promise {\n logger.info(`MediaHandler setVideoInput() running (deviceId=${deviceId})`);\n\n if (this.videoInput === deviceId) return;\n\n this.videoInput = deviceId;\n await this.updateLocalUsermediaStreams();\n }\n\n /**\n * Set media input devices to use for MatrixCalls\n * @param audioInput - the identifier for the audio device\n * @param videoInput - the identifier for the video device\n * undefined treated as unset\n */\n public async setMediaInputs(audioInput: string, videoInput: string): Promise {\n logger.log(`MediaHandler setMediaInputs() running (audioInput: ${audioInput} videoInput: ${videoInput})`);\n this.audioInput = audioInput;\n this.videoInput = videoInput;\n await this.updateLocalUsermediaStreams();\n }\n\n /*\n * Requests new usermedia streams and replace the old ones\n */\n public async updateLocalUsermediaStreams(): Promise {\n if (this.userMediaStreams.length === 0) return;\n\n const callMediaStreamParams: Map = new Map();\n for (const call of this.client.callEventHandler!.calls.values()) {\n callMediaStreamParams.set(call.callId, {\n audio: call.hasLocalUserMediaAudioTrack,\n video: call.hasLocalUserMediaVideoTrack,\n });\n }\n\n for (const stream of this.userMediaStreams) {\n logger.log(`MediaHandler updateLocalUsermediaStreams() stopping all tracks (streamId=${stream.id})`);\n for (const track of stream.getTracks()) {\n track.stop();\n }\n }\n\n this.userMediaStreams = [];\n this.localUserMediaStream = undefined;\n\n for (const call of this.client.callEventHandler!.calls.values()) {\n if (call.callHasEnded() || !callMediaStreamParams.has(call.callId)) {\n continue;\n }\n\n const { audio, video } = callMediaStreamParams.get(call.callId)!;\n\n logger.log(\n `MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (callId=${call.callId})`,\n );\n const stream = await this.getUserMediaStream(audio, video);\n\n if (call.callHasEnded()) {\n continue;\n }\n\n await call.updateLocalUsermediaStream(stream);\n }\n\n for (const groupCall of this.client.groupCallEventHandler!.groupCalls.values()) {\n if (!groupCall.localCallFeed) {\n continue;\n }\n\n logger.log(\n `MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (groupCallId=${groupCall.groupCallId})`,\n );\n const stream = await this.getUserMediaStream(true, groupCall.type === GroupCallType.Video);\n\n if (groupCall.state === GroupCallState.Ended) {\n continue;\n }\n\n await groupCall.updateLocalUsermediaStream(stream);\n }\n\n this.emit(MediaHandlerEvent.LocalStreamsChanged);\n }\n\n public async hasAudioDevice(): Promise {\n try {\n const devices = await navigator.mediaDevices.enumerateDevices();\n return devices.filter((device) => device.kind === \"audioinput\").length > 0;\n } catch (err) {\n logger.log(`MediaHandler hasAudioDevice() calling navigator.mediaDevices.enumerateDevices with error`, err);\n return false;\n }\n }\n\n public async hasVideoDevice(): Promise {\n try {\n const devices = await navigator.mediaDevices.enumerateDevices();\n return devices.filter((device) => device.kind === \"videoinput\").length > 0;\n } catch (err) {\n logger.log(`MediaHandler hasVideoDevice() calling navigator.mediaDevices.enumerateDevices with error`, err);\n return false;\n }\n }\n\n /**\n * @param audio - should have an audio track\n * @param video - should have a video track\n * @param reusable - is allowed to be reused by the MediaHandler\n * @returns based on passed parameters\n */\n public async getUserMediaStream(audio: boolean, video: boolean, reusable = true): Promise {\n // Serialise calls, othertwise we can't sensibly re-use the stream\n if (this.getMediaStreamPromise) {\n this.getMediaStreamPromise = this.getMediaStreamPromise.then(() => {\n return this.getUserMediaStreamInternal(audio, video, reusable);\n });\n } else {\n this.getMediaStreamPromise = this.getUserMediaStreamInternal(audio, video, reusable);\n }\n\n return this.getMediaStreamPromise;\n }\n\n private async getUserMediaStreamInternal(audio: boolean, video: boolean, reusable: boolean): Promise {\n const shouldRequestAudio = audio && (await this.hasAudioDevice());\n const shouldRequestVideo = video && (await this.hasVideoDevice());\n\n let stream: MediaStream;\n\n let canReuseStream = true;\n if (this.localUserMediaStream) {\n // This figures out if we can reuse the current localUsermediaStream\n // based on whether or not the \"mute state\" (presence of tracks of a\n // given kind) matches what is being requested\n if (shouldRequestAudio !== this.localUserMediaStream.getAudioTracks().length > 0) {\n canReuseStream = false;\n }\n if (shouldRequestVideo !== this.localUserMediaStream.getVideoTracks().length > 0) {\n canReuseStream = false;\n }\n\n // This code checks that the device ID is the same as the localUserMediaStream stream, but we update\n // the localUserMediaStream whenever the device ID changes (apart from when restoring) so it's not\n // clear why this would ever be different, unless there's a race.\n if (\n shouldRequestAudio &&\n this.localUserMediaStream.getAudioTracks()[0]?.getSettings()?.deviceId !== this.audioInput\n ) {\n canReuseStream = false;\n }\n if (\n shouldRequestVideo &&\n this.localUserMediaStream.getVideoTracks()[0]?.getSettings()?.deviceId !== this.videoInput\n ) {\n canReuseStream = false;\n }\n } else {\n canReuseStream = false;\n }\n\n if (!canReuseStream) {\n const constraints = this.getUserMediaContraints(shouldRequestAudio, shouldRequestVideo);\n stream = await navigator.mediaDevices.getUserMedia(constraints);\n logger.log(\n `MediaHandler getUserMediaStreamInternal() calling getUserMediaStream (streamId=${\n stream.id\n }, shouldRequestAudio=${shouldRequestAudio}, shouldRequestVideo=${shouldRequestVideo}, constraints=${JSON.stringify(\n constraints,\n )})`,\n );\n\n for (const track of stream.getTracks()) {\n const settings = track.getSettings();\n\n if (track.kind === \"audio\") {\n this.audioInput = settings.deviceId!;\n } else if (track.kind === \"video\") {\n this.videoInput = settings.deviceId!;\n }\n }\n\n if (reusable) {\n this.localUserMediaStream = stream;\n }\n } else {\n stream = this.localUserMediaStream!.clone();\n logger.log(\n `MediaHandler getUserMediaStreamInternal() cloning (oldStreamId=${this.localUserMediaStream?.id} newStreamId=${stream.id} shouldRequestAudio=${shouldRequestAudio} shouldRequestVideo=${shouldRequestVideo})`,\n );\n\n if (!shouldRequestAudio) {\n for (const track of stream.getAudioTracks()) {\n stream.removeTrack(track);\n }\n }\n\n if (!shouldRequestVideo) {\n for (const track of stream.getVideoTracks()) {\n stream.removeTrack(track);\n }\n }\n }\n\n if (reusable) {\n this.userMediaStreams.push(stream);\n }\n\n this.emit(MediaHandlerEvent.LocalStreamsChanged);\n\n return stream;\n }\n\n /**\n * Stops all tracks on the provided usermedia stream\n */\n public stopUserMediaStream(mediaStream: MediaStream): void {\n logger.log(`MediaHandler stopUserMediaStream() stopping (streamId=${mediaStream.id})`);\n for (const track of mediaStream.getTracks()) {\n track.stop();\n }\n\n const index = this.userMediaStreams.indexOf(mediaStream);\n\n if (index !== -1) {\n logger.debug(\n `MediaHandler stopUserMediaStream() splicing usermedia stream out stream array (streamId=${mediaStream.id})`,\n mediaStream.id,\n );\n this.userMediaStreams.splice(index, 1);\n }\n\n this.emit(MediaHandlerEvent.LocalStreamsChanged);\n\n if (this.localUserMediaStream === mediaStream) {\n this.localUserMediaStream = undefined;\n }\n }\n\n /**\n * @param desktopCapturerSourceId - sourceId for Electron DesktopCapturer\n * @param reusable - is allowed to be reused by the MediaHandler\n * @returns based on passed parameters\n */\n public async getScreensharingStream(opts: IScreensharingOpts = {}, reusable = true): Promise {\n let stream: MediaStream;\n\n if (this.screensharingStreams.length === 0) {\n const screenshareConstraints = this.getScreenshareContraints(opts);\n\n if (opts.desktopCapturerSourceId) {\n // We are using Electron\n logger.debug(\n `MediaHandler getScreensharingStream() calling getUserMedia() (opts=${JSON.stringify(opts)})`,\n );\n stream = await navigator.mediaDevices.getUserMedia(screenshareConstraints);\n } else {\n // We are not using Electron\n logger.debug(\n `MediaHandler getScreensharingStream() calling getDisplayMedia() (opts=${JSON.stringify(opts)})`,\n );\n stream = await navigator.mediaDevices.getDisplayMedia(screenshareConstraints);\n }\n } else {\n const matchingStream = this.screensharingStreams[this.screensharingStreams.length - 1];\n logger.log(`MediaHandler getScreensharingStream() cloning (streamId=${matchingStream.id})`);\n stream = matchingStream.clone();\n }\n\n if (reusable) {\n this.screensharingStreams.push(stream);\n }\n\n this.emit(MediaHandlerEvent.LocalStreamsChanged);\n\n return stream;\n }\n\n /**\n * Stops all tracks on the provided screensharing stream\n */\n public stopScreensharingStream(mediaStream: MediaStream): void {\n logger.debug(`MediaHandler stopScreensharingStream() stopping stream (streamId=${mediaStream.id})`);\n for (const track of mediaStream.getTracks()) {\n track.stop();\n }\n\n const index = this.screensharingStreams.indexOf(mediaStream);\n\n if (index !== -1) {\n logger.debug(`MediaHandler stopScreensharingStream() splicing stream out (streamId=${mediaStream.id})`);\n this.screensharingStreams.splice(index, 1);\n }\n\n this.emit(MediaHandlerEvent.LocalStreamsChanged);\n }\n\n /**\n * Stops all local media tracks\n */\n public stopAllStreams(): void {\n for (const stream of this.userMediaStreams) {\n logger.log(`MediaHandler stopAllStreams() stopping (streamId=${stream.id})`);\n for (const track of stream.getTracks()) {\n track.stop();\n }\n }\n\n for (const stream of this.screensharingStreams) {\n for (const track of stream.getTracks()) {\n track.stop();\n }\n }\n\n this.userMediaStreams = [];\n this.screensharingStreams = [];\n this.localUserMediaStream = undefined;\n\n this.emit(MediaHandlerEvent.LocalStreamsChanged);\n }\n\n private getUserMediaContraints(audio: boolean, video: boolean): MediaStreamConstraints {\n const isWebkit = !!navigator.webkitGetUserMedia;\n\n return {\n audio: audio\n ? {\n deviceId: this.audioInput ? { ideal: this.audioInput } : undefined,\n autoGainControl: this.audioSettings ? { ideal: this.audioSettings.autoGainControl } : undefined,\n echoCancellation: this.audioSettings ? { ideal: this.audioSettings.echoCancellation } : undefined,\n noiseSuppression: this.audioSettings ? { ideal: this.audioSettings.noiseSuppression } : undefined,\n }\n : false,\n video: video\n ? {\n deviceId: this.videoInput ? { ideal: this.videoInput } : undefined,\n /* We want 640x360. Chrome will give it only if we ask exactly,\n FF refuses entirely if we ask exactly, so have to ask for ideal\n instead\n XXX: Is this still true?\n */\n width: isWebkit ? { exact: 640 } : { ideal: 640 },\n height: isWebkit ? { exact: 360 } : { ideal: 360 },\n }\n : false,\n };\n }\n\n private getScreenshareContraints(opts: IScreensharingOpts): DesktopCapturerConstraints {\n const { desktopCapturerSourceId, audio } = opts;\n if (desktopCapturerSourceId) {\n return {\n audio: audio ?? false,\n video: {\n mandatory: {\n chromeMediaSource: \"desktop\",\n chromeMediaSourceId: desktopCapturerSourceId,\n },\n },\n };\n } else {\n return {\n audio: audio ?? false,\n video: true,\n };\n }\n }\n}\n", - "/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { TransportStats } from \"./transportStats\";\nimport { Bitrate } from \"./media/mediaTrackStats\";\n\nexport interface ConnectionStatsBandwidth {\n /**\n * bytes per second\n */\n download: number;\n /**\n * bytes per second\n */\n upload: number;\n}\n\nexport interface ConnectionStatsBitrate extends Bitrate {\n audio?: Bitrate;\n video?: Bitrate;\n}\n\nexport interface PacketLoos {\n total: number;\n download: number;\n upload: number;\n}\n\nexport class ConnectionStats {\n public bandwidth: ConnectionStatsBitrate = {} as ConnectionStatsBitrate;\n public bitrate: ConnectionStatsBitrate = {} as ConnectionStatsBitrate;\n public packetLoss: PacketLoos = {} as PacketLoos;\n public transport: TransportStats[] = [];\n}\n", - "/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport { Bitrate } from \"./media/mediaTrackStats\";\n\nexport class ConnectionStatsReporter {\n public static buildBandwidthReport(now: RTCIceCandidatePairStats): Bitrate {\n const availableIncomingBitrate = now.availableIncomingBitrate;\n const availableOutgoingBitrate = now.availableOutgoingBitrate;\n\n return {\n download: availableIncomingBitrate ? Math.round(availableIncomingBitrate / 1000) : 0,\n upload: availableOutgoingBitrate ? Math.round(availableOutgoingBitrate / 1000) : 0,\n };\n }\n}\n", - "/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport { StatsReportGatherer } from \"./statsReportGatherer\";\nimport { StatsReportEmitter } from \"./statsReportEmitter\";\n\nexport class GroupCallStats {\n private timer: undefined | ReturnType;\n private readonly gatherers: Map = new Map();\n public readonly reports = new StatsReportEmitter();\n\n public constructor(private groupCallId: string, private userId: string, private interval: number = 10000) {}\n\n public start(): void {\n if (this.timer === undefined) {\n this.timer = setInterval(() => {\n this.processStats();\n }, this.interval);\n }\n }\n\n public stop(): void {\n if (this.timer !== undefined) {\n clearInterval(this.timer);\n this.gatherers.forEach((c) => c.stopProcessingStats());\n }\n }\n\n public hasStatsReportGatherer(callId: string): boolean {\n return this.gatherers.has(callId);\n }\n\n public addStatsReportGatherer(callId: string, userId: string, peerConnection: RTCPeerConnection): boolean {\n if (this.hasStatsReportGatherer(callId)) {\n return false;\n }\n this.gatherers.set(callId, new StatsReportGatherer(callId, userId, peerConnection, this.reports));\n return true;\n }\n\n public removeStatsReportGatherer(callId: string): boolean {\n return this.gatherers.delete(callId);\n }\n\n public getStatsReportGatherer(callId: string): StatsReportGatherer | undefined {\n return this.hasStatsReportGatherer(callId) ? this.gatherers.get(callId) : undefined;\n }\n\n private processStats(): void {\n this.gatherers.forEach((c) => c.processStats(this.groupCallId, this.userId));\n }\n}\n", - "/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { parse as parseSdp } from \"sdp-transform\";\n\nexport type Mid = string;\nexport type Ssrc = string;\nexport type MapType = \"local\" | \"remote\";\n\nexport class MediaSsrcHandler {\n private readonly ssrcToMid = { local: new Map(), remote: new Map() };\n\n public findMidBySsrc(ssrc: Ssrc, type: \"local\" | \"remote\"): Mid | undefined {\n let mid: Mid | undefined;\n this.ssrcToMid[type].forEach((ssrcs, m) => {\n if (ssrcs.find((s) => s == ssrc)) {\n mid = m;\n return;\n }\n });\n return mid;\n }\n\n public parse(description: string, type: MapType): void {\n const sdp = parseSdp(description);\n const ssrcToMid = new Map();\n sdp.media.forEach((m) => {\n if ((!!m.mid && m.type === \"video\") || m.type === \"audio\") {\n const ssrcs: Ssrc[] = [];\n m.ssrcs?.forEach((ssrc) => {\n if (ssrc.attribute === \"cname\") {\n ssrcs.push(`${ssrc.id}`);\n }\n });\n ssrcToMid.set(`${m.mid}`, ssrcs);\n }\n });\n this.ssrcToMid[type] = ssrcToMid;\n }\n\n public getSsrcToMidMap(type: MapType): Map {\n return this.ssrcToMid[type];\n }\n}\n", - "/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport type TrackId = string;\n\nexport class MediaTrackHandler {\n public constructor(private readonly pc: RTCPeerConnection) {}\n\n public getLocalTracks(kind: \"audio\" | \"video\"): MediaStreamTrack[] {\n const isNotNullAndKind = (track: MediaStreamTrack | null): boolean => {\n return track !== null && track.kind === kind;\n };\n // @ts-ignore The linter don't get it\n return this.pc\n .getTransceivers()\n .filter((t) => t.currentDirection === \"sendonly\" || t.currentDirection === \"sendrecv\")\n .filter((t) => t.sender !== null)\n .map((t) => t.sender)\n .map((s) => s.track)\n .filter(isNotNullAndKind);\n }\n\n public getTackById(trackId: string): MediaStreamTrack | undefined {\n return this.pc\n .getTransceivers()\n .map((t) => {\n if (t?.sender.track !== null && t.sender.track.id === trackId) {\n return t.sender.track;\n }\n if (t?.receiver.track !== null && t.receiver.track.id === trackId) {\n return t.receiver.track;\n }\n return undefined;\n })\n .find((t) => t !== undefined);\n }\n\n public getLocalTrackIdByMid(mid: string): string | undefined {\n const transceiver = this.pc.getTransceivers().find((t) => t.mid === mid);\n if (transceiver !== undefined && !!transceiver.sender && !!transceiver.sender.track) {\n return transceiver.sender.track.id;\n }\n return undefined;\n }\n\n public getRemoteTrackIdByMid(mid: string): string | undefined {\n const transceiver = this.pc.getTransceivers().find((t) => t.mid === mid);\n if (transceiver !== undefined && !!transceiver.receiver && !!transceiver.receiver.track) {\n return transceiver.receiver.track.id;\n }\n return undefined;\n }\n\n public getActiveSimulcastStreams(): number {\n //@TODO implement this right.. Check how many layer configured\n return 3;\n }\n}\n", - "/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { TrackId } from \"./mediaTrackHandler\";\n\nexport interface PacketLoss {\n packetsTotal: number;\n packetsLost: number;\n isDownloadStream: boolean;\n}\n\nexport interface Bitrate {\n /**\n * bytes per second\n */\n download: number;\n /**\n * bytes per second\n */\n upload: number;\n}\n\nexport interface Resolution {\n width: number;\n height: number;\n}\n\nexport type TrackStatsType = \"local\" | \"remote\";\n\nexport class MediaTrackStats {\n private loss: PacketLoss = { packetsTotal: 0, packetsLost: 0, isDownloadStream: false };\n private bitrate: Bitrate = { download: 0, upload: 0 };\n private resolution: Resolution = { width: -1, height: -1 };\n private framerate = 0;\n private codec = \"\";\n\n public constructor(\n public readonly trackId: TrackId,\n public readonly type: TrackStatsType,\n public readonly kind: \"audio\" | \"video\",\n ) {}\n\n public getType(): TrackStatsType {\n return this.type;\n }\n\n public setLoss(loos: PacketLoss): void {\n this.loss = loos;\n }\n\n public getLoss(): PacketLoss {\n return this.loss;\n }\n\n public setResolution(resolution: Resolution): void {\n this.resolution = resolution;\n }\n\n public getResolution(): Resolution {\n return this.resolution;\n }\n\n public setFramerate(framerate: number): void {\n this.framerate = framerate;\n }\n\n public getFramerate(): number {\n return this.framerate;\n }\n\n public setBitrate(bitrate: Bitrate): void {\n this.bitrate = bitrate;\n }\n\n public getBitrate(): Bitrate {\n return this.bitrate;\n }\n\n public setCodec(codecShortType: string): boolean {\n this.codec = codecShortType;\n return true;\n }\n\n public getCodec(): string {\n return this.codec;\n }\n\n public resetBitrate(): void {\n this.bitrate = { download: 0, upload: 0 };\n }\n}\n", - "/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport { TrackID } from \"../statsReport\";\nimport { MediaTrackStats } from \"./mediaTrackStats\";\nimport { MediaTrackHandler } from \"./mediaTrackHandler\";\nimport { MediaSsrcHandler } from \"./mediaSsrcHandler\";\n\nexport class MediaTrackStatsHandler {\n private readonly track2stats = new Map();\n\n public constructor(\n public readonly mediaSsrcHandler: MediaSsrcHandler,\n public readonly mediaTrackHandler: MediaTrackHandler,\n ) {}\n\n /**\n * Find tracks by rtc stats\n * Argument report is any because the stats api is not consistent:\n * For example `trackIdentifier`, `mid` not existing in every implementations\n * https://www.w3.org/TR/webrtc-stats/#dom-rtcinboundrtpstreamstats\n * https://developer.mozilla.org/en-US/docs/Web/API/RTCInboundRtpStreamStats\n */\n public findTrack2Stats(report: any, type: \"remote\" | \"local\"): MediaTrackStats | undefined {\n let trackID;\n if (report.trackIdentifier) {\n trackID = report.trackIdentifier;\n } else if (report.mid) {\n trackID =\n type === \"remote\"\n ? this.mediaTrackHandler.getRemoteTrackIdByMid(report.mid)\n : this.mediaTrackHandler.getLocalTrackIdByMid(report.mid);\n } else if (report.ssrc) {\n const mid = this.mediaSsrcHandler.findMidBySsrc(report.ssrc, type);\n if (!mid) {\n return undefined;\n }\n trackID =\n type === \"remote\"\n ? this.mediaTrackHandler.getRemoteTrackIdByMid(report.mid)\n : this.mediaTrackHandler.getLocalTrackIdByMid(report.mid);\n }\n\n if (!trackID) {\n return undefined;\n }\n\n let trackStats = this.track2stats.get(trackID);\n\n if (!trackStats) {\n const track = this.mediaTrackHandler.getTackById(trackID);\n if (track !== undefined) {\n const kind: \"audio\" | \"video\" = track.kind === \"audio\" ? track.kind : \"video\";\n trackStats = new MediaTrackStats(trackID, type, kind);\n this.track2stats.set(trackID, trackStats);\n } else {\n return undefined;\n }\n }\n return trackStats;\n }\n\n public findLocalVideoTrackStats(report: any): MediaTrackStats | undefined {\n const localVideoTracks = this.mediaTrackHandler.getLocalTracks(\"video\");\n if (localVideoTracks.length === 0) {\n return undefined;\n }\n return this.findTrack2Stats(report, \"local\");\n }\n\n public getTrack2stats(): Map {\n return this.track2stats;\n }\n}\n", - "/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { ConnectionStatsBandwidth, ConnectionStatsBitrate, PacketLoos } from \"./connectionStats\";\nimport { TransportStats } from \"./transportStats\";\nimport { Resolution } from \"./media/mediaTrackStats\";\n\nexport enum StatsReport {\n CONNECTION_STATS = \"StatsReport.connection_stats\",\n BYTE_SENT_STATS = \"StatsReport.byte_sent_stats\",\n}\n\nexport type TrackID = string;\nexport type ByteSend = number;\n\nexport interface ByteSentStatsReport extends Map {\n // is a map: `local trackID` => byte send\n}\n\nexport interface ConnectionStatsReport {\n bandwidth: ConnectionStatsBandwidth;\n bitrate: ConnectionStatsBitrate;\n packetLoss: PacketLoos;\n resolution: ResolutionMap;\n framerate: FramerateMap;\n codec: CodecMap;\n transport: TransportStats[];\n}\n\nexport interface ResolutionMap {\n local: Map;\n remote: Map;\n}\n\nexport interface FramerateMap {\n local: Map;\n remote: Map;\n}\n\nexport interface CodecMap {\n local: Map;\n remote: Map;\n}\n", - "/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport { CodecMap, ConnectionStatsReport, FramerateMap, ResolutionMap, TrackID } from \"./statsReport\";\nimport { MediaTrackStats, Resolution } from \"./media/mediaTrackStats\";\n\nexport class StatsReportBuilder {\n public static build(stats: Map): ConnectionStatsReport {\n const report = {} as ConnectionStatsReport;\n\n // process stats\n const totalPackets = {\n download: 0,\n upload: 0,\n };\n const lostPackets = {\n download: 0,\n upload: 0,\n };\n let bitrateDownload = 0;\n let bitrateUpload = 0;\n const resolutions: ResolutionMap = {\n local: new Map(),\n remote: new Map(),\n };\n const framerates: FramerateMap = { local: new Map(), remote: new Map() };\n const codecs: CodecMap = { local: new Map(), remote: new Map() };\n\n let audioBitrateDownload = 0;\n let audioBitrateUpload = 0;\n let videoBitrateDownload = 0;\n let videoBitrateUpload = 0;\n\n for (const [trackId, trackStats] of stats) {\n // process packet loss stats\n const loss = trackStats.getLoss();\n const type = loss.isDownloadStream ? \"download\" : \"upload\";\n\n totalPackets[type] += loss.packetsTotal;\n lostPackets[type] += loss.packetsLost;\n\n // process bitrate stats\n bitrateDownload += trackStats.getBitrate().download;\n bitrateUpload += trackStats.getBitrate().upload;\n\n // collect resolutions and framerates\n if (trackStats.kind === \"audio\") {\n audioBitrateDownload += trackStats.getBitrate().download;\n audioBitrateUpload += trackStats.getBitrate().upload;\n } else {\n videoBitrateDownload += trackStats.getBitrate().download;\n videoBitrateUpload += trackStats.getBitrate().upload;\n }\n\n resolutions[trackStats.getType()].set(trackId, trackStats.getResolution());\n framerates[trackStats.getType()].set(trackId, trackStats.getFramerate());\n codecs[trackStats.getType()].set(trackId, trackStats.getCodec());\n\n trackStats.resetBitrate();\n }\n\n report.bitrate = {\n upload: bitrateUpload,\n download: bitrateDownload,\n };\n\n report.bitrate.audio = {\n upload: audioBitrateUpload,\n download: audioBitrateDownload,\n };\n\n report.bitrate.video = {\n upload: videoBitrateUpload,\n download: videoBitrateDownload,\n };\n\n report.packetLoss = {\n total: StatsReportBuilder.calculatePacketLoss(\n lostPackets.download + lostPackets.upload,\n totalPackets.download + totalPackets.upload,\n ),\n download: StatsReportBuilder.calculatePacketLoss(lostPackets.download, totalPackets.download),\n upload: StatsReportBuilder.calculatePacketLoss(lostPackets.upload, totalPackets.upload),\n };\n report.framerate = framerates;\n report.resolution = resolutions;\n report.codec = codecs;\n return report;\n }\n\n private static calculatePacketLoss(lostPackets: number, totalPackets: number): number {\n if (!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0) {\n return 0;\n }\n\n return Math.round((lostPackets / totalPackets) * 100);\n }\n}\n", - "/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { TypedEventEmitter } from \"../../models/typed-event-emitter\";\nimport { ByteSentStatsReport, ConnectionStatsReport, StatsReport } from \"./statsReport\";\n\nexport type StatsReportHandlerMap = {\n [StatsReport.BYTE_SENT_STATS]: (report: ByteSentStatsReport) => void;\n [StatsReport.CONNECTION_STATS]: (report: ConnectionStatsReport) => void;\n};\n\nexport class StatsReportEmitter extends TypedEventEmitter {\n public emitByteSendReport(byteSentStats: ByteSentStatsReport): void {\n this.emit(StatsReport.BYTE_SENT_STATS, byteSentStats);\n }\n\n public emitConnectionStatsReport(report: ConnectionStatsReport): void {\n this.emit(StatsReport.CONNECTION_STATS, report);\n }\n}\n", - "/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { ConnectionStats } from \"./connectionStats\";\nimport { StatsReportEmitter } from \"./statsReportEmitter\";\nimport { ByteSend, ByteSentStatsReport, TrackID } from \"./statsReport\";\nimport { ConnectionStatsReporter } from \"./connectionStatsReporter\";\nimport { TransportStatsReporter } from \"./transportStatsReporter\";\nimport { MediaSsrcHandler } from \"./media/mediaSsrcHandler\";\nimport { MediaTrackHandler } from \"./media/mediaTrackHandler\";\nimport { MediaTrackStatsHandler } from \"./media/mediaTrackStatsHandler\";\nimport { TrackStatsReporter } from \"./trackStatsReporter\";\nimport { StatsReportBuilder } from \"./statsReportBuilder\";\nimport { StatsValueFormatter } from \"./statsValueFormatter\";\n\nexport class StatsReportGatherer {\n private isActive = true;\n private previousStatsReport: RTCStatsReport | undefined;\n private currentStatsReport: RTCStatsReport | undefined;\n private readonly connectionStats = new ConnectionStats();\n\n private readonly trackStats: MediaTrackStatsHandler;\n\n // private readonly ssrcToMid = { local: new Map(), remote: new Map() };\n\n public constructor(\n public readonly callId: string,\n public readonly remoteUserId: string,\n private readonly pc: RTCPeerConnection,\n private readonly emitter: StatsReportEmitter,\n private readonly isFocus = true,\n ) {\n pc.addEventListener(\"signalingstatechange\", this.onSignalStateChange.bind(this));\n this.trackStats = new MediaTrackStatsHandler(new MediaSsrcHandler(), new MediaTrackHandler(pc));\n }\n\n public async processStats(groupCallId: string, localUserId: string): Promise {\n if (this.isActive) {\n const statsPromise = this.pc.getStats();\n if (typeof statsPromise?.then === \"function\") {\n return statsPromise\n .then((report) => {\n // @ts-ignore\n this.currentStatsReport = typeof report?.result === \"function\" ? report.result() : report;\n try {\n this.processStatsReport(groupCallId, localUserId);\n } catch (error) {\n this.isActive = false;\n return false;\n }\n\n this.previousStatsReport = this.currentStatsReport;\n return true;\n })\n .catch((error) => {\n this.handleError(error);\n return false;\n });\n }\n this.isActive = false;\n }\n return Promise.resolve(false);\n }\n\n private processStatsReport(groupCallId: string, localUserId: string): void {\n const byteSentStats: ByteSentStatsReport = new Map();\n\n this.currentStatsReport?.forEach((now) => {\n const before = this.previousStatsReport ? this.previousStatsReport.get(now.id) : null;\n // RTCIceCandidatePairStats - https://w3c.github.io/webrtc-stats/#candidatepair-dict*\n if (now.type === \"candidate-pair\" && now.nominated && now.state === \"succeeded\") {\n this.connectionStats.bandwidth = ConnectionStatsReporter.buildBandwidthReport(now);\n this.connectionStats.transport = TransportStatsReporter.buildReport(\n this.currentStatsReport,\n now,\n this.connectionStats.transport,\n this.isFocus,\n );\n\n // RTCReceivedRtpStreamStats\n // https://w3c.github.io/webrtc-stats/#receivedrtpstats-dict*\n // RTCSentRtpStreamStats\n // https://w3c.github.io/webrtc-stats/#sentrtpstats-dict*\n } else if (now.type === \"inbound-rtp\" || now.type === \"outbound-rtp\") {\n const trackStats = this.trackStats.findTrack2Stats(\n now,\n now.type === \"inbound-rtp\" ? \"remote\" : \"local\",\n );\n if (!trackStats) {\n return;\n }\n\n if (before) {\n TrackStatsReporter.buildPacketsLost(trackStats, now, before);\n }\n\n // Get the resolution and framerate for only remote video sources here. For the local video sources,\n // 'track' stats will be used since they have the updated resolution based on the simulcast streams\n // currently being sent. Promise based getStats reports three 'outbound-rtp' streams and there will be\n // more calculations needed to determine what is the highest resolution stream sent by the client if the\n // 'outbound-rtp' stats are used.\n if (now.type === \"inbound-rtp\") {\n TrackStatsReporter.buildFramerateResolution(trackStats, now);\n if (before) {\n TrackStatsReporter.buildBitrateReceived(trackStats, now, before);\n }\n } else if (before) {\n byteSentStats.set(trackStats.trackId, StatsValueFormatter.getNonNegativeValue(now.bytesSent));\n TrackStatsReporter.buildBitrateSend(trackStats, now, before);\n }\n TrackStatsReporter.buildCodec(this.currentStatsReport, trackStats, now);\n } else if (now.type === \"track\" && now.kind === \"video\" && !now.remoteSource) {\n const trackStats = this.trackStats.findLocalVideoTrackStats(now);\n if (!trackStats) {\n return;\n }\n TrackStatsReporter.buildFramerateResolution(trackStats, now);\n TrackStatsReporter.calculateSimulcastFramerate(\n trackStats,\n now,\n before,\n this.trackStats.mediaTrackHandler.getActiveSimulcastStreams(),\n );\n }\n });\n\n this.emitter.emitByteSendReport(byteSentStats);\n this.processAndEmitReport();\n }\n\n public setActive(isActive: boolean): void {\n this.isActive = isActive;\n }\n\n public getActive(): boolean {\n return this.isActive;\n }\n\n private handleError(_: any): void {\n this.isActive = false;\n }\n\n private processAndEmitReport(): void {\n const report = StatsReportBuilder.build(this.trackStats.getTrack2stats());\n\n this.connectionStats.bandwidth = report.bandwidth;\n this.connectionStats.bitrate = report.bitrate;\n this.connectionStats.packetLoss = report.packetLoss;\n\n this.emitter.emitConnectionStatsReport({\n ...report,\n transport: this.connectionStats.transport,\n });\n\n this.connectionStats.transport = [];\n }\n\n public stopProcessingStats(): void {}\n\n private onSignalStateChange(): void {\n if (this.pc.signalingState === \"stable\") {\n if (this.pc.currentRemoteDescription) {\n this.trackStats.mediaSsrcHandler.parse(this.pc.currentRemoteDescription.sdp, \"remote\");\n }\n if (this.pc.currentLocalDescription) {\n this.trackStats.mediaSsrcHandler.parse(this.pc.currentLocalDescription.sdp, \"local\");\n }\n }\n }\n}\n", - "/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nexport class StatsValueFormatter {\n public static getNonNegativeValue(imput: any): number {\n let value = imput;\n\n if (typeof value !== \"number\") {\n value = Number(value);\n }\n\n if (isNaN(value)) {\n return 0;\n }\n\n return Math.max(0, value);\n }\n}\n", - "import { MediaTrackStats } from \"./media/mediaTrackStats\";\nimport { StatsValueFormatter } from \"./statsValueFormatter\";\n\nexport class TrackStatsReporter {\n public static buildFramerateResolution(trackStats: MediaTrackStats, now: any): void {\n const resolution = {\n height: now.frameHeight,\n width: now.frameWidth,\n };\n const frameRate = now.framesPerSecond;\n\n if (resolution.height && resolution.width) {\n trackStats.setResolution(resolution);\n }\n trackStats.setFramerate(Math.round(frameRate || 0));\n }\n\n public static calculateSimulcastFramerate(trackStats: MediaTrackStats, now: any, before: any, layer: number): void {\n let frameRate = trackStats.getFramerate();\n if (!frameRate) {\n if (before) {\n const timeMs = now.timestamp - before.timestamp;\n\n if (timeMs > 0 && now.framesSent) {\n const numberOfFramesSinceBefore = now.framesSent - before.framesSent;\n\n frameRate = (numberOfFramesSinceBefore / timeMs) * 1000;\n }\n }\n\n if (!frameRate) {\n return;\n }\n }\n\n // Reset frame rate to 0 when video is suspended as a result of endpoint falling out of last-n.\n frameRate = layer ? Math.round(frameRate / layer) : 0;\n trackStats.setFramerate(frameRate);\n }\n\n public static buildCodec(report: RTCStatsReport | undefined, trackStats: MediaTrackStats, now: any): void {\n const codec = report?.get(now.codecId);\n\n if (codec) {\n /**\n * The mime type has the following form: video/VP8 or audio/ISAC,\n * so we what to keep just the type after the '/', audio and video\n * keys will be added on the processing side.\n */\n const codecShortType = codec.mimeType.split(\"/\")[1];\n\n codecShortType && trackStats.setCodec(codecShortType);\n }\n }\n\n public static buildBitrateReceived(trackStats: MediaTrackStats, now: any, before: any): void {\n trackStats.setBitrate({\n download: TrackStatsReporter.calculateBitrate(\n now.bytesReceived,\n before.bytesReceived,\n now.timestamp,\n before.timestamp,\n ),\n upload: 0,\n });\n }\n\n public static buildBitrateSend(trackStats: MediaTrackStats, now: any, before: any): void {\n trackStats.setBitrate({\n download: 0,\n upload: this.calculateBitrate(now.bytesSent, before.bytesSent, now.timestamp, before.timestamp),\n });\n }\n\n public static buildPacketsLost(trackStats: MediaTrackStats, now: any, before: any): void {\n const key = now.type === \"outbound-rtp\" ? \"packetsSent\" : \"packetsReceived\";\n\n let packetsNow = now[key];\n if (!packetsNow || packetsNow < 0) {\n packetsNow = 0;\n }\n\n const packetsBefore = StatsValueFormatter.getNonNegativeValue(before[key]);\n const packetsDiff = Math.max(0, packetsNow - packetsBefore);\n\n const packetsLostNow = StatsValueFormatter.getNonNegativeValue(now.packetsLost);\n const packetsLostBefore = StatsValueFormatter.getNonNegativeValue(before.packetsLost);\n const packetsLostDiff = Math.max(0, packetsLostNow - packetsLostBefore);\n\n trackStats.setLoss({\n packetsTotal: packetsDiff + packetsLostDiff,\n packetsLost: packetsLostDiff,\n isDownloadStream: now.type !== \"outbound-rtp\",\n });\n }\n\n private static calculateBitrate(\n bytesNowAny: any,\n bytesBeforeAny: any,\n nowTimestamp: number,\n beforeTimestamp: number,\n ): number {\n const bytesNow = StatsValueFormatter.getNonNegativeValue(bytesNowAny);\n const bytesBefore = StatsValueFormatter.getNonNegativeValue(bytesBeforeAny);\n const bytesProcessed = Math.max(0, bytesNow - bytesBefore);\n\n const timeMs = nowTimestamp - beforeTimestamp;\n let bitrateKbps = 0;\n\n if (timeMs > 0) {\n // TODO is there any reason to round here?\n bitrateKbps = Math.round((bytesProcessed * 8) / timeMs);\n }\n\n return bitrateKbps;\n }\n}\n", - "import { TransportStats } from \"./transportStats\";\n\nexport class TransportStatsReporter {\n public static buildReport(\n report: RTCStatsReport | undefined,\n now: RTCIceCandidatePairStats,\n conferenceStatsTransport: TransportStats[],\n isFocus: boolean,\n ): TransportStats[] {\n const localUsedCandidate = report?.get(now.localCandidateId);\n const remoteUsedCandidate = report?.get(now.remoteCandidateId);\n\n // RTCIceCandidateStats\n // https://w3c.github.io/webrtc-stats/#icecandidate-dict*\n if (remoteUsedCandidate && localUsedCandidate) {\n const remoteIpAddress =\n remoteUsedCandidate.ip !== undefined ? remoteUsedCandidate.ip : remoteUsedCandidate.address;\n const remotePort = remoteUsedCandidate.port;\n const ip = `${remoteIpAddress}:${remotePort}`;\n\n const localIpAddress =\n localUsedCandidate.ip !== undefined ? localUsedCandidate.ip : localUsedCandidate.address;\n const localPort = localUsedCandidate.port;\n const localIp = `${localIpAddress}:${localPort}`;\n\n const type = remoteUsedCandidate.protocol;\n\n // Save the address unless it has been saved already.\n if (\n !conferenceStatsTransport.some(\n (t: TransportStats) => t.ip === ip && t.type === type && t.localIp === localIp,\n )\n ) {\n conferenceStatsTransport.push({\n ip,\n type,\n localIp,\n isFocus,\n localCandidateType: localUsedCandidate.candidateType,\n remoteCandidateType: remoteUsedCandidate.candidateType,\n networkType: localUsedCandidate.networkType,\n rtt: now.currentRoundTripTime ? now.currentRoundTripTime * 1000 : NaN,\n } as TransportStats);\n }\n }\n return conferenceStatsTransport;\n }\n}\n" - ] -} \ No newline at end of file diff --git a/includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.min.js b/includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.min.js deleted file mode 100644 index 12920d0..0000000 --- a/includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.min.js +++ /dev/null @@ -1,18 +0,0 @@ -!function e(t,i,n){function r(s,a){if(!i[s]){if(!t[s]){var c="function"==typeof require&&require;if(!a&&c)return c(s,!0);if(o)return o(s,!0);var d=new Error("Cannot find module '"+s+"'");throw d.code="MODULE_NOT_FOUND",d}var l=i[s]={exports:{}};t[s][0].call(l.exports,(function(e){return r(t[s][1][e]||e)}),l,l.exports,e,t,i,n)}return i[s].exports}for(var o="function"==typeof require&&require,s=0;s>6],r=0==(32&i);if(31==(31&i)){let n=i;for(i=0;128==(128&n);){if(n=e.readUInt8(t),e.isError(n))return n;i<<=7,i|=127&n}}else i&=31;return{cls:n,primitive:r,tag:i,tagStr:a.tag[i]}}function u(e,t,i){let n=e.readUInt8(i);if(e.isError(n))return n;if(!t&&128===n)return null;if(0==(128&n))return n;const r=127&n;if(r>4)return e.error("length octect is too long");n=0;for(let t=0;t=31)return n.error("Multi-octet tag encoding unsupported");t||(r|=32);return r|=s.tagClassByName[i||"universal"]<<6,r}(e,t,i,this.reporter);if(n.length<128){const e=r.alloc(2);return e[0]=o,e[1]=n.length,this._createEncoderBuffer([e,n])}let a=1;for(let e=n.length;e>=256;e>>=8)a++;const c=r.alloc(2+a);c[0]=o,c[1]=128|a;for(let e=1+a,t=n.length;t>0;e--,t>>=8)c[e]=255&t;return this._createEncoderBuffer([c,n])},c.prototype._encodeStr=function(e,t){if("bitstr"===t)return this._createEncoderBuffer([0|e.unused,e.data]);if("bmpstr"===t){const t=r.alloc(2*e.length);for(let i=0;i=40)return this.reporter.error("Second objid identifier OOB");e.splice(0,2,40*e[0]+e[1])}let n=0;for(let t=0;t=128;i>>=7)n++}const o=r.alloc(n);let s=o.length-1;for(let t=e.length-1;t>=0;t--){let i=e[t];for(o[s--]=127&i;(i>>=7)>0;)o[s--]=128|127&i}return this._createEncoderBuffer(o)},c.prototype._encodeTime=function(e,t){let i;const n=new Date(e);return"gentime"===t?i=[d(n.getUTCFullYear()),d(n.getUTCMonth()+1),d(n.getUTCDate()),d(n.getUTCHours()),d(n.getUTCMinutes()),d(n.getUTCSeconds()),"Z"].join(""):"utctime"===t?i=[d(n.getUTCFullYear()%100),d(n.getUTCMonth()+1),d(n.getUTCDate()),d(n.getUTCHours()),d(n.getUTCMinutes()),d(n.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+t+" time is not supported yet"),this._encodeStr(i,"octstr")},c.prototype._encodeNull=function(){return this._createEncoderBuffer("")},c.prototype._encodeInt=function(e,t){if("string"==typeof e){if(!t)return this.reporter.error("String int or enum given, but no values map");if(!t.hasOwnProperty(e))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(e));e=t[e]}if("number"!=typeof e&&!r.isBuffer(e)){const t=e.toArray();!e.sign&&128&t[0]&&t.unshift(0),e=r.from(t)}if(r.isBuffer(e)){let t=e.length;0===e.length&&t++;const i=r.alloc(t);return e.copy(i),0===e.length&&(i[0]=0),this._createEncoderBuffer(i)}if(e<128)return this._createEncoderBuffer(e);if(e<256)return this._createEncoderBuffer([0,e]);let i=1;for(let t=e;t>=256;t>>=8)i++;const n=new Array(i);for(let t=n.length-1;t>=0;t--)n[t]=255&e,e>>=8;return 128&n[0]&&n.unshift(0),this._createEncoderBuffer(r.from(n))},c.prototype._encodeBool=function(e){return this._createEncoderBuffer(e?255:0)},c.prototype._use=function(e,t){return"function"==typeof e&&(e=e(t)),e._getEncoder("der").tree},c.prototype._skipDefault=function(e,t,i){const n=this._baseState;let r;if(null===n.default)return!1;const o=e.join();if(void 0===n.defaultBuffer&&(n.defaultBuffer=this._encodeValue(n.default,t,i).join()),o.length!==n.defaultBuffer.length)return!1;for(r=0;r0?s-4:s;for(i=0;i>16&255,c[l++]=t>>8&255,c[l++]=255&t;2===a&&(t=r[e.charCodeAt(i)]<<2|r[e.charCodeAt(i+1)]>>4,c[l++]=255&t);1===a&&(t=r[e.charCodeAt(i)]<<10|r[e.charCodeAt(i+1)]<<4|r[e.charCodeAt(i+2)]>>2,c[l++]=t>>8&255,c[l++]=255&t);return c},i.fromByteArray=function(e){for(var t,i=e.length,r=i%3,o=[],s=16383,a=0,c=i-r;ac?c:a+s));1===r?(t=e[i-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===r&&(t=(e[i-2]<<8)+e[i-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return o.join("")};for(var n=[],r=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,c=s.length;a0)throw new Error("Invalid string. Length must be a multiple of 4");var i=e.indexOf("=");return-1===i&&(i=t),[i,i===t?0:4-i%4]}function l(e,t,i){for(var r,o,s=[],a=t;a>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return s.join("")}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},{}],18:[function(e,t,i){!function(t,i){"use strict";function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function r(e,t){e.super_=t;var i=function(){};i.prototype=t.prototype,e.prototype=new i,e.prototype.constructor=e}function o(e,t,i){if(o.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(i=t,t=10),this._init(e||0,t||10,i||"be"))}var s;"object"==typeof t?t.exports=o:i.BN=o,o.BN=o,o.wordSize=26;try{s="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:e("buffer").Buffer}catch(e){}function a(e,t){var i=e.charCodeAt(t);return i>=65&&i<=70?i-55:i>=97&&i<=102?i-87:i-48&15}function c(e,t,i){var n=a(e,i);return i-1>=t&&(n|=a(e,i-1)<<4),n}function d(e,t,i,n){for(var r=0,o=Math.min(e.length,i),s=t;s=49?a-49+10:a>=17?a-17+10:a}return r}o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,i){if("number"==typeof e)return this._initNumber(e,t,i);if("object"==typeof e)return this._initArray(e,t,i);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var r=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(r++,this.negative=1),r=0;r-=3)s=e[r]|e[r-1]<<8|e[r-2]<<16,this.words[o]|=s<>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);else if("le"===i)for(r=0,o=0;r>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);return this.strip()},o.prototype._parseHex=function(e,t,i){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var n=0;n=t;n-=2)r=c(e,t,n)<=18?(o-=18,s+=1,this.words[s]|=r>>>26):o+=8;else for(n=(e.length-t)%2==0?t+1:t;n=18?(o-=18,s+=1,this.words[s]|=r>>>26):o+=8;this.strip()},o.prototype._parseBase=function(e,t,i){this.words=[0],this.length=1;for(var n=0,r=1;r<=67108863;r*=t)n++;n--,r=r/t|0;for(var o=e.length-i,s=o%n,a=Math.min(o,o-s)+i,c=0,l=i;l1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},o.prototype.inspect=function(){return(this.red?""};var l=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],u=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function f(e,t,i){i.negative=t.negative^e.negative;var n=e.length+t.length|0;i.length=n,n=n-1|0;var r=0|e.words[0],o=0|t.words[0],s=r*o,a=67108863&s,c=s/67108864|0;i.words[0]=a;for(var d=1;d>>26,u=67108863&c,h=Math.min(d,t.length-1),f=Math.max(0,d-e.length+1);f<=h;f++){var p=d-f|0;l+=(s=(r=0|e.words[p])*(o=0|t.words[f])+u)/67108864|0,u=67108863&s}i.words[d]=0|u,c=0|l}return 0!==c?i.words[d]=0|c:i.length--,i.strip()}o.prototype.toString=function(e,t){var i;if(t=0|t||1,16===(e=e||10)||"hex"===e){i="";for(var r=0,o=0,s=0;s>>24-r&16777215)||s!==this.length-1?l[6-c.length]+c+i:c+i,(r+=2)>=26&&(r-=26,s--)}for(0!==o&&(i=o.toString(16)+i);i.length%t!=0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}if(e===(0|e)&&e>=2&&e<=36){var d=u[e],f=h[e];i="";var p=this.clone();for(p.negative=0;!p.isZero();){var g=p.modn(f).toString(e);i=(p=p.idivn(f)).isZero()?g+i:l[d-g.length]+g+i}for(this.isZero()&&(i="0"+i);i.length%t!=0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16)},o.prototype.toBuffer=function(e,t){return n(void 0!==s),this.toArrayLike(s,e,t)},o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,i){var r=this.byteLength(),o=i||Math.max(1,r);n(r<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0"),this.strip();var s,a,c="le"===t,d=new e(o),l=this.clone();if(c){for(a=0;!l.isZero();a++)s=l.andln(255),l.iushrn(8),d[a]=s;for(;a=4096&&(i+=13,t>>>=13),t>=64&&(i+=7,t>>>=7),t>=8&&(i+=4,t>>>=4),t>=2&&(i+=2,t>>>=2),i+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,i=0;return 0==(8191&t)&&(i+=13,t>>>=13),0==(127&t)&&(i+=7,t>>>=7),0==(15&t)&&(i+=4,t>>>=4),0==(3&t)&&(i+=2,t>>>=2),0==(1&t)&&i++,i},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var i=0;ie.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,i;this.length>e.length?(t=this,i=e):(t=e,i=this);for(var n=0;ne.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),i=e%26;this._expand(t),i>0&&t--;for(var r=0;r0&&(this.words[r]=~this.words[r]&67108863>>26-i),this.strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var i=e/26|0,r=e%26;return this._expand(i+1),this.words[i]=t?this.words[i]|1<e.length?(i=this,n=e):(i=e,n=this);for(var r=0,o=0;o>>26;for(;0!==r&&o>>26;if(this.length=i.length,0!==r)this.words[this.length]=r,this.length++;else if(i!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var i,n,r=this.cmp(e);if(0===r)return this.negative=0,this.length=1,this.words[0]=0,this;r>0?(i=this,n=e):(i=e,n=this);for(var o=0,s=0;s>26,this.words[s]=67108863&t;for(;0!==o&&s>26,this.words[s]=67108863&t;if(0===o&&s>>13,f=0|s[1],p=8191&f,g=f>>>13,v=0|s[2],m=8191&v,y=v>>>13,b=0|s[3],S=8191&b,_=b>>>13,E=0|s[4],w=8191&E,T=E>>>13,I=0|s[5],R=8191&I,M=I>>>13,k=0|s[6],C=8191&k,O=k>>>13,A=0|s[7],P=8191&A,D=A>>>13,x=0|s[8],L=8191&x,U=x>>>13,B=0|s[9],N=8191&B,j=B>>>13,F=0|a[0],K=8191&F,q=F>>>13,$=0|a[1],V=8191&$,H=$>>>13,W=0|a[2],G=8191&W,z=W>>>13,Y=0|a[3],J=8191&Y,Q=Y>>>13,X=0|a[4],Z=8191&X,ee=X>>>13,te=0|a[5],ie=8191&te,ne=te>>>13,re=0|a[6],oe=8191&re,se=re>>>13,ae=0|a[7],ce=8191&ae,de=ae>>>13,le=0|a[8],ue=8191&le,he=le>>>13,fe=0|a[9],pe=8191&fe,ge=fe>>>13;i.negative=e.negative^t.negative,i.length=19;var ve=(d+(n=Math.imul(u,K))|0)+((8191&(r=(r=Math.imul(u,q))+Math.imul(h,K)|0))<<13)|0;d=((o=Math.imul(h,q))+(r>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(p,K),r=(r=Math.imul(p,q))+Math.imul(g,K)|0,o=Math.imul(g,q);var me=(d+(n=n+Math.imul(u,V)|0)|0)+((8191&(r=(r=r+Math.imul(u,H)|0)+Math.imul(h,V)|0))<<13)|0;d=((o=o+Math.imul(h,H)|0)+(r>>>13)|0)+(me>>>26)|0,me&=67108863,n=Math.imul(m,K),r=(r=Math.imul(m,q))+Math.imul(y,K)|0,o=Math.imul(y,q),n=n+Math.imul(p,V)|0,r=(r=r+Math.imul(p,H)|0)+Math.imul(g,V)|0,o=o+Math.imul(g,H)|0;var ye=(d+(n=n+Math.imul(u,G)|0)|0)+((8191&(r=(r=r+Math.imul(u,z)|0)+Math.imul(h,G)|0))<<13)|0;d=((o=o+Math.imul(h,z)|0)+(r>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(S,K),r=(r=Math.imul(S,q))+Math.imul(_,K)|0,o=Math.imul(_,q),n=n+Math.imul(m,V)|0,r=(r=r+Math.imul(m,H)|0)+Math.imul(y,V)|0,o=o+Math.imul(y,H)|0,n=n+Math.imul(p,G)|0,r=(r=r+Math.imul(p,z)|0)+Math.imul(g,G)|0,o=o+Math.imul(g,z)|0;var be=(d+(n=n+Math.imul(u,J)|0)|0)+((8191&(r=(r=r+Math.imul(u,Q)|0)+Math.imul(h,J)|0))<<13)|0;d=((o=o+Math.imul(h,Q)|0)+(r>>>13)|0)+(be>>>26)|0,be&=67108863,n=Math.imul(w,K),r=(r=Math.imul(w,q))+Math.imul(T,K)|0,o=Math.imul(T,q),n=n+Math.imul(S,V)|0,r=(r=r+Math.imul(S,H)|0)+Math.imul(_,V)|0,o=o+Math.imul(_,H)|0,n=n+Math.imul(m,G)|0,r=(r=r+Math.imul(m,z)|0)+Math.imul(y,G)|0,o=o+Math.imul(y,z)|0,n=n+Math.imul(p,J)|0,r=(r=r+Math.imul(p,Q)|0)+Math.imul(g,J)|0,o=o+Math.imul(g,Q)|0;var Se=(d+(n=n+Math.imul(u,Z)|0)|0)+((8191&(r=(r=r+Math.imul(u,ee)|0)+Math.imul(h,Z)|0))<<13)|0;d=((o=o+Math.imul(h,ee)|0)+(r>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(R,K),r=(r=Math.imul(R,q))+Math.imul(M,K)|0,o=Math.imul(M,q),n=n+Math.imul(w,V)|0,r=(r=r+Math.imul(w,H)|0)+Math.imul(T,V)|0,o=o+Math.imul(T,H)|0,n=n+Math.imul(S,G)|0,r=(r=r+Math.imul(S,z)|0)+Math.imul(_,G)|0,o=o+Math.imul(_,z)|0,n=n+Math.imul(m,J)|0,r=(r=r+Math.imul(m,Q)|0)+Math.imul(y,J)|0,o=o+Math.imul(y,Q)|0,n=n+Math.imul(p,Z)|0,r=(r=r+Math.imul(p,ee)|0)+Math.imul(g,Z)|0,o=o+Math.imul(g,ee)|0;var _e=(d+(n=n+Math.imul(u,ie)|0)|0)+((8191&(r=(r=r+Math.imul(u,ne)|0)+Math.imul(h,ie)|0))<<13)|0;d=((o=o+Math.imul(h,ne)|0)+(r>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(C,K),r=(r=Math.imul(C,q))+Math.imul(O,K)|0,o=Math.imul(O,q),n=n+Math.imul(R,V)|0,r=(r=r+Math.imul(R,H)|0)+Math.imul(M,V)|0,o=o+Math.imul(M,H)|0,n=n+Math.imul(w,G)|0,r=(r=r+Math.imul(w,z)|0)+Math.imul(T,G)|0,o=o+Math.imul(T,z)|0,n=n+Math.imul(S,J)|0,r=(r=r+Math.imul(S,Q)|0)+Math.imul(_,J)|0,o=o+Math.imul(_,Q)|0,n=n+Math.imul(m,Z)|0,r=(r=r+Math.imul(m,ee)|0)+Math.imul(y,Z)|0,o=o+Math.imul(y,ee)|0,n=n+Math.imul(p,ie)|0,r=(r=r+Math.imul(p,ne)|0)+Math.imul(g,ie)|0,o=o+Math.imul(g,ne)|0;var Ee=(d+(n=n+Math.imul(u,oe)|0)|0)+((8191&(r=(r=r+Math.imul(u,se)|0)+Math.imul(h,oe)|0))<<13)|0;d=((o=o+Math.imul(h,se)|0)+(r>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(P,K),r=(r=Math.imul(P,q))+Math.imul(D,K)|0,o=Math.imul(D,q),n=n+Math.imul(C,V)|0,r=(r=r+Math.imul(C,H)|0)+Math.imul(O,V)|0,o=o+Math.imul(O,H)|0,n=n+Math.imul(R,G)|0,r=(r=r+Math.imul(R,z)|0)+Math.imul(M,G)|0,o=o+Math.imul(M,z)|0,n=n+Math.imul(w,J)|0,r=(r=r+Math.imul(w,Q)|0)+Math.imul(T,J)|0,o=o+Math.imul(T,Q)|0,n=n+Math.imul(S,Z)|0,r=(r=r+Math.imul(S,ee)|0)+Math.imul(_,Z)|0,o=o+Math.imul(_,ee)|0,n=n+Math.imul(m,ie)|0,r=(r=r+Math.imul(m,ne)|0)+Math.imul(y,ie)|0,o=o+Math.imul(y,ne)|0,n=n+Math.imul(p,oe)|0,r=(r=r+Math.imul(p,se)|0)+Math.imul(g,oe)|0,o=o+Math.imul(g,se)|0;var we=(d+(n=n+Math.imul(u,ce)|0)|0)+((8191&(r=(r=r+Math.imul(u,de)|0)+Math.imul(h,ce)|0))<<13)|0;d=((o=o+Math.imul(h,de)|0)+(r>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(L,K),r=(r=Math.imul(L,q))+Math.imul(U,K)|0,o=Math.imul(U,q),n=n+Math.imul(P,V)|0,r=(r=r+Math.imul(P,H)|0)+Math.imul(D,V)|0,o=o+Math.imul(D,H)|0,n=n+Math.imul(C,G)|0,r=(r=r+Math.imul(C,z)|0)+Math.imul(O,G)|0,o=o+Math.imul(O,z)|0,n=n+Math.imul(R,J)|0,r=(r=r+Math.imul(R,Q)|0)+Math.imul(M,J)|0,o=o+Math.imul(M,Q)|0,n=n+Math.imul(w,Z)|0,r=(r=r+Math.imul(w,ee)|0)+Math.imul(T,Z)|0,o=o+Math.imul(T,ee)|0,n=n+Math.imul(S,ie)|0,r=(r=r+Math.imul(S,ne)|0)+Math.imul(_,ie)|0,o=o+Math.imul(_,ne)|0,n=n+Math.imul(m,oe)|0,r=(r=r+Math.imul(m,se)|0)+Math.imul(y,oe)|0,o=o+Math.imul(y,se)|0,n=n+Math.imul(p,ce)|0,r=(r=r+Math.imul(p,de)|0)+Math.imul(g,ce)|0,o=o+Math.imul(g,de)|0;var Te=(d+(n=n+Math.imul(u,ue)|0)|0)+((8191&(r=(r=r+Math.imul(u,he)|0)+Math.imul(h,ue)|0))<<13)|0;d=((o=o+Math.imul(h,he)|0)+(r>>>13)|0)+(Te>>>26)|0,Te&=67108863,n=Math.imul(N,K),r=(r=Math.imul(N,q))+Math.imul(j,K)|0,o=Math.imul(j,q),n=n+Math.imul(L,V)|0,r=(r=r+Math.imul(L,H)|0)+Math.imul(U,V)|0,o=o+Math.imul(U,H)|0,n=n+Math.imul(P,G)|0,r=(r=r+Math.imul(P,z)|0)+Math.imul(D,G)|0,o=o+Math.imul(D,z)|0,n=n+Math.imul(C,J)|0,r=(r=r+Math.imul(C,Q)|0)+Math.imul(O,J)|0,o=o+Math.imul(O,Q)|0,n=n+Math.imul(R,Z)|0,r=(r=r+Math.imul(R,ee)|0)+Math.imul(M,Z)|0,o=o+Math.imul(M,ee)|0,n=n+Math.imul(w,ie)|0,r=(r=r+Math.imul(w,ne)|0)+Math.imul(T,ie)|0,o=o+Math.imul(T,ne)|0,n=n+Math.imul(S,oe)|0,r=(r=r+Math.imul(S,se)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,se)|0,n=n+Math.imul(m,ce)|0,r=(r=r+Math.imul(m,de)|0)+Math.imul(y,ce)|0,o=o+Math.imul(y,de)|0,n=n+Math.imul(p,ue)|0,r=(r=r+Math.imul(p,he)|0)+Math.imul(g,ue)|0,o=o+Math.imul(g,he)|0;var Ie=(d+(n=n+Math.imul(u,pe)|0)|0)+((8191&(r=(r=r+Math.imul(u,ge)|0)+Math.imul(h,pe)|0))<<13)|0;d=((o=o+Math.imul(h,ge)|0)+(r>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,n=Math.imul(N,V),r=(r=Math.imul(N,H))+Math.imul(j,V)|0,o=Math.imul(j,H),n=n+Math.imul(L,G)|0,r=(r=r+Math.imul(L,z)|0)+Math.imul(U,G)|0,o=o+Math.imul(U,z)|0,n=n+Math.imul(P,J)|0,r=(r=r+Math.imul(P,Q)|0)+Math.imul(D,J)|0,o=o+Math.imul(D,Q)|0,n=n+Math.imul(C,Z)|0,r=(r=r+Math.imul(C,ee)|0)+Math.imul(O,Z)|0,o=o+Math.imul(O,ee)|0,n=n+Math.imul(R,ie)|0,r=(r=r+Math.imul(R,ne)|0)+Math.imul(M,ie)|0,o=o+Math.imul(M,ne)|0,n=n+Math.imul(w,oe)|0,r=(r=r+Math.imul(w,se)|0)+Math.imul(T,oe)|0,o=o+Math.imul(T,se)|0,n=n+Math.imul(S,ce)|0,r=(r=r+Math.imul(S,de)|0)+Math.imul(_,ce)|0,o=o+Math.imul(_,de)|0,n=n+Math.imul(m,ue)|0,r=(r=r+Math.imul(m,he)|0)+Math.imul(y,ue)|0,o=o+Math.imul(y,he)|0;var Re=(d+(n=n+Math.imul(p,pe)|0)|0)+((8191&(r=(r=r+Math.imul(p,ge)|0)+Math.imul(g,pe)|0))<<13)|0;d=((o=o+Math.imul(g,ge)|0)+(r>>>13)|0)+(Re>>>26)|0,Re&=67108863,n=Math.imul(N,G),r=(r=Math.imul(N,z))+Math.imul(j,G)|0,o=Math.imul(j,z),n=n+Math.imul(L,J)|0,r=(r=r+Math.imul(L,Q)|0)+Math.imul(U,J)|0,o=o+Math.imul(U,Q)|0,n=n+Math.imul(P,Z)|0,r=(r=r+Math.imul(P,ee)|0)+Math.imul(D,Z)|0,o=o+Math.imul(D,ee)|0,n=n+Math.imul(C,ie)|0,r=(r=r+Math.imul(C,ne)|0)+Math.imul(O,ie)|0,o=o+Math.imul(O,ne)|0,n=n+Math.imul(R,oe)|0,r=(r=r+Math.imul(R,se)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,se)|0,n=n+Math.imul(w,ce)|0,r=(r=r+Math.imul(w,de)|0)+Math.imul(T,ce)|0,o=o+Math.imul(T,de)|0,n=n+Math.imul(S,ue)|0,r=(r=r+Math.imul(S,he)|0)+Math.imul(_,ue)|0,o=o+Math.imul(_,he)|0;var Me=(d+(n=n+Math.imul(m,pe)|0)|0)+((8191&(r=(r=r+Math.imul(m,ge)|0)+Math.imul(y,pe)|0))<<13)|0;d=((o=o+Math.imul(y,ge)|0)+(r>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(N,J),r=(r=Math.imul(N,Q))+Math.imul(j,J)|0,o=Math.imul(j,Q),n=n+Math.imul(L,Z)|0,r=(r=r+Math.imul(L,ee)|0)+Math.imul(U,Z)|0,o=o+Math.imul(U,ee)|0,n=n+Math.imul(P,ie)|0,r=(r=r+Math.imul(P,ne)|0)+Math.imul(D,ie)|0,o=o+Math.imul(D,ne)|0,n=n+Math.imul(C,oe)|0,r=(r=r+Math.imul(C,se)|0)+Math.imul(O,oe)|0,o=o+Math.imul(O,se)|0,n=n+Math.imul(R,ce)|0,r=(r=r+Math.imul(R,de)|0)+Math.imul(M,ce)|0,o=o+Math.imul(M,de)|0,n=n+Math.imul(w,ue)|0,r=(r=r+Math.imul(w,he)|0)+Math.imul(T,ue)|0,o=o+Math.imul(T,he)|0;var ke=(d+(n=n+Math.imul(S,pe)|0)|0)+((8191&(r=(r=r+Math.imul(S,ge)|0)+Math.imul(_,pe)|0))<<13)|0;d=((o=o+Math.imul(_,ge)|0)+(r>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(N,Z),r=(r=Math.imul(N,ee))+Math.imul(j,Z)|0,o=Math.imul(j,ee),n=n+Math.imul(L,ie)|0,r=(r=r+Math.imul(L,ne)|0)+Math.imul(U,ie)|0,o=o+Math.imul(U,ne)|0,n=n+Math.imul(P,oe)|0,r=(r=r+Math.imul(P,se)|0)+Math.imul(D,oe)|0,o=o+Math.imul(D,se)|0,n=n+Math.imul(C,ce)|0,r=(r=r+Math.imul(C,de)|0)+Math.imul(O,ce)|0,o=o+Math.imul(O,de)|0,n=n+Math.imul(R,ue)|0,r=(r=r+Math.imul(R,he)|0)+Math.imul(M,ue)|0,o=o+Math.imul(M,he)|0;var Ce=(d+(n=n+Math.imul(w,pe)|0)|0)+((8191&(r=(r=r+Math.imul(w,ge)|0)+Math.imul(T,pe)|0))<<13)|0;d=((o=o+Math.imul(T,ge)|0)+(r>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,n=Math.imul(N,ie),r=(r=Math.imul(N,ne))+Math.imul(j,ie)|0,o=Math.imul(j,ne),n=n+Math.imul(L,oe)|0,r=(r=r+Math.imul(L,se)|0)+Math.imul(U,oe)|0,o=o+Math.imul(U,se)|0,n=n+Math.imul(P,ce)|0,r=(r=r+Math.imul(P,de)|0)+Math.imul(D,ce)|0,o=o+Math.imul(D,de)|0,n=n+Math.imul(C,ue)|0,r=(r=r+Math.imul(C,he)|0)+Math.imul(O,ue)|0,o=o+Math.imul(O,he)|0;var Oe=(d+(n=n+Math.imul(R,pe)|0)|0)+((8191&(r=(r=r+Math.imul(R,ge)|0)+Math.imul(M,pe)|0))<<13)|0;d=((o=o+Math.imul(M,ge)|0)+(r>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,n=Math.imul(N,oe),r=(r=Math.imul(N,se))+Math.imul(j,oe)|0,o=Math.imul(j,se),n=n+Math.imul(L,ce)|0,r=(r=r+Math.imul(L,de)|0)+Math.imul(U,ce)|0,o=o+Math.imul(U,de)|0,n=n+Math.imul(P,ue)|0,r=(r=r+Math.imul(P,he)|0)+Math.imul(D,ue)|0,o=o+Math.imul(D,he)|0;var Ae=(d+(n=n+Math.imul(C,pe)|0)|0)+((8191&(r=(r=r+Math.imul(C,ge)|0)+Math.imul(O,pe)|0))<<13)|0;d=((o=o+Math.imul(O,ge)|0)+(r>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(N,ce),r=(r=Math.imul(N,de))+Math.imul(j,ce)|0,o=Math.imul(j,de),n=n+Math.imul(L,ue)|0,r=(r=r+Math.imul(L,he)|0)+Math.imul(U,ue)|0,o=o+Math.imul(U,he)|0;var Pe=(d+(n=n+Math.imul(P,pe)|0)|0)+((8191&(r=(r=r+Math.imul(P,ge)|0)+Math.imul(D,pe)|0))<<13)|0;d=((o=o+Math.imul(D,ge)|0)+(r>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,n=Math.imul(N,ue),r=(r=Math.imul(N,he))+Math.imul(j,ue)|0,o=Math.imul(j,he);var De=(d+(n=n+Math.imul(L,pe)|0)|0)+((8191&(r=(r=r+Math.imul(L,ge)|0)+Math.imul(U,pe)|0))<<13)|0;d=((o=o+Math.imul(U,ge)|0)+(r>>>13)|0)+(De>>>26)|0,De&=67108863;var xe=(d+(n=Math.imul(N,pe))|0)+((8191&(r=(r=Math.imul(N,ge))+Math.imul(j,pe)|0))<<13)|0;return d=((o=Math.imul(j,ge))+(r>>>13)|0)+(xe>>>26)|0,xe&=67108863,c[0]=ve,c[1]=me,c[2]=ye,c[3]=be,c[4]=Se,c[5]=_e,c[6]=Ee,c[7]=we,c[8]=Te,c[9]=Ie,c[10]=Re,c[11]=Me,c[12]=ke,c[13]=Ce,c[14]=Oe,c[15]=Ae,c[16]=Pe,c[17]=De,c[18]=xe,0!==d&&(c[19]=d,i.length++),i};function g(e,t,i){return(new v).mulp(e,t,i)}function v(e,t){this.x=e,this.y=t}Math.imul||(p=f),o.prototype.mulTo=function(e,t){var i,n=this.length+e.length;return i=10===this.length&&10===e.length?p(this,e,t):n<63?f(this,e,t):n<1024?function(e,t,i){i.negative=t.negative^e.negative,i.length=e.length+t.length;for(var n=0,r=0,o=0;o>>26)|0)>>>26,s&=67108863}i.words[o]=a,n=s,s=r}return 0!==n?i.words[o]=n:i.length--,i.strip()}(this,e,t):g(this,e,t),i},v.prototype.makeRBT=function(e){for(var t=new Array(e),i=o.prototype._countBits(e)-1,n=0;n>=1;return n},v.prototype.permute=function(e,t,i,n,r,o){for(var s=0;s>>=1)r++;return 1<>>=13,i[2*s+1]=8191&o,o>>>=13;for(s=2*t;s>=26,t+=r/67108864|0,t+=o>>>26,this.words[i]=67108863&o}return 0!==t&&(this.words[i]=t,this.length++),this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),i=0;i>>r}return t}(e);if(0===t.length)return new o(1);for(var i=this,n=0;n=0);var t,i=e%26,r=(e-i)/26,o=67108863>>>26-i<<26-i;if(0!==i){var s=0;for(t=0;t>>26-i}s&&(this.words[t]=s,this.length++)}if(0!==r){for(t=this.length-1;t>=0;t--)this.words[t+r]=this.words[t];for(t=0;t=0),r=t?(t-t%26)/26:0;var o=e%26,s=Math.min((e-o)/26,this.length),a=67108863^67108863>>>o<s)for(this.length-=s,d=0;d=0&&(0!==l||d>=r);d--){var u=0|this.words[d];this.words[d]=l<<26-o|u>>>o,l=u&a}return c&&0!==l&&(c.words[c.length++]=l),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},o.prototype.ishrn=function(e,t,i){return n(0===this.negative),this.iushrn(e,t,i)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,i=(e-t)/26,r=1<=0);var t=e%26,i=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=i)return this;if(0!==t&&i++,this.length=Math.min(i,this.length),0!==t){var r=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(c/67108864|0),this.words[r+i]=67108863&o}for(;r>26,this.words[r+i]=67108863&o;if(0===a)return this.strip();for(n(-1===a),a=0,r=0;r>26,this.words[r]=67108863&o;return this.negative=1,this.strip()},o.prototype._wordDiv=function(e,t){var i=(this.length,e.length),n=this.clone(),r=e,s=0|r.words[r.length-1];0!==(i=26-this._countBits(s))&&(r=r.ushln(i),n.iushln(i),s=0|r.words[r.length-1]);var a,c=n.length-r.length;if("mod"!==t){(a=new o(null)).length=c+1,a.words=new Array(a.length);for(var d=0;d=0;u--){var h=67108864*(0|n.words[r.length+u])+(0|n.words[r.length+u-1]);for(h=Math.min(h/s|0,67108863),n._ishlnsubmul(r,h,u);0!==n.negative;)h--,n.negative=0,n._ishlnsubmul(r,1,u),n.isZero()||(n.negative^=1);a&&(a.words[u]=h)}return a&&a.strip(),n.strip(),"div"!==t&&0!==i&&n.iushrn(i),{div:a||null,mod:n}},o.prototype.divmod=function(e,t,i){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(r=a.div.neg()),"div"!==t&&(s=a.mod.neg(),i&&0!==s.negative&&s.iadd(e)),{div:r,mod:s}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(r=a.div.neg()),{div:r,mod:a.mod}):0!=(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(s=a.mod.neg(),i&&0!==s.negative&&s.isub(e)),{div:a.div,mod:s}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modn(e.words[0]))}:this._wordDiv(e,t);var r,s,a},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var i=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),r=e.andln(1),o=i.cmp(n);return o<0||1===r&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modn=function(e){n(e<=67108863);for(var t=(1<<26)%e,i=0,r=this.length-1;r>=0;r--)i=(t*i+(0|this.words[r]))%e;return i},o.prototype.idivn=function(e){n(e<=67108863);for(var t=0,i=this.length-1;i>=0;i--){var r=(0|this.words[i])+67108864*t;this.words[i]=r/e|0,t=r%e}return this.strip()},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var r=new o(1),s=new o(0),a=new o(0),c=new o(1),d=0;t.isEven()&&i.isEven();)t.iushrn(1),i.iushrn(1),++d;for(var l=i.clone(),u=t.clone();!t.isZero();){for(var h=0,f=1;0==(t.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(t.iushrn(h);h-- >0;)(r.isOdd()||s.isOdd())&&(r.iadd(l),s.isub(u)),r.iushrn(1),s.iushrn(1);for(var p=0,g=1;0==(i.words[0]&g)&&p<26;++p,g<<=1);if(p>0)for(i.iushrn(p);p-- >0;)(a.isOdd()||c.isOdd())&&(a.iadd(l),c.isub(u)),a.iushrn(1),c.iushrn(1);t.cmp(i)>=0?(t.isub(i),r.isub(a),s.isub(c)):(i.isub(t),a.isub(r),c.isub(s))}return{a:a,b:c,gcd:i.iushln(d)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var r,s=new o(1),a=new o(0),c=i.clone();t.cmpn(1)>0&&i.cmpn(1)>0;){for(var d=0,l=1;0==(t.words[0]&l)&&d<26;++d,l<<=1);if(d>0)for(t.iushrn(d);d-- >0;)s.isOdd()&&s.iadd(c),s.iushrn(1);for(var u=0,h=1;0==(i.words[0]&h)&&u<26;++u,h<<=1);if(u>0)for(i.iushrn(u);u-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);t.cmp(i)>=0?(t.isub(i),s.isub(a)):(i.isub(t),a.isub(s))}return(r=0===t.cmpn(1)?s:a).cmpn(0)<0&&r.iadd(e),r},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),i=e.clone();t.negative=0,i.negative=0;for(var n=0;t.isEven()&&i.isEven();n++)t.iushrn(1),i.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;i.isEven();)i.iushrn(1);var r=t.cmp(i);if(r<0){var o=t;t=i,i=o}else if(0===r||0===i.cmpn(1))break;t.isub(i)}return i.iushln(n)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,i=(e-t)/26,r=1<>>26,a&=67108863,this.words[s]=a}return 0!==o&&(this.words[s]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,i=e<0;if(0!==this.negative&&!i)return-1;if(0===this.negative&&i)return 1;if(this.strip(),this.length>1)t=1;else{i&&(e=-e),n(e<=67108863,"Number is too big");var r=0|this.words[0];t=r===e?0:re.length)return 1;if(this.length=0;i--){var n=0|this.words[i],r=0|e.words[i];if(n!==r){nr&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new w(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var m={k256:null,p224:null,p192:null,p25519:null};function y(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function b(){y.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function S(){y.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function _(){y.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function E(){y.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function w(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function T(e){w.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}y.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},y.prototype.ireduce=function(e){var t,i=e;do{this.split(i,this.tmp),t=(i=(i=this.imulK(i)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t0?i.isub(this.p):void 0!==i.strip?i.strip():i._strip(),i},y.prototype.split=function(e,t){e.iushrn(this.n,0,t)},y.prototype.imulK=function(e){return e.imul(this.k)},r(b,y),b.prototype.split=function(e,t){for(var i=4194303,n=Math.min(e.length,9),r=0;r>>22,o=s}o>>>=22,e.words[r-10]=o,0===o&&e.length>10?e.length-=10:e.length-=9},b.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,i=0;i>>=26,e.words[i]=r,t=n}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(m[e])return m[e];var t;if("k256"===e)t=new b;else if("p224"===e)t=new S;else if("p192"===e)t=new _;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new E}return m[e]=t,t},w.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},w.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},w.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},w.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},w.prototype.add=function(e,t){this._verify2(e,t);var i=e.add(t);return i.cmp(this.m)>=0&&i.isub(this.m),i._forceRed(this)},w.prototype.iadd=function(e,t){this._verify2(e,t);var i=e.iadd(t);return i.cmp(this.m)>=0&&i.isub(this.m),i},w.prototype.sub=function(e,t){this._verify2(e,t);var i=e.sub(t);return i.cmpn(0)<0&&i.iadd(this.m),i._forceRed(this)},w.prototype.isub=function(e,t){this._verify2(e,t);var i=e.isub(t);return i.cmpn(0)<0&&i.iadd(this.m),i},w.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},w.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},w.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},w.prototype.isqr=function(e){return this.imul(e,e.clone())},w.prototype.sqr=function(e){return this.mul(e,e)},w.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var i=this.m.add(new o(1)).iushrn(2);return this.pow(e,i)}for(var r=this.m.subn(1),s=0;!r.isZero()&&0===r.andln(1);)s++,r.iushrn(1);n(!r.isZero());var a=new o(1).toRed(this),c=a.redNeg(),d=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new o(2*l*l).toRed(this);0!==this.pow(l,d).cmp(c);)l.redIAdd(c);for(var u=this.pow(l,r),h=this.pow(e,r.addn(1).iushrn(1)),f=this.pow(e,r),p=s;0!==f.cmp(a);){for(var g=f,v=0;0!==g.cmp(a);v++)g=g.redSqr();n(v=0;n--){for(var d=t.words[n],l=c-1;l>=0;l--){var u=d>>l&1;r!==i[0]&&(r=this.sqr(r)),0!==u||0!==s?(s<<=1,s|=u,(4===++a||0===n&&0===l)&&(r=this.mul(r,i[s]),a=0,s=0)):a=0}c=26}return r},w.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},w.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new T(e)},r(T,w),T.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},T.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},T.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var i=e.imul(t),n=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),r=i.isub(n).iushrn(this.shift),o=r;return r.cmp(this.m)>=0?o=r.isub(this.m):r.cmpn(0)<0&&(o=r.iadd(this.m)),o._forceRed(this)},T.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var i=e.mul(t),n=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),r=i.isub(n).iushrn(this.shift),s=r;return r.cmp(this.m)>=0?s=r.isub(this.m):r.cmpn(0)<0&&(s=r.iadd(this.m)),s._forceRed(this)},T.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{buffer:20}],19:[function(e,t,i){var n;function r(e){this.rand=e}if(t.exports=function(e){return n||(n=new r(null)),n.generate(e)},t.exports.Rand=r,r.prototype.generate=function(e){return this._rand(e)},r.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),i=0;i>>24]^l[p>>>16&255]^u[g>>>8&255]^h[255&v]^t[m++],s=d[p>>>24]^l[g>>>16&255]^u[v>>>8&255]^h[255&f]^t[m++],a=d[g>>>24]^l[v>>>16&255]^u[f>>>8&255]^h[255&p]^t[m++],c=d[v>>>24]^l[f>>>16&255]^u[p>>>8&255]^h[255&g]^t[m++],f=o,p=s,g=a,v=c;return o=(n[f>>>24]<<24|n[p>>>16&255]<<16|n[g>>>8&255]<<8|n[255&v])^t[m++],s=(n[p>>>24]<<24|n[g>>>16&255]<<16|n[v>>>8&255]<<8|n[255&f])^t[m++],a=(n[g>>>24]<<24|n[v>>>16&255]<<16|n[f>>>8&255]<<8|n[255&p])^t[m++],c=(n[v>>>24]<<24|n[f>>>16&255]<<16|n[p>>>8&255]<<8|n[255&g])^t[m++],[o>>>=0,s>>>=0,a>>>=0,c>>>=0]}var a=[0,1,2,4,8,16,32,64,128,27,54],c=function(){for(var e=new Array(256),t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;for(var i=[],n=[],r=[[],[],[],[]],o=[[],[],[],[]],s=0,a=0,c=0;c<256;++c){var d=a^a<<1^a<<2^a<<3^a<<4;d=d>>>8^255&d^99,i[s]=d,n[d]=s;var l=e[s],u=e[l],h=e[u],f=257*e[d]^16843008*d;r[0][s]=f<<24|f>>>8,r[1][s]=f<<16|f>>>16,r[2][s]=f<<8|f>>>24,r[3][s]=f,f=16843009*h^65537*u^257*l^16843008*s,o[0][d]=f<<24|f>>>8,o[1][d]=f<<16|f>>>16,o[2][d]=f<<8|f>>>24,o[3][d]=f,0===s?s=a=1:(s=l^e[e[e[h^l]]],a^=e[e[a]])}return{SBOX:i,INV_SBOX:n,SUB_MIX:r,INV_SUB_MIX:o}}();function d(e){this._key=r(e),this._reset()}d.blockSize=16,d.keySize=32,d.prototype.blockSize=d.blockSize,d.prototype.keySize=d.keySize,d.prototype._reset=function(){for(var e=this._key,t=e.length,i=t+6,n=4*(i+1),r=[],o=0;o>>24,s=c.SBOX[s>>>24]<<24|c.SBOX[s>>>16&255]<<16|c.SBOX[s>>>8&255]<<8|c.SBOX[255&s],s^=a[o/t|0]<<24):t>6&&o%t==4&&(s=c.SBOX[s>>>24]<<24|c.SBOX[s>>>16&255]<<16|c.SBOX[s>>>8&255]<<8|c.SBOX[255&s]),r[o]=r[o-t]^s}for(var d=[],l=0;l>>24]]^c.INV_SUB_MIX[1][c.SBOX[h>>>16&255]]^c.INV_SUB_MIX[2][c.SBOX[h>>>8&255]]^c.INV_SUB_MIX[3][c.SBOX[255&h]]}this._nRounds=i,this._keySchedule=r,this._invKeySchedule=d},d.prototype.encryptBlockRaw=function(e){return s(e=r(e),this._keySchedule,c.SUB_MIX,c.SBOX,this._nRounds)},d.prototype.encryptBlock=function(e){var t=this.encryptBlockRaw(e),i=n.allocUnsafe(16);return i.writeUInt32BE(t[0],0),i.writeUInt32BE(t[1],4),i.writeUInt32BE(t[2],8),i.writeUInt32BE(t[3],12),i},d.prototype.decryptBlock=function(e){var t=(e=r(e))[1];e[1]=e[3],e[3]=t;var i=s(e,this._invKeySchedule,c.INV_SUB_MIX,c.INV_SBOX,this._nRounds),o=n.allocUnsafe(16);return o.writeUInt32BE(i[0],0),o.writeUInt32BE(i[3],4),o.writeUInt32BE(i[2],8),o.writeUInt32BE(i[1],12),o},d.prototype.scrub=function(){o(this._keySchedule),o(this._invKeySchedule),o(this._key)},t.exports.AES=d},{"safe-buffer":250}],22:[function(e,t,i){var n=e("./aes"),r=e("safe-buffer").Buffer,o=e("cipher-base"),s=e("inherits"),a=e("./ghash"),c=e("buffer-xor"),d=e("./incr32");function l(e,t,i,s){o.call(this);var c=r.alloc(4,0);this._cipher=new n.AES(t);var l=this._cipher.encryptBlock(c);this._ghash=new a(l),i=function(e,t,i){if(12===t.length)return e._finID=r.concat([t,r.from([0,0,0,1])]),r.concat([t,r.from([0,0,0,2])]);var n=new a(i),o=t.length,s=o%16;n.update(t),s&&(s=16-s,n.update(r.alloc(s,0))),n.update(r.alloc(8,0));var c=8*o,l=r.alloc(8);l.writeUIntBE(c,0,8),n.update(l),e._finID=n.state;var u=r.from(e._finID);return d(u),u}(this,i,l),this._prev=r.from(i),this._cache=r.allocUnsafe(0),this._secCache=r.allocUnsafe(0),this._decrypt=s,this._alen=0,this._len=0,this._mode=e,this._authTag=null,this._called=!1}s(l,o),l.prototype._update=function(e){if(!this._called&&this._alen){var t=16-this._alen%16;t<16&&(t=r.alloc(t,0),this._ghash.update(t))}this._called=!0;var i=this._mode.encrypt(this,e);return this._decrypt?this._ghash.update(e):this._ghash.update(i),this._len+=e.length,i},l.prototype._final=function(){if(this._decrypt&&!this._authTag)throw new Error("Unsupported state or unable to authenticate data");var e=c(this._ghash.final(8*this._alen,8*this._len),this._cipher.encryptBlock(this._finID));if(this._decrypt&&function(e,t){var i=0;e.length!==t.length&&i++;for(var n=Math.min(e.length,t.length),r=0;r16)throw new Error("unable to decrypt data");var i=-1;for(;++i16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t}else if(this.cache.length>=16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t;return null},u.prototype.flush=function(){if(this.cache.length)return this.cache},i.createDecipher=function(e,t){var i=o[e.toLowerCase()];if(!i)throw new TypeError("invalid suite type");var n=d(t,!1,i.key,i.iv);return h(e,n.key,n.iv)},i.createDecipheriv=h},{"./aes":21,"./authCipher":22,"./modes":34,"./streamCipher":37,"cipher-base":71,evp_bytestokey:106,inherits:146,"safe-buffer":250}],25:[function(e,t,i){var n=e("./modes"),r=e("./authCipher"),o=e("safe-buffer").Buffer,s=e("./streamCipher"),a=e("cipher-base"),c=e("./aes"),d=e("evp_bytestokey");function l(e,t,i){a.call(this),this._cache=new h,this._cipher=new c.AES(t),this._prev=o.from(i),this._mode=e,this._autopadding=!0}e("inherits")(l,a),l.prototype._update=function(e){var t,i;this._cache.add(e);for(var n=[];t=this._cache.get();)i=this._mode.encrypt(this,t),n.push(i);return o.concat(n)};var u=o.alloc(16,16);function h(){this.cache=o.allocUnsafe(0)}function f(e,t,i){var a=n[e.toLowerCase()];if(!a)throw new TypeError("invalid suite type");if("string"==typeof t&&(t=o.from(t)),t.length!==a.key/8)throw new TypeError("invalid key length "+t.length);if("string"==typeof i&&(i=o.from(i)),"GCM"!==a.mode&&i.length!==a.iv)throw new TypeError("invalid iv length "+i.length);return"stream"===a.type?new s(a.module,t,i):"auth"===a.type?new r(a.module,t,i):new l(a.module,t,i)}l.prototype._final=function(){var e=this._cache.flush();if(this._autopadding)return e=this._mode.encrypt(this,e),this._cipher.scrub(),e;if(!e.equals(u))throw this._cipher.scrub(),new Error("data not multiple of block length")},l.prototype.setAutoPadding=function(e){return this._autopadding=!!e,this},h.prototype.add=function(e){this.cache=o.concat([this.cache,e])},h.prototype.get=function(){if(this.cache.length>15){var e=this.cache.slice(0,16);return this.cache=this.cache.slice(16),e}return null},h.prototype.flush=function(){for(var e=16-this.cache.length,t=o.allocUnsafe(e),i=-1;++i>>0,0),t.writeUInt32BE(e[1]>>>0,4),t.writeUInt32BE(e[2]>>>0,8),t.writeUInt32BE(e[3]>>>0,12),t}function s(e){this.h=e,this.state=n.alloc(16,0),this.cache=n.allocUnsafe(0)}s.prototype.ghash=function(e){for(var t=-1;++t0;t--)n[t]=n[t]>>>1|(1&n[t-1])<<31;n[0]=n[0]>>>1,i&&(n[0]=n[0]^225<<24)}this.state=o(r)},s.prototype.update=function(e){var t;for(this.cache=n.concat([this.cache,e]);this.cache.length>=16;)t=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(t)},s.prototype.final=function(e,t){return this.cache.length&&this.ghash(n.concat([this.cache,r],16)),this.ghash(o([0,e,0,t])),this.state},t.exports=s},{"safe-buffer":250}],27:[function(e,t,i){t.exports=function(e){for(var t,i=e.length;i--;){if(255!==(t=e.readUInt8(i))){t++,e.writeUInt8(t,i);break}e.writeUInt8(0,i)}}},{}],28:[function(e,t,i){var n=e("buffer-xor");i.encrypt=function(e,t){var i=n(t,e._prev);return e._prev=e._cipher.encryptBlock(i),e._prev},i.decrypt=function(e,t){var i=e._prev;e._prev=t;var r=e._cipher.decryptBlock(t);return n(r,i)}},{"buffer-xor":67}],29:[function(e,t,i){var n=e("safe-buffer").Buffer,r=e("buffer-xor");function o(e,t,i){var o=t.length,s=r(t,e._cache);return e._cache=e._cache.slice(o),e._prev=n.concat([e._prev,i?t:s]),s}i.encrypt=function(e,t,i){for(var r,s=n.allocUnsafe(0);t.length;){if(0===e._cache.length&&(e._cache=e._cipher.encryptBlock(e._prev),e._prev=n.allocUnsafe(0)),!(e._cache.length<=t.length)){s=n.concat([s,o(e,t,i)]);break}r=e._cache.length,s=n.concat([s,o(e,t.slice(0,r),i)]),t=t.slice(r)}return s}},{"buffer-xor":67,"safe-buffer":250}],30:[function(e,t,i){var n=e("safe-buffer").Buffer;function r(e,t,i){for(var n,r,s=-1,a=0;++s<8;)n=t&1<<7-s?128:0,a+=(128&(r=e._cipher.encryptBlock(e._prev)[0]^n))>>s%8,e._prev=o(e._prev,i?n:r);return a}function o(e,t){var i=e.length,r=-1,o=n.allocUnsafe(e.length);for(e=n.concat([e,n.from([t])]);++r>7;return o}i.encrypt=function(e,t,i){for(var o=t.length,s=n.allocUnsafe(o),a=-1;++a=0||!t.umod(e.prime1)||!t.umod(e.prime2));return t}function s(e,t){var r=function(e){var t=o(e);return{blinder:t.toRed(n.mont(e.modulus)).redPow(new n(e.publicExponent)).fromRed(),unblinder:t.invm(e.modulus)}}(t),s=t.modulus.byteLength(),a=new n(e).mul(r.blinder).umod(t.modulus),c=a.toRed(n.mont(t.prime1)),d=a.toRed(n.mont(t.prime2)),l=t.coefficient,u=t.prime1,h=t.prime2,f=c.redPow(t.exponent1).fromRed(),p=d.redPow(t.exponent2).fromRed(),g=f.isub(p).imul(l).umod(u).imul(h);return p.iadd(g).imul(r.unblinder).umod(t.modulus).toArrayLike(i,"be",s)}s.getr=o,t.exports=s}).call(this)}).call(this,e("buffer").Buffer)},{"bn.js":42,buffer:68,randombytes:244}],42:[function(e,t,i){!function(t,i){"use strict";function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function r(e,t){e.super_=t;var i=function(){};i.prototype=t.prototype,e.prototype=new i,e.prototype.constructor=e}function o(e,t,i){if(o.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(i=t,t=10),this._init(e||0,t||10,i||"be"))}var s;"object"==typeof t?t.exports=o:i.BN=o,o.BN=o,o.wordSize=26;try{s="undefined"!=typeof window&&void 0!==window.Buffer?window.Buffer:e("buffer").Buffer}catch(e){}function a(e,t){var i=e.charCodeAt(t);return i>=48&&i<=57?i-48:i>=65&&i<=70?i-55:i>=97&&i<=102?i-87:void n(!1,"Invalid character in "+e)}function c(e,t,i){var n=a(e,i);return i-1>=t&&(n|=a(e,i-1)<<4),n}function d(e,t,i,r){for(var o=0,s=0,a=Math.min(e.length,i),c=t;c=49?d-49+10:d>=17?d-17+10:d,n(d>=0&&s0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,i){if("number"==typeof e)return this._initNumber(e,t,i);if("object"==typeof e)return this._initArray(e,t,i);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var r=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&(r++,this.negative=1),r=0;r-=3)s=e[r]|e[r-1]<<8|e[r-2]<<16,this.words[o]|=s<>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);else if("le"===i)for(r=0,o=0;r>>26-a&67108863,(a+=24)>=26&&(a-=26,o++);return this._strip()},o.prototype._parseHex=function(e,t,i){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var n=0;n=t;n-=2)r=c(e,t,n)<=18?(o-=18,s+=1,this.words[s]|=r>>>26):o+=8;else for(n=(e.length-t)%2==0?t+1:t;n=18?(o-=18,s+=1,this.words[s]|=r>>>26):o+=8;this._strip()},o.prototype._parseBase=function(e,t,i){this.words=[0],this.length=1;for(var n=0,r=1;r<=67108863;r*=t)n++;n--,r=r/t|0;for(var o=e.length-i,s=o%n,a=Math.min(o,o-s)+i,c=0,l=i;l1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},"undefined"!=typeof Symbol&&"function"==typeof Symbol.for)try{o.prototype[Symbol.for("nodejs.util.inspect.custom")]=u}catch(e){o.prototype.inspect=u}else o.prototype.inspect=u;function u(){return(this.red?""}var h=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],f=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],p=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];o.prototype.toString=function(e,t){var i;if(t=0|t||1,16===(e=e||10)||"hex"===e){i="";for(var r=0,o=0,s=0;s>>24-r&16777215,(r+=2)>=26&&(r-=26,s--),i=0!==o||s!==this.length-1?h[6-c.length]+c+i:c+i}for(0!==o&&(i=o.toString(16)+i);i.length%t!=0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}if(e===(0|e)&&e>=2&&e<=36){var d=f[e],l=p[e];i="";var u=this.clone();for(u.negative=0;!u.isZero();){var g=u.modrn(l).toString(e);i=(u=u.idivn(l)).isZero()?g+i:h[d-g.length]+g+i}for(this.isZero()&&(i="0"+i);i.length%t!=0;)i="0"+i;return 0!==this.negative&&(i="-"+i),i}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16,2)},s&&(o.prototype.toBuffer=function(e,t){return this.toArrayLike(s,e,t)}),o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)};function g(e,t,i){i.negative=t.negative^e.negative;var n=e.length+t.length|0;i.length=n,n=n-1|0;var r=0|e.words[0],o=0|t.words[0],s=r*o,a=67108863&s,c=s/67108864|0;i.words[0]=a;for(var d=1;d>>26,u=67108863&c,h=Math.min(d,t.length-1),f=Math.max(0,d-e.length+1);f<=h;f++){var p=d-f|0;l+=(s=(r=0|e.words[p])*(o=0|t.words[f])+u)/67108864|0,u=67108863&s}i.words[d]=0|u,c=0|l}return 0!==c?i.words[d]=0|c:i.length--,i._strip()}o.prototype.toArrayLike=function(e,t,i){this._strip();var r=this.byteLength(),o=i||Math.max(1,r);n(r<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0");var s=function(e,t){return e.allocUnsafe?e.allocUnsafe(t):new e(t)}(e,o);return this["_toArrayLike"+("le"===t?"LE":"BE")](s,r),s},o.prototype._toArrayLikeLE=function(e,t){for(var i=0,n=0,r=0,o=0;r>8&255),i>16&255),6===o?(i>24&255),n=0,o=0):(n=s>>>24,o+=2)}if(i=0&&(e[i--]=s>>8&255),i>=0&&(e[i--]=s>>16&255),6===o?(i>=0&&(e[i--]=s>>24&255),n=0,o=0):(n=s>>>24,o+=2)}if(i>=0)for(e[i--]=n;i>=0;)e[i--]=0},Math.clz32?o.prototype._countBits=function(e){return 32-Math.clz32(e)}:o.prototype._countBits=function(e){var t=e,i=0;return t>=4096&&(i+=13,t>>>=13),t>=64&&(i+=7,t>>>=7),t>=8&&(i+=4,t>>>=4),t>=2&&(i+=2,t>>>=2),i+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,i=0;return 0==(8191&t)&&(i+=13,t>>>=13),0==(127&t)&&(i+=7,t>>>=7),0==(15&t)&&(i+=4,t>>>=4),0==(3&t)&&(i+=2,t>>>=2),0==(1&t)&&i++,i},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var i=0;ie.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,i;this.length>e.length?(t=this,i=e):(t=e,i=this);for(var n=0;ne.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),i=e%26;this._expand(t),i>0&&t--;for(var r=0;r0&&(this.words[r]=~this.words[r]&67108863>>26-i),this._strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var i=e/26|0,r=e%26;return this._expand(i+1),this.words[i]=t?this.words[i]|1<e.length?(i=this,n=e):(i=e,n=this);for(var r=0,o=0;o>>26;for(;0!==r&&o>>26;if(this.length=i.length,0!==r)this.words[this.length]=r,this.length++;else if(i!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var i,n,r=this.cmp(e);if(0===r)return this.negative=0,this.length=1,this.words[0]=0,this;r>0?(i=this,n=e):(i=e,n=this);for(var o=0,s=0;s>26,this.words[s]=67108863&t;for(;0!==o&&s>26,this.words[s]=67108863&t;if(0===o&&s>>13,f=0|s[1],p=8191&f,g=f>>>13,v=0|s[2],m=8191&v,y=v>>>13,b=0|s[3],S=8191&b,_=b>>>13,E=0|s[4],w=8191&E,T=E>>>13,I=0|s[5],R=8191&I,M=I>>>13,k=0|s[6],C=8191&k,O=k>>>13,A=0|s[7],P=8191&A,D=A>>>13,x=0|s[8],L=8191&x,U=x>>>13,B=0|s[9],N=8191&B,j=B>>>13,F=0|a[0],K=8191&F,q=F>>>13,$=0|a[1],V=8191&$,H=$>>>13,W=0|a[2],G=8191&W,z=W>>>13,Y=0|a[3],J=8191&Y,Q=Y>>>13,X=0|a[4],Z=8191&X,ee=X>>>13,te=0|a[5],ie=8191&te,ne=te>>>13,re=0|a[6],oe=8191&re,se=re>>>13,ae=0|a[7],ce=8191&ae,de=ae>>>13,le=0|a[8],ue=8191&le,he=le>>>13,fe=0|a[9],pe=8191&fe,ge=fe>>>13;i.negative=e.negative^t.negative,i.length=19;var ve=(d+(n=Math.imul(u,K))|0)+((8191&(r=(r=Math.imul(u,q))+Math.imul(h,K)|0))<<13)|0;d=((o=Math.imul(h,q))+(r>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(p,K),r=(r=Math.imul(p,q))+Math.imul(g,K)|0,o=Math.imul(g,q);var me=(d+(n=n+Math.imul(u,V)|0)|0)+((8191&(r=(r=r+Math.imul(u,H)|0)+Math.imul(h,V)|0))<<13)|0;d=((o=o+Math.imul(h,H)|0)+(r>>>13)|0)+(me>>>26)|0,me&=67108863,n=Math.imul(m,K),r=(r=Math.imul(m,q))+Math.imul(y,K)|0,o=Math.imul(y,q),n=n+Math.imul(p,V)|0,r=(r=r+Math.imul(p,H)|0)+Math.imul(g,V)|0,o=o+Math.imul(g,H)|0;var ye=(d+(n=n+Math.imul(u,G)|0)|0)+((8191&(r=(r=r+Math.imul(u,z)|0)+Math.imul(h,G)|0))<<13)|0;d=((o=o+Math.imul(h,z)|0)+(r>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(S,K),r=(r=Math.imul(S,q))+Math.imul(_,K)|0,o=Math.imul(_,q),n=n+Math.imul(m,V)|0,r=(r=r+Math.imul(m,H)|0)+Math.imul(y,V)|0,o=o+Math.imul(y,H)|0,n=n+Math.imul(p,G)|0,r=(r=r+Math.imul(p,z)|0)+Math.imul(g,G)|0,o=o+Math.imul(g,z)|0;var be=(d+(n=n+Math.imul(u,J)|0)|0)+((8191&(r=(r=r+Math.imul(u,Q)|0)+Math.imul(h,J)|0))<<13)|0;d=((o=o+Math.imul(h,Q)|0)+(r>>>13)|0)+(be>>>26)|0,be&=67108863,n=Math.imul(w,K),r=(r=Math.imul(w,q))+Math.imul(T,K)|0,o=Math.imul(T,q),n=n+Math.imul(S,V)|0,r=(r=r+Math.imul(S,H)|0)+Math.imul(_,V)|0,o=o+Math.imul(_,H)|0,n=n+Math.imul(m,G)|0,r=(r=r+Math.imul(m,z)|0)+Math.imul(y,G)|0,o=o+Math.imul(y,z)|0,n=n+Math.imul(p,J)|0,r=(r=r+Math.imul(p,Q)|0)+Math.imul(g,J)|0,o=o+Math.imul(g,Q)|0;var Se=(d+(n=n+Math.imul(u,Z)|0)|0)+((8191&(r=(r=r+Math.imul(u,ee)|0)+Math.imul(h,Z)|0))<<13)|0;d=((o=o+Math.imul(h,ee)|0)+(r>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(R,K),r=(r=Math.imul(R,q))+Math.imul(M,K)|0,o=Math.imul(M,q),n=n+Math.imul(w,V)|0,r=(r=r+Math.imul(w,H)|0)+Math.imul(T,V)|0,o=o+Math.imul(T,H)|0,n=n+Math.imul(S,G)|0,r=(r=r+Math.imul(S,z)|0)+Math.imul(_,G)|0,o=o+Math.imul(_,z)|0,n=n+Math.imul(m,J)|0,r=(r=r+Math.imul(m,Q)|0)+Math.imul(y,J)|0,o=o+Math.imul(y,Q)|0,n=n+Math.imul(p,Z)|0,r=(r=r+Math.imul(p,ee)|0)+Math.imul(g,Z)|0,o=o+Math.imul(g,ee)|0;var _e=(d+(n=n+Math.imul(u,ie)|0)|0)+((8191&(r=(r=r+Math.imul(u,ne)|0)+Math.imul(h,ie)|0))<<13)|0;d=((o=o+Math.imul(h,ne)|0)+(r>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(C,K),r=(r=Math.imul(C,q))+Math.imul(O,K)|0,o=Math.imul(O,q),n=n+Math.imul(R,V)|0,r=(r=r+Math.imul(R,H)|0)+Math.imul(M,V)|0,o=o+Math.imul(M,H)|0,n=n+Math.imul(w,G)|0,r=(r=r+Math.imul(w,z)|0)+Math.imul(T,G)|0,o=o+Math.imul(T,z)|0,n=n+Math.imul(S,J)|0,r=(r=r+Math.imul(S,Q)|0)+Math.imul(_,J)|0,o=o+Math.imul(_,Q)|0,n=n+Math.imul(m,Z)|0,r=(r=r+Math.imul(m,ee)|0)+Math.imul(y,Z)|0,o=o+Math.imul(y,ee)|0,n=n+Math.imul(p,ie)|0,r=(r=r+Math.imul(p,ne)|0)+Math.imul(g,ie)|0,o=o+Math.imul(g,ne)|0;var Ee=(d+(n=n+Math.imul(u,oe)|0)|0)+((8191&(r=(r=r+Math.imul(u,se)|0)+Math.imul(h,oe)|0))<<13)|0;d=((o=o+Math.imul(h,se)|0)+(r>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(P,K),r=(r=Math.imul(P,q))+Math.imul(D,K)|0,o=Math.imul(D,q),n=n+Math.imul(C,V)|0,r=(r=r+Math.imul(C,H)|0)+Math.imul(O,V)|0,o=o+Math.imul(O,H)|0,n=n+Math.imul(R,G)|0,r=(r=r+Math.imul(R,z)|0)+Math.imul(M,G)|0,o=o+Math.imul(M,z)|0,n=n+Math.imul(w,J)|0,r=(r=r+Math.imul(w,Q)|0)+Math.imul(T,J)|0,o=o+Math.imul(T,Q)|0,n=n+Math.imul(S,Z)|0,r=(r=r+Math.imul(S,ee)|0)+Math.imul(_,Z)|0,o=o+Math.imul(_,ee)|0,n=n+Math.imul(m,ie)|0,r=(r=r+Math.imul(m,ne)|0)+Math.imul(y,ie)|0,o=o+Math.imul(y,ne)|0,n=n+Math.imul(p,oe)|0,r=(r=r+Math.imul(p,se)|0)+Math.imul(g,oe)|0,o=o+Math.imul(g,se)|0;var we=(d+(n=n+Math.imul(u,ce)|0)|0)+((8191&(r=(r=r+Math.imul(u,de)|0)+Math.imul(h,ce)|0))<<13)|0;d=((o=o+Math.imul(h,de)|0)+(r>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(L,K),r=(r=Math.imul(L,q))+Math.imul(U,K)|0,o=Math.imul(U,q),n=n+Math.imul(P,V)|0,r=(r=r+Math.imul(P,H)|0)+Math.imul(D,V)|0,o=o+Math.imul(D,H)|0,n=n+Math.imul(C,G)|0,r=(r=r+Math.imul(C,z)|0)+Math.imul(O,G)|0,o=o+Math.imul(O,z)|0,n=n+Math.imul(R,J)|0,r=(r=r+Math.imul(R,Q)|0)+Math.imul(M,J)|0,o=o+Math.imul(M,Q)|0,n=n+Math.imul(w,Z)|0,r=(r=r+Math.imul(w,ee)|0)+Math.imul(T,Z)|0,o=o+Math.imul(T,ee)|0,n=n+Math.imul(S,ie)|0,r=(r=r+Math.imul(S,ne)|0)+Math.imul(_,ie)|0,o=o+Math.imul(_,ne)|0,n=n+Math.imul(m,oe)|0,r=(r=r+Math.imul(m,se)|0)+Math.imul(y,oe)|0,o=o+Math.imul(y,se)|0,n=n+Math.imul(p,ce)|0,r=(r=r+Math.imul(p,de)|0)+Math.imul(g,ce)|0,o=o+Math.imul(g,de)|0;var Te=(d+(n=n+Math.imul(u,ue)|0)|0)+((8191&(r=(r=r+Math.imul(u,he)|0)+Math.imul(h,ue)|0))<<13)|0;d=((o=o+Math.imul(h,he)|0)+(r>>>13)|0)+(Te>>>26)|0,Te&=67108863,n=Math.imul(N,K),r=(r=Math.imul(N,q))+Math.imul(j,K)|0,o=Math.imul(j,q),n=n+Math.imul(L,V)|0,r=(r=r+Math.imul(L,H)|0)+Math.imul(U,V)|0,o=o+Math.imul(U,H)|0,n=n+Math.imul(P,G)|0,r=(r=r+Math.imul(P,z)|0)+Math.imul(D,G)|0,o=o+Math.imul(D,z)|0,n=n+Math.imul(C,J)|0,r=(r=r+Math.imul(C,Q)|0)+Math.imul(O,J)|0,o=o+Math.imul(O,Q)|0,n=n+Math.imul(R,Z)|0,r=(r=r+Math.imul(R,ee)|0)+Math.imul(M,Z)|0,o=o+Math.imul(M,ee)|0,n=n+Math.imul(w,ie)|0,r=(r=r+Math.imul(w,ne)|0)+Math.imul(T,ie)|0,o=o+Math.imul(T,ne)|0,n=n+Math.imul(S,oe)|0,r=(r=r+Math.imul(S,se)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,se)|0,n=n+Math.imul(m,ce)|0,r=(r=r+Math.imul(m,de)|0)+Math.imul(y,ce)|0,o=o+Math.imul(y,de)|0,n=n+Math.imul(p,ue)|0,r=(r=r+Math.imul(p,he)|0)+Math.imul(g,ue)|0,o=o+Math.imul(g,he)|0;var Ie=(d+(n=n+Math.imul(u,pe)|0)|0)+((8191&(r=(r=r+Math.imul(u,ge)|0)+Math.imul(h,pe)|0))<<13)|0;d=((o=o+Math.imul(h,ge)|0)+(r>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,n=Math.imul(N,V),r=(r=Math.imul(N,H))+Math.imul(j,V)|0,o=Math.imul(j,H),n=n+Math.imul(L,G)|0,r=(r=r+Math.imul(L,z)|0)+Math.imul(U,G)|0,o=o+Math.imul(U,z)|0,n=n+Math.imul(P,J)|0,r=(r=r+Math.imul(P,Q)|0)+Math.imul(D,J)|0,o=o+Math.imul(D,Q)|0,n=n+Math.imul(C,Z)|0,r=(r=r+Math.imul(C,ee)|0)+Math.imul(O,Z)|0,o=o+Math.imul(O,ee)|0,n=n+Math.imul(R,ie)|0,r=(r=r+Math.imul(R,ne)|0)+Math.imul(M,ie)|0,o=o+Math.imul(M,ne)|0,n=n+Math.imul(w,oe)|0,r=(r=r+Math.imul(w,se)|0)+Math.imul(T,oe)|0,o=o+Math.imul(T,se)|0,n=n+Math.imul(S,ce)|0,r=(r=r+Math.imul(S,de)|0)+Math.imul(_,ce)|0,o=o+Math.imul(_,de)|0,n=n+Math.imul(m,ue)|0,r=(r=r+Math.imul(m,he)|0)+Math.imul(y,ue)|0,o=o+Math.imul(y,he)|0;var Re=(d+(n=n+Math.imul(p,pe)|0)|0)+((8191&(r=(r=r+Math.imul(p,ge)|0)+Math.imul(g,pe)|0))<<13)|0;d=((o=o+Math.imul(g,ge)|0)+(r>>>13)|0)+(Re>>>26)|0,Re&=67108863,n=Math.imul(N,G),r=(r=Math.imul(N,z))+Math.imul(j,G)|0,o=Math.imul(j,z),n=n+Math.imul(L,J)|0,r=(r=r+Math.imul(L,Q)|0)+Math.imul(U,J)|0,o=o+Math.imul(U,Q)|0,n=n+Math.imul(P,Z)|0,r=(r=r+Math.imul(P,ee)|0)+Math.imul(D,Z)|0,o=o+Math.imul(D,ee)|0,n=n+Math.imul(C,ie)|0,r=(r=r+Math.imul(C,ne)|0)+Math.imul(O,ie)|0,o=o+Math.imul(O,ne)|0,n=n+Math.imul(R,oe)|0,r=(r=r+Math.imul(R,se)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,se)|0,n=n+Math.imul(w,ce)|0,r=(r=r+Math.imul(w,de)|0)+Math.imul(T,ce)|0,o=o+Math.imul(T,de)|0,n=n+Math.imul(S,ue)|0,r=(r=r+Math.imul(S,he)|0)+Math.imul(_,ue)|0,o=o+Math.imul(_,he)|0;var Me=(d+(n=n+Math.imul(m,pe)|0)|0)+((8191&(r=(r=r+Math.imul(m,ge)|0)+Math.imul(y,pe)|0))<<13)|0;d=((o=o+Math.imul(y,ge)|0)+(r>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(N,J),r=(r=Math.imul(N,Q))+Math.imul(j,J)|0,o=Math.imul(j,Q),n=n+Math.imul(L,Z)|0,r=(r=r+Math.imul(L,ee)|0)+Math.imul(U,Z)|0,o=o+Math.imul(U,ee)|0,n=n+Math.imul(P,ie)|0,r=(r=r+Math.imul(P,ne)|0)+Math.imul(D,ie)|0,o=o+Math.imul(D,ne)|0,n=n+Math.imul(C,oe)|0,r=(r=r+Math.imul(C,se)|0)+Math.imul(O,oe)|0,o=o+Math.imul(O,se)|0,n=n+Math.imul(R,ce)|0,r=(r=r+Math.imul(R,de)|0)+Math.imul(M,ce)|0,o=o+Math.imul(M,de)|0,n=n+Math.imul(w,ue)|0,r=(r=r+Math.imul(w,he)|0)+Math.imul(T,ue)|0,o=o+Math.imul(T,he)|0;var ke=(d+(n=n+Math.imul(S,pe)|0)|0)+((8191&(r=(r=r+Math.imul(S,ge)|0)+Math.imul(_,pe)|0))<<13)|0;d=((o=o+Math.imul(_,ge)|0)+(r>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(N,Z),r=(r=Math.imul(N,ee))+Math.imul(j,Z)|0,o=Math.imul(j,ee),n=n+Math.imul(L,ie)|0,r=(r=r+Math.imul(L,ne)|0)+Math.imul(U,ie)|0,o=o+Math.imul(U,ne)|0,n=n+Math.imul(P,oe)|0,r=(r=r+Math.imul(P,se)|0)+Math.imul(D,oe)|0,o=o+Math.imul(D,se)|0,n=n+Math.imul(C,ce)|0,r=(r=r+Math.imul(C,de)|0)+Math.imul(O,ce)|0,o=o+Math.imul(O,de)|0,n=n+Math.imul(R,ue)|0,r=(r=r+Math.imul(R,he)|0)+Math.imul(M,ue)|0,o=o+Math.imul(M,he)|0;var Ce=(d+(n=n+Math.imul(w,pe)|0)|0)+((8191&(r=(r=r+Math.imul(w,ge)|0)+Math.imul(T,pe)|0))<<13)|0;d=((o=o+Math.imul(T,ge)|0)+(r>>>13)|0)+(Ce>>>26)|0,Ce&=67108863,n=Math.imul(N,ie),r=(r=Math.imul(N,ne))+Math.imul(j,ie)|0,o=Math.imul(j,ne),n=n+Math.imul(L,oe)|0,r=(r=r+Math.imul(L,se)|0)+Math.imul(U,oe)|0,o=o+Math.imul(U,se)|0,n=n+Math.imul(P,ce)|0,r=(r=r+Math.imul(P,de)|0)+Math.imul(D,ce)|0,o=o+Math.imul(D,de)|0,n=n+Math.imul(C,ue)|0,r=(r=r+Math.imul(C,he)|0)+Math.imul(O,ue)|0,o=o+Math.imul(O,he)|0;var Oe=(d+(n=n+Math.imul(R,pe)|0)|0)+((8191&(r=(r=r+Math.imul(R,ge)|0)+Math.imul(M,pe)|0))<<13)|0;d=((o=o+Math.imul(M,ge)|0)+(r>>>13)|0)+(Oe>>>26)|0,Oe&=67108863,n=Math.imul(N,oe),r=(r=Math.imul(N,se))+Math.imul(j,oe)|0,o=Math.imul(j,se),n=n+Math.imul(L,ce)|0,r=(r=r+Math.imul(L,de)|0)+Math.imul(U,ce)|0,o=o+Math.imul(U,de)|0,n=n+Math.imul(P,ue)|0,r=(r=r+Math.imul(P,he)|0)+Math.imul(D,ue)|0,o=o+Math.imul(D,he)|0;var Ae=(d+(n=n+Math.imul(C,pe)|0)|0)+((8191&(r=(r=r+Math.imul(C,ge)|0)+Math.imul(O,pe)|0))<<13)|0;d=((o=o+Math.imul(O,ge)|0)+(r>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(N,ce),r=(r=Math.imul(N,de))+Math.imul(j,ce)|0,o=Math.imul(j,de),n=n+Math.imul(L,ue)|0,r=(r=r+Math.imul(L,he)|0)+Math.imul(U,ue)|0,o=o+Math.imul(U,he)|0;var Pe=(d+(n=n+Math.imul(P,pe)|0)|0)+((8191&(r=(r=r+Math.imul(P,ge)|0)+Math.imul(D,pe)|0))<<13)|0;d=((o=o+Math.imul(D,ge)|0)+(r>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,n=Math.imul(N,ue),r=(r=Math.imul(N,he))+Math.imul(j,ue)|0,o=Math.imul(j,he);var De=(d+(n=n+Math.imul(L,pe)|0)|0)+((8191&(r=(r=r+Math.imul(L,ge)|0)+Math.imul(U,pe)|0))<<13)|0;d=((o=o+Math.imul(U,ge)|0)+(r>>>13)|0)+(De>>>26)|0,De&=67108863;var xe=(d+(n=Math.imul(N,pe))|0)+((8191&(r=(r=Math.imul(N,ge))+Math.imul(j,pe)|0))<<13)|0;return d=((o=Math.imul(j,ge))+(r>>>13)|0)+(xe>>>26)|0,xe&=67108863,c[0]=ve,c[1]=me,c[2]=ye,c[3]=be,c[4]=Se,c[5]=_e,c[6]=Ee,c[7]=we,c[8]=Te,c[9]=Ie,c[10]=Re,c[11]=Me,c[12]=ke,c[13]=Ce,c[14]=Oe,c[15]=Ae,c[16]=Pe,c[17]=De,c[18]=xe,0!==d&&(c[19]=d,i.length++),i};function m(e,t,i){i.negative=t.negative^e.negative,i.length=e.length+t.length;for(var n=0,r=0,o=0;o>>26)|0)>>>26,s&=67108863}i.words[o]=a,n=s,s=r}return 0!==n?i.words[o]=n:i.length--,i._strip()}function y(e,t,i){return m(e,t,i)}function b(e,t){this.x=e,this.y=t}Math.imul||(v=g),o.prototype.mulTo=function(e,t){var i=this.length+e.length;return 10===this.length&&10===e.length?v(this,e,t):i<63?g(this,e,t):i<1024?m(this,e,t):y(this,e,t)},b.prototype.makeRBT=function(e){for(var t=new Array(e),i=o.prototype._countBits(e)-1,n=0;n>=1;return n},b.prototype.permute=function(e,t,i,n,r,o){for(var s=0;s>>=1)r++;return 1<>>=13,i[2*s+1]=8191&o,o>>>=13;for(s=2*t;s>=26,i+=o/67108864|0,i+=s>>>26,this.words[r]=67108863&s}return 0!==i&&(this.words[r]=i,this.length++),t?this.ineg():this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),i=0;i>>r&1}return t}(e);if(0===t.length)return new o(1);for(var i=this,n=0;n=0);var t,i=e%26,r=(e-i)/26,o=67108863>>>26-i<<26-i;if(0!==i){var s=0;for(t=0;t>>26-i}s&&(this.words[t]=s,this.length++)}if(0!==r){for(t=this.length-1;t>=0;t--)this.words[t+r]=this.words[t];for(t=0;t=0),r=t?(t-t%26)/26:0;var o=e%26,s=Math.min((e-o)/26,this.length),a=67108863^67108863>>>o<s)for(this.length-=s,d=0;d=0&&(0!==l||d>=r);d--){var u=0|this.words[d];this.words[d]=l<<26-o|u>>>o,l=u&a}return c&&0!==l&&(c.words[c.length++]=l),0===this.length&&(this.words[0]=0,this.length=1),this._strip()},o.prototype.ishrn=function(e,t,i){return n(0===this.negative),this.iushrn(e,t,i)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,i=(e-t)/26,r=1<=0);var t=e%26,i=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=i)return this;if(0!==t&&i++,this.length=Math.min(i,this.length),0!==t){var r=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(c/67108864|0),this.words[r+i]=67108863&o}for(;r>26,this.words[r+i]=67108863&o;if(0===a)return this._strip();for(n(-1===a),a=0,r=0;r>26,this.words[r]=67108863&o;return this.negative=1,this._strip()},o.prototype._wordDiv=function(e,t){var i=(this.length,e.length),n=this.clone(),r=e,s=0|r.words[r.length-1];0!==(i=26-this._countBits(s))&&(r=r.ushln(i),n.iushln(i),s=0|r.words[r.length-1]);var a,c=n.length-r.length;if("mod"!==t){(a=new o(null)).length=c+1,a.words=new Array(a.length);for(var d=0;d=0;u--){var h=67108864*(0|n.words[r.length+u])+(0|n.words[r.length+u-1]);for(h=Math.min(h/s|0,67108863),n._ishlnsubmul(r,h,u);0!==n.negative;)h--,n.negative=0,n._ishlnsubmul(r,1,u),n.isZero()||(n.negative^=1);a&&(a.words[u]=h)}return a&&a._strip(),n._strip(),"div"!==t&&0!==i&&n.iushrn(i),{div:a||null,mod:n}},o.prototype.divmod=function(e,t,i){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(a=this.neg().divmod(e,t),"mod"!==t&&(r=a.div.neg()),"div"!==t&&(s=a.mod.neg(),i&&0!==s.negative&&s.iadd(e)),{div:r,mod:s}):0===this.negative&&0!==e.negative?(a=this.divmod(e.neg(),t),"mod"!==t&&(r=a.div.neg()),{div:r,mod:a.mod}):0!=(this.negative&e.negative)?(a=this.neg().divmod(e.neg(),t),"div"!==t&&(s=a.mod.neg(),i&&0!==s.negative&&s.isub(e)),{div:a.div,mod:s}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modrn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modrn(e.words[0]))}:this._wordDiv(e,t);var r,s,a},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var i=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),r=e.andln(1),o=i.cmp(n);return o<0||1===r&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modrn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var i=(1<<26)%e,r=0,o=this.length-1;o>=0;o--)r=(i*r+(0|this.words[o]))%e;return t?-r:r},o.prototype.modn=function(e){return this.modrn(e)},o.prototype.idivn=function(e){var t=e<0;t&&(e=-e),n(e<=67108863);for(var i=0,r=this.length-1;r>=0;r--){var o=(0|this.words[r])+67108864*i;this.words[r]=o/e|0,i=o%e}return this._strip(),t?this.ineg():this},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var r=new o(1),s=new o(0),a=new o(0),c=new o(1),d=0;t.isEven()&&i.isEven();)t.iushrn(1),i.iushrn(1),++d;for(var l=i.clone(),u=t.clone();!t.isZero();){for(var h=0,f=1;0==(t.words[0]&f)&&h<26;++h,f<<=1);if(h>0)for(t.iushrn(h);h-- >0;)(r.isOdd()||s.isOdd())&&(r.iadd(l),s.isub(u)),r.iushrn(1),s.iushrn(1);for(var p=0,g=1;0==(i.words[0]&g)&&p<26;++p,g<<=1);if(p>0)for(i.iushrn(p);p-- >0;)(a.isOdd()||c.isOdd())&&(a.iadd(l),c.isub(u)),a.iushrn(1),c.iushrn(1);t.cmp(i)>=0?(t.isub(i),r.isub(a),s.isub(c)):(i.isub(t),a.isub(r),c.isub(s))}return{a:a,b:c,gcd:i.iushln(d)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,i=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var r,s=new o(1),a=new o(0),c=i.clone();t.cmpn(1)>0&&i.cmpn(1)>0;){for(var d=0,l=1;0==(t.words[0]&l)&&d<26;++d,l<<=1);if(d>0)for(t.iushrn(d);d-- >0;)s.isOdd()&&s.iadd(c),s.iushrn(1);for(var u=0,h=1;0==(i.words[0]&h)&&u<26;++u,h<<=1);if(u>0)for(i.iushrn(u);u-- >0;)a.isOdd()&&a.iadd(c),a.iushrn(1);t.cmp(i)>=0?(t.isub(i),s.isub(a)):(i.isub(t),a.isub(s))}return(r=0===t.cmpn(1)?s:a).cmpn(0)<0&&r.iadd(e),r},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),i=e.clone();t.negative=0,i.negative=0;for(var n=0;t.isEven()&&i.isEven();n++)t.iushrn(1),i.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;i.isEven();)i.iushrn(1);var r=t.cmp(i);if(r<0){var o=t;t=i,i=o}else if(0===r||0===i.cmpn(1))break;t.isub(i)}return i.iushln(n)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,i=(e-t)/26,r=1<>>26,a&=67108863,this.words[s]=a}return 0!==o&&(this.words[s]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,i=e<0;if(0!==this.negative&&!i)return-1;if(0===this.negative&&i)return 1;if(this._strip(),this.length>1)t=1;else{i&&(e=-e),n(e<=67108863,"Number is too big");var r=0|this.words[0];t=r===e?0:re.length)return 1;if(this.length=0;i--){var n=0|this.words[i],r=0|e.words[i];if(n!==r){nr&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new R(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var S={k256:null,p224:null,p192:null,p25519:null};function _(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function E(){_.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function w(){_.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function T(){_.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function I(){_.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function R(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function M(e){R.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}_.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},_.prototype.ireduce=function(e){var t,i=e;do{this.split(i,this.tmp),t=(i=(i=this.imulK(i)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t0?i.isub(this.p):void 0!==i.strip?i.strip():i._strip(),i},_.prototype.split=function(e,t){e.iushrn(this.n,0,t)},_.prototype.imulK=function(e){return e.imul(this.k)},r(E,_),E.prototype.split=function(e,t){for(var i=4194303,n=Math.min(e.length,9),r=0;r>>22,o=s}o>>>=22,e.words[r-10]=o,0===o&&e.length>10?e.length-=10:e.length-=9},E.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,i=0;i>>=26,e.words[i]=r,t=n}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(S[e])return S[e];var t;if("k256"===e)t=new E;else if("p224"===e)t=new w;else if("p192"===e)t=new T;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new I}return S[e]=t,t},R.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},R.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},R.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):(l(e,e.umod(this.m)._forceRed(this)),e)},R.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},R.prototype.add=function(e,t){this._verify2(e,t);var i=e.add(t);return i.cmp(this.m)>=0&&i.isub(this.m),i._forceRed(this)},R.prototype.iadd=function(e,t){this._verify2(e,t);var i=e.iadd(t);return i.cmp(this.m)>=0&&i.isub(this.m),i},R.prototype.sub=function(e,t){this._verify2(e,t);var i=e.sub(t);return i.cmpn(0)<0&&i.iadd(this.m),i._forceRed(this)},R.prototype.isub=function(e,t){this._verify2(e,t);var i=e.isub(t);return i.cmpn(0)<0&&i.iadd(this.m),i},R.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},R.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},R.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},R.prototype.isqr=function(e){return this.imul(e,e.clone())},R.prototype.sqr=function(e){return this.mul(e,e)},R.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var i=this.m.add(new o(1)).iushrn(2);return this.pow(e,i)}for(var r=this.m.subn(1),s=0;!r.isZero()&&0===r.andln(1);)s++,r.iushrn(1);n(!r.isZero());var a=new o(1).toRed(this),c=a.redNeg(),d=this.m.subn(1).iushrn(1),l=this.m.bitLength();for(l=new o(2*l*l).toRed(this);0!==this.pow(l,d).cmp(c);)l.redIAdd(c);for(var u=this.pow(l,r),h=this.pow(e,r.addn(1).iushrn(1)),f=this.pow(e,r),p=s;0!==f.cmp(a);){for(var g=f,v=0;0!==g.cmp(a);v++)g=g.redSqr();n(v=0;n--){for(var d=t.words[n],l=c-1;l>=0;l--){var u=d>>l&1;r!==i[0]&&(r=this.sqr(r)),0!==u||0!==s?(s<<=1,s|=u,(4===++a||0===n&&0===l)&&(r=this.mul(r,i[s]),a=0,s=0)):a=0}c=26}return r},R.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},R.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new M(e)},r(M,R),M.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},M.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},M.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var i=e.imul(t),n=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),r=i.isub(n).iushrn(this.shift),o=r;return r.cmp(this.m)>=0?o=r.isub(this.m):r.cmpn(0)<0&&(o=r.iadd(this.m)),o._forceRed(this)},M.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var i=e.mul(t),n=i.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),r=i.isub(n).iushrn(this.shift),s=r;return r.cmp(this.m)>=0?s=r.isub(this.m):r.cmpn(0)<0&&(s=r.iadd(this.m)),s._forceRed(this)},M.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{buffer:20}],43:[function(e,t,i){t.exports=e("./browser/algorithms.json")},{"./browser/algorithms.json":44}],44:[function(e,t,i){t.exports={sha224WithRSAEncryption:{sign:"rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},"RSA-SHA224":{sign:"ecdsa/rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption:{sign:"rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},"RSA-SHA256":{sign:"ecdsa/rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption:{sign:"rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},"RSA-SHA384":{sign:"ecdsa/rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption:{sign:"rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA512":{sign:"ecdsa/rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA1":{sign:"rsa",hash:"sha1",id:"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{sign:"ecdsa",hash:"sha1",id:""},sha256:{sign:"ecdsa",hash:"sha256",id:""},sha224:{sign:"ecdsa",hash:"sha224",id:""},sha384:{sign:"ecdsa",hash:"sha384",id:""},sha512:{sign:"ecdsa",hash:"sha512",id:""},"DSA-SHA":{sign:"dsa",hash:"sha1",id:""},"DSA-SHA1":{sign:"dsa",hash:"sha1",id:""},DSA:{sign:"dsa",hash:"sha1",id:""},"DSA-WITH-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-WITH-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-WITH-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-WITH-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-RIPEMD160":{sign:"dsa",hash:"rmd160",id:""},ripemd160WithRSA:{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},"RSA-RIPEMD160":{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption:{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"},"RSA-MD5":{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"}}},{}],45:[function(e,t,i){t.exports={"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}},{}],46:[function(e,t,i){var n=e("safe-buffer").Buffer,r=e("create-hash"),o=e("readable-stream"),s=e("inherits"),a=e("./sign"),c=e("./verify"),d=e("./algorithms.json");function l(e){o.Writable.call(this);var t=d[e];if(!t)throw new Error("Unknown message digest");this._hashType=t.hash,this._hash=r(t.hash),this._tag=t.id,this._signType=t.sign}function u(e){o.Writable.call(this);var t=d[e];if(!t)throw new Error("Unknown message digest");this._hash=r(t.hash),this._tag=t.id,this._signType=t.sign}function h(e){return new l(e)}function f(e){return new u(e)}Object.keys(d).forEach((function(e){d[e].id=n.from(d[e].id,"hex"),d[e.toLowerCase()]=d[e]})),s(l,o.Writable),l.prototype._write=function(e,t,i){this._hash.update(e),i()},l.prototype.update=function(e,t){return"string"==typeof e&&(e=n.from(e,t)),this._hash.update(e),this},l.prototype.sign=function(e,t){this.end();var i=this._hash.digest(),n=a(i,e,this._hashType,this._signType,this._tag);return t?n.toString(t):n},s(u,o.Writable),u.prototype._write=function(e,t,i){this._hash.update(e),i()},u.prototype.update=function(e,t){return"string"==typeof e&&(e=n.from(e,t)),this._hash.update(e),this},u.prototype.verify=function(e,t,i){"string"==typeof t&&(t=n.from(t,i)),this.end();var r=this._hash.digest();return c(t,r,e,this._signType,this._tag)},t.exports={Sign:h,Verify:f,createSign:h,createVerify:f}},{"./algorithms.json":44,"./sign":47,"./verify":48,"create-hash":74,inherits:146,"readable-stream":64,"safe-buffer":250}],47:[function(e,t,i){var n=e("safe-buffer").Buffer,r=e("create-hmac"),o=e("browserify-rsa"),s=e("elliptic").ec,a=e("bn.js"),c=e("parse-asn1"),d=e("./curves.json");function l(e,t,i,o){if((e=n.from(e.toArray())).length0&&i.ishrn(n),i}function h(e,t,i){var o,s;do{for(o=n.alloc(0);8*o.length=t)throw new Error("invalid sig")}t.exports=function(e,t,i,d,l){var u=s(i);if("ec"===u.type){if("ecdsa"!==d&&"ecdsa/rsa"!==d)throw new Error("wrong public key type");return function(e,t,i){var n=a[i.data.algorithm.curve.join(".")];if(!n)throw new Error("unknown curve "+i.data.algorithm.curve.join("."));var r=new o(n),s=i.data.subjectPrivateKey.data;return r.verify(t,e,s)}(e,t,u)}if("dsa"===u.type){if("dsa"!==d)throw new Error("wrong public key type");return function(e,t,i){var n=i.data.p,o=i.data.q,a=i.data.g,d=i.data.pub_key,l=s.signature.decode(e,"der"),u=l.s,h=l.r;c(u,o),c(h,o);var f=r.mont(n),p=u.invm(o),g=a.toRed(f).redPow(new r(t).mul(p).mod(o)).fromRed().mul(d.toRed(f).redPow(h.mul(p).mod(o)).fromRed()).mod(n).mod(o);return 0===g.cmp(h)}(e,t,u)}if("rsa"!==d&&"ecdsa/rsa"!==d)throw new Error("wrong public key type");t=n.concat([l,t]);for(var h=u.modulus.byteLength(),f=[1],p=0;t.length+f.length+22?"one of ".concat(t," ").concat(e.slice(0,i-1).join(", "),", or ")+e[i-1]:2===i?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}r("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),r("ERR_INVALID_ARG_TYPE",(function(e,t,i){var n,r,s,a;if("string"==typeof t&&(r="not ",t.substr(!s||s<0?0:+s,r.length)===r)?(n="must not be",t=t.replace(/^not /,"")):n="must be",function(e,t,i){return(void 0===i||i>e.length)&&(i=e.length),e.substring(i-t.length,i)===t}(e," argument"))a="The ".concat(e," ").concat(n," ").concat(o(t,"type"));else{var c=function(e,t,i){return"number"!=typeof i&&(i=0),!(i+t.length>e.length)&&-1!==e.indexOf(t,i)}(e,".")?"property":"argument";a='The "'.concat(e,'" ').concat(c," ").concat(n," ").concat(o(t,"type"))}return a+=". Received type ".concat(typeof i)}),TypeError),r("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),r("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),r("ERR_STREAM_PREMATURE_CLOSE","Premature close"),r("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),r("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),r("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),r("ERR_STREAM_WRITE_AFTER_END","write after end"),r("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),r("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),r("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=n},{}],51:[function(e,t,i){(function(i){(function(){"use strict";var n=Object.keys||function(e){var t=[];for(var i in e)t.push(i);return t};t.exports=d;var r=e("./_stream_readable"),o=e("./_stream_writable");e("inherits")(d,r);for(var s=n(o.prototype),a=0;a0)if("string"==typeof t||s.objectMode||Object.getPrototypeOf(t)===a.prototype||(t=function(e){return a.from(e)}(t)),n)s.endEmitted?E(e,new _):M(e,s,t,!0);else if(s.ended)E(e,new b);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!i?(t=s.decoder.write(t),s.objectMode||0!==t.length?M(e,s,t,!1):P(e,s)):M(e,s,t,!1)}else n||(s.reading=!1,P(e,s));return!s.ended&&(s.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=k?e=k:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function O(e){var t=e._readableState;d("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(d("emitReadable",t.flowing),t.emittedReadable=!0,i.nextTick(A,e))}function A(e){var t=e._readableState;d("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,B(e)}function P(e,t){t.readingMore||(t.readingMore=!0,i.nextTick(D,e,t))}function D(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function L(e){d("readable nexttick read 0"),e.read(0)}function U(e,t){d("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),B(e),t.flowing&&!t.reading&&e.read(0)}function B(e){var t=e._readableState;for(d("flow",t.flowing);t.flowing&&null!==e.read(););}function N(e,t){return 0===t.length?null:(t.objectMode?i=t.buffer.shift():!e||e>=t.length?(i=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):i=t.buffer.consume(e,t.decoder),i);var i}function j(e){var t=e._readableState;d("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,i.nextTick(F,t,e))}function F(e,t){if(d("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var i=t._writableState;(!i||i.autoDestroy&&i.finished)&&t.destroy()}}function K(e,t){for(var i=0,n=e.length;i=t.highWaterMark:t.length>0)||t.ended))return d("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?j(this):O(this),null;if(0===(e=C(e,t))&&t.ended)return 0===t.length&&j(this),null;var n,r=t.needReadable;return d("need readable",r),(0===t.length||t.length-e0?N(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),i!==e&&t.ended&&j(this)),null!==n&&this.emit("data",n),n},I.prototype._read=function(e){E(this,new S("_read()"))},I.prototype.pipe=function(e,t){var n=this,r=this._readableState;switch(r.pipesCount){case 0:r.pipes=e;break;case 1:r.pipes=[r.pipes,e];break;default:r.pipes.push(e)}r.pipesCount+=1,d("pipe count=%d opts=%j",r.pipesCount,t);var s=(!t||!1!==t.end)&&e!==i.stdout&&e!==i.stderr?c:v;function a(t,i){d("onunpipe"),t===n&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,d("cleanup"),e.removeListener("close",p),e.removeListener("finish",g),e.removeListener("drain",l),e.removeListener("error",f),e.removeListener("unpipe",a),n.removeListener("end",c),n.removeListener("end",v),n.removeListener("data",h),u=!0,!r.awaitDrain||e._writableState&&!e._writableState.needDrain||l())}function c(){d("onend"),e.end()}r.endEmitted?i.nextTick(s):n.once("end",s),e.on("unpipe",a);var l=function(e){return function(){var t=e._readableState;d("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&o(e,"data")&&(t.flowing=!0,B(e))}}(n);e.on("drain",l);var u=!1;function h(t){d("ondata");var i=e.write(t);d("dest.write",i),!1===i&&((1===r.pipesCount&&r.pipes===e||r.pipesCount>1&&-1!==K(r.pipes,e))&&!u&&(d("false write response, pause",r.awaitDrain),r.awaitDrain++),n.pause())}function f(t){d("onerror",t),v(),e.removeListener("error",f),0===o(e,"error")&&E(e,t)}function p(){e.removeListener("finish",g),v()}function g(){d("onfinish"),e.removeListener("close",p),v()}function v(){d("unpipe"),n.unpipe(e)}return n.on("data",h),function(e,t,i){if("function"==typeof e.prependListener)return e.prependListener(t,i);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(i):e._events[t]=[i,e._events[t]]:e.on(t,i)}(e,"error",f),e.once("close",p),e.once("finish",g),e.emit("pipe",n),r.flowing||(d("pipe resume"),n.resume()),e},I.prototype.unpipe=function(e){var t=this._readableState,i={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,i)),this;if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o0,!1!==r.flowing&&this.resume()):"readable"===e&&(r.endEmitted||r.readableListening||(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,d("on readable",r.length,r.reading),r.length?O(this):r.reading||i.nextTick(L,this))),n},I.prototype.addListener=I.prototype.on,I.prototype.removeListener=function(e,t){var n=s.prototype.removeListener.call(this,e,t);return"readable"===e&&i.nextTick(x,this),n},I.prototype.removeAllListeners=function(e){var t=s.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||i.nextTick(x,this),t},I.prototype.resume=function(){var e=this._readableState;return e.flowing||(d("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,i.nextTick(U,e,t))}(this,e)),e.paused=!1,this},I.prototype.pause=function(){return d("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(d("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},I.prototype.wrap=function(e){var t=this,i=this._readableState,n=!1;for(var r in e.on("end",(function(){if(d("wrapped end"),i.decoder&&!i.ended){var e=i.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(r){(d("wrapped data"),i.decoder&&(r=i.decoder.write(r)),i.objectMode&&null==r)||(i.objectMode||r&&r.length)&&(t.push(r)||(n=!0,e.pause()))})),e)void 0===this[r]&&"function"==typeof e[r]&&(this[r]=function(t){return function(){return e[t].apply(e,arguments)}}(r));for(var o=0;o-1))throw new _(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(I.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(I.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),I.prototype._write=function(e,t,i){i(new g("_write()"))},I.prototype._writev=null,I.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||function(e,t,n){t.ending=!0,A(e,t),n&&(t.finished?i.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,r,n),this},Object.defineProperty(I.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(I.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),I.prototype.destroy=u.destroy,I.prototype._undestroy=u.undestroy,I.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":50,"./_stream_duplex":51,"./internal/streams/destroy":58,"./internal/streams/state":62,"./internal/streams/stream":63,_process:237,buffer:68,inherits:146,"util-deprecate":283}],56:[function(e,t,i){(function(i){(function(){"use strict";var n;function r(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var o=e("./end-of-stream"),s=Symbol("lastResolve"),a=Symbol("lastReject"),c=Symbol("error"),d=Symbol("ended"),l=Symbol("lastPromise"),u=Symbol("handlePromise"),h=Symbol("stream");function f(e,t){return{value:e,done:t}}function p(e){var t=e[s];if(null!==t){var i=e[h].read();null!==i&&(e[l]=null,e[s]=null,e[a]=null,t(f(i,!1)))}}function g(e){i.nextTick(p,e)}var v=Object.getPrototypeOf((function(){})),m=Object.setPrototypeOf((r(n={get stream(){return this[h]},next:function(){var e=this,t=this[c];if(null!==t)return Promise.reject(t);if(this[d])return Promise.resolve(f(void 0,!0));if(this[h].destroyed)return new Promise((function(t,n){i.nextTick((function(){e[c]?n(e[c]):t(f(void 0,!0))}))}));var n,r=this[l];if(r)n=new Promise(function(e,t){return function(i,n){e.then((function(){t[d]?i(f(void 0,!0)):t[u](i,n)}),n)}}(r,this));else{var o=this[h].read();if(null!==o)return Promise.resolve(f(o,!1));n=new Promise(this[u])}return this[l]=n,n}},Symbol.asyncIterator,(function(){return this})),r(n,"return",(function(){var e=this;return new Promise((function(t,i){e[h].destroy(null,(function(e){e?i(e):t(f(void 0,!0))}))}))})),n),v);t.exports=function(e){var t,i=Object.create(m,(r(t={},h,{value:e,writable:!0}),r(t,s,{value:null,writable:!0}),r(t,a,{value:null,writable:!0}),r(t,c,{value:null,writable:!0}),r(t,d,{value:e._readableState.endEmitted,writable:!0}),r(t,u,{value:function(e,t){var n=i[h].read();n?(i[l]=null,i[s]=null,i[a]=null,e(f(n,!1))):(i[s]=e,i[a]=t)},writable:!0}),t));return i[l]=null,o(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=i[a];return null!==t&&(i[l]=null,i[s]=null,i[a]=null,t(e)),void(i[c]=e)}var n=i[s];null!==n&&(i[l]=null,i[s]=null,i[a]=null,n(f(void 0,!0))),i[d]=!0})),e.on("readable",g.bind(null,i)),i}}).call(this)}).call(this,e("_process"))},{"./end-of-stream":59,_process:237}],57:[function(e,t,i){"use strict";function n(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function r(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function o(e,t){for(var i=0;i0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,i=""+t.data;t=t.next;)i+=e+t.data;return i}},{key:"concat",value:function(e){if(0===this.length)return s.alloc(0);for(var t,i,n,r=s.allocUnsafe(e>>>0),o=this.head,a=0;o;)t=o.data,i=r,n=a,s.prototype.copy.call(t,i,n),a+=o.data.length,o=o.next;return r}},{key:"consume",value:function(e,t){var i;return er.length?r.length:e;if(o===r.length?n+=r:n+=r.slice(0,e),0==(e-=o)){o===r.length?(++i,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=r.slice(o));break}++i}return this.length-=i,n}},{key:"_getBuffer",value:function(e){var t=s.allocUnsafe(e),i=this.head,n=1;for(i.data.copy(t),e-=i.data.length;i=i.next;){var r=i.data,o=e>r.length?r.length:e;if(r.copy(t,t.length-e,0,o),0==(e-=o)){o===r.length?(++n,i.next?this.head=i.next:this.head=this.tail=null):(this.head=i,i.data=r.slice(o));break}++n}return this.length-=n,t}},{key:c,value:function(e,t){return a(this,function(e){for(var t=1;t0,(function(e){l||(l=e),e&&h.forEach(c),o||(h.forEach(c),u(l))}))}));return i.reduce(d)}},{"../../../errors":50,"./end-of-stream":59}],62:[function(e,t,i){"use strict";var n=e("../../../errors").codes.ERR_INVALID_OPT_VALUE;t.exports={getHighWaterMark:function(e,t,i,r){var o=function(e,t,i){return null!=e.highWaterMark?e.highWaterMark:t?e[i]:null}(t,r,i);if(null!=o){if(!isFinite(o)||Math.floor(o)!==o||o<0)throw new n(r?i:"highWaterMark",o);return Math.floor(o)}return e.objectMode?16:16384}}},{"../../../errors":50}],63:[function(e,t,i){t.exports=e("events").EventEmitter},{events:105}],64:[function(e,t,i){(i=t.exports=e("./lib/_stream_readable.js")).Stream=i,i.Readable=i,i.Writable=e("./lib/_stream_writable.js"),i.Duplex=e("./lib/_stream_duplex.js"),i.Transform=e("./lib/_stream_transform.js"),i.PassThrough=e("./lib/_stream_passthrough.js"),i.finished=e("./lib/internal/streams/end-of-stream.js"),i.pipeline=e("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":51,"./lib/_stream_passthrough.js":52,"./lib/_stream_readable.js":53,"./lib/_stream_transform.js":54,"./lib/_stream_writable.js":55,"./lib/internal/streams/end-of-stream.js":59,"./lib/internal/streams/pipeline.js":61}],65:[function(e,t,i){const n=e("base-x");t.exports=n("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")},{"base-x":66}],66:[function(e,t,i){"use strict";t.exports=function(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),i=0;i>>0,d=new Uint8Array(o);e[i];){var l=t[e.charCodeAt(i)];if(255===l)return;for(var u=0,h=o-1;(0!==l||u>>0,d[h]=l%256>>>0,l=l/256>>>0;if(0!==l)throw new Error("Non-zero carry");r=u,i++}for(var f=o-r;f!==o&&0===d[f];)f++;for(var p=new Uint8Array(n+(o-f)),g=n;f!==o;)p[g++]=d[f++];return p}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var i=0,n=0,r=0,o=t.length;r!==o&&0===t[r];)r++,i++;for(var c=(o-r)*d+1>>>0,l=new Uint8Array(c);r!==o;){for(var u=t[r],h=0,f=c-1;(0!==u||h>>0,l[f]=u%s>>>0,u=u/s>>>0;if(0!==u)throw new Error("Non-zero carry");n=h,r++}for(var p=c-n;p!==c&&0===l[p];)p++;for(var g=a.repeat(i);p - * @license MIT - */ -"use strict";var t=e("base64-js"),n=e("ieee754");i.Buffer=s,i.SlowBuffer=function(e){+e!=e&&(e=0);return s.alloc(+e)},i.INSPECT_MAX_BYTES=50;var r=2147483647;function o(e){if(e>r)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=s.prototype,t}function s(e,t,i){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return d(e)}return a(e,t,i)}function a(e,t,i){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var i=0|h(e,t),n=o(i),r=n.write(e,t);r!==i&&(n=n.slice(0,r));return n}(e,t);if(ArrayBuffer.isView(e))return l(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(F(e,ArrayBuffer)||e&&F(e.buffer,ArrayBuffer))return function(e,t,i){if(t<0||e.byteLength=r)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r.toString(16)+" bytes");return 0|e}function h(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||F(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var i=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===i)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":return B(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;case"base64":return N(e).length;default:if(r)return n?-1:B(e).length;t=(""+t).toLowerCase(),r=!0}}function f(e,t,i){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===i||i>this.length)&&(i=this.length),i<=0)return"";if((i>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return k(this,t,i);case"utf8":case"utf-8":return T(this,t,i);case"ascii":return R(this,t,i);case"latin1":case"binary":return M(this,t,i);case"base64":return w(this,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,i);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function p(e,t,i){var n=e[t];e[t]=e[i],e[i]=n}function g(e,t,i,n,r){if(0===e.length)return-1;if("string"==typeof i?(n=i,i=0):i>2147483647?i=2147483647:i<-2147483648&&(i=-2147483648),K(i=+i)&&(i=r?0:e.length-1),i<0&&(i=e.length+i),i>=e.length){if(r)return-1;i=e.length-1}else if(i<0){if(!r)return-1;i=0}if("string"==typeof t&&(t=s.from(t,n)),s.isBuffer(t))return 0===t.length?-1:v(e,t,i,n,r);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,i):Uint8Array.prototype.lastIndexOf.call(e,t,i):v(e,[t],i,n,r);throw new TypeError("val must be string, number or Buffer")}function v(e,t,i,n,r){var o,s=1,a=e.length,c=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,i/=2}function d(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(r){var l=-1;for(o=i;oa&&(i=a-c),o=i;o>=0;o--){for(var u=!0,h=0;hr&&(n=r):n=r;var o=t.length;n>o/2&&(n=o/2);for(var s=0;s>8,r=i%256,o.push(r),o.push(n);return o}(t,e.length-i),e,i,n)}function w(e,i,n){return 0===i&&n===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(i,n))}function T(e,t,i){i=Math.min(e.length,i);for(var n=[],r=t;r239?4:d>223?3:d>191?2:1;if(r+u<=i)switch(u){case 1:d<128&&(l=d);break;case 2:128==(192&(o=e[r+1]))&&(c=(31&d)<<6|63&o)>127&&(l=c);break;case 3:o=e[r+1],s=e[r+2],128==(192&o)&&128==(192&s)&&(c=(15&d)<<12|(63&o)<<6|63&s)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:o=e[r+1],s=e[r+2],a=e[r+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(c=(15&d)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(l=c)}null===l?(l=65533,u=1):l>65535&&(l-=65536,n.push(l>>>10&1023|55296),l=56320|1023&l),n.push(l),r+=u}return function(e){var t=e.length;if(t<=I)return String.fromCharCode.apply(String,e);var i="",n=0;for(;nt&&(e+=" ... "),""},s.prototype.compare=function(e,t,i,n,r){if(F(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===i&&(i=e?e.length:0),void 0===n&&(n=0),void 0===r&&(r=this.length),t<0||i>e.length||n<0||r>this.length)throw new RangeError("out of range index");if(n>=r&&t>=i)return 0;if(n>=r)return-1;if(t>=i)return 1;if(this===e)return 0;for(var o=(r>>>=0)-(n>>>=0),a=(i>>>=0)-(t>>>=0),c=Math.min(o,a),d=this.slice(n,r),l=e.slice(t,i),u=0;u>>=0,isFinite(i)?(i>>>=0,void 0===n&&(n="utf8")):(n=i,i=void 0)}var r=this.length-t;if((void 0===i||i>r)&&(i=r),e.length>0&&(i<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return m(this,e,t,i);case"utf8":case"utf-8":return y(this,e,t,i);case"ascii":return b(this,e,t,i);case"latin1":case"binary":return S(this,e,t,i);case"base64":return _(this,e,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,i);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var I=4096;function R(e,t,i){var n="";i=Math.min(e.length,i);for(var r=t;rn)&&(i=n);for(var r="",o=t;oi)throw new RangeError("Trying to access beyond buffer length")}function A(e,t,i,n,r,o){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>r||te.length)throw new RangeError("Index out of range")}function P(e,t,i,n,r,o){if(i+n>e.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("Index out of range")}function D(e,t,i,r,o){return t=+t,i>>>=0,o||P(e,0,i,4),n.write(e,t,i,r,23,4),i+4}function x(e,t,i,r,o){return t=+t,i>>>=0,o||P(e,0,i,8),n.write(e,t,i,r,52,8),i+8}s.prototype.slice=function(e,t){var i=this.length;(e=~~e)<0?(e+=i)<0&&(e=0):e>i&&(e=i),(t=void 0===t?i:~~t)<0?(t+=i)<0&&(t=0):t>i&&(t=i),t>>=0,t>>>=0,i||O(e,t,this.length);for(var n=this[e],r=1,o=0;++o>>=0,t>>>=0,i||O(e,t,this.length);for(var n=this[e+--t],r=1;t>0&&(r*=256);)n+=this[e+--t]*r;return n},s.prototype.readUInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),this[e]},s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,i){e>>>=0,t>>>=0,i||O(e,t,this.length);for(var n=this[e],r=1,o=0;++o=(r*=128)&&(n-=Math.pow(2,8*t)),n},s.prototype.readIntBE=function(e,t,i){e>>>=0,t>>>=0,i||O(e,t,this.length);for(var n=t,r=1,o=this[e+--n];n>0&&(r*=256);)o+=this[e+--n]*r;return o>=(r*=128)&&(o-=Math.pow(2,8*t)),o},s.prototype.readInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||O(e,2,this.length);var i=this[e]|this[e+1]<<8;return 32768&i?4294901760|i:i},s.prototype.readInt16BE=function(e,t){e>>>=0,t||O(e,2,this.length);var i=this[e+1]|this[e]<<8;return 32768&i?4294901760|i:i},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readFloatLE=function(e,t){return e>>>=0,t||O(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||O(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||O(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||O(e,8,this.length),n.read(this,e,!1,52,8)},s.prototype.writeUIntLE=function(e,t,i,n){(e=+e,t>>>=0,i>>>=0,n)||A(this,e,t,i,Math.pow(2,8*i)-1,0);var r=1,o=0;for(this[t]=255&e;++o>>=0,i>>>=0,n)||A(this,e,t,i,Math.pow(2,8*i)-1,0);var r=i-1,o=1;for(this[t+r]=255&e;--r>=0&&(o*=256);)this[t+r]=e/o&255;return t+i},s.prototype.writeUInt8=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUInt16LE=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUInt16BE=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUInt32LE=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUInt32BE=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeIntLE=function(e,t,i,n){if(e=+e,t>>>=0,!n){var r=Math.pow(2,8*i-1);A(this,e,t,i,r-1,-r)}var o=0,s=1,a=0;for(this[t]=255&e;++o>0)-a&255;return t+i},s.prototype.writeIntBE=function(e,t,i,n){if(e=+e,t>>>=0,!n){var r=Math.pow(2,8*i-1);A(this,e,t,i,r-1,-r)}var o=i-1,s=1,a=0;for(this[t+o]=255&e;--o>=0&&(s*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/s>>0)-a&255;return t+i},s.prototype.writeInt8=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,i){return e=+e,t>>>=0,i||A(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeFloatLE=function(e,t,i){return D(this,e,t,!0,i)},s.prototype.writeFloatBE=function(e,t,i){return D(this,e,t,!1,i)},s.prototype.writeDoubleLE=function(e,t,i){return x(this,e,t,!0,i)},s.prototype.writeDoubleBE=function(e,t,i){return x(this,e,t,!1,i)},s.prototype.copy=function(e,t,i,n){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(i||(i=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--o)e[o+t]=this[o+i];else Uint8Array.prototype.set.call(e,this.subarray(i,n),t);return r},s.prototype.fill=function(e,t,i,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,i=this.length):"string"==typeof i&&(n=i,i=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!s.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===e.length){var r=e.charCodeAt(0);("utf8"===n&&r<128||"latin1"===n)&&(e=r)}}else"number"==typeof e&&(e&=255);if(t<0||this.length>>=0,i=void 0===i?this.length:i>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&i<57344){if(!r){if(i>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(t-=3)>-1&&o.push(239,191,189);continue}r=i;continue}if(i<56320){(t-=3)>-1&&o.push(239,191,189),r=i;continue}i=65536+(r-55296<<10|i-56320)}else r&&(t-=3)>-1&&o.push(239,191,189);if(r=null,i<128){if((t-=1)<0)break;o.push(i)}else if(i<2048){if((t-=2)<0)break;o.push(i>>6|192,63&i|128)}else if(i<65536){if((t-=3)<0)break;o.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return o}function N(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(L,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function j(e,t,i,n){for(var r=0;r=t.length||r>=e.length);++r)t[r+i]=e[r];return r}function F(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function K(e){return e!=e}}).call(this)}).call(this,e("buffer").Buffer)},{"base64-js":17,buffer:68,ieee754:145}],69:[function(e,t,i){"use strict";var n=e("get-intrinsic"),r=e("./"),o=r(n("String.prototype.indexOf"));t.exports=function(e,t){var i=n(e,!!t);return"function"==typeof i&&o(e,".prototype.")>-1?r(i):i}},{"./":70,"get-intrinsic":110}],70:[function(e,t,i){"use strict";var n=e("function-bind"),r=e("get-intrinsic"),o=r("%Function.prototype.apply%"),s=r("%Function.prototype.call%"),a=r("%Reflect.apply%",!0)||n.call(s,o),c=r("%Object.getOwnPropertyDescriptor%",!0),d=r("%Object.defineProperty%",!0),l=r("%Math.max%");if(d)try{d({},"a",{value:1})}catch(e){d=null}t.exports=function(e){var t=a(n,s,arguments);c&&d&&(c(t,"length").configurable&&d(t,"length",{value:1+l(0,e.length-(arguments.length-1))}));return t};var u=function(){return a(n,o,arguments)};d?d(t.exports,"apply",{value:u}):t.exports.apply=u},{"function-bind":109,"get-intrinsic":110}],71:[function(e,t,i){var n=e("safe-buffer").Buffer,r=e("stream").Transform,o=e("string_decoder").StringDecoder;function s(e){r.call(this),this.hashMode="string"==typeof e,this.hashMode?this[e]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}e("inherits")(s,r),s.prototype.update=function(e,t,i){"string"==typeof e&&(e=n.from(e,t));var r=this._update(e);return this.hashMode?this:(i&&(r=this._toString(r,i)),r)},s.prototype.setAutoPadding=function(){},s.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")},s.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")},s.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")},s.prototype._transform=function(e,t,i){var n;try{this.hashMode?this._update(e):this.push(this._update(e))}catch(e){n=e}finally{i(n)}},s.prototype._flush=function(e){var t;try{this.push(this.__final())}catch(e){t=e}e(t)},s.prototype._finalOrDigest=function(e){var t=this.__final()||n.alloc(0);return e&&(t=this._toString(t,e,!0)),t},s.prototype._toString=function(e,t,i){if(this._decoder||(this._decoder=new o(t),this._encoding=t),this._encoding!==t)throw new Error("can't switch encodings");var n=this._decoder.write(e);return i&&(n+=this._decoder.end()),n},t.exports=s},{inherits:146,"safe-buffer":250,stream:264,string_decoder:279}],72:[function(e,t,i){ -/*! - * content-type - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ -"use strict";var n=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,s=/\\([\u000b\u0020-\u00ff])/g,a=/([\\"])/g,c=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function d(e){var t=String(e);if(o.test(t))return t;if(t.length>0&&!r.test(t))throw new TypeError("invalid parameter value");return'"'+t.replace(a,"\\$1")+'"'}function l(e){this.parameters=Object.create(null),this.type=e}i.format=function(e){if(!e||"object"!=typeof e)throw new TypeError("argument obj is required");var t=e.parameters,i=e.type;if(!i||!c.test(i))throw new TypeError("invalid type");var n=i;if(t&&"object"==typeof t)for(var r,s=Object.keys(t).sort(),a=0;ai)?t=("rmd160"===e?new c:d(e)).update(t).digest():t.lengtha?t=e(t):t.length0;n--)t+=this._buffer(e,t),i+=this._flushBuffer(r,i);return t+=this._buffer(e,t),r},r.prototype.final=function(e){var t,i;return e&&(t=this.update(e)),i="encrypt"===this.type?this._finalEncrypt():this._finalDecrypt(),t?t.concat(i):i},r.prototype._pad=function(e,t){if(0===t)return!1;for(;t>>1];i=o.r28shl(i,a),r=o.r28shl(r,a),o.pc2(i,r,e.keys,s)}},c.prototype._update=function(e,t,i,n){var r=this._desState,s=o.readUInt32BE(e,t),a=o.readUInt32BE(e,t+4);o.ip(s,a,r.tmp,0),s=r.tmp[0],a=r.tmp[1],"encrypt"===this.type?this._encrypt(r,s,a,r.tmp,0):this._decrypt(r,s,a,r.tmp,0),s=r.tmp[0],a=r.tmp[1],o.writeUInt32BE(i,s,n),o.writeUInt32BE(i,a,n+4)},c.prototype._pad=function(e,t){for(var i=e.length-t,n=t;n>>0,s=h}o.rip(a,s,n,r)},c.prototype._decrypt=function(e,t,i,n,r){for(var s=i,a=t,c=e.keys.length-2;c>=0;c-=2){var d=e.keys[c],l=e.keys[c+1];o.expand(s,e.tmp,0),d^=e.tmp[0],l^=e.tmp[1];var u=o.substitute(d,l),h=s;s=(a^o.permute(u))>>>0,a=h}o.rip(s,a,n,r)}},{"./cipher":81,"./utils":84,inherits:146,"minimalistic-assert":223}],83:[function(e,t,i){"use strict";var n=e("minimalistic-assert"),r=e("inherits"),o=e("./cipher"),s=e("./des");function a(e,t){n.equal(t.length,24,"Invalid key length");var i=t.slice(0,8),r=t.slice(8,16),o=t.slice(16,24);this.ciphers="encrypt"===e?[s.create({type:"encrypt",key:i}),s.create({type:"decrypt",key:r}),s.create({type:"encrypt",key:o})]:[s.create({type:"decrypt",key:o}),s.create({type:"encrypt",key:r}),s.create({type:"decrypt",key:i})]}function c(e){o.call(this,e);var t=new a(this.type,this.options.key);this._edeState=t}r(c,o),t.exports=c,c.create=function(e){return new c(e)},c.prototype._update=function(e,t,i,n){var r=this._edeState;r.ciphers[0]._update(e,t,i,n),r.ciphers[1]._update(i,n,i,n),r.ciphers[2]._update(i,n,i,n)},c.prototype._pad=s.prototype._pad,c.prototype._unpad=s.prototype._unpad},{"./cipher":81,"./des":82,inherits:146,"minimalistic-assert":223}],84:[function(e,t,i){"use strict";i.readUInt32BE=function(e,t){return(e[0+t]<<24|e[1+t]<<16|e[2+t]<<8|e[3+t])>>>0},i.writeUInt32BE=function(e,t,i){e[0+i]=t>>>24,e[1+i]=t>>>16&255,e[2+i]=t>>>8&255,e[3+i]=255&t},i.ip=function(e,t,i,n){for(var r=0,o=0,s=6;s>=0;s-=2){for(var a=0;a<=24;a+=8)r<<=1,r|=t>>>a+s&1;for(a=0;a<=24;a+=8)r<<=1,r|=e>>>a+s&1}for(s=6;s>=0;s-=2){for(a=1;a<=25;a+=8)o<<=1,o|=t>>>a+s&1;for(a=1;a<=25;a+=8)o<<=1,o|=e>>>a+s&1}i[n+0]=r>>>0,i[n+1]=o>>>0},i.rip=function(e,t,i,n){for(var r=0,o=0,s=0;s<4;s++)for(var a=24;a>=0;a-=8)r<<=1,r|=t>>>a+s&1,r<<=1,r|=e>>>a+s&1;for(s=4;s<8;s++)for(a=24;a>=0;a-=8)o<<=1,o|=t>>>a+s&1,o<<=1,o|=e>>>a+s&1;i[n+0]=r>>>0,i[n+1]=o>>>0},i.pc1=function(e,t,i,n){for(var r=0,o=0,s=7;s>=5;s--){for(var a=0;a<=24;a+=8)r<<=1,r|=t>>a+s&1;for(a=0;a<=24;a+=8)r<<=1,r|=e>>a+s&1}for(a=0;a<=24;a+=8)r<<=1,r|=t>>a+s&1;for(s=1;s<=3;s++){for(a=0;a<=24;a+=8)o<<=1,o|=t>>a+s&1;for(a=0;a<=24;a+=8)o<<=1,o|=e>>a+s&1}for(a=0;a<=24;a+=8)o<<=1,o|=e>>a+s&1;i[n+0]=r>>>0,i[n+1]=o>>>0},i.r28shl=function(e,t){return e<>>28-t};var n=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];i.pc2=function(e,t,i,r){for(var o=0,s=0,a=n.length>>>1,c=0;c>>n[c]&1;for(c=a;c>>n[c]&1;i[r+0]=o>>>0,i[r+1]=s>>>0},i.expand=function(e,t,i){var n=0,r=0;n=(1&e)<<5|e>>>27;for(var o=23;o>=15;o-=4)n<<=6,n|=e>>>o&63;for(o=11;o>=3;o-=4)r|=e>>>o&63,r<<=6;r|=(31&e)<<1|e>>>31,t[i+0]=n>>>0,t[i+1]=r>>>0};var r=[14,0,4,15,13,7,1,4,2,14,15,2,11,13,8,1,3,10,10,6,6,12,12,11,5,9,9,5,0,3,7,8,4,15,1,12,14,8,8,2,13,4,6,9,2,1,11,7,15,5,12,11,9,3,7,14,3,10,10,0,5,6,0,13,15,3,1,13,8,4,14,7,6,15,11,2,3,8,4,14,9,12,7,0,2,1,13,10,12,6,0,9,5,11,10,5,0,13,14,8,7,10,11,1,10,3,4,15,13,4,1,2,5,11,8,6,12,7,6,12,9,0,3,5,2,14,15,9,10,13,0,7,9,0,14,9,6,3,3,4,15,6,5,10,1,2,13,8,12,5,7,14,11,12,4,11,2,15,8,1,13,1,6,10,4,13,9,0,8,6,15,9,3,8,0,7,11,4,1,15,2,14,12,3,5,11,10,5,14,2,7,12,7,13,13,8,14,11,3,5,0,6,6,15,9,0,10,3,1,4,2,7,8,2,5,12,11,1,12,10,4,14,15,9,10,3,6,15,9,0,0,6,12,10,11,1,7,13,13,8,15,9,1,4,3,5,14,11,5,12,2,7,8,2,4,14,2,14,12,11,4,2,1,12,7,4,10,7,11,13,6,1,8,5,5,0,3,15,15,10,13,3,0,9,14,8,9,6,4,11,2,8,1,12,11,7,10,1,13,14,7,2,8,13,15,6,9,15,12,0,5,9,6,10,3,4,0,5,14,3,12,10,1,15,10,4,15,2,9,7,2,12,6,9,8,5,0,6,13,1,3,13,4,14,14,0,7,11,5,3,11,8,9,4,14,3,15,2,5,12,2,9,8,5,12,15,3,10,7,11,0,14,4,1,10,7,1,6,13,0,11,8,6,13,4,13,11,0,2,11,14,7,15,4,0,9,8,1,13,10,3,14,12,3,9,5,7,12,5,2,10,15,6,8,1,6,1,6,4,11,11,13,13,8,12,1,3,4,7,10,14,7,10,9,15,5,6,0,8,15,0,14,5,2,9,3,2,12,13,1,2,15,8,13,4,8,6,10,15,3,11,7,1,4,10,12,9,5,3,6,14,11,5,0,0,14,12,9,7,2,7,2,11,1,4,14,1,7,9,4,12,10,14,8,2,13,0,15,6,12,10,9,13,0,15,3,3,5,5,6,8,11];i.substitute=function(e,t){for(var i=0,n=0;n<4;n++){i<<=4,i|=r[64*n+(e>>>18-6*n&63)]}for(n=0;n<4;n++){i<<=4,i|=r[256+64*n+(t>>>18-6*n&63)]}return i>>>0};var o=[16,25,12,11,3,20,4,15,31,17,9,6,27,14,1,22,30,24,8,18,0,5,29,23,13,19,2,26,10,21,28,7];i.permute=function(e){for(var t=0,i=0;i>>o[i]&1;return t>>>0},i.padSplit=function(e,t,i){for(var n=e.toString(2);n.lengthe;)i.ishrn(1);if(i.isEven()&&i.iadd(a),i.testn(1)||i.iadd(c),t.cmp(c)){if(!t.cmp(d))for(;i.mod(l).cmp(u);)i.iadd(f)}else for(;i.mod(o).cmp(h);)i.iadd(f);if(v(p=i.shrn(1))&&v(i)&&m(p)&&m(i)&&s.test(p)&&s.test(i))return i}}},{"bn.js":18,"miller-rabin":222,randombytes:244}],88:[function(e,t,i){t.exports={modp1:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},modp2:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},modp5:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},modp14:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},modp15:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},modp16:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},modp17:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},modp18:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}},{}],89:[function(e,t,i){"use strict";var n=i;n.version=e("../package.json").version,n.utils=e("./elliptic/utils"),n.rand=e("brorand"),n.curve=e("./elliptic/curve"),n.curves=e("./elliptic/curves"),n.ec=e("./elliptic/ec"),n.eddsa=e("./elliptic/eddsa")},{"../package.json":104,"./elliptic/curve":92,"./elliptic/curves":95,"./elliptic/ec":96,"./elliptic/eddsa":99,"./elliptic/utils":103,brorand:19}],90:[function(e,t,i){"use strict";var n=e("bn.js"),r=e("../utils"),o=r.getNAF,s=r.getJSF,a=r.assert;function c(e,t){this.type=e,this.p=new n(t.p,16),this.red=t.prime?n.red(t.prime):n.mont(this.p),this.zero=new n(0).toRed(this.red),this.one=new n(1).toRed(this.red),this.two=new n(2).toRed(this.red),this.n=t.n&&new n(t.n,16),this.g=t.g&&this.pointFromJSON(t.g,t.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n?this.n.bitLength():0;var i=this.n&&this.p.div(this.n);!i||i.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}function d(e,t){this.curve=e,this.type=t,this.precomputed=null}t.exports=c,c.prototype.point=function(){throw new Error("Not implemented")},c.prototype.validate=function(){throw new Error("Not implemented")},c.prototype._fixedNafMul=function(e,t){a(e.precomputed);var i=e._getDoubles(),n=o(t,1,this._bitLength),r=(1<=s;l--)c=(c<<1)+n[l];d.push(c)}for(var u=this.jpoint(null,null,null),h=this.jpoint(null,null,null),f=r;f>0;f--){for(s=0;s=0;d--){for(var l=0;d>=0&&0===s[d];d--)l++;if(d>=0&&l++,c=c.dblp(l),d<0)break;var u=s[d];a(0!==u),c="affine"===e.type?u>0?c.mixedAdd(r[u-1>>1]):c.mixedAdd(r[-u-1>>1].neg()):u>0?c.add(r[u-1>>1]):c.add(r[-u-1>>1].neg())}return"affine"===e.type?c.toP():c},c.prototype._wnafMulAdd=function(e,t,i,n,r){var a,c,d,l=this._wnafT1,u=this._wnafT2,h=this._wnafT3,f=0;for(a=0;a=1;a-=2){var g=a-1,v=a;if(1===l[g]&&1===l[v]){var m=[t[g],null,null,t[v]];0===t[g].y.cmp(t[v].y)?(m[1]=t[g].add(t[v]),m[2]=t[g].toJ().mixedAdd(t[v].neg())):0===t[g].y.cmp(t[v].y.redNeg())?(m[1]=t[g].toJ().mixedAdd(t[v]),m[2]=t[g].add(t[v].neg())):(m[1]=t[g].toJ().mixedAdd(t[v]),m[2]=t[g].toJ().mixedAdd(t[v].neg()));var y=[-3,-1,-5,-7,0,7,5,1,3],b=s(i[g],i[v]);for(f=Math.max(b[0].length,f),h[g]=new Array(f),h[v]=new Array(f),c=0;c=0;a--){for(var T=0;a>=0;){var I=!0;for(c=0;c=0&&T++,E=E.dblp(T),a<0)break;for(c=0;c0?d=u[c][R-1>>1]:R<0&&(d=u[c][-R-1>>1].neg()),E="affine"===d.type?E.mixedAdd(d):E.add(d))}}for(a=0;a=Math.ceil((e.bitLength()+1)/t.step)},d.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var i=[this],n=this,r=0;r":""},d.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},d.prototype._extDbl=function(){var e=this.x.redSqr(),t=this.y.redSqr(),i=this.z.redSqr();i=i.redIAdd(i);var n=this.curve._mulA(e),r=this.x.redAdd(this.y).redSqr().redISub(e).redISub(t),o=n.redAdd(t),s=o.redSub(i),a=n.redSub(t),c=r.redMul(s),d=o.redMul(a),l=r.redMul(a),u=s.redMul(o);return this.curve.point(c,d,u,l)},d.prototype._projDbl=function(){var e,t,i,n,r,o,s=this.x.redAdd(this.y).redSqr(),a=this.x.redSqr(),c=this.y.redSqr();if(this.curve.twisted){var d=(n=this.curve._mulA(a)).redAdd(c);this.zOne?(e=s.redSub(a).redSub(c).redMul(d.redSub(this.curve.two)),t=d.redMul(n.redSub(c)),i=d.redSqr().redSub(d).redSub(d)):(r=this.z.redSqr(),o=d.redSub(r).redISub(r),e=s.redSub(a).redISub(c).redMul(o),t=d.redMul(n.redSub(c)),i=d.redMul(o))}else n=a.redAdd(c),r=this.curve._mulC(this.z).redSqr(),o=n.redSub(r).redSub(r),e=this.curve._mulC(s.redISub(n)).redMul(o),t=this.curve._mulC(n).redMul(a.redISub(c)),i=n.redMul(o);return this.curve.point(e,t,i)},d.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},d.prototype._extAdd=function(e){var t=this.y.redSub(this.x).redMul(e.y.redSub(e.x)),i=this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)),n=this.t.redMul(this.curve.dd).redMul(e.t),r=this.z.redMul(e.z.redAdd(e.z)),o=i.redSub(t),s=r.redSub(n),a=r.redAdd(n),c=i.redAdd(t),d=o.redMul(s),l=a.redMul(c),u=o.redMul(c),h=s.redMul(a);return this.curve.point(d,l,h,u)},d.prototype._projAdd=function(e){var t,i,n=this.z.redMul(e.z),r=n.redSqr(),o=this.x.redMul(e.x),s=this.y.redMul(e.y),a=this.curve.d.redMul(o).redMul(s),c=r.redSub(a),d=r.redAdd(a),l=this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(o).redISub(s),u=n.redMul(c).redMul(l);return this.curve.twisted?(t=n.redMul(d).redMul(s.redSub(this.curve._mulA(o))),i=c.redMul(d)):(t=n.redMul(d).redMul(s.redSub(o)),i=this.curve._mulC(c).redMul(d)),this.curve.point(u,t,i)},d.prototype.add=function(e){return this.isInfinity()?e:e.isInfinity()?this:this.curve.extended?this._extAdd(e):this._projAdd(e)},d.prototype.mul=function(e){return this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve._wnafMul(this,e)},d.prototype.mulAdd=function(e,t,i){return this.curve._wnafMulAdd(1,[this,t],[e,i],2,!1)},d.prototype.jmulAdd=function(e,t,i){return this.curve._wnafMulAdd(1,[this,t],[e,i],2,!0)},d.prototype.normalize=function(){if(this.zOne)return this;var e=this.z.redInvm();return this.x=this.x.redMul(e),this.y=this.y.redMul(e),this.t&&(this.t=this.t.redMul(e)),this.z=this.curve.one,this.zOne=!0,this},d.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},d.prototype.getX=function(){return this.normalize(),this.x.fromRed()},d.prototype.getY=function(){return this.normalize(),this.y.fromRed()},d.prototype.eq=function(e){return this===e||0===this.getX().cmp(e.getX())&&0===this.getY().cmp(e.getY())},d.prototype.eqXToP=function(e){var t=e.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(t))return!0;for(var i=e.clone(),n=this.curve.redN.redMul(this.z);;){if(i.iadd(this.curve.n),i.cmp(this.curve.p)>=0)return!1;if(t.redIAdd(n),0===this.x.cmp(t))return!0}},d.prototype.toP=d.prototype.normalize,d.prototype.mixedAdd=d.prototype.add},{"../utils":103,"./base":90,"bn.js":18,inherits:146}],92:[function(e,t,i){"use strict";var n=i;n.base=e("./base"),n.short=e("./short"),n.mont=e("./mont"),n.edwards=e("./edwards")},{"./base":90,"./edwards":91,"./mont":93,"./short":94}],93:[function(e,t,i){"use strict";var n=e("bn.js"),r=e("inherits"),o=e("./base"),s=e("../utils");function a(e){o.call(this,"mont",e),this.a=new n(e.a,16).toRed(this.red),this.b=new n(e.b,16).toRed(this.red),this.i4=new n(4).toRed(this.red).redInvm(),this.two=new n(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}function c(e,t,i){o.BasePoint.call(this,e,"projective"),null===t&&null===i?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new n(t,16),this.z=new n(i,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}r(a,o),t.exports=a,a.prototype.validate=function(e){var t=e.normalize().x,i=t.redSqr(),n=i.redMul(t).redAdd(i.redMul(this.a)).redAdd(t);return 0===n.redSqrt().redSqr().cmp(n)},r(c,o.BasePoint),a.prototype.decodePoint=function(e,t){return this.point(s.toArray(e,t),1)},a.prototype.point=function(e,t){return new c(this,e,t)},a.prototype.pointFromJSON=function(e){return c.fromJSON(this,e)},c.prototype.precompute=function(){},c.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},c.fromJSON=function(e,t){return new c(e,t[0],t[1]||e.one)},c.prototype.inspect=function(){return this.isInfinity()?"":""},c.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},c.prototype.dbl=function(){var e=this.x.redAdd(this.z).redSqr(),t=this.x.redSub(this.z).redSqr(),i=e.redSub(t),n=e.redMul(t),r=i.redMul(t.redAdd(this.curve.a24.redMul(i)));return this.curve.point(n,r)},c.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.diffAdd=function(e,t){var i=this.x.redAdd(this.z),n=this.x.redSub(this.z),r=e.x.redAdd(e.z),o=e.x.redSub(e.z).redMul(i),s=r.redMul(n),a=t.z.redMul(o.redAdd(s).redSqr()),c=t.x.redMul(o.redISub(s).redSqr());return this.curve.point(a,c)},c.prototype.mul=function(e){for(var t=e.clone(),i=this,n=this.curve.point(null,null),r=[];0!==t.cmpn(0);t.iushrn(1))r.push(t.andln(1));for(var o=r.length-1;o>=0;o--)0===r[o]?(i=i.diffAdd(n,this),n=n.dbl()):(n=i.diffAdd(n,this),i=i.dbl());return n},c.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},c.prototype.eq=function(e){return 0===this.getX().cmp(e.getX())},c.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},c.prototype.getX=function(){return this.normalize(),this.x.fromRed()}},{"../utils":103,"./base":90,"bn.js":18,inherits:146}],94:[function(e,t,i){"use strict";var n=e("../utils"),r=e("bn.js"),o=e("inherits"),s=e("./base"),a=n.assert;function c(e){s.call(this,"short",e),this.a=new r(e.a,16).toRed(this.red),this.b=new r(e.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(e),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}function d(e,t,i,n){s.BasePoint.call(this,e,"affine"),null===t&&null===i?(this.x=null,this.y=null,this.inf=!0):(this.x=new r(t,16),this.y=new r(i,16),n&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}function l(e,t,i,n){s.BasePoint.call(this,e,"jacobian"),null===t&&null===i&&null===n?(this.x=this.curve.one,this.y=this.curve.one,this.z=new r(0)):(this.x=new r(t,16),this.y=new r(i,16),this.z=new r(n,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}o(c,s),t.exports=c,c.prototype._getEndomorphism=function(e){if(this.zeroA&&this.g&&this.n&&1===this.p.modn(3)){var t,i;if(e.beta)t=new r(e.beta,16).toRed(this.red);else{var n=this._getEndoRoots(this.p);t=(t=n[0].cmp(n[1])<0?n[0]:n[1]).toRed(this.red)}if(e.lambda)i=new r(e.lambda,16);else{var o=this._getEndoRoots(this.n);0===this.g.mul(o[0]).x.cmp(this.g.x.redMul(t))?i=o[0]:(i=o[1],a(0===this.g.mul(i).x.cmp(this.g.x.redMul(t))))}return{beta:t,lambda:i,basis:e.basis?e.basis.map((function(e){return{a:new r(e.a,16),b:new r(e.b,16)}})):this._getEndoBasis(i)}}},c.prototype._getEndoRoots=function(e){var t=e===this.p?this.red:r.mont(e),i=new r(2).toRed(t).redInvm(),n=i.redNeg(),o=new r(3).toRed(t).redNeg().redSqrt().redMul(i);return[n.redAdd(o).fromRed(),n.redSub(o).fromRed()]},c.prototype._getEndoBasis=function(e){for(var t,i,n,o,s,a,c,d,l,u=this.n.ushrn(Math.floor(this.n.bitLength()/2)),h=e,f=this.n.clone(),p=new r(1),g=new r(0),v=new r(0),m=new r(1),y=0;0!==h.cmpn(0);){var b=f.div(h);d=f.sub(b.mul(h)),l=v.sub(b.mul(p));var S=m.sub(b.mul(g));if(!n&&d.cmp(u)<0)t=c.neg(),i=p,n=d.neg(),o=l;else if(n&&2==++y)break;c=d,f=h,h=d,v=p,p=l,m=g,g=S}s=d.neg(),a=l;var _=n.sqr().add(o.sqr());return s.sqr().add(a.sqr()).cmp(_)>=0&&(s=t,a=i),n.negative&&(n=n.neg(),o=o.neg()),s.negative&&(s=s.neg(),a=a.neg()),[{a:n,b:o},{a:s,b:a}]},c.prototype._endoSplit=function(e){var t=this.endo.basis,i=t[0],n=t[1],r=n.b.mul(e).divRound(this.n),o=i.b.neg().mul(e).divRound(this.n),s=r.mul(i.a),a=o.mul(n.a),c=r.mul(i.b),d=o.mul(n.b);return{k1:e.sub(s).sub(a),k2:c.add(d).neg()}},c.prototype.pointFromX=function(e,t){(e=new r(e,16)).red||(e=e.toRed(this.red));var i=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),n=i.redSqrt();if(0!==n.redSqr().redSub(i).cmp(this.zero))throw new Error("invalid point");var o=n.fromRed().isOdd();return(t&&!o||!t&&o)&&(n=n.redNeg()),this.point(e,n)},c.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,i=e.y,n=this.a.redMul(t),r=t.redSqr().redMul(t).redIAdd(n).redIAdd(this.b);return 0===i.redSqr().redISub(r).cmpn(0)},c.prototype._endoWnafMulAdd=function(e,t,i){for(var n=this._endoWnafT1,r=this._endoWnafT2,o=0;o":""},d.prototype.isInfinity=function(){return this.inf},d.prototype.add=function(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return this.curve.point(null,null);if(0===this.x.cmp(e.x))return this.curve.point(null,null);var t=this.y.redSub(e.y);0!==t.cmpn(0)&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var i=t.redSqr().redISub(this.x).redISub(e.x),n=t.redMul(this.x.redSub(i)).redISub(this.y);return this.curve.point(i,n)},d.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(0===e.cmpn(0))return this.curve.point(null,null);var t=this.curve.a,i=this.x.redSqr(),n=e.redInvm(),r=i.redAdd(i).redIAdd(i).redIAdd(t).redMul(n),o=r.redSqr().redISub(this.x.redAdd(this.x)),s=r.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,s)},d.prototype.getX=function(){return this.x.fromRed()},d.prototype.getY=function(){return this.y.fromRed()},d.prototype.mul=function(e){return e=new r(e,16),this.isInfinity()?this:this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve.endo?this.curve._endoWnafMulAdd([this],[e]):this.curve._wnafMul(this,e)},d.prototype.mulAdd=function(e,t,i){var n=[this,t],r=[e,i];return this.curve.endo?this.curve._endoWnafMulAdd(n,r):this.curve._wnafMulAdd(1,n,r,2)},d.prototype.jmulAdd=function(e,t,i){var n=[this,t],r=[e,i];return this.curve.endo?this.curve._endoWnafMulAdd(n,r,!0):this.curve._wnafMulAdd(1,n,r,2,!0)},d.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||0===this.x.cmp(e.x)&&0===this.y.cmp(e.y))},d.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var i=this.precomputed,n=function(e){return e.neg()};t.precomputed={naf:i.naf&&{wnd:i.naf.wnd,points:i.naf.points.map(n)},doubles:i.doubles&&{step:i.doubles.step,points:i.doubles.points.map(n)}}}return t},d.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},o(l,s.BasePoint),c.prototype.jpoint=function(e,t,i){return new l(this,e,t,i)},l.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),i=this.x.redMul(t),n=this.y.redMul(t).redMul(e);return this.curve.point(i,n)},l.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},l.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),i=this.z.redSqr(),n=this.x.redMul(t),r=e.x.redMul(i),o=this.y.redMul(t.redMul(e.z)),s=e.y.redMul(i.redMul(this.z)),a=n.redSub(r),c=o.redSub(s);if(0===a.cmpn(0))return 0!==c.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var d=a.redSqr(),l=d.redMul(a),u=n.redMul(d),h=c.redSqr().redIAdd(l).redISub(u).redISub(u),f=c.redMul(u.redISub(h)).redISub(o.redMul(l)),p=this.z.redMul(e.z).redMul(a);return this.curve.jpoint(h,f,p)},l.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),i=this.x,n=e.x.redMul(t),r=this.y,o=e.y.redMul(t).redMul(this.z),s=i.redSub(n),a=r.redSub(o);if(0===s.cmpn(0))return 0!==a.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var c=s.redSqr(),d=c.redMul(s),l=i.redMul(c),u=a.redSqr().redIAdd(d).redISub(l).redISub(l),h=a.redMul(l.redISub(u)).redISub(r.redMul(d)),f=this.z.redMul(s);return this.curve.jpoint(u,h,f)},l.prototype.dblp=function(e){if(0===e)return this;if(this.isInfinity())return this;if(!e)return this.dbl();var t;if(this.curve.zeroA||this.curve.threeA){var i=this;for(t=0;t=0)return!1;if(i.redIAdd(r),0===this.x.cmp(i))return!0}},l.prototype.inspect=function(){return this.isInfinity()?"":""},l.prototype.isInfinity=function(){return 0===this.z.cmpn(0)}},{"../utils":103,"./base":90,"bn.js":18,inherits:146}],95:[function(e,t,i){"use strict";var n,r=i,o=e("hash.js"),s=e("./curve"),a=e("./utils").assert;function c(e){"short"===e.type?this.curve=new s.short(e):"edwards"===e.type?this.curve=new s.edwards(e):this.curve=new s.mont(e),this.g=this.curve.g,this.n=this.curve.n,this.hash=e.hash,a(this.g.validate(),"Invalid curve"),a(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}function d(e,t){Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get:function(){var i=new c(t);return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,value:i}),i}})}r.PresetCurve=c,d("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:o.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),d("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:o.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),d("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:o.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),d("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:o.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),d("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:o.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),d("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:o.sha256,gRed:!1,g:["9"]}),d("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:o.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});try{n=e("./precomputed/secp256k1")}catch(e){n=void 0}d("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:o.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",n]})},{"./curve":92,"./precomputed/secp256k1":102,"./utils":103,"hash.js":132}],96:[function(e,t,i){"use strict";var n=e("bn.js"),r=e("hmac-drbg"),o=e("../utils"),s=e("../curves"),a=e("brorand"),c=o.assert,d=e("./key"),l=e("./signature");function u(e){if(!(this instanceof u))return new u(e);"string"==typeof e&&(c(Object.prototype.hasOwnProperty.call(s,e),"Unknown curve "+e),e=s[e]),e instanceof s.PresetCurve&&(e={curve:e}),this.curve=e.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=e.curve.g,this.g.precompute(e.curve.n.bitLength()+1),this.hash=e.hash||e.curve.hash}t.exports=u,u.prototype.keyPair=function(e){return new d(this,e)},u.prototype.keyFromPrivate=function(e,t){return d.fromPrivate(this,e,t)},u.prototype.keyFromPublic=function(e,t){return d.fromPublic(this,e,t)},u.prototype.genKeyPair=function(e){e||(e={});for(var t=new r({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||a(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()}),i=this.n.byteLength(),o=this.n.sub(new n(2));;){var s=new n(t.generate(i));if(!(s.cmp(o)>0))return s.iaddn(1),this.keyFromPrivate(s)}},u.prototype._truncateToN=function(e,t){var i=8*e.byteLength()-this.n.bitLength();return i>0&&(e=e.ushrn(i)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},u.prototype.sign=function(e,t,i,o){"object"==typeof i&&(o=i,i=null),o||(o={}),t=this.keyFromPrivate(t,i),e=this._truncateToN(new n(e,16));for(var s=this.n.byteLength(),a=t.getPrivate().toArray("be",s),c=e.toArray("be",s),d=new r({hash:this.hash,entropy:a,nonce:c,pers:o.pers,persEnc:o.persEnc||"utf8"}),u=this.n.sub(new n(1)),h=0;;h++){var f=o.k?o.k(h):new n(d.generate(this.n.byteLength()));if(!((f=this._truncateToN(f,!0)).cmpn(1)<=0||f.cmp(u)>=0)){var p=this.g.mul(f);if(!p.isInfinity()){var g=p.getX(),v=g.umod(this.n);if(0!==v.cmpn(0)){var m=f.invm(this.n).mul(v.mul(t.getPrivate()).iadd(e));if(0!==(m=m.umod(this.n)).cmpn(0)){var y=(p.getY().isOdd()?1:0)|(0!==g.cmp(v)?2:0);return o.canonical&&m.cmp(this.nh)>0&&(m=this.n.sub(m),y^=1),new l({r:v,s:m,recoveryParam:y})}}}}}},u.prototype.verify=function(e,t,i,r){e=this._truncateToN(new n(e,16)),i=this.keyFromPublic(i,r);var o=(t=new l(t,"hex")).r,s=t.s;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;if(s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var a,c=s.invm(this.n),d=c.mul(e).umod(this.n),u=c.mul(o).umod(this.n);return this.curve._maxwellTrick?!(a=this.g.jmulAdd(d,i.getPublic(),u)).isInfinity()&&a.eqXToP(o):!(a=this.g.mulAdd(d,i.getPublic(),u)).isInfinity()&&0===a.getX().umod(this.n).cmp(o)},u.prototype.recoverPubKey=function(e,t,i,r){c((3&i)===i,"The recovery param is more than two bits"),t=new l(t,r);var o=this.n,s=new n(e),a=t.r,d=t.s,u=1&i,h=i>>1;if(a.cmp(this.curve.p.umod(this.curve.n))>=0&&h)throw new Error("Unable to find sencond key candinate");a=h?this.curve.pointFromX(a.add(this.curve.n),u):this.curve.pointFromX(a,u);var f=t.r.invm(o),p=o.sub(s).mul(f).umod(o),g=d.mul(f).umod(o);return this.g.mulAdd(p,a,g)},u.prototype.getKeyRecoveryParam=function(e,t,i,n){if(null!==(t=new l(t,n)).recoveryParam)return t.recoveryParam;for(var r=0;r<4;r++){var o;try{o=this.recoverPubKey(e,t,r)}catch(e){continue}if(o.eq(i))return r}throw new Error("Unable to find valid recovery factor")}},{"../curves":95,"../utils":103,"./key":97,"./signature":98,"bn.js":18,brorand:19,"hmac-drbg":144}],97:[function(e,t,i){"use strict";var n=e("bn.js"),r=e("../utils").assert;function o(e,t){this.ec=e,this.priv=null,this.pub=null,t.priv&&this._importPrivate(t.priv,t.privEnc),t.pub&&this._importPublic(t.pub,t.pubEnc)}t.exports=o,o.fromPublic=function(e,t,i){return t instanceof o?t:new o(e,{pub:t,pubEnc:i})},o.fromPrivate=function(e,t,i){return t instanceof o?t:new o(e,{priv:t,privEnc:i})},o.prototype.validate=function(){var e=this.getPublic();return e.isInfinity()?{result:!1,reason:"Invalid public key"}:e.validate()?e.mul(this.ec.curve.n).isInfinity()?{result:!0,reason:null}:{result:!1,reason:"Public key * N != O"}:{result:!1,reason:"Public key is not a point"}},o.prototype.getPublic=function(e,t){return"string"==typeof e&&(t=e,e=null),this.pub||(this.pub=this.ec.g.mul(this.priv)),t?this.pub.encode(t,e):this.pub},o.prototype.getPrivate=function(e){return"hex"===e?this.priv.toString(16,2):this.priv},o.prototype._importPrivate=function(e,t){this.priv=new n(e,t||16),this.priv=this.priv.umod(this.ec.curve.n)},o.prototype._importPublic=function(e,t){if(e.x||e.y)return"mont"===this.ec.curve.type?r(e.x,"Need x coordinate"):"short"!==this.ec.curve.type&&"edwards"!==this.ec.curve.type||r(e.x&&e.y,"Need both x and y coordinate"),void(this.pub=this.ec.curve.point(e.x,e.y));this.pub=this.ec.curve.decodePoint(e,t)},o.prototype.derive=function(e){return e.validate()||r(e.validate(),"public point not validated"),e.mul(this.priv).getX()},o.prototype.sign=function(e,t,i){return this.ec.sign(e,this,t,i)},o.prototype.verify=function(e,t){return this.ec.verify(e,t,this)},o.prototype.inspect=function(){return""}},{"../utils":103,"bn.js":18}],98:[function(e,t,i){"use strict";var n=e("bn.js"),r=e("../utils"),o=r.assert;function s(e,t){if(e instanceof s)return e;this._importDER(e,t)||(o(e.r&&e.s,"Signature without r or s"),this.r=new n(e.r,16),this.s=new n(e.s,16),void 0===e.recoveryParam?this.recoveryParam=null:this.recoveryParam=e.recoveryParam)}function a(){this.place=0}function c(e,t){var i=e[t.place++];if(!(128&i))return i;var n=15&i;if(0===n||n>4)return!1;for(var r=0,o=0,s=t.place;o>>=0;return!(r<=127)&&(t.place=s,r)}function d(e){for(var t=0,i=e.length-1;!e[t]&&!(128&e[t+1])&&t>>3);for(e.push(128|i);--i;)e.push(t>>>(i<<3)&255);e.push(t)}}t.exports=s,s.prototype._importDER=function(e,t){e=r.toArray(e,t);var i=new a;if(48!==e[i.place++])return!1;var o=c(e,i);if(!1===o)return!1;if(o+i.place!==e.length)return!1;if(2!==e[i.place++])return!1;var s=c(e,i);if(!1===s)return!1;var d=e.slice(i.place,s+i.place);if(i.place+=s,2!==e[i.place++])return!1;var l=c(e,i);if(!1===l)return!1;if(e.length!==l+i.place)return!1;var u=e.slice(i.place,l+i.place);if(0===d[0]){if(!(128&d[1]))return!1;d=d.slice(1)}if(0===u[0]){if(!(128&u[1]))return!1;u=u.slice(1)}return this.r=new n(d),this.s=new n(u),this.recoveryParam=null,!0},s.prototype.toDER=function(e){var t=this.r.toArray(),i=this.s.toArray();for(128&t[0]&&(t=[0].concat(t)),128&i[0]&&(i=[0].concat(i)),t=d(t),i=d(i);!(i[0]||128&i[1]);)i=i.slice(1);var n=[2];l(n,t.length),(n=n.concat(t)).push(2),l(n,i.length);var o=n.concat(i),s=[48];return l(s,o.length),s=s.concat(o),r.encode(s,e)}},{"../utils":103,"bn.js":18}],99:[function(e,t,i){"use strict";var n=e("hash.js"),r=e("../curves"),o=e("../utils"),s=o.assert,a=o.parseBytes,c=e("./key"),d=e("./signature");function l(e){if(s("ed25519"===e,"only tested with ed25519 so far"),!(this instanceof l))return new l(e);e=r[e].curve,this.curve=e,this.g=e.g,this.g.precompute(e.n.bitLength()+1),this.pointClass=e.point().constructor,this.encodingLength=Math.ceil(e.n.bitLength()/8),this.hash=n.sha512}t.exports=l,l.prototype.sign=function(e,t){e=a(e);var i=this.keyFromSecret(t),n=this.hashInt(i.messagePrefix(),e),r=this.g.mul(n),o=this.encodePoint(r),s=this.hashInt(o,i.pubBytes(),e).mul(i.priv()),c=n.add(s).umod(this.curve.n);return this.makeSignature({R:r,S:c,Rencoded:o})},l.prototype.verify=function(e,t,i){e=a(e),t=this.makeSignature(t);var n=this.keyFromPublic(i),r=this.hashInt(t.Rencoded(),n.pubBytes(),e),o=this.g.mul(t.S());return t.R().add(n.pub().mul(r)).eq(o)},l.prototype.hashInt=function(){for(var e=this.hash(),t=0;t(r>>1)-1?(r>>1)-c:c,o.isubn(a)):a=0,n[s]=a,o.iushrn(1)}return n},n.getJSF=function(e,t){var i=[[],[]];e=e.clone(),t=t.clone();for(var n,r=0,o=0;e.cmpn(-r)>0||t.cmpn(-o)>0;){var s,a,c=e.andln(3)+r&3,d=t.andln(3)+o&3;3===c&&(c=-1),3===d&&(d=-1),s=0==(1&c)?0:3!==(n=e.andln(7)+r&7)&&5!==n||2!==d?c:-c,i[0].push(s),a=0==(1&d)?0:3!==(n=t.andln(7)+o&7)&&5!==n||2!==c?d:-d,i[1].push(a),2*r===s+1&&(r=1-r),2*o===a+1&&(o=1-o),e.iushrn(1),t.iushrn(1)}return i},n.cachedProperty=function(e,t,i){var n="_"+t;e.prototype[t]=function(){return void 0!==this[n]?this[n]:this[n]=i.call(this)}},n.parseBytes=function(e){return"string"==typeof e?n.toArray(e,"hex"):e},n.intFromLE=function(e){return new r(e,"hex","le")}},{"bn.js":18,"minimalistic-assert":223,"minimalistic-crypto-utils":224}],104:[function(e,t,i){t.exports={name:"elliptic",version:"6.5.4",description:"EC cryptography",main:"lib/elliptic.js",files:["lib"],scripts:{lint:"eslint lib test","lint:fix":"npm run lint -- --fix",unit:"istanbul test _mocha --reporter=spec test/index.js",test:"npm run lint && npm run unit",version:"grunt dist && git add dist/"},repository:{type:"git",url:"git@github.com:indutny/elliptic"},keywords:["EC","Elliptic","curve","Cryptography"],author:"Fedor Indutny ",license:"MIT",bugs:{url:"https://github.com/indutny/elliptic/issues"},homepage:"https://github.com/indutny/elliptic",devDependencies:{brfs:"^2.0.2",coveralls:"^3.1.0",eslint:"^7.6.0",grunt:"^1.2.1","grunt-browserify":"^5.3.0","grunt-cli":"^1.3.2","grunt-contrib-connect":"^3.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^5.0.0","grunt-mocha-istanbul":"^5.0.2","grunt-saucelabs":"^9.0.1",istanbul:"^0.4.5",mocha:"^8.0.1"},dependencies:{"bn.js":"^4.11.9",brorand:"^1.1.0","hash.js":"^1.0.0","hmac-drbg":"^1.0.1",inherits:"^2.0.4","minimalistic-assert":"^1.0.1","minimalistic-crypto-utils":"^1.0.1"}}},{}],105:[function(e,t,i){"use strict";var n,r="object"==typeof Reflect?Reflect:null,o=r&&"function"==typeof r.apply?r.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};n=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var s=Number.isNaN||function(e){return e!=e};function a(){a.init.call(this)}t.exports=a,t.exports.once=function(e,t){return new Promise((function(i,n){function r(i){e.removeListener(t,o),n(i)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",r),i([].slice.call(arguments))}m(e,t,o,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&m(e,"error",t,i)}(e,r,{once:!0})}))},a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var c=10;function d(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function l(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function u(e,t,i,n){var r,o,s,a;if(d(i),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),o=e._events),s=o[t]),void 0===s)s=o[t]=i,++e._eventsCount;else if("function"==typeof s?s=o[t]=n?[i,s]:[s,i]:n?s.unshift(i):s.push(i),(r=l(e))>0&&s.length>r&&!s.warned){s.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=s.length,a=c,console&&console.warn&&console.warn(a)}return e}function h(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function f(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},r=h.bind(n);return r.listener=i,n.wrapFn=r,r}function p(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]:i?function(e){for(var t=new Array(e.length),i=0;i0&&(s=t[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=r[e];if(void 0===c)return!1;if("function"==typeof c)o(c,this,t);else{var d=c.length,l=v(c,d);for(i=0;i=0;o--)if(i[o]===t||i[o].listener===t){s=i[o].listener,r=o;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},a.prototype.listeners=function(e){return p(this,e,!0)},a.prototype.rawListeners=function(e){return p(this,e,!1)},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):g.call(e,t)},a.prototype.listenerCount=g,a.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]}},{}],106:[function(e,t,i){var n=e("safe-buffer").Buffer,r=e("md5.js");t.exports=function(e,t,i,o){if(n.isBuffer(e)||(e=n.from(e,"binary")),t&&(n.isBuffer(t)||(t=n.from(t,"binary")),8!==t.length))throw new RangeError("salt should be Buffer with 8 byte length");for(var s=i/8,a=n.alloc(s),c=n.alloc(o||0),d=n.alloc(0);s>0||o>0;){var l=new r;l.update(d),l.update(e),t&&l.update(t),d=l.digest();var u=0;if(s>0){var h=a.length-s;u=Math.min(s,d.length),d.copy(a,h,0,u),s-=u}if(u0){var f=c.length-o,p=Math.min(o,d.length-u);d.copy(c,f,u,u+p),o-=p}}return d.fill(0),{key:a,iv:c}}},{"md5.js":221,"safe-buffer":250}],107:[function(e,t,i){"use strict";var n=e("is-callable"),r=Object.prototype.toString,o=Object.prototype.hasOwnProperty,s=function(e,t,i){for(var n=0,r=e.length;n=3&&(o=i),"[object Array]"===r.call(e)?s(e,t,o):"string"==typeof e?a(e,t,o):c(e,t,o)}},{"is-callable":148}],108:[function(e,t,i){"use strict";var n="Function.prototype.bind called on incompatible ",r=Array.prototype.slice,o=Object.prototype.toString,s="[object Function]";t.exports=function(e){var t=this;if("function"!=typeof t||o.call(t)!==s)throw new TypeError(n+t);for(var i,a=r.call(arguments,1),c=Math.max(0,t.length-a.length),d=[],l=0;l1&&"boolean"!=typeof t)throw new s('"allowMissing" argument must be a boolean');if(null===I(/^%?[^%]*%?$/,e))throw new r("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var i=k(e),n=i.length>0?i[0]:"",o=C("%"+n+"%",t),a=o.name,d=o.value,l=!1,u=o.alias;u&&(n=u[0],E(i,_([0,1],u)));for(var h=1,f=!0;h=i.length){var y=c(d,p);d=(f=!!y)&&"get"in y&&!("originalValue"in y.get)?y.get:d[p]}else f=S(d,p),d=d[p];f&&!l&&(g[a]=d)}}return d}},{"function-bind":109,has:115,"has-symbols":112}],111:[function(e,t,i){"use strict";var n=e("get-intrinsic")("%Object.getOwnPropertyDescriptor%",!0);if(n)try{n([],"length")}catch(e){n=null}t.exports=n},{"get-intrinsic":110}],112:[function(e,t,i){"use strict";var n="undefined"!=typeof Symbol&&Symbol,r=e("./shams");t.exports=function(){return"function"==typeof n&&("function"==typeof Symbol&&("symbol"==typeof n("foo")&&("symbol"==typeof Symbol("bar")&&r())))}},{"./shams":113}],113:[function(e,t,i){"use strict";t.exports=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),i=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(i))return!1;for(t in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var n=Object.getOwnPropertySymbols(e);if(1!==n.length||n[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var r=Object.getOwnPropertyDescriptor(e,t);if(42!==r.value||!0!==r.enumerable)return!1}return!0}},{}],114:[function(e,t,i){"use strict";var n=e("has-symbols/shams");t.exports=function(){return n()&&!!Symbol.toStringTag}},{"has-symbols/shams":113}],115:[function(e,t,i){"use strict";var n=e("function-bind");t.exports=n.call(Function.call,Object.prototype.hasOwnProperty)},{"function-bind":109}],116:[function(e,t,i){"use strict";var n=e("safe-buffer").Buffer,r=e("readable-stream").Transform;function o(e){r.call(this),this._block=n.allocUnsafe(e),this._blockSize=e,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}e("inherits")(o,r),o.prototype._transform=function(e,t,i){var n=null;try{this.update(e,t)}catch(e){n=e}i(n)},o.prototype._flush=function(e){var t=null;try{this.push(this.digest())}catch(e){t=e}e(t)},o.prototype.update=function(e,t){if(function(e,t){if(!n.isBuffer(e)&&"string"!=typeof e)throw new TypeError(t+" must be a string or a buffer")}(e,"Data"),this._finalized)throw new Error("Digest already called");n.isBuffer(e)||(e=n.from(e,t));for(var i=this._block,r=0;this._blockOffset+e.length-r>=this._blockSize;){for(var o=this._blockOffset;o0;++s)this._length[s]+=a,(a=this._length[s]/4294967296|0)>0&&(this._length[s]-=4294967296*a);return this},o.prototype._update=function(){throw new Error("_update is not implemented")},o.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();void 0!==e&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var i=0;i<4;++i)this._length[i]=0;return t},o.prototype._digest=function(){throw new Error("_digest is not implemented")},t.exports=o},{inherits:146,"readable-stream":131,"safe-buffer":250}],117:[function(e,t,i){arguments[4][50][0].apply(i,arguments)},{dup:50}],118:[function(e,t,i){(function(i){(function(){"use strict";var n=Object.keys||function(e){var t=[];for(var i in e)t.push(i);return t};t.exports=d;var r=e("./_stream_readable"),o=e("./_stream_writable");e("inherits")(d,r);for(var s=n(o.prototype),a=0;a0)if("string"==typeof t||s.objectMode||Object.getPrototypeOf(t)===a.prototype||(t=function(e){return a.from(e)}(t)),n)s.endEmitted?E(e,new _):M(e,s,t,!0);else if(s.ended)E(e,new b);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!i?(t=s.decoder.write(t),s.objectMode||0!==t.length?M(e,s,t,!1):P(e,s)):M(e,s,t,!1)}else n||(s.reading=!1,P(e,s));return!s.ended&&(s.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=k?e=k:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function O(e){var t=e._readableState;d("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(d("emitReadable",t.flowing),t.emittedReadable=!0,i.nextTick(A,e))}function A(e){var t=e._readableState;d("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,B(e)}function P(e,t){t.readingMore||(t.readingMore=!0,i.nextTick(D,e,t))}function D(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function L(e){d("readable nexttick read 0"),e.read(0)}function U(e,t){d("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),B(e),t.flowing&&!t.reading&&e.read(0)}function B(e){var t=e._readableState;for(d("flow",t.flowing);t.flowing&&null!==e.read(););}function N(e,t){return 0===t.length?null:(t.objectMode?i=t.buffer.shift():!e||e>=t.length?(i=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):i=t.buffer.consume(e,t.decoder),i);var i}function j(e){var t=e._readableState;d("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,i.nextTick(F,t,e))}function F(e,t){if(d("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var i=t._writableState;(!i||i.autoDestroy&&i.finished)&&t.destroy()}}function K(e,t){for(var i=0,n=e.length;i=t.highWaterMark:t.length>0)||t.ended))return d("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?j(this):O(this),null;if(0===(e=C(e,t))&&t.ended)return 0===t.length&&j(this),null;var n,r=t.needReadable;return d("need readable",r),(0===t.length||t.length-e0?N(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),i!==e&&t.ended&&j(this)),null!==n&&this.emit("data",n),n},I.prototype._read=function(e){E(this,new S("_read()"))},I.prototype.pipe=function(e,t){var n=this,r=this._readableState;switch(r.pipesCount){case 0:r.pipes=e;break;case 1:r.pipes=[r.pipes,e];break;default:r.pipes.push(e)}r.pipesCount+=1,d("pipe count=%d opts=%j",r.pipesCount,t);var s=(!t||!1!==t.end)&&e!==i.stdout&&e!==i.stderr?c:v;function a(t,i){d("onunpipe"),t===n&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,d("cleanup"),e.removeListener("close",p),e.removeListener("finish",g),e.removeListener("drain",l),e.removeListener("error",f),e.removeListener("unpipe",a),n.removeListener("end",c),n.removeListener("end",v),n.removeListener("data",h),u=!0,!r.awaitDrain||e._writableState&&!e._writableState.needDrain||l())}function c(){d("onend"),e.end()}r.endEmitted?i.nextTick(s):n.once("end",s),e.on("unpipe",a);var l=function(e){return function(){var t=e._readableState;d("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&o(e,"data")&&(t.flowing=!0,B(e))}}(n);e.on("drain",l);var u=!1;function h(t){d("ondata");var i=e.write(t);d("dest.write",i),!1===i&&((1===r.pipesCount&&r.pipes===e||r.pipesCount>1&&-1!==K(r.pipes,e))&&!u&&(d("false write response, pause",r.awaitDrain),r.awaitDrain++),n.pause())}function f(t){d("onerror",t),v(),e.removeListener("error",f),0===o(e,"error")&&E(e,t)}function p(){e.removeListener("finish",g),v()}function g(){d("onfinish"),e.removeListener("close",p),v()}function v(){d("unpipe"),n.unpipe(e)}return n.on("data",h),function(e,t,i){if("function"==typeof e.prependListener)return e.prependListener(t,i);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(i):e._events[t]=[i,e._events[t]]:e.on(t,i)}(e,"error",f),e.once("close",p),e.once("finish",g),e.emit("pipe",n),r.flowing||(d("pipe resume"),n.resume()),e},I.prototype.unpipe=function(e){var t=this._readableState,i={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,i)),this;if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o0,!1!==r.flowing&&this.resume()):"readable"===e&&(r.endEmitted||r.readableListening||(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,d("on readable",r.length,r.reading),r.length?O(this):r.reading||i.nextTick(L,this))),n},I.prototype.addListener=I.prototype.on,I.prototype.removeListener=function(e,t){var n=s.prototype.removeListener.call(this,e,t);return"readable"===e&&i.nextTick(x,this),n},I.prototype.removeAllListeners=function(e){var t=s.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||i.nextTick(x,this),t},I.prototype.resume=function(){var e=this._readableState;return e.flowing||(d("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,i.nextTick(U,e,t))}(this,e)),e.paused=!1,this},I.prototype.pause=function(){return d("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(d("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},I.prototype.wrap=function(e){var t=this,i=this._readableState,n=!1;for(var r in e.on("end",(function(){if(d("wrapped end"),i.decoder&&!i.ended){var e=i.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(r){(d("wrapped data"),i.decoder&&(r=i.decoder.write(r)),i.objectMode&&null==r)||(i.objectMode||r&&r.length)&&(t.push(r)||(n=!0,e.pause()))})),e)void 0===this[r]&&"function"==typeof e[r]&&(this[r]=function(t){return function(){return e[t].apply(e,arguments)}}(r));for(var o=0;o-1))throw new _(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(I.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(I.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),I.prototype._write=function(e,t,i){i(new g("_write()"))},I.prototype._writev=null,I.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||function(e,t,n){t.ending=!0,A(e,t),n&&(t.finished?i.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,r,n),this},Object.defineProperty(I.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(I.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),I.prototype.destroy=u.destroy,I.prototype._undestroy=u.undestroy,I.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":117,"./_stream_duplex":118,"./internal/streams/destroy":125,"./internal/streams/state":129,"./internal/streams/stream":130,_process:237,buffer:68,inherits:146,"util-deprecate":283}],123:[function(e,t,i){(function(i){(function(){"use strict";var n;function r(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var o=e("./end-of-stream"),s=Symbol("lastResolve"),a=Symbol("lastReject"),c=Symbol("error"),d=Symbol("ended"),l=Symbol("lastPromise"),u=Symbol("handlePromise"),h=Symbol("stream");function f(e,t){return{value:e,done:t}}function p(e){var t=e[s];if(null!==t){var i=e[h].read();null!==i&&(e[l]=null,e[s]=null,e[a]=null,t(f(i,!1)))}}function g(e){i.nextTick(p,e)}var v=Object.getPrototypeOf((function(){})),m=Object.setPrototypeOf((r(n={get stream(){return this[h]},next:function(){var e=this,t=this[c];if(null!==t)return Promise.reject(t);if(this[d])return Promise.resolve(f(void 0,!0));if(this[h].destroyed)return new Promise((function(t,n){i.nextTick((function(){e[c]?n(e[c]):t(f(void 0,!0))}))}));var n,r=this[l];if(r)n=new Promise(function(e,t){return function(i,n){e.then((function(){t[d]?i(f(void 0,!0)):t[u](i,n)}),n)}}(r,this));else{var o=this[h].read();if(null!==o)return Promise.resolve(f(o,!1));n=new Promise(this[u])}return this[l]=n,n}},Symbol.asyncIterator,(function(){return this})),r(n,"return",(function(){var e=this;return new Promise((function(t,i){e[h].destroy(null,(function(e){e?i(e):t(f(void 0,!0))}))}))})),n),v);t.exports=function(e){var t,i=Object.create(m,(r(t={},h,{value:e,writable:!0}),r(t,s,{value:null,writable:!0}),r(t,a,{value:null,writable:!0}),r(t,c,{value:null,writable:!0}),r(t,d,{value:e._readableState.endEmitted,writable:!0}),r(t,u,{value:function(e,t){var n=i[h].read();n?(i[l]=null,i[s]=null,i[a]=null,e(f(n,!1))):(i[s]=e,i[a]=t)},writable:!0}),t));return i[l]=null,o(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=i[a];return null!==t&&(i[l]=null,i[s]=null,i[a]=null,t(e)),void(i[c]=e)}var n=i[s];null!==n&&(i[l]=null,i[s]=null,i[a]=null,n(f(void 0,!0))),i[d]=!0})),e.on("readable",g.bind(null,i)),i}}).call(this)}).call(this,e("_process"))},{"./end-of-stream":126,_process:237}],124:[function(e,t,i){arguments[4][57][0].apply(i,arguments)},{buffer:68,dup:57,util:20}],125:[function(e,t,i){(function(e){(function(){"use strict";function i(e,t){r(e,t),n(e)}function n(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function r(e,t){e.emit("error",t)}t.exports={destroy:function(t,o){var s=this,a=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return a||c?(o?o(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,e.nextTick(r,this,t)):e.nextTick(r,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,(function(t){!o&&t?s._writableState?s._writableState.errorEmitted?e.nextTick(n,s):(s._writableState.errorEmitted=!0,e.nextTick(i,s,t)):e.nextTick(i,s,t):o?(e.nextTick(n,s),o(t)):e.nextTick(n,s)})),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var i=e._readableState,n=e._writableState;i&&i.autoDestroy||n&&n.autoDestroy?e.destroy(t):e.emit("error",t)}}}).call(this)}).call(this,e("_process"))},{_process:237}],126:[function(e,t,i){arguments[4][59][0].apply(i,arguments)},{"../../../errors":117,dup:59}],127:[function(e,t,i){arguments[4][60][0].apply(i,arguments)},{dup:60}],128:[function(e,t,i){arguments[4][61][0].apply(i,arguments)},{"../../../errors":117,"./end-of-stream":126,dup:61}],129:[function(e,t,i){arguments[4][62][0].apply(i,arguments)},{"../../../errors":117,dup:62}],130:[function(e,t,i){arguments[4][63][0].apply(i,arguments)},{dup:63,events:105}],131:[function(e,t,i){arguments[4][64][0].apply(i,arguments)},{"./lib/_stream_duplex.js":118,"./lib/_stream_passthrough.js":119,"./lib/_stream_readable.js":120,"./lib/_stream_transform.js":121,"./lib/_stream_writable.js":122,"./lib/internal/streams/end-of-stream.js":126,"./lib/internal/streams/pipeline.js":128,dup:64}],132:[function(e,t,i){var n=i;n.utils=e("./hash/utils"),n.common=e("./hash/common"),n.sha=e("./hash/sha"),n.ripemd=e("./hash/ripemd"),n.hmac=e("./hash/hmac"),n.sha1=n.sha.sha1,n.sha256=n.sha.sha256,n.sha224=n.sha.sha224,n.sha384=n.sha.sha384,n.sha512=n.sha.sha512,n.ripemd160=n.ripemd.ripemd160},{"./hash/common":133,"./hash/hmac":134,"./hash/ripemd":135,"./hash/sha":136,"./hash/utils":143}],133:[function(e,t,i){"use strict";var n=e("./utils"),r=e("minimalistic-assert");function o(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}i.BlockHash=o,o.prototype.update=function(e,t){if(e=n.toArray(e,t),this.pending?this.pending=this.pending.concat(e):this.pending=e,this.pendingTotal+=e.length,this.pending.length>=this._delta8){var i=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-i,e.length),0===this.pending.length&&(this.pending=null),e=n.join32(e,0,e.length-i,this.endian);for(var r=0;r>>24&255,n[r++]=e>>>16&255,n[r++]=e>>>8&255,n[r++]=255&e}else for(n[r++]=255&e,n[r++]=e>>>8&255,n[r++]=e>>>16&255,n[r++]=e>>>24&255,n[r++]=0,n[r++]=0,n[r++]=0,n[r++]=0,o=8;othis.blockSize&&(e=(new this.Hash).update(e).digest()),r(e.length<=this.blockSize);for(var t=e.length;t>>3},i.g1_256=function(e){return n(e,17)^n(e,19)^e>>>10}},{"../utils":143}],143:[function(e,t,i){"use strict";var n=e("minimalistic-assert"),r=e("inherits");function o(e,t){return 55296==(64512&e.charCodeAt(t))&&(!(t<0||t+1>=e.length)&&56320==(64512&e.charCodeAt(t+1)))}function s(e){return(e>>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}function a(e){return 1===e.length?"0"+e:e}function c(e){return 7===e.length?"0"+e:6===e.length?"00"+e:5===e.length?"000"+e:4===e.length?"0000"+e:3===e.length?"00000"+e:2===e.length?"000000"+e:1===e.length?"0000000"+e:e}i.inherits=r,i.toArray=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var i=[];if("string"==typeof e)if(t){if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),r=0;r>6|192,i[n++]=63&s|128):o(e,r)?(s=65536+((1023&s)<<10)+(1023&e.charCodeAt(++r)),i[n++]=s>>18|240,i[n++]=s>>12&63|128,i[n++]=s>>6&63|128,i[n++]=63&s|128):(i[n++]=s>>12|224,i[n++]=s>>6&63|128,i[n++]=63&s|128)}else for(r=0;r>>0}return s},i.split32=function(e,t){for(var i=new Array(4*e.length),n=0,r=0;n>>24,i[r+1]=o>>>16&255,i[r+2]=o>>>8&255,i[r+3]=255&o):(i[r+3]=o>>>24,i[r+2]=o>>>16&255,i[r+1]=o>>>8&255,i[r]=255&o)}return i},i.rotr32=function(e,t){return e>>>t|e<<32-t},i.rotl32=function(e,t){return e<>>32-t},i.sum32=function(e,t){return e+t>>>0},i.sum32_3=function(e,t,i){return e+t+i>>>0},i.sum32_4=function(e,t,i,n){return e+t+i+n>>>0},i.sum32_5=function(e,t,i,n,r){return e+t+i+n+r>>>0},i.sum64=function(e,t,i,n){var r=e[t],o=n+e[t+1]>>>0,s=(o>>0,e[t+1]=o},i.sum64_hi=function(e,t,i,n){return(t+n>>>0>>0},i.sum64_lo=function(e,t,i,n){return t+n>>>0},i.sum64_4_hi=function(e,t,i,n,r,o,s,a){var c=0,d=t;return c+=(d=d+n>>>0)>>0)>>0)>>0},i.sum64_4_lo=function(e,t,i,n,r,o,s,a){return t+n+o+a>>>0},i.sum64_5_hi=function(e,t,i,n,r,o,s,a,c,d){var l=0,u=t;return l+=(u=u+n>>>0)>>0)>>0)>>0)>>0},i.sum64_5_lo=function(e,t,i,n,r,o,s,a,c,d){return t+n+o+a+d>>>0},i.rotr64_hi=function(e,t,i){return(t<<32-i|e>>>i)>>>0},i.rotr64_lo=function(e,t,i){return(e<<32-i|t>>>i)>>>0},i.shr64_hi=function(e,t,i){return e>>>i},i.shr64_lo=function(e,t,i){return(e<<32-i|t>>>i)>>>0}},{inherits:146,"minimalistic-assert":223}],144:[function(e,t,i){"use strict";var n=e("hash.js"),r=e("minimalistic-crypto-utils"),o=e("minimalistic-assert");function s(e){if(!(this instanceof s))return new s(e);this.hash=e.hash,this.predResist=!!e.predResist,this.outLen=this.hash.outSize,this.minEntropy=e.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var t=r.toArray(e.entropy,e.entropyEnc||"hex"),i=r.toArray(e.nonce,e.nonceEnc||"hex"),n=r.toArray(e.pers,e.persEnc||"hex");o(t.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(t,i,n)}t.exports=s,s.prototype._init=function(e,t,i){var n=e.concat(t).concat(i);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var r=0;r=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(i||[])),this._reseed=1},s.prototype.generate=function(e,t,i,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof t&&(n=i,i=t,t=null),i&&(i=r.toArray(i,n||"hex"),this._update(i));for(var o=[];o.length */ -i.read=function(e,t,i,n,r){var o,s,a=8*r-n-1,c=(1<>1,l=-7,u=i?r-1:0,h=i?-1:1,f=e[t+u];for(u+=h,o=f&(1<<-l)-1,f>>=-l,l+=a;l>0;o=256*o+e[t+u],u+=h,l-=8);for(s=o&(1<<-l)-1,o>>=-l,l+=n;l>0;s=256*s+e[t+u],u+=h,l-=8);if(0===o)o=1-d;else{if(o===c)return s?NaN:1/0*(f?-1:1);s+=Math.pow(2,n),o-=d}return(f?-1:1)*s*Math.pow(2,o-n)},i.write=function(e,t,i,n,r,o){var s,a,c,d=8*o-r-1,l=(1<>1,h=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:o-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+u>=1?h/c:h*Math.pow(2,1-u))*c>=2&&(s++,c/=2),s+u>=l?(a=0,s=l):s+u>=1?(a=(t*c-1)*Math.pow(2,r),s+=u):(a=t*Math.pow(2,u-1)*Math.pow(2,r),s=0));r>=8;e[i+f]=255&a,f+=p,a/=256,r-=8);for(s=s<0;e[i+f]=255&s,f+=p,s/=256,d-=8);e[i+f-p]|=128*g}},{}],146:[function(e,t,i){"function"==typeof Object.create?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var i=function(){};i.prototype=t.prototype,e.prototype=new i,e.prototype.constructor=e}}},{}],147:[function(e,t,i){"use strict";var n=e("has-tostringtag/shams")(),r=e("call-bind/callBound")("Object.prototype.toString"),o=function(e){return!(n&&e&&"object"==typeof e&&Symbol.toStringTag in e)&&"[object Arguments]"===r(e)},s=function(e){return!!o(e)||null!==e&&"object"==typeof e&&"number"==typeof e.length&&e.length>=0&&"[object Array]"!==r(e)&&"[object Function]"===r(e.callee)},a=function(){return o(arguments)}();o.isLegacyArguments=s,t.exports=a?o:s},{"call-bind/callBound":69,"has-tostringtag/shams":114}],148:[function(e,t,i){"use strict";var n,r,o=Function.prototype.toString,s="object"==typeof Reflect&&null!==Reflect&&Reflect.apply;if("function"==typeof s&&"function"==typeof Object.defineProperty)try{n=Object.defineProperty({},"length",{get:function(){throw r}}),r={},s((function(){throw 42}),null,n)}catch(e){e!==r&&(s=null)}else s=null;var a=/^\s*class\b/,c=function(e){try{var t=o.call(e);return a.test(t)}catch(e){return!1}},d=function(e){try{return!c(e)&&(o.call(e),!0)}catch(e){return!1}},l=Object.prototype.toString,u="function"==typeof Symbol&&!!Symbol.toStringTag,h=!(0 in[,]),f=function(){return!1};if("object"==typeof document){var p=document.all;l.call(p)===l.call(document.all)&&(f=function(e){if((h||!e)&&(void 0===e||"object"==typeof e))try{var t=l.call(e);return("[object HTMLAllCollection]"===t||"[object HTML document.all class]"===t||"[object HTMLCollection]"===t||"[object Object]"===t)&&null==e("")}catch(e){}return!1})}t.exports=s?function(e){if(f(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;try{s(e,null,n)}catch(e){if(e!==r)return!1}return!c(e)&&d(e)}:function(e){if(f(e))return!0;if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;if(u)return d(e);if(c(e))return!1;var t=l.call(e);return!("[object Function]"!==t&&"[object GeneratorFunction]"!==t&&!/^\[object HTML/.test(t))&&d(e)}},{}],149:[function(e,t,i){"use strict";var n,r=Object.prototype.toString,o=Function.prototype.toString,s=/^\s*(?:function)?\*/,a=e("has-tostringtag/shams")(),c=Object.getPrototypeOf;t.exports=function(e){if("function"!=typeof e)return!1;if(s.test(o.call(e)))return!0;if(!a)return"[object GeneratorFunction]"===r.call(e);if(!c)return!1;if(void 0===n){var t=function(){if(!a)return!1;try{return Function("return function*() {}")()}catch(e){}}();n=!!t&&c(t)}return c(e)===n}},{"has-tostringtag/shams":114}],150:[function(e,t,i){(function(i){(function(){"use strict";var n=e("for-each"),r=e("available-typed-arrays"),o=e("call-bind/callBound"),s=o("Object.prototype.toString"),a=e("has-tostringtag/shams")(),c=e("gopd"),d="undefined"==typeof globalThis?i:globalThis,l=r(),u=o("Array.prototype.indexOf",!0)||function(e,t){for(var i=0;i-1}return!!c&&function(e){var t=!1;return n(f,(function(i,n){if(!t)try{t=i.call(e)===n}catch(e){}})),t}(e)}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"available-typed-arrays":16,"call-bind/callBound":69,"for-each":107,gopd:111,"has-tostringtag/shams":114}],151:[function(e,t,i){!function(e,i){"use strict";"function"==typeof define&&define.amd?define(i):"object"==typeof t&&t.exports?t.exports=i():e.log=i()}(this,(function(){"use strict";var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"];function r(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function s(t,i){for(var r=0;r=0&&i<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+i;if(o=i,!1!==r&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&d){try{return void(window.localStorage[d]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"="+i+";"}catch(e){}}}(i),s.call(a,i,e),typeof console===t&&i=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:r}}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 o,s=!0,a=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return s=e.done,e},e:function(e){a=!0,o=e},f:function(){try{s||null==i.return||i.return()}finally{if(a)throw o}}}}function u(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);i=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}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 s,a=!0,c=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return a=e.done,e},e:function(e){c=!0,s=e},f:function(){try{a||null==i.return||i.return()}finally{if(c)throw s}}}}function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);ie.length)&&(t=e.length);for(var i=0,n=new Array(t);i0?s.max_selections:1,!Array.isArray(s.answers))throw new a.InvalidEventError("Poll answers must be an array");var c=s.answers.slice(0,20).map((function(e){return new T({type:"org.matrix.sdk.poll.answer",content:e})}));if(c.length<=0)throw new a.InvalidEventError("No answers available");return n.answers=c,n}return m(i,[{key:"isEquivalentTo",value:function(e){return(0,d.isEventTypeSame)(e,r.M_POLL_START)}},{key:"serialize",value:function(){var e;return{type:r.M_POLL_START.name,content:(e={},w(e,r.M_POLL_START.name,{question:this.question.serialize().content,kind:this.rawKind,max_selections:this.maxSelections,answers:this.answers.map((function(e){return e.serialize().content}))}),w(e,s.M_TEXT.name,"".concat(this.question.text,"\n").concat(this.answers.map((function(e,t){return"".concat(t+1,". ").concat(e.text)})).join("\n"))),e)}}}],[{key:"from",value:function(e,t,n){var o,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;return new i({type:r.M_POLL_START.name,content:(o={},w(o,s.M_TEXT.name,e),w(o,r.M_POLL_START.name,{question:w({},s.M_TEXT.name,e),kind:n instanceof c.NamespacedValue?n.name:n,max_selections:a,answers:t.map((function(e){return w({id:u(Array(16)).map((function(){return R.charAt(Math.floor(Math.random()*R.length))})).join("")},s.M_TEXT.name,e)}))}),o)})}}]),i}(l.ExtensibleEvent);i.PollStartEvent=I;var R="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"},{"../InvalidEventError":154,"../NamespacedValue":156,"../utility/events":173,"./ExtensibleEvent":158,"./MessageEvent":159,"./message_types":164,"./poll_types":165}],164:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.M_TEXT=i.M_NOTICE=i.M_MESSAGE=i.M_HTML=i.M_EMOTE=void 0;var n=e("../NamespacedValue"),r=new n.UnstableValue("m.message","org.matrix.msc1767.message");i.M_MESSAGE=r;var o=new n.UnstableValue("m.text","org.matrix.msc1767.text");i.M_TEXT=o;var s=new n.UnstableValue("m.html","org.matrix.msc1767.html");i.M_HTML=s;var a=new n.UnstableValue("m.emote","org.matrix.msc1767.emote");i.M_EMOTE=a;var c=new n.UnstableValue("m.notice","org.matrix.msc1767.notice");i.M_NOTICE=c},{"../NamespacedValue":156}],165:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.M_POLL_START=i.M_POLL_RESPONSE=i.M_POLL_KIND_UNDISCLOSED=i.M_POLL_KIND_DISCLOSED=i.M_POLL_END=void 0;var n=e("../NamespacedValue"),r=new n.UnstableValue("m.poll.disclosed","org.matrix.msc3381.poll.disclosed");i.M_POLL_KIND_DISCLOSED=r;var o=new n.UnstableValue("m.poll.undisclosed","org.matrix.msc3381.poll.undisclosed");i.M_POLL_KIND_UNDISCLOSED=o;var s=new n.UnstableValue("m.poll.start","org.matrix.msc3381.poll.start");i.M_POLL_START=s;var a=new n.UnstableValue("m.poll.response","org.matrix.msc3381.poll.response");i.M_POLL_RESPONSE=a;var c=new n.UnstableValue("m.poll.end","org.matrix.msc3381.poll.end");i.M_POLL_END=c},{"../NamespacedValue":156}],166:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.REFERENCE_RELATION=void 0;var n=new(e("../NamespacedValue").NamespacedValue)("m.reference");i.REFERENCE_RELATION=n},{"../NamespacedValue":156}],167:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0});var n=e("./ExtensibleEvents");Object.keys(n).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===n[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return n[e]}}))}));var r=e("./IPartialEvent");Object.keys(r).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===r[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return r[e]}}))}));var o=e("./InvalidEventError");Object.keys(o).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===o[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return o[e]}}))}));var s=e("./NamespacedValue");Object.keys(s).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===s[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return s[e]}}))}));var a=e("./NamespacedMap");Object.keys(a).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===a[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return a[e]}}))}));var c=e("./types");Object.keys(c).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===c[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return c[e]}}))}));var d=e("./utility/MessageMatchers");Object.keys(d).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===d[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return d[e]}}))}));var l=e("./utility/events");Object.keys(l).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===l[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return l[e]}}))}));var u=e("./interpreters/legacy/MRoomMessage");Object.keys(u).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===u[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return u[e]}}))}));var h=e("./interpreters/modern/MMessage");Object.keys(h).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===h[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return h[e]}}))}));var f=e("./interpreters/modern/MPoll");Object.keys(f).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===f[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return f[e]}}))}));var p=e("./events/relationship_types");Object.keys(p).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===p[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return p[e]}}))}));var g=e("./events/ExtensibleEvent");Object.keys(g).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===g[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return g[e]}}))}));var v=e("./events/message_types");Object.keys(v).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===v[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return v[e]}}))}));var m=e("./events/MessageEvent");Object.keys(m).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===m[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return m[e]}}))}));var y=e("./events/EmoteEvent");Object.keys(y).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===y[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return y[e]}}))}));var b=e("./events/NoticeEvent");Object.keys(b).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===b[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return b[e]}}))}));var S=e("./events/poll_types");Object.keys(S).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===S[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return S[e]}}))}));var _=e("./events/PollStartEvent");Object.keys(_).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===_[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return _[e]}}))}));var E=e("./events/PollResponseEvent");Object.keys(E).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===E[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return E[e]}}))}));var w=e("./events/PollEndEvent");Object.keys(w).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in i&&i[e]===w[e]||Object.defineProperty(i,e,{enumerable:!0,get:function(){return w[e]}}))}))},{"./ExtensibleEvents":152,"./IPartialEvent":153,"./InvalidEventError":154,"./NamespacedMap":155,"./NamespacedValue":156,"./events/EmoteEvent":157,"./events/ExtensibleEvent":158,"./events/MessageEvent":159,"./events/NoticeEvent":160,"./events/PollEndEvent":161,"./events/PollResponseEvent":162,"./events/PollStartEvent":163,"./events/message_types":164,"./events/poll_types":165,"./events/relationship_types":166,"./interpreters/legacy/MRoomMessage":168,"./interpreters/modern/MMessage":169,"./interpreters/modern/MPoll":170,"./types":171,"./utility/MessageMatchers":172,"./utility/events":173}],168:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.LEGACY_M_ROOM_MESSAGE=void 0,i.parseMRoomMessage=function(e){var t,i,s;if(a.M_MESSAGE.findIn(e.content)||a.M_TEXT.findIn(e.content))return new n.MessageEvent(e);var c,u=null===(t=e.content)||void 0===t?void 0:t.msgtype,h=null===(i=e.content)||void 0===i?void 0:i.body,f="org.matrix.custom.html"===(null===(s=e.content)||void 0===s?void 0:s.format)?e.content.formatted_body:null;return"m.text"===u?new n.MessageEvent(d(d({},e),{},{content:d(d({},e.content),{},(c={},l(c,a.M_TEXT.name,h),l(c,a.M_HTML.name,f),c))})):"m.notice"===u?new r.NoticeEvent(d(d({},e),{},{content:d(d({},e.content),{},(p={},l(p,a.M_TEXT.name,h),l(p,a.M_HTML.name,f),p))})):"m.emote"===u?new o.EmoteEvent(d(d({},e),{},{content:d(d({},e.content),{},(g={},l(g,a.M_TEXT.name,h),l(g,a.M_HTML.name,f),g))})):null;var p,g};var n=e("../../events/MessageEvent"),r=e("../../events/NoticeEvent"),o=e("../../events/EmoteEvent"),s=e("../../NamespacedValue"),a=e("../../events/message_types");function c(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,n)}return i}function d(e){for(var t=1;t=0;--r){var o=this.tryEntries[r],s=o.completion;if("root"===o.tryLoc)return n("end");if(o.tryLoc<=this.prev){var a=i.call(o,"catchLoc"),c=i.call(o,"finallyLoc");if(a&&c){if(this.prev=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&i.call(r,"finallyLoc")&&this.prev=0;--t){var i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),T(i),u}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var n=i.completion;if("throw"===n.type){var r=n.arg;T(i)}return r}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,i){return this.delegate={iterator:R(e),resultName:t,nextLoc:i},"next"===this.method&&(this.arg=void 0),u}},e}function g(e,t,i,n,r,o,s){try{var a=e[o](s),c=a.value}catch(e){return void i(e)}a.done?t(c):Promise.resolve(c).then(n,r)}function v(e){return function(){var t=this,i=arguments;return new Promise((function(n,r){var o=e.apply(t,i);function s(e){g(o,n,r,s,a,"next",e)}function a(e){g(o,n,r,s,a,"throw",e)}s(void 0)}))}}function m(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=function(e,t){if(!e)return;if("string"==typeof e)return y(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);"Object"===i&&e.constructor&&(i=e.constructor.name);if("Map"===i||"Set"===i)return Array.from(e);if("Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i))return y(e,t)}(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var n=0,r=function(){};return{s:r,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:r}}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 o,s=!0,a=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return s=e.done,e},e:function(e){a=!0,o=e},f:function(){try{s||null==i.return||i.return()}finally{if(a)throw o}}}}function y(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);i1&&void 0!==arguments[1]?arguments[1]:null;return this.allowedEvents.some((function(i){return i.matchesAsRoomEvent(l.EventDirection.Send,e,t)}))}},{key:"canSendStateEvent",value:function(e,t){return this.allowedEvents.some((function(i){return i.matchesAsStateEvent(l.EventDirection.Send,e,t)}))}},{key:"canSendToDeviceEvent",value:function(e){return this.allowedEvents.some((function(t){return t.matchesAsToDeviceEvent(l.EventDirection.Send,e)}))}},{key:"canReceiveRoomEvent",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return this.allowedEvents.some((function(i){return i.matchesAsRoomEvent(l.EventDirection.Receive,e,t)}))}},{key:"canReceiveStateEvent",value:function(e,t){return this.allowedEvents.some((function(i){return i.matchesAsStateEvent(l.EventDirection.Receive,e,t)}))}},{key:"canReceiveToDeviceEvent",value:function(e){return this.allowedEvents.some((function(t){return t.matchesAsToDeviceEvent(l.EventDirection.Receive,e)}))}},{key:"stop",value:function(){this.isStopped=!0,this.transport.stop()}},{key:"beginCapabilities",value:function(){var e,t=this;this.emit("preparing"),this.transport.send(a.WidgetApiToWidgetAction.Capabilities,{}).then((function(i){return e=i.capabilities,t.driver.validateCapabilities(new Set(i.capabilities))})).then((function(i){console.log("Widget ".concat(t.widget.id," is allowed capabilities:"),Array.from(i)),t.allowedCapabilities=i,t.allowedEvents=l.WidgetEventCapability.findEventCapabilities(i),t.notifyCapabilities(e),t.emit("ready")}))}},{key:"notifyCapabilities",value:function(e){var t=this;this.transport.send(a.WidgetApiToWidgetAction.NotifyCapabilities,{requested:e,approved:Array.from(this.allowedCapabilities)}).catch((function(e){console.warn("non-fatal error notifying widget of approved capabilities:",e)})).then((function(){t.emit("capabilitiesNotified")}))}},{key:"onIframeLoad",value:function(e){this.widget.waitForIframeLoad?this.beginCapabilities():this.contentLoadedActionSent=!1}},{key:"handleContentLoadedAction",value:function(e){if(this.contentLoadedActionSent)throw new Error("Improper sequence: ContentLoaded Action can only be send once after the widget loaded and should only be used if waitForIframeLoad is false (default=true)");this.widget.waitForIframeLoad?this.transport.reply(e,{error:{message:"Improper sequence: not expecting ContentLoaded event if waitForIframLoad is true (default=true)"}}):(this.transport.reply(e,{}),this.beginCapabilities()),this.contentLoadedActionSent=!0}},{key:"replyVersions",value:function(e){this.transport.reply(e,{supported_versions:d.CurrentApiVersions})}},{key:"handleCapabilitiesRenegotiate",value:function(e){var t,i=this;this.transport.reply(e,{});var n=(null===(t=e.data)||void 0===t?void 0:t.capabilities)||[],r=new Set(n.filter((function(e){return!i.hasCapability(e)})));if(0===r.size)return this.notifyCapabilities([]);this.driver.validateCapabilities(r).then((function(e){return e.forEach((function(e){return i.allowedCapabilities.add(e)})),l.WidgetEventCapability.findEventCapabilities(e).forEach((function(e){return i.allowedEvents.push(e)})),i.notifyCapabilities(Array.from(r))}))}},{key:"handleNavigate",value:function(e){var t,i,n=this;if(!this.hasCapability(c.MatrixCapabilities.MSC2931Navigate))return this.transport.reply(e,{error:{message:"Missing capability"}});if(null===(t=e.data)||void 0===t||!t.uri||null===(i=e.data)||void 0===i||!i.uri.toString().startsWith("https://matrix.to/#"))return this.transport.reply(e,{error:{message:"Invalid matrix.to URI"}});var r=function(t){return console.error("[ClientWidgetApi] Failed to handle navigation: ",t),n.transport.reply(e,{error:{message:"Error handling navigation"}})};try{this.driver.navigate(e.data.uri.toString()).catch((function(e){return r(e)})).then((function(){return n.transport.reply(e,{})}))}catch(e){return r(e)}}},{key:"handleOIDC",value:function(e){var t=this,i=1,n=function(n,r){return r=r||{},i>1?t.transport.send(a.WidgetApiToWidgetAction.OpenIDCredentials,S({state:n,original_request_id:e.requestId},r)):t.transport.reply(e,S({state:n},r))},r=function(r){return console.error("[ClientWidgetApi] Failed to handle OIDC: ",r),i>1?n(u.OpenIDRequestState.Blocked):t.transport.reply(e,{error:{message:r}})},o=new h.SimpleObservable((function(e){return e.state===u.OpenIDRequestState.PendingUserConfirmation&&i>1?(o.close(),r("client provided out-of-phase response to OIDC flow")):e.state===u.OpenIDRequestState.PendingUserConfirmation?(n(e.state),void i++):e.state!==u.OpenIDRequestState.Allowed||e.token?(e.state===u.OpenIDRequestState.Blocked&&(e.token=void 0),o.close(),n(e.state,e.token)):r("client provided invalid OIDC token for an allowed request")}));this.driver.askOpenID(o)}},{key:"handleReadEvents",value:function(e){var t=this;if(!e.data.type)return this.transport.reply(e,{error:{message:"Invalid request - missing event type"}});if(void 0!==e.data.limit&&(!e.data.limit||e.data.limit<0))return this.transport.reply(e,{error:{message:"Invalid request - limit out of range"}});var i=null;if(e.data.room_ids){i=e.data.room_ids,Array.isArray(i)||(i=[i]);var n,r=m(i);try{for(r.s();!(n=r.n()).done;){var o=n.value;if(!this.canUseRoomTimeline(o))return this.transport.reply(e,{error:{message:"Unable to access room timeline: ".concat(o)}})}}catch(e){r.e(e)}finally{r.f()}}var s=e.data.limit||0,a=Promise.resolve([]);if(void 0!==e.data.state_key){var c=!0===e.data.state_key?void 0:e.data.state_key.toString();if(!this.canReceiveStateEvent(e.data.type,null!=c?c:null))return this.transport.reply(e,{error:{message:"Cannot read state events of this type"}});a=this.driver.readStateEvents(e.data.type,c,s,i)}else{if(!this.canReceiveRoomEvent(e.data.type,e.data.msgtype))return this.transport.reply(e,{error:{message:"Cannot read room events of this type"}});a=this.driver.readRoomEvents(e.data.type,e.data.msgtype,s,i)}return a.then((function(i){return t.transport.reply(e,{events:i})}))}},{key:"handleSendEvent",value:function(e){var t,i=this;if(!e.data.type)return this.transport.reply(e,{error:{message:"Invalid request - missing event type"}});if(e.data.room_id&&!this.canUseRoomTimeline(e.data.room_id))return this.transport.reply(e,{error:{message:"Unable to access room timeline: ".concat(e.data.room_id)}});if(null!==e.data.state_key&&void 0!==e.data.state_key){if(!this.canSendStateEvent(e.data.type,e.data.state_key))return this.transport.reply(e,{error:{message:"Cannot send state events of this type"}});t=this.driver.sendEvent(e.data.type,e.data.content||{},e.data.state_key,e.data.room_id)}else{var n=e.data.content||{},r=n.msgtype;if(!this.canSendRoomEvent(e.data.type,r))return this.transport.reply(e,{error:{message:"Cannot send room events of this type"}});t=this.driver.sendEvent(e.data.type,n,null,e.data.room_id)}t.then((function(t){return i.transport.reply(e,{room_id:t.roomId,event_id:t.eventId})})).catch((function(t){return console.error("error sending event: ",t),i.transport.reply(e,{error:{message:"Error sending event"}})}))}},{key:"handleSendToDevice",value:(O=v(p().mark((function e(t){return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.data.type){e.next=5;break}return e.next=3,this.transport.reply(t,{error:{message:"Invalid request - missing event type"}});case 3:case 8:case 13:case 18:case 25:e.next=32;break;case 5:if(t.data.messages){e.next=10;break}return e.next=8,this.transport.reply(t,{error:{message:"Invalid request - missing event contents"}});case 10:if("boolean"==typeof t.data.encrypted){e.next=15;break}return e.next=13,this.transport.reply(t,{error:{message:"Invalid request - missing encryption flag"}});case 15:if(this.canSendToDeviceEvent(t.data.type)){e.next=20;break}return e.next=18,this.transport.reply(t,{error:{message:"Cannot send to-device events of this type"}});case 20:return e.prev=20,e.next=23,this.driver.sendToDevice(t.data.type,t.data.encrypted,t.data.messages);case 23:return e.next=25,this.transport.reply(t,{});case 27:return e.prev=27,e.t0=e.catch(20),console.error("error sending to-device event",e.t0),e.next=32,this.transport.reply(t,{error:{message:"Error sending event"}});case 32:case"end":return e.stop()}}),e,this,[[20,27]])}))),function(e){return O.apply(this,arguments)})},{key:"pollTurnServers",value:(C=v(p().mark((function e(t,i){var n,r,o,s,c,d;return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.transport.send(a.WidgetApiToWidgetAction.UpdateTurnServers,i);case 3:n=!1,r=!1,e.prev=5,s=M(t);case 7:return e.next=9,s.next();case 9:if(!(n=!(c=e.sent).done)){e.next=16;break}return d=c.value,e.next=13,this.transport.send(a.WidgetApiToWidgetAction.UpdateTurnServers,d);case 13:n=!1,e.next=7;break;case 16:e.next=22;break;case 18:e.prev=18,e.t0=e.catch(5),r=!0,o=e.t0;case 22:if(e.prev=22,e.prev=23,!n||null==s.return){e.next=27;break}return e.next=27,s.return();case 27:if(e.prev=27,!r){e.next=30;break}throw o;case 30:return e.finish(27);case 31:return e.finish(22);case 32:e.next=37;break;case 34:e.prev=34,e.t1=e.catch(0),console.error("error polling for TURN servers",e.t1);case 37:case"end":return e.stop()}}),e,this,[[0,34],[5,18,22,32],[23,,27,31]])}))),function(e,t){return C.apply(this,arguments)})},{key:"handleWatchTurnServers",value:(k=v(p().mark((function e(t){var i,n,r,o;return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasCapability(c.MatrixCapabilities.MSC3846TurnServers)){e.next=5;break}return e.next=3,this.transport.reply(t,{error:{message:"Missing capability"}});case 3:case 8:e.next=30;break;case 5:if(!this.turnServers){e.next=10;break}return e.next=8,this.transport.reply(t,{});case 10:return e.prev=10,i=this.driver.getTurnServers(),e.next=14,i.next();case 14:if(n=e.sent,r=n.done,o=n.value,!r){e.next=19;break}throw new Error("Client refuses to provide any TURN servers");case 19:return e.next=21,this.transport.reply(t,{});case 21:this.pollTurnServers(i,o),this.turnServers=i,e.next=30;break;case 25:return e.prev=25,e.t0=e.catch(10),console.error("error getting first TURN server results",e.t0),e.next=30,this.transport.reply(t,{error:{message:"TURN servers not available"}});case 30:case"end":return e.stop()}}),e,this,[[10,25]])}))),function(e){return k.apply(this,arguments)})},{key:"handleUnwatchTurnServers",value:(I=v(p().mark((function e(t){return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasCapability(c.MatrixCapabilities.MSC3846TurnServers)){e.next=5;break}return e.next=3,this.transport.reply(t,{error:{message:"Missing capability"}});case 3:case 8:e.next=15;break;case 5:if(this.turnServers){e.next=10;break}return e.next=8,this.transport.reply(t,{});case 10:return e.next=12,this.turnServers.return(void 0);case 12:return this.turnServers=null,e.next=15,this.transport.reply(t,{});case 15:case"end":return e.stop()}}),e,this)}))),function(e){return I.apply(this,arguments)})},{key:"handleReadRelations",value:(b=v(p().mark((function e(t){var i,n,r=this;return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.data.event_id){e.next=2;break}return e.abrupt("return",this.transport.reply(t,{error:{message:"Invalid request - missing event ID"}}));case 2:if(!(void 0!==t.data.limit&&t.data.limit<0)){e.next=4;break}return e.abrupt("return",this.transport.reply(t,{error:{message:"Invalid request - limit out of range"}}));case 4:if(void 0===t.data.room_id||this.canUseRoomTimeline(t.data.room_id)){e.next=6;break}return e.abrupt("return",this.transport.reply(t,{error:{message:"Unable to access room timeline: ".concat(t.data.room_id)}}));case 6:return e.prev=6,e.next=9,this.driver.readEventRelations(t.data.event_id,t.data.room_id,t.data.rel_type,t.data.event_type,t.data.from,t.data.to,t.data.limit,t.data.direction);case 9:return i=e.sent,n=i.chunk.filter((function(e){return void 0!==e.state_key?r.canReceiveStateEvent(e.type,e.state_key):r.canReceiveRoomEvent(e.type,e.content.msgtype)})),e.abrupt("return",this.transport.reply(t,{chunk:n,prev_batch:i.prevBatch,next_batch:i.nextBatch}));case 14:return e.prev=14,e.t0=e.catch(6),console.error("error getting the relations",e.t0),e.next=19,this.transport.reply(t,{error:{message:"Unexpected error while reading relations"}});case 19:case"end":return e.stop()}}),e,this,[[6,14]])}))),function(e){return b.apply(this,arguments)})},{key:"handleUserDirectorySearch",value:(y=v(p().mark((function e(t){var i;return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasCapability(c.MatrixCapabilities.MSC3973UserDirectorySearch)){e.next=2;break}return e.abrupt("return",this.transport.reply(t,{error:{message:"Missing capability"}}));case 2:if("string"==typeof t.data.search_term){e.next=4;break}return e.abrupt("return",this.transport.reply(t,{error:{message:"Invalid request - missing search term"}}));case 4:if(!(void 0!==t.data.limit&&t.data.limit<0)){e.next=6;break}return e.abrupt("return",this.transport.reply(t,{error:{message:"Invalid request - limit out of range"}}));case 6:return e.prev=6,e.next=9,this.driver.searchUserDirectory(t.data.search_term,t.data.limit);case 9:return i=e.sent,e.abrupt("return",this.transport.reply(t,{limited:i.limited,results:i.results.map((function(e){return{user_id:e.userId,display_name:e.displayName,avatar_url:e.avatarUrl}}))}));case 13:return e.prev=13,e.t0=e.catch(6),console.error("error searching in the user directory",e.t0),e.next=18,this.transport.reply(t,{error:{message:"Unexpected error while searching in the user directory"}});case 18:case"end":return e.stop()}}),e,this,[[6,13]])}))),function(e){return y.apply(this,arguments)})},{key:"handleMessage",value:function(e){if(!this.isStopped){var t=new CustomEvent("action:".concat(e.detail.action),{detail:e.detail,cancelable:!0});if(this.emit("action:".concat(e.detail.action),t),!t.defaultPrevented)switch(e.detail.action){case a.WidgetApiFromWidgetAction.ContentLoaded:return this.handleContentLoadedAction(e.detail);case a.WidgetApiFromWidgetAction.SupportedApiVersions:return this.replyVersions(e.detail);case a.WidgetApiFromWidgetAction.SendEvent:return this.handleSendEvent(e.detail);case a.WidgetApiFromWidgetAction.SendToDevice:return this.handleSendToDevice(e.detail);case a.WidgetApiFromWidgetAction.GetOpenIDCredentials:return this.handleOIDC(e.detail);case a.WidgetApiFromWidgetAction.MSC2931Navigate:return this.handleNavigate(e.detail);case a.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities:return this.handleCapabilitiesRenegotiate(e.detail);case a.WidgetApiFromWidgetAction.MSC2876ReadEvents:return this.handleReadEvents(e.detail);case a.WidgetApiFromWidgetAction.WatchTurnServers:return this.handleWatchTurnServers(e.detail);case a.WidgetApiFromWidgetAction.UnwatchTurnServers:return this.handleUnwatchTurnServers(e.detail);case a.WidgetApiFromWidgetAction.MSC3869ReadRelations:return this.handleReadRelations(e.detail);case a.WidgetApiFromWidgetAction.MSC3973UserDirectorySearch:return this.handleUserDirectorySearch(e.detail);default:return this.transport.reply(e.detail,{error:{message:"Unknown or unsupported action: "+e.detail.action}})}}}},{key:"takeScreenshot",value:function(){return this.transport.send(a.WidgetApiToWidgetAction.TakeScreenshot,{})}},{key:"updateVisibility",value:function(e){return this.transport.send(a.WidgetApiToWidgetAction.UpdateVisibility,{visible:e})}},{key:"sendWidgetConfig",value:function(e){return this.transport.send(a.WidgetApiToWidgetAction.WidgetConfig,e).then()}},{key:"notifyModalWidgetButtonClicked",value:function(e){return this.transport.send(a.WidgetApiToWidgetAction.ButtonClicked,{id:e}).then()}},{key:"notifyModalWidgetClose",value:function(e){return this.transport.send(a.WidgetApiToWidgetAction.CloseModalWidget,e).then()}},{key:"feedEvent",value:(g=v(p().mark((function e(t,i){var n;return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.room_id===i||this.canUseRoomTimeline(t.room_id)){e.next=2;break}return e.abrupt("return");case 2:if(void 0===t.state_key||null===t.state_key){e.next=7;break}if(this.canReceiveStateEvent(t.type,t.state_key)){e.next=5;break}return e.abrupt("return");case 5:e.next=9;break;case 7:if(this.canReceiveRoomEvent(t.type,null===(n=t.content)||void 0===n?void 0:n.msgtype)){e.next=9;break}return e.abrupt("return");case 9:return e.next=11,this.transport.send(a.WidgetApiToWidgetAction.SendEvent,t);case 11:case"end":return e.stop()}}),e,this)}))),function(e,t){return g.apply(this,arguments)})},{key:"feedToDevice",value:(r=v(p().mark((function e(t,i){return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.canReceiveToDeviceEvent(t.type)){e.next=3;break}return e.next=3,this.transport.send(a.WidgetApiToWidgetAction.SendToDevice,S(S({},t),{},{encrypted:i}));case 3:case"end":return e.stop()}}),e,this)}))),function(e,t){return r.apply(this,arguments)})}],i&&_(t.prototype,i),n&&_(t,n),Object.defineProperty(t,"prototype",{writable:!1}),P}(r.EventEmitter);i.ClientWidgetApi=C},{"./Symbols":175,"./interfaces/ApiVersion":179,"./interfaces/Capabilities":180,"./interfaces/GetOpenIDAction":183,"./interfaces/WidgetApiAction":207,"./interfaces/WidgetApiDirection":208,"./models/WidgetEventCapability":213,"./transport/PostmessageTransport":219,"./util/SimpleObservable":220,events:105}],175:[function(e,t,i){"use strict";var n;Object.defineProperty(i,"__esModule",{value:!0}),i.Symbols=void 0,i.Symbols=n,function(e){e.AnyRoom="*"}(n||(i.Symbols=n={}))},{}],176:[function(e,t,i){"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}Object.defineProperty(i,"__esModule",{value:!0}),i.WidgetApi=void 0;var r=e("events"),o=e("./interfaces/WidgetApiDirection"),s=e("./interfaces/ApiVersion"),a=e("./transport/PostmessageTransport"),c=e("./interfaces/WidgetApiAction"),d=e("./interfaces/GetOpenIDAction"),l=e("./interfaces/WidgetType"),u=e("./interfaces/ModalWidgetActions"),h=e("./models/WidgetEventCapability"),f=e("./Symbols");function p(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */p=function(){return e};var e={},t=Object.prototype,i=t.hasOwnProperty,r="function"==typeof Symbol?Symbol:{},o=r.iterator||"@@iterator",s=r.asyncIterator||"@@asyncIterator",a=r.toStringTag||"@@toStringTag";function c(e,t,i){return Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{c({},"")}catch(e){c=function(e,t,i){return e[t]=i}}function d(e,t,i,n){var r=t&&t.prototype instanceof h?t:h,o=Object.create(r.prototype),s=new I(n||[]);return o._invoke=function(e,t,i){var n="suspendedStart";return function(r,o){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===r)throw o;return M()}for(i.method=r,i.arg=o;;){var s=i.delegate;if(s){var a=E(s,i);if(a){if(a===u)continue;return a}}if("next"===i.method)i.sent=i._sent=i.arg;else if("throw"===i.method){if("suspendedStart"===n)throw n="completed",i.arg;i.dispatchException(i.arg)}else"return"===i.method&&i.abrupt("return",i.arg);n="executing";var c=l(e,t,i);if("normal"===c.type){if(n=i.done?"completed":"suspendedYield",c.arg===u)continue;return{value:c.arg,done:i.done}}"throw"===c.type&&(n="completed",i.method="throw",i.arg=c.arg)}}}(e,i,s),o}function l(e,t,i){try{return{type:"normal",arg:e.call(t,i)}}catch(e){return{type:"throw",arg:e}}}e.wrap=d;var u={};function h(){}function f(){}function g(){}var v={};c(v,o,(function(){return this}));var m=Object.getPrototypeOf,y=m&&m(m(R([])));y&&y!==t&&i.call(y,o)&&(v=y);var b=g.prototype=h.prototype=Object.create(v);function S(e){["next","throw","return"].forEach((function(t){c(e,t,(function(e){return this._invoke(t,e)}))}))}function _(e,t){function r(o,s,a,c){var d=l(e[o],e,s);if("throw"!==d.type){var u=d.arg,h=u.value;return h&&"object"==n(h)&&i.call(h,"__await")?t.resolve(h.__await).then((function(e){r("next",e,a,c)}),(function(e){r("throw",e,a,c)})):t.resolve(h).then((function(e){u.value=e,a(u)}),(function(e){return r("throw",e,a,c)}))}c(d.arg)}var o;this._invoke=function(e,i){function n(){return new t((function(t,n){r(e,i,t,n)}))}return o=o?o.then(n,n):n()}}function E(e,t){var i=e.iterator[t.method];if(void 0===i){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,E(e,t),"throw"===t.method))return u;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return u}var n=l(i,e.iterator,t.arg);if("throw"===n.type)return t.method="throw",t.arg=n.arg,t.delegate=null,u;var r=n.arg;return r?r.done?(t[e.resultName]=r.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,u):r:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,u)}function w(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function T(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function I(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(w,this),this.reset(!0)}function R(e){if(e){var t=e[o];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,r=function t(){for(;++n=0;--r){var o=this.tryEntries[r],s=o.completion;if("root"===o.tryLoc)return n("end");if(o.tryLoc<=this.prev){var a=i.call(o,"catchLoc"),c=i.call(o,"finallyLoc");if(a&&c){if(this.prev=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&i.call(r,"finallyLoc")&&this.prev=0;--t){var i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),T(i),u}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var n=i.completion;if("throw"===n.type){var r=n.arg;T(i)}return r}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,i){return this.delegate={iterator:R(e),resultName:t,nextLoc:i},"next"===this.method&&(this.arg=void 0),u}},e}function g(e,t,i,n,r,o,s){try{var a=e[o](s),c=a.value}catch(e){return void i(e)}a.done?t(c):Promise.resolve(c).then(n,r)}function v(e){return function(){var t=this,i=arguments;return new Promise((function(n,r){var o=e.apply(t,i);function s(e){g(o,n,r,s,a,"next",e)}function a(e){g(o,n,r,s,a,"throw",e)}s(void 0)}))}}function m(e,t){for(var i=0;i0&&void 0!==arguments[0]?arguments[0]:null,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,I),(e=_.call(this)).clientOrigin=i,E(S(e),"transport",void 0),E(S(e),"capabilitiesFinished",!1),E(S(e),"supportsMSC2974Renegotiate",!1),E(S(e),"requestedCapabilities",[]),E(S(e),"approvedCapabilities",void 0),E(S(e),"cachedClientVersions",void 0),E(S(e),"turnServerWatchers",0),!window.parent)throw new Error("No parent window. This widget doesn't appear to be embedded properly.");return e.transport=new a.PostmessageTransport(o.WidgetApiDirection.FromWidget,t,window.parent,window),e.transport.targetOrigin=i,e.transport.on("message",e.handleMessage.bind(S(e))),e}return t=I,i=[{key:"hasCapability",value:function(e){return Array.isArray(this.approvedCapabilities)?this.approvedCapabilities.includes(e):this.requestedCapabilities.includes(e)}},{key:"requestCapability",value:function(e){if(this.capabilitiesFinished&&!this.supportsMSC2974Renegotiate)throw new Error("Capabilities have already been negotiated");this.requestedCapabilities.push(e)}},{key:"requestCapabilities",value:function(e){var t=this;e.forEach((function(e){return t.requestCapability(e)}))}},{key:"requestCapabilityForRoomTimeline",value:function(e){this.requestCapability("org.matrix.msc2762.timeline:".concat(e))}},{key:"requestCapabilityToSendState",value:function(e,t){this.requestCapability(h.WidgetEventCapability.forStateEvent(h.EventDirection.Send,e,t).raw)}},{key:"requestCapabilityToReceiveState",value:function(e,t){this.requestCapability(h.WidgetEventCapability.forStateEvent(h.EventDirection.Receive,e,t).raw)}},{key:"requestCapabilityToSendToDevice",value:function(e){this.requestCapability(h.WidgetEventCapability.forToDeviceEvent(h.EventDirection.Send,e).raw)}},{key:"requestCapabilityToReceiveToDevice",value:function(e){this.requestCapability(h.WidgetEventCapability.forToDeviceEvent(h.EventDirection.Receive,e).raw)}},{key:"requestCapabilityToSendEvent",value:function(e){this.requestCapability(h.WidgetEventCapability.forRoomEvent(h.EventDirection.Send,e).raw)}},{key:"requestCapabilityToReceiveEvent",value:function(e){this.requestCapability(h.WidgetEventCapability.forRoomEvent(h.EventDirection.Receive,e).raw)}},{key:"requestCapabilityToSendMessage",value:function(e){this.requestCapability(h.WidgetEventCapability.forRoomMessageEvent(h.EventDirection.Send,e).raw)}},{key:"requestCapabilityToReceiveMessage",value:function(e){this.requestCapability(h.WidgetEventCapability.forRoomMessageEvent(h.EventDirection.Receive,e).raw)}},{key:"requestOpenIDConnectToken",value:function(){var e=this;return new Promise((function(t,i){e.transport.sendComplete(c.WidgetApiFromWidgetAction.GetOpenIDCredentials,{}).then((function(n){var r=n.response;r.state===d.OpenIDRequestState.Allowed?t(r):r.state===d.OpenIDRequestState.Blocked?i(new Error("User declined to verify their identity")):r.state===d.OpenIDRequestState.PendingUserConfirmation?e.on("action:".concat(c.WidgetApiToWidgetAction.OpenIDCredentials),(function o(s){s.preventDefault();var a=s.detail;a.data.original_request_id===n.requestId&&(a.data.state===d.OpenIDRequestState.Allowed?(t(a.data),e.transport.reply(a,{})):a.data.state===d.OpenIDRequestState.Blocked?(i(new Error("User declined to verify their identity")),e.transport.reply(a,{})):(i(new Error("Invalid state on reply: "+r.state)),e.transport.reply(a,{error:{message:"Invalid state"}})),e.off("action:".concat(c.WidgetApiToWidgetAction.OpenIDCredentials),o))})):i(new Error("Invalid state: "+r.state))})).catch(i)}))}},{key:"updateRequestedCapabilities",value:function(){return this.transport.send(c.WidgetApiFromWidgetAction.MSC2974RenegotiateCapabilities,{capabilities:this.requestedCapabilities}).then()}},{key:"sendContentLoaded",value:function(){return this.transport.send(c.WidgetApiFromWidgetAction.ContentLoaded,{}).then()}},{key:"sendSticker",value:function(e){return this.transport.send(c.WidgetApiFromWidgetAction.SendSticker,e).then()}},{key:"setAlwaysOnScreen",value:function(e){return this.transport.send(c.WidgetApiFromWidgetAction.UpdateAlwaysOnScreen,{value:e}).then((function(e){return e.success}))}},{key:"openModalWidget",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:l.MatrixWidgetType.Custom;return this.transport.send(c.WidgetApiFromWidgetAction.OpenModalWidget,{type:r,url:e,name:t,buttons:i,data:n}).then()}},{key:"closeModalWidget",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.transport.send(c.WidgetApiFromWidgetAction.CloseModalWidget,e).then()}},{key:"sendRoomEvent",value:function(e,t,i){return this.transport.send(c.WidgetApiFromWidgetAction.SendEvent,{type:e,content:t,room_id:i})}},{key:"sendStateEvent",value:function(e,t,i,n){return this.transport.send(c.WidgetApiFromWidgetAction.SendEvent,{type:e,content:i,state_key:t,room_id:n})}},{key:"sendToDevice",value:function(e,t,i){return this.transport.send(c.WidgetApiFromWidgetAction.SendToDevice,{type:e,encrypted:t,messages:i})}},{key:"readRoomEvents",value:function(e,t,i,n){var r={type:e,msgtype:i};return void 0!==t&&(r.limit=t),n&&(n.includes(f.Symbols.AnyRoom)?r.room_ids=f.Symbols.AnyRoom:r.room_ids=n),this.transport.send(c.WidgetApiFromWidgetAction.MSC2876ReadEvents,r).then((function(e){return e.events}))}},{key:"readEventRelations",value:(g=v(p().mark((function e(t,i,n,r,o,a,d,l){var u;return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getClientVersions();case 2:if(e.sent.includes(s.UnstableApiVersion.MSC3869)){e.next=5;break}throw new Error("The read_relations action is not supported by the client.");case 5:return u={event_id:t,rel_type:n,event_type:r,room_id:i,to:d,from:a,limit:o,direction:l},e.abrupt("return",this.transport.send(c.WidgetApiFromWidgetAction.MSC3869ReadRelations,u));case 7:case"end":return e.stop()}}),e,this)}))),function(e,t,i,n,r,o,s,a){return g.apply(this,arguments)})},{key:"readStateEvents",value:function(e,t,i,n){var r={type:e,state_key:void 0===i||i};return void 0!==t&&(r.limit=t),n&&(n.includes(f.Symbols.AnyRoom)?r.room_ids=f.Symbols.AnyRoom:r.room_ids=n),this.transport.send(c.WidgetApiFromWidgetAction.MSC2876ReadEvents,r).then((function(e){return e.events}))}},{key:"setModalButtonEnabled",value:function(e,t){if(e===u.BuiltInModalButtonID.Close)throw new Error("The close button cannot be disabled");return this.transport.send(c.WidgetApiFromWidgetAction.SetModalButtonEnabled,{button:e,enabled:t}).then()}},{key:"navigateTo",value:function(e){if(!e||!e.startsWith("https://matrix.to/#"))throw new Error("Invalid matrix.to URI");return this.transport.send(c.WidgetApiFromWidgetAction.MSC2931Navigate,{uri:e}).then()}},{key:"getTurnServers",value:function(){var e,t=this;return(e=p().mark((function e(){var i,n;return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=function(){var e=v(p().mark((function e(n){return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n.preventDefault(),i(n.detail.data),e.next=4,t.transport.reply(n.detail,{});case 4:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),t.on("action:".concat(c.WidgetApiToWidgetAction.UpdateTurnServers),n),0!==t.turnServerWatchers){e.next=12;break}return e.prev=3,e.next=6,w(t.transport.send(c.WidgetApiFromWidgetAction.WatchTurnServers,{}));case 6:e.next=12;break;case 8:throw e.prev=8,e.t0=e.catch(3),t.off("action:".concat(c.WidgetApiToWidgetAction.UpdateTurnServers),n),e.t0;case 12:t.turnServerWatchers++,e.prev=13;case 14:return e.next=17,w(new Promise((function(e){return i=e})));case 17:return e.next=19,e.sent;case 19:e.next=14;break;case 21:if(e.prev=21,t.off("action:".concat(c.WidgetApiToWidgetAction.UpdateTurnServers),n),t.turnServerWatchers--,0!==t.turnServerWatchers){e.next=27;break}return e.next=27,w(t.transport.send(c.WidgetApiFromWidgetAction.UnwatchTurnServers,{}));case 27:return e.finish(21);case 28:case"end":return e.stop()}}),e,null,[[3,8],[13,,21,28]])})),function(){return new T(e.apply(this,arguments))})()}},{key:"searchUserDirectory",value:(r=v(p().mark((function e(t,i){var n;return p().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.getClientVersions();case 2:if(e.sent.includes(s.UnstableApiVersion.MSC3973)){e.next=5;break}throw new Error("The user_directory_search action is not supported by the client.");case 5:return n={search_term:t,limit:i},e.abrupt("return",this.transport.send(c.WidgetApiFromWidgetAction.MSC3973UserDirectorySearch,n));case 7:case"end":return e.stop()}}),e,this)}))),function(e,t){return r.apply(this,arguments)})},{key:"start",value:function(){var e=this;this.transport.start(),this.getClientVersions().then((function(t){t.includes(s.UnstableApiVersion.MSC2974)&&(e.supportsMSC2974Renegotiate=!0)}))}},{key:"handleMessage",value:function(e){var t=new CustomEvent("action:".concat(e.detail.action),{detail:e.detail,cancelable:!0});if(this.emit("action:".concat(e.detail.action),t),!t.defaultPrevented)switch(e.detail.action){case c.WidgetApiToWidgetAction.SupportedApiVersions:return this.replyVersions(e.detail);case c.WidgetApiToWidgetAction.Capabilities:return this.handleCapabilities(e.detail);case c.WidgetApiToWidgetAction.UpdateVisibility:case c.WidgetApiToWidgetAction.NotifyCapabilities:return this.transport.reply(e.detail,{});default:return this.transport.reply(e.detail,{error:{message:"Unknown or unsupported action: "+e.detail.action}})}}},{key:"replyVersions",value:function(e){this.transport.reply(e,{supported_versions:s.CurrentApiVersions})}},{key:"getClientVersions",value:function(){var e=this;return Array.isArray(this.cachedClientVersions)?Promise.resolve(this.cachedClientVersions):this.transport.send(c.WidgetApiFromWidgetAction.SupportedApiVersions,{}).then((function(t){return e.cachedClientVersions=t.supported_versions,t.supported_versions})).catch((function(e){return console.warn("non-fatal error getting supported client versions: ",e),[]}))}},{key:"handleCapabilities",value:function(e){var t=this;return this.capabilitiesFinished?this.transport.reply(e,{error:{message:"Capability negotiation already completed"}}):this.getClientVersions().then((function(i){return i.includes(s.UnstableApiVersion.MSC2871)?t.once("action:".concat(c.WidgetApiToWidgetAction.NotifyCapabilities),(function(e){t.approvedCapabilities=e.detail.data.approved,t.emit("ready")})):t.emit("ready"),t.capabilitiesFinished=!0,t.transport.reply(e,{capabilities:t.requestedCapabilities})}))}}],i&&m(t.prototype,i),n&&m(t,n),Object.defineProperty(t,"prototype",{writable:!1}),I}(r.EventEmitter);i.WidgetApi=R},{"./Symbols":175,"./interfaces/ApiVersion":179,"./interfaces/GetOpenIDAction":183,"./interfaces/ModalWidgetActions":193,"./interfaces/WidgetApiAction":207,"./interfaces/WidgetApiDirection":208,"./interfaces/WidgetType":211,"./models/WidgetEventCapability":213,"./transport/PostmessageTransport":219,events:105}],177:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.WidgetDriver=void 0;var n=e("..");function r(e,t){for(var i=0;i=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}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 s,a=!0,c=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return a=e.done,e},e:function(e){c=!0,s=e},f:function(){try{a||null==i.return||i.return()}finally{if(c)throw s}}}}function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);i2&&void 0!==arguments[2]?arguments[2]:null;return this.kind===s.Event&&this.direction===e&&this.eventType===t&&("m.room.message"!==this.eventType||null===this.keyStr||this.keyStr===i)}}],r=[{key:"forStateEvent",value:function(t,i,n){i=i.replace(/#/g,"\\#"),n=null!=n?"#".concat(n):"";var r="org.matrix.msc2762.".concat(t,".state_event:").concat(i).concat(n);return e.findEventCapabilities([r])[0]}},{key:"forToDeviceEvent",value:function(t,i){var n="org.matrix.msc3819.".concat(t,".to_device:").concat(i);return e.findEventCapabilities([n])[0]}},{key:"forRoomEvent",value:function(t,i){var n="org.matrix.msc2762.".concat(t,".event:").concat(i);return e.findEventCapabilities([n])[0]}},{key:"forRoomMessageEvent",value:function(t,i){i=null==i?"":i;var n="org.matrix.msc2762.".concat(t,".event:m.room.message#").concat(i);return e.findEventCapabilities([n])[0]}},{key:"findEventCapabilities",value:function(t){var i,r=[],o=n(t);try{for(o.s();!(i=o.n()).done;){var c=i.value,d=null,l=void 0,u=null;if(c.startsWith("org.matrix.msc2762.send.event:")?(d=a.Send,u=s.Event,l=c.substring("org.matrix.msc2762.send.event:".length)):c.startsWith("org.matrix.msc2762.send.state_event:")?(d=a.Send,u=s.State,l=c.substring("org.matrix.msc2762.send.state_event:".length)):c.startsWith("org.matrix.msc3819.send.to_device:")?(d=a.Send,u=s.ToDevice,l=c.substring("org.matrix.msc3819.send.to_device:".length)):c.startsWith("org.matrix.msc2762.receive.event:")?(d=a.Receive,u=s.Event,l=c.substring("org.matrix.msc2762.receive.event:".length)):c.startsWith("org.matrix.msc2762.receive.state_event:")?(d=a.Receive,u=s.State,l=c.substring("org.matrix.msc2762.receive.state_event:".length)):c.startsWith("org.matrix.msc3819.receive.to_device:")&&(d=a.Receive,u=s.ToDevice,l=c.substring("org.matrix.msc3819.receive.to_device:".length)),null!==d&&null!==u&&void 0!==l){var h=l.startsWith("m.room.message#")||u===s.State,f=null;if(l.includes("#")&&h){var p=l.split("#"),g=p.findIndex((function(e){return!e.endsWith("\\")}));l=p.slice(0,g+1).map((function(e){return e.endsWith("\\")?e.substring(0,e.length-1):e})).join("#"),f=p.slice(g+1).join("#")}r.push(new e(d,l,u,f,c))}}}catch(e){o.e(e)}finally{o.f()}return r}}],i&&o(t.prototype,i),r&&o(t,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();i.WidgetEventCapability=c},{}],214:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.WidgetParser=void 0;var n=e("./Widget"),r=e("./validation/url");function o(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=function(e,t){if(!e)return;if("string"==typeof e)return s(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);"Object"===i&&e.constructor&&(i=e.constructor.name);if("Map"===i||"Set"===i)return Array.from(e);if("Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i))return s(e,t)}(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var n=0,r=function(){};return{s:r,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:r}}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 o,a=!0,c=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return a=e.done,e},e:function(e){c=!0,o=e},f:function(){try{a||null==i.return||i.return()}finally{if(c)throw o}}}}function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);i=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:o}}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 s,a=!0,c=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return a=e.done,e},e:function(e){c=!0,s=e},f:function(){try{a||null==i.return||i.return()}finally{if(c)throw s}}}}function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,n=new Array(t);i>>32-t}function d(e,t,i,n,r,o,s){return c(e+(t&i|~t&n)+r+o|0,s)+t|0}function l(e,t,i,n,r,o,s){return c(e+(t&n|i&~n)+r+o|0,s)+t|0}function u(e,t,i,n,r,o,s){return c(e+(t^i^n)+r+o|0,s)+t|0}function h(e,t,i,n,r,o,s){return c(e+(i^(t|~n))+r+o|0,s)+t|0}n(a,r),a.prototype._update=function(){for(var e=s,t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);var i=this._a,n=this._b,r=this._c,o=this._d;i=d(i,n,r,o,e[0],3614090360,7),o=d(o,i,n,r,e[1],3905402710,12),r=d(r,o,i,n,e[2],606105819,17),n=d(n,r,o,i,e[3],3250441966,22),i=d(i,n,r,o,e[4],4118548399,7),o=d(o,i,n,r,e[5],1200080426,12),r=d(r,o,i,n,e[6],2821735955,17),n=d(n,r,o,i,e[7],4249261313,22),i=d(i,n,r,o,e[8],1770035416,7),o=d(o,i,n,r,e[9],2336552879,12),r=d(r,o,i,n,e[10],4294925233,17),n=d(n,r,o,i,e[11],2304563134,22),i=d(i,n,r,o,e[12],1804603682,7),o=d(o,i,n,r,e[13],4254626195,12),r=d(r,o,i,n,e[14],2792965006,17),i=l(i,n=d(n,r,o,i,e[15],1236535329,22),r,o,e[1],4129170786,5),o=l(o,i,n,r,e[6],3225465664,9),r=l(r,o,i,n,e[11],643717713,14),n=l(n,r,o,i,e[0],3921069994,20),i=l(i,n,r,o,e[5],3593408605,5),o=l(o,i,n,r,e[10],38016083,9),r=l(r,o,i,n,e[15],3634488961,14),n=l(n,r,o,i,e[4],3889429448,20),i=l(i,n,r,o,e[9],568446438,5),o=l(o,i,n,r,e[14],3275163606,9),r=l(r,o,i,n,e[3],4107603335,14),n=l(n,r,o,i,e[8],1163531501,20),i=l(i,n,r,o,e[13],2850285829,5),o=l(o,i,n,r,e[2],4243563512,9),r=l(r,o,i,n,e[7],1735328473,14),i=u(i,n=l(n,r,o,i,e[12],2368359562,20),r,o,e[5],4294588738,4),o=u(o,i,n,r,e[8],2272392833,11),r=u(r,o,i,n,e[11],1839030562,16),n=u(n,r,o,i,e[14],4259657740,23),i=u(i,n,r,o,e[1],2763975236,4),o=u(o,i,n,r,e[4],1272893353,11),r=u(r,o,i,n,e[7],4139469664,16),n=u(n,r,o,i,e[10],3200236656,23),i=u(i,n,r,o,e[13],681279174,4),o=u(o,i,n,r,e[0],3936430074,11),r=u(r,o,i,n,e[3],3572445317,16),n=u(n,r,o,i,e[6],76029189,23),i=u(i,n,r,o,e[9],3654602809,4),o=u(o,i,n,r,e[12],3873151461,11),r=u(r,o,i,n,e[15],530742520,16),i=h(i,n=u(n,r,o,i,e[2],3299628645,23),r,o,e[0],4096336452,6),o=h(o,i,n,r,e[7],1126891415,10),r=h(r,o,i,n,e[14],2878612391,15),n=h(n,r,o,i,e[5],4237533241,21),i=h(i,n,r,o,e[12],1700485571,6),o=h(o,i,n,r,e[3],2399980690,10),r=h(r,o,i,n,e[10],4293915773,15),n=h(n,r,o,i,e[1],2240044497,21),i=h(i,n,r,o,e[8],1873313359,6),o=h(o,i,n,r,e[15],4264355552,10),r=h(r,o,i,n,e[6],2734768916,15),n=h(n,r,o,i,e[13],1309151649,21),i=h(i,n,r,o,e[4],4149444226,6),o=h(o,i,n,r,e[11],3174756917,10),r=h(r,o,i,n,e[2],718787259,15),n=h(n,r,o,i,e[9],3951481745,21),this._a=this._a+i|0,this._b=this._b+n|0,this._c=this._c+r|0,this._d=this._d+o|0},a.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=o.allocUnsafe(16);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e},t.exports=a},{"hash-base":116,inherits:146,"safe-buffer":250}],222:[function(e,t,i){var n=e("bn.js"),r=e("brorand");function o(e){this.rand=e||new r.Rand}t.exports=o,o.create=function(e){return new o(e)},o.prototype._randbelow=function(e){var t=e.bitLength(),i=Math.ceil(t/8);do{var r=new n(this.rand.generate(i))}while(r.cmp(e)>=0);return r},o.prototype._randrange=function(e,t){var i=t.sub(e);return e.add(this._randbelow(i))},o.prototype.test=function(e,t,i){var r=e.bitLength(),o=n.mont(e),s=new n(1).toRed(o);t||(t=Math.max(1,r/48|0));for(var a=e.subn(1),c=0;!a.testn(c);c++);for(var d=e.shrn(c),l=a.toRed(o);t>0;t--){var u=this._randrange(new n(2),a);i&&i(u);var h=u.toRed(o).redPow(d);if(0!==h.cmp(s)&&0!==h.cmp(l)){for(var f=1;f0;t--){var l=this._randrange(new n(2),s),u=e.gcd(l);if(0!==u.cmpn(1))return u;var h=l.toRed(r).redPow(c);if(0!==h.cmp(o)&&0!==h.cmp(d)){for(var f=1;f>8,s=255&r;o?i.push(o,s):i.push(s)}return i},n.zero2=r,n.toHex=o,n.encode=function(e,t){return"hex"===t?o(e):e}},{}],225:[function(e,t,i){"use strict";const n=e("retry"),r=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class o extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const s=(e,t)=>new Promise(((i,s)=>{t={onFailedAttempt:()=>{},retries:10,...t};const a=n.operation(t);a.attempt((async n=>{try{i(await e(n))}catch(e){if(!(e instanceof Error))return void s(new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`));if(e instanceof o)a.stop(),s(e.originalError);else if(e instanceof TypeError&&(c=e.message,!r.includes(c)))a.stop(),s(e);else{((e,t,i)=>{const n=i.retries-(t-1);e.attemptNumber=t,e.retriesLeft=n})(e,n,t);try{await t.onFailedAttempt(e)}catch(e){return void s(e)}a.retry(e)||s(a.mainError())}}var c}))}));t.exports=s,t.exports.default=s,t.exports.AbortError=o},{retry:246}],226:[function(e,t,i){t.exports={"2.16.840.1.101.3.4.1.1":"aes-128-ecb","2.16.840.1.101.3.4.1.2":"aes-128-cbc","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}},{}],227:[function(e,t,i){"use strict";var n=e("asn1.js");i.certificate=e("./certificate");var r=n.define("RSAPrivateKey",(function(){this.seq().obj(this.key("version").int(),this.key("modulus").int(),this.key("publicExponent").int(),this.key("privateExponent").int(),this.key("prime1").int(),this.key("prime2").int(),this.key("exponent1").int(),this.key("exponent2").int(),this.key("coefficient").int())}));i.RSAPrivateKey=r;var o=n.define("RSAPublicKey",(function(){this.seq().obj(this.key("modulus").int(),this.key("publicExponent").int())}));i.RSAPublicKey=o;var s=n.define("SubjectPublicKeyInfo",(function(){this.seq().obj(this.key("algorithm").use(a),this.key("subjectPublicKey").bitstr())}));i.PublicKey=s;var a=n.define("AlgorithmIdentifier",(function(){this.seq().obj(this.key("algorithm").objid(),this.key("none").null_().optional(),this.key("curve").objid().optional(),this.key("params").seq().obj(this.key("p").int(),this.key("q").int(),this.key("g").int()).optional())})),c=n.define("PrivateKeyInfo",(function(){this.seq().obj(this.key("version").int(),this.key("algorithm").use(a),this.key("subjectPrivateKey").octstr())}));i.PrivateKey=c;var d=n.define("EncryptedPrivateKeyInfo",(function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("id").objid(),this.key("decrypt").seq().obj(this.key("kde").seq().obj(this.key("id").objid(),this.key("kdeparams").seq().obj(this.key("salt").octstr(),this.key("iters").int())),this.key("cipher").seq().obj(this.key("algo").objid(),this.key("iv").octstr()))),this.key("subjectPrivateKey").octstr())}));i.EncryptedPrivateKey=d;var l=n.define("DSAPrivateKey",(function(){this.seq().obj(this.key("version").int(),this.key("p").int(),this.key("q").int(),this.key("g").int(),this.key("pub_key").int(),this.key("priv_key").int())}));i.DSAPrivateKey=l,i.DSAparam=n.define("DSAparam",(function(){this.int()}));var u=n.define("ECPrivateKey",(function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").optional().explicit(0).use(h),this.key("publicKey").optional().explicit(1).bitstr())}));i.ECPrivateKey=u;var h=n.define("ECParameters",(function(){this.choice({namedCurve:this.objid()})}));i.signature=n.define("signature",(function(){this.seq().obj(this.key("r").int(),this.key("s").int())}))},{"./certificate":228,"asn1.js":2}],228:[function(e,t,i){"use strict";var n=e("asn1.js"),r=n.define("Time",(function(){this.choice({utcTime:this.utctime(),generalTime:this.gentime()})})),o=n.define("AttributeTypeValue",(function(){this.seq().obj(this.key("type").objid(),this.key("value").any())})),s=n.define("AlgorithmIdentifier",(function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional(),this.key("curve").objid().optional())})),a=n.define("SubjectPublicKeyInfo",(function(){this.seq().obj(this.key("algorithm").use(s),this.key("subjectPublicKey").bitstr())})),c=n.define("RelativeDistinguishedName",(function(){this.setof(o)})),d=n.define("RDNSequence",(function(){this.seqof(c)})),l=n.define("Name",(function(){this.choice({rdnSequence:this.use(d)})})),u=n.define("Validity",(function(){this.seq().obj(this.key("notBefore").use(r),this.key("notAfter").use(r))})),h=n.define("Extension",(function(){this.seq().obj(this.key("extnID").objid(),this.key("critical").bool().def(!1),this.key("extnValue").octstr())})),f=n.define("TBSCertificate",(function(){this.seq().obj(this.key("version").explicit(0).int().optional(),this.key("serialNumber").int(),this.key("signature").use(s),this.key("issuer").use(l),this.key("validity").use(u),this.key("subject").use(l),this.key("subjectPublicKeyInfo").use(a),this.key("issuerUniqueID").implicit(1).bitstr().optional(),this.key("subjectUniqueID").implicit(2).bitstr().optional(),this.key("extensions").explicit(3).seqof(h).optional())})),p=n.define("X509Certificate",(function(){this.seq().obj(this.key("tbsCertificate").use(f),this.key("signatureAlgorithm").use(s),this.key("signatureValue").bitstr())}));t.exports=p},{"asn1.js":2}],229:[function(e,t,i){var n=/Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m,r=/^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m,o=/^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m,s=e("evp_bytestokey"),a=e("browserify-aes"),c=e("safe-buffer").Buffer;t.exports=function(e,t){var i,d=e.toString(),l=d.match(n);if(l){var u="aes"+l[1],h=c.from(l[2],"hex"),f=c.from(l[3].replace(/[\r\n]/g,""),"base64"),p=s(t,h.slice(0,8),parseInt(l[1],10)).key,g=[],v=a.createDecipheriv(u,p,h);g.push(v.update(f)),g.push(v.final()),i=c.concat(g)}else{var m=d.match(o);i=c.from(m[2].replace(/[\r\n]/g,""),"base64")}return{tag:d.match(r)[1],data:i}}},{"browserify-aes":23,evp_bytestokey:106,"safe-buffer":250}],230:[function(e,t,i){var n=e("./asn1"),r=e("./aesid.json"),o=e("./fixProc"),s=e("browserify-aes"),a=e("pbkdf2"),c=e("safe-buffer").Buffer;function d(e){var t;"object"!=typeof e||c.isBuffer(e)||(t=e.passphrase,e=e.key),"string"==typeof e&&(e=c.from(e));var i,d,l=o(e,t),u=l.tag,h=l.data;switch(u){case"CERTIFICATE":d=n.certificate.decode(h,"der").tbsCertificate.subjectPublicKeyInfo;case"PUBLIC KEY":switch(d||(d=n.PublicKey.decode(h,"der")),i=d.algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return n.RSAPublicKey.decode(d.subjectPublicKey.data,"der");case"1.2.840.10045.2.1":return d.subjectPrivateKey=d.subjectPublicKey,{type:"ec",data:d};case"1.2.840.10040.4.1":return d.algorithm.params.pub_key=n.DSAparam.decode(d.subjectPublicKey.data,"der"),{type:"dsa",data:d.algorithm.params};default:throw new Error("unknown key id "+i)}case"ENCRYPTED PRIVATE KEY":h=function(e,t){var i=e.algorithm.decrypt.kde.kdeparams.salt,n=parseInt(e.algorithm.decrypt.kde.kdeparams.iters.toString(),10),o=r[e.algorithm.decrypt.cipher.algo.join(".")],d=e.algorithm.decrypt.cipher.iv,l=e.subjectPrivateKey,u=parseInt(o.split("-")[1],10)/8,h=a.pbkdf2Sync(t,i,n,u,"sha1"),f=s.createDecipheriv(o,h,d),p=[];return p.push(f.update(l)),p.push(f.final()),c.concat(p)}(h=n.EncryptedPrivateKey.decode(h,"der"),t);case"PRIVATE KEY":switch(i=(d=n.PrivateKey.decode(h,"der")).algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return n.RSAPrivateKey.decode(d.subjectPrivateKey,"der");case"1.2.840.10045.2.1":return{curve:d.algorithm.curve,privateKey:n.ECPrivateKey.decode(d.subjectPrivateKey,"der").privateKey};case"1.2.840.10040.4.1":return d.algorithm.params.priv_key=n.DSAparam.decode(d.subjectPrivateKey,"der"),{type:"dsa",params:d.algorithm.params};default:throw new Error("unknown key id "+i)}case"RSA PUBLIC KEY":return n.RSAPublicKey.decode(h,"der");case"RSA PRIVATE KEY":return n.RSAPrivateKey.decode(h,"der");case"DSA PRIVATE KEY":return{type:"dsa",params:n.DSAPrivateKey.decode(h,"der")};case"EC PRIVATE KEY":return{curve:(h=n.ECPrivateKey.decode(h,"der")).parameters.value,privateKey:h.privateKey};default:throw new Error("unknown key type "+u)}}t.exports=d,d.signature=n.signature},{"./aesid.json":226,"./asn1":227,"./fixProc":229,"browserify-aes":23,pbkdf2:231,"safe-buffer":250}],231:[function(e,t,i){i.pbkdf2=e("./lib/async"),i.pbkdf2Sync=e("./lib/sync")},{"./lib/async":232,"./lib/sync":235}],232:[function(e,t,i){(function(i){(function(){var n,r,o=e("safe-buffer").Buffer,s=e("./precondition"),a=e("./default-encoding"),c=e("./sync"),d=e("./to-buffer"),l=i.crypto&&i.crypto.subtle,u={sha:"SHA-1","sha-1":"SHA-1",sha1:"SHA-1",sha256:"SHA-256","sha-256":"SHA-256",sha384:"SHA-384","sha-384":"SHA-384","sha-512":"SHA-512",sha512:"SHA-512"},h=[];function f(){return r||(r=i.process&&i.process.nextTick?i.process.nextTick:i.queueMicrotask?i.queueMicrotask:i.setImmediate?i.setImmediate:i.setTimeout)}function p(e,t,i,n,r){return l.importKey("raw",e,{name:"PBKDF2"},!1,["deriveBits"]).then((function(e){return l.deriveBits({name:"PBKDF2",salt:t,iterations:i,hash:{name:r}},e,n<<3)})).then((function(e){return o.from(e)}))}t.exports=function(e,t,r,g,v,m){"function"==typeof v&&(m=v,v=void 0);var y=u[(v=v||"sha1").toLowerCase()];if(y&&"function"==typeof i.Promise){if(s(r,g),e=d(e,a,"Password"),t=d(t,a,"Salt"),"function"!=typeof m)throw new Error("No callback provided to pbkdf2");!function(e,t){e.then((function(e){f()((function(){t(null,e)}))}),(function(e){f()((function(){t(e)}))}))}(function(e){if(i.process&&!i.process.browser)return Promise.resolve(!1);if(!l||!l.importKey||!l.deriveBits)return Promise.resolve(!1);if(void 0!==h[e])return h[e];var t=p(n=n||o.alloc(8),n,10,128,e).then((function(){return!0})).catch((function(){return!1}));return h[e]=t,t}(y).then((function(i){return i?p(e,t,r,g,y):c(e,t,r,g,v)})),m)}else f()((function(){var i;try{i=c(e,t,r,g,v)}catch(e){return m(e)}m(null,i)}))}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./default-encoding":233,"./precondition":234,"./sync":235,"./to-buffer":236,"safe-buffer":250}],233:[function(e,t,i){(function(e,i){(function(){var n;if(i.process&&i.process.browser)n="utf-8";else if(i.process&&i.process.version){n=parseInt(e.version.split(".")[0].slice(1),10)>=6?"utf-8":"binary"}else n="utf-8";t.exports=n}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:237}],234:[function(e,t,i){var n=Math.pow(2,30)-1;t.exports=function(e,t){if("number"!=typeof e)throw new TypeError("Iterations not a number");if(e<0)throw new TypeError("Bad iterations");if("number"!=typeof t)throw new TypeError("Key length not a number");if(t<0||t>n||t!=t)throw new TypeError("Bad key length")}},{}],235:[function(e,t,i){var n=e("create-hash/md5"),r=e("ripemd160"),o=e("sha.js"),s=e("safe-buffer").Buffer,a=e("./precondition"),c=e("./default-encoding"),d=e("./to-buffer"),l=s.alloc(128),u={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,rmd160:20,ripemd160:20};function h(e,t,i){var a=function(e){function t(t){return o(e).update(t).digest()}function i(e){return(new r).update(e).digest()}return"rmd160"===e||"ripemd160"===e?i:"md5"===e?n:t}(e),c="sha512"===e||"sha384"===e?128:64;t.length>c?t=a(t):t.length1)for(var i=1;ip||new s(t).cmp(f.modulus)>=0)throw new Error("decryption error");h=i?d(new s(t),f):a(t,f);var g=l.alloc(p-h.length);if(h=l.concat([g,h],p),4===u)return function(e,t){var i=e.modulus.byteLength(),n=c("sha1").update(l.alloc(0)).digest(),s=n.length;if(0!==t[0])throw new Error("decryption error");var a=t.slice(1,s+1),d=t.slice(s+1),u=o(a,r(d,s)),h=o(d,r(u,i-s-1));if(function(e,t){e=l.from(e),t=l.from(t);var i=0,n=e.length;e.length!==t.length&&(i++,n=Math.min(e.length,t.length));var r=-1;for(;++r=t.length){o++;break}var s=t.slice(2,r-1);("0002"!==n.toString("hex")&&!i||"0001"!==n.toString("hex")&&i)&&o++;s.length<8&&o++;if(o)throw new Error("decryption error");return t.slice(r)}(0,h,i);if(3===u)return h;throw new Error("unknown padding")}},{"./mgf":239,"./withPublic":242,"./xor":243,"bn.js":18,"browserify-rsa":41,"create-hash":74,"parse-asn1":230,"safe-buffer":250}],241:[function(e,t,i){var n=e("parse-asn1"),r=e("randombytes"),o=e("create-hash"),s=e("./mgf"),a=e("./xor"),c=e("bn.js"),d=e("./withPublic"),l=e("browserify-rsa"),u=e("safe-buffer").Buffer;t.exports=function(e,t,i){var h;h=e.padding?e.padding:i?1:4;var f,p=n(e);if(4===h)f=function(e,t){var i=e.modulus.byteLength(),n=t.length,d=o("sha1").update(u.alloc(0)).digest(),l=d.length,h=2*l;if(n>i-h-2)throw new Error("message too long");var f=u.alloc(i-n-h-2),p=i-l-1,g=r(l),v=a(u.concat([d,f,u.alloc(1,1),t],p),s(g,p)),m=a(g,s(v,l));return new c(u.concat([u.alloc(1),m,v],i))}(p,t);else if(1===h)f=function(e,t,i){var n,o=t.length,s=e.modulus.byteLength();if(o>s-11)throw new Error("message too long");n=i?u.alloc(s-o-3,255):function(e){var t,i=u.allocUnsafe(e),n=0,o=r(2*e),s=0;for(;n=0)throw new Error("data too long for modulus")}return i?l(f,p):d(f,p)}},{"./mgf":239,"./withPublic":242,"./xor":243,"bn.js":18,"browserify-rsa":41,"create-hash":74,"parse-asn1":230,randombytes:244,"safe-buffer":250}],242:[function(e,t,i){var n=e("bn.js"),r=e("safe-buffer").Buffer;t.exports=function(e,t){return r.from(e.toRed(n.mont(t.modulus)).redPow(new n(t.publicExponent)).fromRed().toArray())}},{"bn.js":18,"safe-buffer":250}],243:[function(e,t,i){t.exports=function(e,t){for(var i=e.length,n=-1;++no)throw new RangeError("requested too many random bytes");var n=s.allocUnsafe(e);if(e>0)if(e>r)for(var c=0;cl||e<0)throw new TypeError("offset must be a uint32");if(e>c||e>t)throw new RangeError("offset out of range")}function h(e,t,i){if("number"!=typeof e||e!=e)throw new TypeError("size must be a number");if(e>l||e<0)throw new TypeError("size must be a uint32");if(e+t>i||e>c)throw new RangeError("buffer too small")}function f(e,i,n,r){if(t.browser){var o=e.buffer,a=new Uint8Array(o,i,n);return d.getRandomValues(a),r?void t.nextTick((function(){r(null,e)})):e}if(!r)return s(n).copy(e,i),e;s(n,(function(t,n){if(t)return r(t);n.copy(e,i),r(null,e)}))}d&&d.getRandomValues||!t.browser?(i.randomFill=function(e,t,i,r){if(!(a.isBuffer(e)||e instanceof n.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');if("function"==typeof t)r=t,t=0,i=e.length;else if("function"==typeof i)r=i,i=e.length-t;else if("function"!=typeof r)throw new TypeError('"cb" argument must be a function');return u(t,e.length),h(i,t,e.length),f(e,t,i,r)},i.randomFillSync=function(e,t,i){void 0===t&&(t=0);if(!(a.isBuffer(e)||e instanceof n.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');u(t,e.length),void 0===i&&(i=e.length-t);return h(i,t,e.length),f(e,t,i)}):(i.randomFill=r,i.randomFillSync=r)}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:237,randombytes:244,"safe-buffer":250}],246:[function(e,t,i){t.exports=e("./lib/retry")},{"./lib/retry":247}],247:[function(e,t,i){var n=e("./retry_operation");i.operation=function(e){var t=i.timeouts(e);return new n(t,{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})},i.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var i in e)t[i]=e[i];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],r=0;r=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var i=this._timeouts.shift();if(void 0===i){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),i=this._cachedTimeouts.slice(-1)}var n=this;return this._timer=setTimeout((function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout((function(){n._operationTimeoutCb(n._attempts)}),n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)}),i),this._options.unref&&this._timer.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var i=this;this._operationTimeoutCb&&(this._timeout=setTimeout((function(){i._operationTimeoutCb()}),i._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},n.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,i=0,n=0;n=i&&(t=r,i=s)}return t}},{}],249:[function(e,t,i){"use strict";var n=e("buffer").Buffer,r=e("inherits"),o=e("hash-base"),s=new Array(16),a=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],c=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],d=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],l=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],u=[0,1518500249,1859775393,2400959708,2840853838],h=[1352829926,1548603684,1836072691,2053994217,0];function f(){o.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function p(e,t){return e<>>32-t}function g(e,t,i,n,r,o,s,a){return p(e+(t^i^n)+o+s|0,a)+r|0}function v(e,t,i,n,r,o,s,a){return p(e+(t&i|~t&n)+o+s|0,a)+r|0}function m(e,t,i,n,r,o,s,a){return p(e+((t|~i)^n)+o+s|0,a)+r|0}function y(e,t,i,n,r,o,s,a){return p(e+(t&n|i&~n)+o+s|0,a)+r|0}function b(e,t,i,n,r,o,s,a){return p(e+(t^(i|~n))+o+s|0,a)+r|0}r(f,o),f.prototype._update=function(){for(var e=s,t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);for(var i=0|this._a,n=0|this._b,r=0|this._c,o=0|this._d,f=0|this._e,S=0|this._a,_=0|this._b,E=0|this._c,w=0|this._d,T=0|this._e,I=0;I<80;I+=1){var R,M;I<16?(R=g(i,n,r,o,f,e[a[I]],u[0],d[I]),M=b(S,_,E,w,T,e[c[I]],h[0],l[I])):I<32?(R=v(i,n,r,o,f,e[a[I]],u[1],d[I]),M=y(S,_,E,w,T,e[c[I]],h[1],l[I])):I<48?(R=m(i,n,r,o,f,e[a[I]],u[2],d[I]),M=m(S,_,E,w,T,e[c[I]],h[2],l[I])):I<64?(R=y(i,n,r,o,f,e[a[I]],u[3],d[I]),M=v(S,_,E,w,T,e[c[I]],h[3],l[I])):(R=b(i,n,r,o,f,e[a[I]],u[4],d[I]),M=g(S,_,E,w,T,e[c[I]],h[4],l[I])),i=f,f=o,o=p(r,10),r=n,n=R,S=T,T=w,w=p(E,10),E=_,_=M}var k=this._b+r+w|0;this._b=this._c+o+T|0,this._c=this._d+f+S|0,this._d=this._e+i+_|0,this._e=this._a+n+E|0,this._a=k},f.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=n.alloc?n.alloc(20):new n(20);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e.writeInt32LE(this._e,16),e},t.exports=f},{buffer:68,"hash-base":116,inherits:146}],250:[function(e,t,i){ -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -var n=e("buffer"),r=n.Buffer;function o(e,t){for(var i in e)t[i]=e[i]}function s(e,t,i){return r(e,t,i)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?t.exports=n:(o(n,i),i.Buffer=s),s.prototype=Object.create(r.prototype),o(r,s),s.from=function(e,t,i){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,i)},s.alloc=function(e,t,i){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=r(e);return void 0!==t?"string"==typeof i?n.fill(t,i):n.fill(t):n.fill(0),n},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},{buffer:68}],251:[function(e,t,i){(function(i){(function(){"use strict";var n,r=e("buffer"),o=r.Buffer,s={};for(n in r)r.hasOwnProperty(n)&&"SlowBuffer"!==n&&"Buffer"!==n&&(s[n]=r[n]);var a=s.Buffer={};for(n in o)o.hasOwnProperty(n)&&"allocUnsafe"!==n&&"allocUnsafeSlow"!==n&&(a[n]=o[n]);if(s.Buffer.prototype=o.prototype,a.from&&a.from!==Uint8Array.from||(a.from=function(e,t,i){if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type '+typeof e);if(e&&void 0===e.length)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);return o(e,t,i)}),a.alloc||(a.alloc=function(e,t,i){if("number"!=typeof e)throw new TypeError('The "size" argument must be of type number. Received type '+typeof e);if(e<0||e>=2*(1<<30))throw new RangeError('The value "'+e+'" is invalid for option "size"');var n=o(e);return t&&0!==t.length?"string"==typeof i?n.fill(t,i):n.fill(t):n.fill(0),n}),!s.kStringMaxLength)try{s.kStringMaxLength=i.binding("buffer").kStringMaxLength}catch(e){}s.constants||(s.constants={MAX_LENGTH:s.kMaxLength},s.kStringMaxLength&&(s.constants.MAX_STRING_LENGTH=s.kStringMaxLength)),t.exports=s}).call(this)}).call(this,e("_process"))},{_process:237,buffer:68}],252:[function(e,t,i){var n=t.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(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.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(e){return null!=e.address?"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(e){return null!=e.subtype?"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(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"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"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%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(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{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(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(t+=":%s")),t}},{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(e){return null!=e.maxMessageSize?"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(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg: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(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.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(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{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(n).forEach((function(e){n[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))},{}],253:[function(e,t,i){var n=e("./parser"),r=e("./writer");i.write=r,i.parse=n.parse,i.parseParams=n.parseParams,i.parseFmtpConfig=n.parseFmtpConfig,i.parsePayloads=n.parsePayloads,i.parseRemoteCandidates=n.parseRemoteCandidates,i.parseImageAttributes=n.parseImageAttributes,i.parseSimulcastStreamList=n.parseSimulcastStreamList},{"./parser":254,"./writer":255}],254:[function(e,t,i){var n=function(e){return String(Number(e))===e?Number(e):e},r=function(e,t,i){var r=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:r&&!t[e.name]&&(t[e.name]={});var o=e.push?{}:r?t[e.name]:t;!function(e,t,i,r){if(r&&!i)t[r]=n(e[1]);else for(var o=0;o1&&(e[i[0]]=void 0),e};i.parseParams=function(e){return e.split(/;\s?/).reduce(a,{})},i.parseFmtpConfig=i.parseParams,i.parsePayloads=function(e){return e.toString().split(" ").map(Number)},i.parseRemoteCandidates=function(e){for(var t=[],i=e.split(" ").map(n),r=0;r=n)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},s=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var r=0;r=this._finalSize&&(this._update(this._block),this._block.fill(0));var i=8*this._len;if(i<=4294967295)this._block.writeUInt32BE(i,this._blockSize-4);else{var n=(4294967295&i)>>>0,r=(i-n)/4294967296;this._block.writeUInt32BE(r,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return e?o.toString(e):o},r.prototype._update=function(){throw new Error("_update must be implemented by subclass")},t.exports=r},{"safe-buffer":250}],257:[function(e,t,i){(i=t.exports=function(e){e=e.toLowerCase();var t=i[e];if(!t)throw new Error(e+" is not supported (we accept pull requests)");return new t}).sha=e("./sha"),i.sha1=e("./sha1"),i.sha224=e("./sha224"),i.sha256=e("./sha256"),i.sha384=e("./sha384"),i.sha512=e("./sha512")},{"./sha":258,"./sha1":259,"./sha224":260,"./sha256":261,"./sha384":262,"./sha512":263}],258:[function(e,t,i){var n=e("inherits"),r=e("./hash"),o=e("safe-buffer").Buffer,s=[1518500249,1859775393,-1894007588,-899497514],a=new Array(80);function c(){this.init(),this._w=a,r.call(this,64,56)}function d(e){return e<<30|e>>>2}function l(e,t,i,n){return 0===e?t&i|~t&n:2===e?t&i|t&n|i&n:t^i^n}n(c,r),c.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},c.prototype._update=function(e){for(var t,i=this._w,n=0|this._a,r=0|this._b,o=0|this._c,a=0|this._d,c=0|this._e,u=0;u<16;++u)i[u]=e.readInt32BE(4*u);for(;u<80;++u)i[u]=i[u-3]^i[u-8]^i[u-14]^i[u-16];for(var h=0;h<80;++h){var f=~~(h/20),p=0|((t=n)<<5|t>>>27)+l(f,r,o,a)+c+i[h]+s[f];c=a,a=o,o=d(r),r=n,n=p}this._a=n+this._a|0,this._b=r+this._b|0,this._c=o+this._c|0,this._d=a+this._d|0,this._e=c+this._e|0},c.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},t.exports=c},{"./hash":256,inherits:146,"safe-buffer":250}],259:[function(e,t,i){var n=e("inherits"),r=e("./hash"),o=e("safe-buffer").Buffer,s=[1518500249,1859775393,-1894007588,-899497514],a=new Array(80);function c(){this.init(),this._w=a,r.call(this,64,56)}function d(e){return e<<5|e>>>27}function l(e){return e<<30|e>>>2}function u(e,t,i,n){return 0===e?t&i|~t&n:2===e?t&i|t&n|i&n:t^i^n}n(c,r),c.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},c.prototype._update=function(e){for(var t,i=this._w,n=0|this._a,r=0|this._b,o=0|this._c,a=0|this._d,c=0|this._e,h=0;h<16;++h)i[h]=e.readInt32BE(4*h);for(;h<80;++h)i[h]=(t=i[h-3]^i[h-8]^i[h-14]^i[h-16])<<1|t>>>31;for(var f=0;f<80;++f){var p=~~(f/20),g=d(n)+u(p,r,o,a)+c+i[f]+s[p]|0;c=a,a=o,o=l(r),r=n,n=g}this._a=n+this._a|0,this._b=r+this._b|0,this._c=o+this._c|0,this._d=a+this._d|0,this._e=c+this._e|0},c.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},t.exports=c},{"./hash":256,inherits:146,"safe-buffer":250}],260:[function(e,t,i){var n=e("inherits"),r=e("./sha256"),o=e("./hash"),s=e("safe-buffer").Buffer,a=new Array(64);function c(){this.init(),this._w=a,o.call(this,64,56)}n(c,r),c.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},c.prototype._hash=function(){var e=s.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e},t.exports=c},{"./hash":256,"./sha256":261,inherits:146,"safe-buffer":250}],261:[function(e,t,i){var n=e("inherits"),r=e("./hash"),o=e("safe-buffer").Buffer,s=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],a=new Array(64);function c(){this.init(),this._w=a,r.call(this,64,56)}function d(e,t,i){return i^e&(t^i)}function l(e,t,i){return e&t|i&(e|t)}function u(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function h(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function f(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}n(c,r),c.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},c.prototype._update=function(e){for(var t,i=this._w,n=0|this._a,r=0|this._b,o=0|this._c,a=0|this._d,c=0|this._e,p=0|this._f,g=0|this._g,v=0|this._h,m=0;m<16;++m)i[m]=e.readInt32BE(4*m);for(;m<64;++m)i[m]=0|(((t=i[m-2])>>>17|t<<15)^(t>>>19|t<<13)^t>>>10)+i[m-7]+f(i[m-15])+i[m-16];for(var y=0;y<64;++y){var b=v+h(c)+d(c,p,g)+s[y]+i[y]|0,S=u(n)+l(n,r,o)|0;v=g,g=p,p=c,c=a+b|0,a=o,o=r,r=n,n=b+S|0}this._a=n+this._a|0,this._b=r+this._b|0,this._c=o+this._c|0,this._d=a+this._d|0,this._e=c+this._e|0,this._f=p+this._f|0,this._g=g+this._g|0,this._h=v+this._h|0},c.prototype._hash=function(){var e=o.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e},t.exports=c},{"./hash":256,inherits:146,"safe-buffer":250}],262:[function(e,t,i){var n=e("inherits"),r=e("./sha512"),o=e("./hash"),s=e("safe-buffer").Buffer,a=new Array(160);function c(){this.init(),this._w=a,o.call(this,128,112)}n(c,r),c.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},c.prototype._hash=function(){var e=s.allocUnsafe(48);function t(t,i,n){e.writeInt32BE(t,n),e.writeInt32BE(i,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e},t.exports=c},{"./hash":256,"./sha512":263,inherits:146,"safe-buffer":250}],263:[function(e,t,i){var n=e("inherits"),r=e("./hash"),o=e("safe-buffer").Buffer,s=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],a=new Array(160);function c(){this.init(),this._w=a,r.call(this,128,112)}function d(e,t,i){return i^e&(t^i)}function l(e,t,i){return e&t|i&(e|t)}function u(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function h(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function f(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function p(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function g(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function v(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function m(e,t){return e>>>0>>0?1:0}n(c,r),c.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},c.prototype._update=function(e){for(var t=this._w,i=0|this._ah,n=0|this._bh,r=0|this._ch,o=0|this._dh,a=0|this._eh,c=0|this._fh,y=0|this._gh,b=0|this._hh,S=0|this._al,_=0|this._bl,E=0|this._cl,w=0|this._dl,T=0|this._el,I=0|this._fl,R=0|this._gl,M=0|this._hl,k=0;k<32;k+=2)t[k]=e.readInt32BE(4*k),t[k+1]=e.readInt32BE(4*k+4);for(;k<160;k+=2){var C=t[k-30],O=t[k-30+1],A=f(C,O),P=p(O,C),D=g(C=t[k-4],O=t[k-4+1]),x=v(O,C),L=t[k-14],U=t[k-14+1],B=t[k-32],N=t[k-32+1],j=P+U|0,F=A+L+m(j,P)|0;F=(F=F+D+m(j=j+x|0,x)|0)+B+m(j=j+N|0,N)|0,t[k]=F,t[k+1]=j}for(var K=0;K<160;K+=2){F=t[K],j=t[K+1];var q=l(i,n,r),$=l(S,_,E),V=u(i,S),H=u(S,i),W=h(a,T),G=h(T,a),z=s[K],Y=s[K+1],J=d(a,c,y),Q=d(T,I,R),X=M+G|0,Z=b+W+m(X,M)|0;Z=(Z=(Z=Z+J+m(X=X+Q|0,Q)|0)+z+m(X=X+Y|0,Y)|0)+F+m(X=X+j|0,j)|0;var ee=H+$|0,te=V+q+m(ee,H)|0;b=y,M=R,y=c,R=I,c=a,I=T,a=o+Z+m(T=w+X|0,w)|0,o=r,w=E,r=n,E=_,n=i,_=S,i=Z+te+m(S=X+ee|0,X)|0}this._al=this._al+S|0,this._bl=this._bl+_|0,this._cl=this._cl+E|0,this._dl=this._dl+w|0,this._el=this._el+T|0,this._fl=this._fl+I|0,this._gl=this._gl+R|0,this._hl=this._hl+M|0,this._ah=this._ah+i+m(this._al,S)|0,this._bh=this._bh+n+m(this._bl,_)|0,this._ch=this._ch+r+m(this._cl,E)|0,this._dh=this._dh+o+m(this._dl,w)|0,this._eh=this._eh+a+m(this._el,T)|0,this._fh=this._fh+c+m(this._fl,I)|0,this._gh=this._gh+y+m(this._gl,R)|0,this._hh=this._hh+b+m(this._hl,M)|0},c.prototype._hash=function(){var e=o.allocUnsafe(64);function t(t,i,n){e.writeInt32BE(t,n),e.writeInt32BE(i,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e},t.exports=c},{"./hash":256,inherits:146,"safe-buffer":250}],264:[function(e,t,i){t.exports=r;var n=e("events").EventEmitter;function r(){n.call(this)}e("inherits")(r,n),r.Readable=e("readable-stream/lib/_stream_readable.js"),r.Writable=e("readable-stream/lib/_stream_writable.js"),r.Duplex=e("readable-stream/lib/_stream_duplex.js"),r.Transform=e("readable-stream/lib/_stream_transform.js"),r.PassThrough=e("readable-stream/lib/_stream_passthrough.js"),r.finished=e("readable-stream/lib/internal/streams/end-of-stream.js"),r.pipeline=e("readable-stream/lib/internal/streams/pipeline.js"),r.Stream=r,r.prototype.pipe=function(e,t){var i=this;function r(t){e.writable&&!1===e.write(t)&&i.pause&&i.pause()}function o(){i.readable&&i.resume&&i.resume()}i.on("data",r),e.on("drain",o),e._isStdio||t&&!1===t.end||(i.on("end",a),i.on("close",c));var s=!1;function a(){s||(s=!0,e.end())}function c(){s||(s=!0,"function"==typeof e.destroy&&e.destroy())}function d(e){if(l(),0===n.listenerCount(this,"error"))throw e}function l(){i.removeListener("data",r),e.removeListener("drain",o),i.removeListener("end",a),i.removeListener("close",c),i.removeListener("error",d),e.removeListener("error",d),i.removeListener("end",l),i.removeListener("close",l),e.removeListener("close",l)}return i.on("error",d),e.on("error",d),i.on("end",l),i.on("close",l),e.on("close",l),e.emit("pipe",i),e}},{events:105,inherits:146,"readable-stream/lib/_stream_duplex.js":266,"readable-stream/lib/_stream_passthrough.js":267,"readable-stream/lib/_stream_readable.js":268,"readable-stream/lib/_stream_transform.js":269,"readable-stream/lib/_stream_writable.js":270,"readable-stream/lib/internal/streams/end-of-stream.js":274,"readable-stream/lib/internal/streams/pipeline.js":276}],265:[function(e,t,i){arguments[4][50][0].apply(i,arguments)},{dup:50}],266:[function(e,t,i){(function(i){(function(){"use strict";var n=Object.keys||function(e){var t=[];for(var i in e)t.push(i);return t};t.exports=d;var r=e("./_stream_readable"),o=e("./_stream_writable");e("inherits")(d,r);for(var s=n(o.prototype),a=0;a0)if("string"==typeof t||s.objectMode||Object.getPrototypeOf(t)===a.prototype||(t=function(e){return a.from(e)}(t)),n)s.endEmitted?E(e,new _):M(e,s,t,!0);else if(s.ended)E(e,new b);else{if(s.destroyed)return!1;s.reading=!1,s.decoder&&!i?(t=s.decoder.write(t),s.objectMode||0!==t.length?M(e,s,t,!1):P(e,s)):M(e,s,t,!1)}else n||(s.reading=!1,P(e,s));return!s.ended&&(s.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=k?e=k:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function O(e){var t=e._readableState;d("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(d("emitReadable",t.flowing),t.emittedReadable=!0,i.nextTick(A,e))}function A(e){var t=e._readableState;d("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,B(e)}function P(e,t){t.readingMore||(t.readingMore=!0,i.nextTick(D,e,t))}function D(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function L(e){d("readable nexttick read 0"),e.read(0)}function U(e,t){d("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),B(e),t.flowing&&!t.reading&&e.read(0)}function B(e){var t=e._readableState;for(d("flow",t.flowing);t.flowing&&null!==e.read(););}function N(e,t){return 0===t.length?null:(t.objectMode?i=t.buffer.shift():!e||e>=t.length?(i=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):i=t.buffer.consume(e,t.decoder),i);var i}function j(e){var t=e._readableState;d("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,i.nextTick(F,t,e))}function F(e,t){if(d("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var i=t._writableState;(!i||i.autoDestroy&&i.finished)&&t.destroy()}}function K(e,t){for(var i=0,n=e.length;i=t.highWaterMark:t.length>0)||t.ended))return d("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?j(this):O(this),null;if(0===(e=C(e,t))&&t.ended)return 0===t.length&&j(this),null;var n,r=t.needReadable;return d("need readable",r),(0===t.length||t.length-e0?N(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),i!==e&&t.ended&&j(this)),null!==n&&this.emit("data",n),n},I.prototype._read=function(e){E(this,new S("_read()"))},I.prototype.pipe=function(e,t){var n=this,r=this._readableState;switch(r.pipesCount){case 0:r.pipes=e;break;case 1:r.pipes=[r.pipes,e];break;default:r.pipes.push(e)}r.pipesCount+=1,d("pipe count=%d opts=%j",r.pipesCount,t);var s=(!t||!1!==t.end)&&e!==i.stdout&&e!==i.stderr?c:v;function a(t,i){d("onunpipe"),t===n&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,d("cleanup"),e.removeListener("close",p),e.removeListener("finish",g),e.removeListener("drain",l),e.removeListener("error",f),e.removeListener("unpipe",a),n.removeListener("end",c),n.removeListener("end",v),n.removeListener("data",h),u=!0,!r.awaitDrain||e._writableState&&!e._writableState.needDrain||l())}function c(){d("onend"),e.end()}r.endEmitted?i.nextTick(s):n.once("end",s),e.on("unpipe",a);var l=function(e){return function(){var t=e._readableState;d("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&o(e,"data")&&(t.flowing=!0,B(e))}}(n);e.on("drain",l);var u=!1;function h(t){d("ondata");var i=e.write(t);d("dest.write",i),!1===i&&((1===r.pipesCount&&r.pipes===e||r.pipesCount>1&&-1!==K(r.pipes,e))&&!u&&(d("false write response, pause",r.awaitDrain),r.awaitDrain++),n.pause())}function f(t){d("onerror",t),v(),e.removeListener("error",f),0===o(e,"error")&&E(e,t)}function p(){e.removeListener("finish",g),v()}function g(){d("onfinish"),e.removeListener("close",p),v()}function v(){d("unpipe"),n.unpipe(e)}return n.on("data",h),function(e,t,i){if("function"==typeof e.prependListener)return e.prependListener(t,i);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(i):e._events[t]=[i,e._events[t]]:e.on(t,i)}(e,"error",f),e.once("close",p),e.once("finish",g),e.emit("pipe",n),r.flowing||(d("pipe resume"),n.resume()),e},I.prototype.unpipe=function(e){var t=this._readableState,i={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,i)),this;if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o0,!1!==r.flowing&&this.resume()):"readable"===e&&(r.endEmitted||r.readableListening||(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,d("on readable",r.length,r.reading),r.length?O(this):r.reading||i.nextTick(L,this))),n},I.prototype.addListener=I.prototype.on,I.prototype.removeListener=function(e,t){var n=s.prototype.removeListener.call(this,e,t);return"readable"===e&&i.nextTick(x,this),n},I.prototype.removeAllListeners=function(e){var t=s.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||i.nextTick(x,this),t},I.prototype.resume=function(){var e=this._readableState;return e.flowing||(d("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,i.nextTick(U,e,t))}(this,e)),e.paused=!1,this},I.prototype.pause=function(){return d("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(d("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},I.prototype.wrap=function(e){var t=this,i=this._readableState,n=!1;for(var r in e.on("end",(function(){if(d("wrapped end"),i.decoder&&!i.ended){var e=i.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(r){(d("wrapped data"),i.decoder&&(r=i.decoder.write(r)),i.objectMode&&null==r)||(i.objectMode||r&&r.length)&&(t.push(r)||(n=!0,e.pause()))})),e)void 0===this[r]&&"function"==typeof e[r]&&(this[r]=function(t){return function(){return e[t].apply(e,arguments)}}(r));for(var o=0;o-1))throw new _(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(I.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(I.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),I.prototype._write=function(e,t,i){i(new g("_write()"))},I.prototype._writev=null,I.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||function(e,t,n){t.ending=!0,A(e,t),n&&(t.finished?i.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,r,n),this},Object.defineProperty(I.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(I.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),I.prototype.destroy=u.destroy,I.prototype._undestroy=u.undestroy,I.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":265,"./_stream_duplex":266,"./internal/streams/destroy":273,"./internal/streams/state":277,"./internal/streams/stream":278,_process:237,buffer:68,inherits:146,"util-deprecate":283}],271:[function(e,t,i){(function(i){(function(){"use strict";var n;function r(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}var o=e("./end-of-stream"),s=Symbol("lastResolve"),a=Symbol("lastReject"),c=Symbol("error"),d=Symbol("ended"),l=Symbol("lastPromise"),u=Symbol("handlePromise"),h=Symbol("stream");function f(e,t){return{value:e,done:t}}function p(e){var t=e[s];if(null!==t){var i=e[h].read();null!==i&&(e[l]=null,e[s]=null,e[a]=null,t(f(i,!1)))}}function g(e){i.nextTick(p,e)}var v=Object.getPrototypeOf((function(){})),m=Object.setPrototypeOf((r(n={get stream(){return this[h]},next:function(){var e=this,t=this[c];if(null!==t)return Promise.reject(t);if(this[d])return Promise.resolve(f(void 0,!0));if(this[h].destroyed)return new Promise((function(t,n){i.nextTick((function(){e[c]?n(e[c]):t(f(void 0,!0))}))}));var n,r=this[l];if(r)n=new Promise(function(e,t){return function(i,n){e.then((function(){t[d]?i(f(void 0,!0)):t[u](i,n)}),n)}}(r,this));else{var o=this[h].read();if(null!==o)return Promise.resolve(f(o,!1));n=new Promise(this[u])}return this[l]=n,n}},Symbol.asyncIterator,(function(){return this})),r(n,"return",(function(){var e=this;return new Promise((function(t,i){e[h].destroy(null,(function(e){e?i(e):t(f(void 0,!0))}))}))})),n),v);t.exports=function(e){var t,i=Object.create(m,(r(t={},h,{value:e,writable:!0}),r(t,s,{value:null,writable:!0}),r(t,a,{value:null,writable:!0}),r(t,c,{value:null,writable:!0}),r(t,d,{value:e._readableState.endEmitted,writable:!0}),r(t,u,{value:function(e,t){var n=i[h].read();n?(i[l]=null,i[s]=null,i[a]=null,e(f(n,!1))):(i[s]=e,i[a]=t)},writable:!0}),t));return i[l]=null,o(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=i[a];return null!==t&&(i[l]=null,i[s]=null,i[a]=null,t(e)),void(i[c]=e)}var n=i[s];null!==n&&(i[l]=null,i[s]=null,i[a]=null,n(f(void 0,!0))),i[d]=!0})),e.on("readable",g.bind(null,i)),i}}).call(this)}).call(this,e("_process"))},{"./end-of-stream":274,_process:237}],272:[function(e,t,i){arguments[4][57][0].apply(i,arguments)},{buffer:68,dup:57,util:20}],273:[function(e,t,i){(function(e){(function(){"use strict";function i(e,t){r(e,t),n(e)}function n(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function r(e,t){e.emit("error",t)}t.exports={destroy:function(t,o){var s=this,a=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return a||c?(o?o(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,e.nextTick(r,this,t)):e.nextTick(r,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,(function(t){!o&&t?s._writableState?s._writableState.errorEmitted?e.nextTick(n,s):(s._writableState.errorEmitted=!0,e.nextTick(i,s,t)):e.nextTick(i,s,t):o?(e.nextTick(n,s),o(t)):e.nextTick(n,s)})),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var i=e._readableState,n=e._writableState;i&&i.autoDestroy||n&&n.autoDestroy?e.destroy(t):e.emit("error",t)}}}).call(this)}).call(this,e("_process"))},{_process:237}],274:[function(e,t,i){arguments[4][59][0].apply(i,arguments)},{"../../../errors":265,dup:59}],275:[function(e,t,i){arguments[4][60][0].apply(i,arguments)},{dup:60}],276:[function(e,t,i){arguments[4][61][0].apply(i,arguments)},{"../../../errors":265,"./end-of-stream":274,dup:61}],277:[function(e,t,i){arguments[4][62][0].apply(i,arguments)},{"../../../errors":265,dup:62}],278:[function(e,t,i){arguments[4][63][0].apply(i,arguments)},{dup:63,events:105}],279:[function(e,t,i){"use strict";var n=e("safe-buffer").Buffer,r=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===r||!r(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=c,this.end=d,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=l,this.end=u,t=3;break;default:return this.write=h,void(this.end=f)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function s(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function a(e){var t=this.lastTotal-this.lastNeed,i=function(e,t,i){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==i?i:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){if((e.length-t)%2==0){var i=e.toString("utf16le",t);if(i){var n=i.charCodeAt(i.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],i.slice(0,-1)}return i}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function d(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var i=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,i)}return t}function l(e,t){var i=(e.length-t)%3;return 0===i?e.toString("base64",t):(this.lastNeed=3-i,this.lastTotal=3,1===i?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-i))}function u(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function f(e){return e&&e.length?this.write(e):""}i.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,i;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i=0)return r>0&&(e.lastNeed=r-1),r;if(--n=0)return r>0&&(e.lastNeed=r-2),r;if(--n=0)return r>0&&(2===r?r=0:e.lastNeed=r-3),r;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=i;var n=e.length-(i-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},{"safe-buffer":250}],280:[function(e,t,i){(function(t,n){(function(){var r=e("process/browser.js").nextTick,o=Function.prototype.apply,s=Array.prototype.slice,a={},c=0;function d(e,t){this._id=e,this._clearFn=t}i.setTimeout=function(){return new d(o.call(setTimeout,window,arguments),clearTimeout)},i.setInterval=function(){return new d(o.call(setInterval,window,arguments),clearInterval)},i.clearTimeout=i.clearInterval=function(e){e.close()},d.prototype.unref=d.prototype.ref=function(){},d.prototype.close=function(){this._clearFn.call(window,this._id)},i.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},i.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},i._unrefActive=i.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},i.setImmediate="function"==typeof t?t:function(e){var t=c++,n=!(arguments.length<2)&&s.call(arguments,1);return a[t]=!0,r((function(){a[t]&&(n?e.apply(null,n):e.call(null),i.clearImmediate(t))})),t},i.clearImmediate="function"==typeof n?n:function(e){delete a[e]}}).call(this)}).call(this,e("timers").setImmediate,e("timers").clearImmediate)},{"process/browser.js":237,timers:280}],281:[function(e,t,i){t.exports={0:"O",1:"l","֭":"֖","֮":"֘","֨":"֙","֤":"֚","᪴":"ۛ","⃛":"ۛ","ؙ":"̓","ࣳ":"̓","̓":"̓","̕":"̓","ُ":"̓","ٝ":"̔","֜":"́","֝":"́","ؘ":"́","݇":"́","́":"́","॔":"́","َ":"́","̀":"̀","॓":"̀","̌":"̆","꙼":"̆","٘":"̆","ٚ":"̆","ͮ":"̆","ۨ":"̆̇","̐":"̆̇","ँ":"̆̇","ঁ":"̆̇","ઁ":"̆̇","ଁ":"̆̇","ఀ":"̆̇","ಁ":"̆̇","ഁ":"̆̇","𑒿":"̆̇","᳐":"̂","̑":"̂","ٛ":"̂","߮":"̂","꛰":"̂","֯":"̊","۟":"̊","៓":"̊","゚":"̊","ْ":"̊","ஂ":"̊","ံ":"̊","ំ":"̊","𑌀":"̊","ํ":"̊","ໍ":"̊","ͦ":"̊","ⷪ":"̊","࣫":"̈","߳":"̈","ً":"̋","ࣰ":"̋","͂":"̃","ٓ":"̃","ׄ":"̇","۬":"̇","݀":"̇","࣪":"̇","݁":"̇","͘":"̇","ֹ":"̇","ֺ":"̇","ׂ":"̇","ׁ":"̇","߭":"̇","ं":"̇","ਂ":"̇","ં":"̇","்":"̇","̷":"̸","᪷":"̨","̢":"̨","ͅ":"̨","᳒":"̄","̅":"̄","ٙ":"̄","߫":"̄","꛱":"̄","᳚":"̎","ٗ":"̒","͗":"͐","ࣿ":"͐","ࣸ":"͐","ऀ":"͒","᳭":"̖","᳜":"̩","ٖ":"̩","᳕":"̫","͇":"̳","ࣹ":"͔","ࣺ":"͕","゛":"゙","゜":"゚","̶":"̵","〬":"̉","ׅ":"̣","࣭":"̣","᳝":"̣","ִ":"̣","ٜ":"̣","़":"̣","়":"̣","਼":"̣","઼":"̣","଼":"̣","𑇊":"̣","𑓃":"̣","𐨺":"̣","࣮":"̤","᳞":"̤","༷":"̥","〭":"̥","̧":"̦","̡":"̦","̹":"̦","᳙":"̭","᳘":"̮","॒":"̱","̠":"̱","ࣱ":"ٌ","ࣨ":"ٌ","ࣥ":"ٌ","ﱞ":"ﹲّ","ࣲ":"ٍ","ﱟ":"ﹴّ","ﳲ":"ﹷّ","ﱠ":"ﹶّ","ﳳ":"ﹹّ","ﱡ":"ﹸّ","ؚ":"ِ","̗":"ِ","ﳴ":"ﹻّ","ﱢ":"ﹺّ","ﱣ":"ﹼٰ","ٟ":"ٕ","̍":"ٰ","݂":"ܼ","ਃ":"ঃ","ః":"ঃ","ಃ":"ঃ","ഃ":"ঃ","ඃ":"ঃ","း":"ঃ","𑓁":"ঃ","់":"่","່":"่","້":"้","໊":"๊","໋":"๋","꙯":"⃩","\u2028":" ","\u2029":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" ","ߺ":"_","﹍":"_","﹎":"_","﹏":"_","‐":"-","‑":"-","‒":"-","–":"-","﹘":"-","۔":"-","⁃":"-","˗":"-","−":"-","➖":"-","Ⲻ":"-","⨩":"-̓","⸚":"-̈","﬩":"-̇","∸":"-̇","⨪":"-̣","꓾":"-.","~":"〜","؍":",","٫":",","‚":",","¸":",","ꓹ":",","⸲":"،","٬":"،",";":";","⸵":"؛","ः":":","ઃ":":",":":":","։":":","܃":":","܄":":","᛬":":","︰":":","᠃":":","᠉":":","⁚":":","׃":":","˸":":","꞉":":","∶":":","ː":":","ꓽ":":","⩴":"::=","⧴":":→","!":"!","ǃ":"!","ⵑ":"!","‼":"!!","⁉":"!?","ʔ":"?","Ɂ":"?","ॽ":"?","Ꭾ":"?","ꛫ":"?","⁈":"?!","⁇":"??","⸮":"؟","𝅭":".","․":".","܁":".","܂":".","꘎":".","𐩐":".","٠":".","۰":".","ꓸ":".","ꓻ":".,","‥":"..","ꓺ":"..","…":"...","꛴":"꛳꛳","・":"·","・":"·","᛫":"·","·":"·","⸱":"·","𐄁":"·","•":"·","‧":"·","∙":"·","⋅":"·","ꞏ":"·","ᐧ":"·","⋯":"···","ⵈ":"···","ᑄ":"·<","⋗":"·>","ᐷ":"·>","ᑀ":"·>","ᔯ":"·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","🅭":"㏄\t⃝","⋴":"ꞓ","ɛ":"ꞓ","ε":"ꞓ","ϵ":"ꞓ","𝛆":"ꞓ","𝛜":"ꞓ","𝜀":"ꞓ","𝜖":"ꞓ","𝜺":"ꞓ","𝝐":"ꞓ","𝝴":"ꞓ","𝞊":"ꞓ","𝞮":"ꞓ","𝟄":"ꞓ","ⲉ":"ꞓ","є":"ꞓ","ԑ":"ꞓ","ꮛ":"ꞓ","𑣎":"ꞓ","𐐩":"ꞓ","€":"Ꞓ","Ⲉ":"Ꞓ","Є":"Ꞓ","⍷":"ꞓ̲","ͽ":"ꜿ","Ͽ":"Ꜿ","ⅾ":"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","ᙱ":"ᖖᒋ","ᙲ":"ᖖᒌ","ᙴ":"ᖖᒎ","ᙵ":"ᖖᒐ","ᙶ":"ᖖᒑ","ᣪ":"ᖗ·","ᙷ":"ᖧ·","ᙸ":"ᖨ·","ᙹ":"ᖩ·","ᙺ":"ᖪ·","ᙻ":"ᖫ·","ᙼ":"ᖬ·","ᙽ":"ᖭ·","⪫":"ᗒ","⪪":"ᗕ","ꓷ":"ᗡ","ᣰ":"ᗴ·","ᣲ":"ᘛ·","ᶻ":"ᙆ","ꓭ":"ᙠ","ᶺ":"ᣔ","ᴾ":"ᣖ","ᣜ":"ᣟᐞ","ˡ":"ᣳ","ʳ":"ᣴ","ˢ":"ᣵ","ᣛ":"ᣵ","ꚰ":"ᚹ","ᛡ":"ᚼ","⍿":"ᚽ","ᛂ":"ᚽ","𝈿":"ᛋ","↑":"ᛏ","↿":"ᛐ","⥮":"ᛐ⇂","⥣":"ᛐᛚ","ⵣ":"ᛯ","↾":"ᛚ","⨡":"ᛚ","⋄":"ᛜ","◇":"ᛜ","◊":"ᛜ","♢":"ᛜ","🝔":"ᛜ","𑢷":"ᛜ","𐊔":"ᛜ","⍚":"ᛜ̲","⋈":"ᛞ","⨝":"ᛞ","𐓐":"ᛦ","↕":"ᛨ","𐳼":"𐲂","𐳺":"𐲥","ㄱ":"ᄀ","ᆨ":"ᄀ","ᄁ":"ᄀᄀ","ㄲ":"ᄀᄀ","ᆩ":"ᄀᄀ","ᇺ":"ᄀᄂ","ᅚ":"ᄀᄃ","ᇃ":"ᄀᄅ","ᇻ":"ᄀᄇ","ᆪ":"ᄀᄉ","ㄳ":"ᄀᄉ","ᇄ":"ᄀᄉᄀ","ᇼ":"ᄀᄎ","ᇽ":"ᄀᄏ","ᇾ":"ᄀᄒ","ㄴ":"ᄂ","ᆫ":"ᄂ","ᄓ":"ᄂᄀ","ᇅ":"ᄂᄀ","ᄔ":"ᄂᄂ","ㅥ":"ᄂᄂ","ᇿ":"ᄂᄂ","ᄕ":"ᄂᄃ","ㅦ":"ᄂᄃ","ᇆ":"ᄂᄃ","ퟋ":"ᄂᄅ","ᄖ":"ᄂᄇ","ᅛ":"ᄂᄉ","ᇇ":"ᄂᄉ","ㅧ":"ᄂᄉ","ᅜ":"ᄂᄌ","ᆬ":"ᄂᄌ","ㄵ":"ᄂᄌ","ퟌ":"ᄂᄎ","ᇉ":"ᄂᄐ","ᅝ":"ᄂᄒ","ᆭ":"ᄂᄒ","ㄶ":"ᄂᄒ","ᇈ":"ᄂᅀ","ㅨ":"ᄂᅀ","ㄷ":"ᄃ","ᆮ":"ᄃ","ᄗ":"ᄃᄀ","ᇊ":"ᄃᄀ","ᄄ":"ᄃᄃ","ㄸ":"ᄃᄃ","ퟍ":"ᄃᄃ","ퟎ":"ᄃᄃᄇ","ᅞ":"ᄃᄅ","ᇋ":"ᄃᄅ","ꥠ":"ᄃᄆ","ꥡ":"ᄃᄇ","ퟏ":"ᄃᄇ","ꥢ":"ᄃᄉ","ퟐ":"ᄃᄉ","ퟑ":"ᄃᄉᄀ","ꥣ":"ᄃᄌ","ퟒ":"ᄃᄌ","ퟓ":"ᄃᄎ","ퟔ":"ᄃᄐ","ㄹ":"ᄅ","ᆯ":"ᄅ","ꥤ":"ᄅᄀ","ᆰ":"ᄅᄀ","ㄺ":"ᄅᄀ","ꥥ":"ᄅᄀᄀ","ퟕ":"ᄅᄀᄀ","ᇌ":"ᄅᄀᄉ","ㅩ":"ᄅᄀᄉ","ퟖ":"ᄅᄀᄒ","ᄘ":"ᄅᄂ","ᇍ":"ᄅᄂ","ꥦ":"ᄅᄃ","ᇎ":"ᄅᄃ","ㅪ":"ᄅᄃ","ꥧ":"ᄅᄃᄃ","ᇏ":"ᄅᄃᄒ","ᄙ":"ᄅᄅ","ᇐ":"ᄅᄅ","ퟗ":"ᄅᄅᄏ","ꥨ":"ᄅᄆ","ᆱ":"ᄅᄆ","ㄻ":"ᄅᄆ","ᇑ":"ᄅᄆᄀ","ᇒ":"ᄅᄆᄉ","ퟘ":"ᄅᄆᄒ","ꥩ":"ᄅᄇ","ᆲ":"ᄅᄇ","ㄼ":"ᄅᄇ","ퟙ":"ᄅᄇᄃ","ꥪ":"ᄅᄇᄇ","ᇓ":"ᄅᄇᄉ","ㅫ":"ᄅᄇᄉ","ꥫ":"ᄅᄇᄋ","ᇕ":"ᄅᄇᄋ","ퟚ":"ᄅᄇᄑ","ᇔ":"ᄅᄇᄒ","ꥬ":"ᄅᄉ","ᆳ":"ᄅᄉ","ㄽ":"ᄅᄉ","ᇖ":"ᄅᄉᄉ","ᄛ":"ᄅᄋ","ퟝ":"ᄅᄋ","ꥭ":"ᄅᄌ","ꥮ":"ᄅᄏ","ᇘ":"ᄅᄏ","ᆴ":"ᄅᄐ","ㄾ":"ᄅᄐ","ᆵ":"ᄅᄑ","ㄿ":"ᄅᄑ","ᄚ":"ᄅᄒ","ㅀ":"ᄅᄒ","ᄻ":"ᄅᄒ","ᆶ":"ᄅᄒ","ퟲ":"ᄅᄒ","ᇗ":"ᄅᅀ","ㅬ":"ᄅᅀ","ퟛ":"ᄅᅌ","ᇙ":"ᄅᅙ","ㅭ":"ᄅᅙ","ퟜ":"ᄅᅙᄒ","ㅁ":"ᄆ","ᆷ":"ᄆ","ꥯ":"ᄆᄀ","ᇚ":"ᄆᄀ","ퟞ":"ᄆᄂ","ퟟ":"ᄆᄂᄂ","ꥰ":"ᄆᄃ","ᇛ":"ᄆᄅ","ퟠ":"ᄆᄆ","ᄜ":"ᄆᄇ","ㅮ":"ᄆᄇ","ᇜ":"ᄆᄇ","ퟡ":"ᄆᄇᄉ","ꥱ":"ᄆᄉ","ᇝ":"ᄆᄉ","ㅯ":"ᄆᄉ","ᇞ":"ᄆᄉᄉ","ᄝ":"ᄆᄋ","ㅱ":"ᄆᄋ","ᇢ":"ᄆᄋ","ퟢ":"ᄆᄌ","ᇠ":"ᄆᄎ","ᇡ":"ᄆᄒ","ᇟ":"ᄆᅀ","ㅰ":"ᄆᅀ","ㅂ":"ᄇ","ᆸ":"ᄇ","ᄞ":"ᄇᄀ","ㅲ":"ᄇᄀ","ᄟ":"ᄇᄂ","ᄠ":"ᄇᄃ","ㅳ":"ᄇᄃ","ퟣ":"ᄇᄃ","ᇣ":"ᄇᄅ","ퟤ":"ᄇᄅᄑ","ퟥ":"ᄇᄆ","ᄈ":"ᄇᄇ","ㅃ":"ᄇᄇ","ퟦ":"ᄇᄇ","ᄬ":"ᄇᄇᄋ","ㅹ":"ᄇᄇᄋ","ᄡ":"ᄇᄉ","ㅄ":"ᄇᄉ","ᆹ":"ᄇᄉ","ᄢ":"ᄇᄉᄀ","ㅴ":"ᄇᄉᄀ","ᄣ":"ᄇᄉᄃ","ㅵ":"ᄇᄉᄃ","ퟧ":"ᄇᄉᄃ","ᄤ":"ᄇᄉᄇ","ᄥ":"ᄇᄉᄉ","ᄦ":"ᄇᄉᄌ","ꥲ":"ᄇᄉᄐ","ᄫ":"ᄇᄋ","ㅸ":"ᄇᄋ","ᇦ":"ᄇᄋ","ᄧ":"ᄇᄌ","ㅶ":"ᄇᄌ","ퟨ":"ᄇᄌ","ᄨ":"ᄇᄎ","ퟩ":"ᄇᄎ","ꥳ":"ᄇᄏ","ᄩ":"ᄇᄐ","ㅷ":"ᄇᄐ","ᄪ":"ᄇᄑ","ᇤ":"ᄇᄑ","ꥴ":"ᄇᄒ","ᇥ":"ᄇᄒ","ㅅ":"ᄉ","ᆺ":"ᄉ","ᄭ":"ᄉᄀ","ㅺ":"ᄉᄀ","ᇧ":"ᄉᄀ","ᄮ":"ᄉᄂ","ㅻ":"ᄉᄂ","ᄯ":"ᄉᄃ","ㅼ":"ᄉᄃ","ᇨ":"ᄉᄃ","ᄰ":"ᄉᄅ","ᇩ":"ᄉᄅ","ᄱ":"ᄉᄆ","ퟪ":"ᄉᄆ","ᄲ":"ᄉᄇ","ㅽ":"ᄉᄇ","ᇪ":"ᄉᄇ","ᄳ":"ᄉᄇᄀ","ퟫ":"ᄉᄇᄋ","ᄊ":"ᄉᄉ","ㅆ":"ᄉᄉ","ᆻ":"ᄉᄉ","ퟬ":"ᄉᄉᄀ","ퟭ":"ᄉᄉᄃ","ꥵ":"ᄉᄉᄇ","ᄴ":"ᄉᄉᄉ","ᄵ":"ᄉᄋ","ᄶ":"ᄉᄌ","ㅾ":"ᄉᄌ","ퟯ":"ᄉᄌ","ᄷ":"ᄉᄎ","ퟰ":"ᄉᄎ","ᄸ":"ᄉᄏ","ᄹ":"ᄉᄐ","ퟱ":"ᄉᄐ","ᄺ":"ᄉᄑ","ퟮ":"ᄉᅀ","ㅇ":"ᄋ","ᆼ":"ᄋ","ᅁ":"ᄋᄀ","ᇬ":"ᄋᄀ","ᇭ":"ᄋᄀᄀ","ᅂ":"ᄋᄃ","ꥶ":"ᄋᄅ","ᅃ":"ᄋᄆ","ᅄ":"ᄋᄇ","ᅅ":"ᄋᄉ","ᇱ":"ᄋᄉ","ㆂ":"ᄋᄉ","ᅇ":"ᄋᄋ","ㆀ":"ᄋᄋ","ᇮ":"ᄋᄋ","ᅈ":"ᄋᄌ","ᅉ":"ᄋᄎ","ᇯ":"ᄋᄏ","ᅊ":"ᄋᄐ","ᅋ":"ᄋᄑ","ꥷ":"ᄋᄒ","ᅆ":"ᄋᅀ","ᇲ":"ᄋᅀ","ㆃ":"ᄋᅀ","ㅈ":"ᄌ","ᆽ":"ᄌ","ퟷ":"ᄌᄇ","ퟸ":"ᄌᄇᄇ","ᅍ":"ᄌᄋ","ᄍ":"ᄌᄌ","ㅉ":"ᄌᄌ","ퟹ":"ᄌᄌ","ꥸ":"ᄌᄌᄒ","ㅊ":"ᄎ","ᆾ":"ᄎ","ᅒ":"ᄎᄏ","ᅓ":"ᄎᄒ","ㅋ":"ᄏ","ᆿ":"ᄏ","ㅌ":"ᄐ","ᇀ":"ᄐ","ꥹ":"ᄐᄐ","ㅍ":"ᄑ","ᇁ":"ᄑ","ᅖ":"ᄑᄇ","ᇳ":"ᄑᄇ","ퟺ":"ᄑᄉ","ᅗ":"ᄑᄋ","ㆄ":"ᄑᄋ","ᇴ":"ᄑᄋ","ퟻ":"ᄑᄐ","ꥺ":"ᄑᄒ","ㅎ":"ᄒ","ᇂ":"ᄒ","ᇵ":"ᄒᄂ","ᇶ":"ᄒᄅ","ᇷ":"ᄒᄆ","ᇸ":"ᄒᄇ","ꥻ":"ᄒᄉ","ᅘ":"ᄒᄒ","ㆅ":"ᄒᄒ","ᄽ":"ᄼᄼ","ᄿ":"ᄾᄾ","ㅿ":"ᅀ","ᇫ":"ᅀ","ퟳ":"ᅀᄇ","ퟴ":"ᅀᄇᄋ","ㆁ":"ᅌ","ᇰ":"ᅌ","ퟵ":"ᅌᄆ","ퟶ":"ᅌᄒ","ᅏ":"ᅎᅎ","ᅑ":"ᅐᅐ","ㆆ":"ᅙ","ᇹ":"ᅙ","ꥼ":"ᅙᅙ","ㅤ":"ᅠ","ㅏ":"ᅡ","ᆣ":"ᅡー","ᅶ":"ᅡᅩ","ᅷ":"ᅡᅮ","ᅢ":"ᅡ丨","ㅐ":"ᅡ丨","ㅑ":"ᅣ","ᅸ":"ᅣᅩ","ᅹ":"ᅣᅭ","ᆤ":"ᅣᅮ","ᅤ":"ᅣ丨","ㅒ":"ᅣ丨","ㅓ":"ᅥ","ᅼ":"ᅥー","ᅺ":"ᅥᅩ","ᅻ":"ᅥᅮ","ᅦ":"ᅥ丨","ㅔ":"ᅥ丨","ㅕ":"ᅧ","ᆥ":"ᅧᅣ","ᅽ":"ᅧᅩ","ᅾ":"ᅧᅮ","ᅨ":"ᅧ丨","ㅖ":"ᅧ丨","ㅗ":"ᅩ","ᅪ":"ᅩᅡ","ㅘ":"ᅩᅡ","ᅫ":"ᅩᅡ丨","ㅙ":"ᅩᅡ丨","ᆦ":"ᅩᅣ","ᆧ":"ᅩᅣ丨","ᅿ":"ᅩᅥ","ᆀ":"ᅩᅥ丨","ힰ":"ᅩᅧ","ᆁ":"ᅩᅧ丨","ᆂ":"ᅩᅩ","ힱ":"ᅩᅩ丨","ᆃ":"ᅩᅮ","ᅬ":"ᅩ丨","ㅚ":"ᅩ丨","ㅛ":"ᅭ","ힲ":"ᅭᅡ","ힳ":"ᅭᅡ丨","ᆄ":"ᅭᅣ","ㆇ":"ᅭᅣ","ᆆ":"ᅭᅣ","ᆅ":"ᅭᅣ丨","ㆈ":"ᅭᅣ丨","ힴ":"ᅭᅥ","ᆇ":"ᅭᅩ","ᆈ":"ᅭ丨","ㆉ":"ᅭ丨","ㅜ":"ᅮ","ᆉ":"ᅮᅡ","ᆊ":"ᅮᅡ丨","ᅯ":"ᅮᅥ","ㅝ":"ᅮᅥ","ᆋ":"ᅮᅥー","ᅰ":"ᅮᅥ丨","ㅞ":"ᅮᅥ丨","ힵ":"ᅮᅧ","ᆌ":"ᅮᅧ丨","ᆍ":"ᅮᅮ","ᅱ":"ᅮ丨","ㅟ":"ᅮ丨","ힶ":"ᅮ丨丨","ㅠ":"ᅲ","ᆎ":"ᅲᅡ","ힷ":"ᅲᅡ丨","ᆏ":"ᅲᅥ","ᆐ":"ᅲᅥ丨","ᆑ":"ᅲᅧ","ㆊ":"ᅲᅧ","ᆒ":"ᅲᅧ丨","ㆋ":"ᅲᅧ丨","ힸ":"ᅲᅩ","ᆓ":"ᅲᅮ","ᆔ":"ᅲ丨","ㆌ":"ᅲ丨","ㆍ":"ᆞ","ퟅ":"ᆞᅡ","ᆟ":"ᆞᅥ","ퟆ":"ᆞᅥ丨","ᆠ":"ᆞᅮ","ᆢ":"ᆞᆞ","ᆡ":"ᆞ丨","ㆎ":"ᆞ丨","ヘ":"へ","⍁":"〼","⧄":"〼","꒞":"ꁊ","꒬":"ꁐ","꒜":"ꃀ","꒨":"ꄲ","꒿":"ꉙ","꒾":"ꊱ","꒔":"ꋍ","꓀":"ꎫ","꓂":"ꎵ","꒺":"ꎿ","꒰":"ꏂ","꒧":"ꑘ","⊥":"ꓕ","⟂":"ꓕ","𝈜":"ꓕ","Ʇ":"ꓕ","Ꞟ":"ꓤ","⅁":"ꓨ","⅂":"ꓶ","𝈕":"ꓶ","𝈫":"ꓶ","𖼦":"ꓶ","𐐑":"ꓶ","⅃":"𖼀","𑫦":"𑫥𑫯","𑫨":"𑫥𑫥","𑫩":"𑫥𑫥𑫯","𑫪":"𑫥𑫥𑫰","𑫧":"𑫥𑫰","𑫴":"𑫳𑫯","𑫶":"𑫳𑫳","𑫷":"𑫳𑫳𑫯","𑫸":"𑫳𑫳𑫰","𑫵":"𑫳𑫰","𑫬":"𑫫𑫯","𑫭":"𑫫𑫫","𑫮":"𑫫𑫫𑫯","⊕":"𐊨","⨁":"𐊨","🜨":"𐊨","Ꚛ":"𐊨","▽":"𐊼","𝈔":"𐊼","🜄":"𐊼","⧖":"𐋀","ꞛ":"𐐺","Ꞛ":"𐐒","𐒠":"𐒆","𐏑":"𐎂","𐏓":"𐎓","𒀸":"𐎚","☥":"𐦞","𓋹":"𐦞","〹":"卄","不":"不","丽":"丽","並":"並","⎜":"丨","⎟":"丨","⎢":"丨","⎥":"丨","⎪":"丨","⎮":"丨","㇑":"丨","ᅵ":"丨","ㅣ":"丨","⼁":"丨","ᆜ":"丨ー","ᆘ":"丨ᅡ","ᆙ":"丨ᅣ","ힽ":"丨ᅣᅩ","ힾ":"丨ᅣ丨","ힿ":"丨ᅧ","ퟀ":"丨ᅧ丨","ᆚ":"丨ᅩ","ퟁ":"丨ᅩ丨","ퟂ":"丨ᅭ","ᆛ":"丨ᅮ","ퟃ":"丨ᅲ","ᆝ":"丨ᆞ","ퟄ":"丨丨","串":"串","丸":"丸","丹":"丹","乁":"乁","㇠":"乙","⼄":"乙","㇟":"乚","⺃":"乚","㇖":"乛","⺂":"乛","⻲":"亀","亂":"亂","㇚":"亅","⼅":"亅","了":"了","ニ":"二","⼆":"二","𠄢":"𠄢","⼇":"亠","亮":"亮","⼈":"人","イ":"亻","⺅":"亻","什":"什","仌":"仌","令":"令","你":"你","倂":"併","倂":"併","侀":"侀","來":"來","例":"例","侮":"侮","侮":"侮","侻":"侻","便":"便","值":"値","倫":"倫","偺":"偺","備":"備","像":"像","僚":"僚","僧":"僧","僧":"僧","㒞":"㒞","⼉":"儿","兀":"兀","⺎":"兀","充":"充","免":"免","免":"免","兔":"兔","兤":"兤","⼊":"入","內":"內","全":"全","兩":"兩","ハ":"八","⼋":"八","六":"六","具":"具","𠔜":"𠔜","𠔥":"𠔥","冀":"冀","㒹":"㒹","⼌":"冂","再":"再","𠕋":"𠕋","冒":"冒","冕":"冕","㒻":"㒻","最":"最","⼍":"冖","冗":"冗","冤":"冤","⼎":"冫","冬":"冬","况":"况","况":"况","冷":"冷","凉":"凉","凌":"凌","凜":"凜","凞":"凞","⼏":"几","𠘺":"𠘺","凵":"凵","⼐":"凵","⼑":"刀","⺉":"刂","刃":"刃","切":"切","切":"切","列":"列","利":"利","㓟":"㓟","刺":"刺","刻":"刻","剆":"剆","割":"割","剷":"剷","劉":"劉","𠠄":"𠠄","カ":"力","力":"力","⼒":"力","劣":"劣","㔕":"㔕","劳":"劳","勇":"勇","勇":"勇","勉":"勉","勉":"勉","勒":"勒","勞":"勞","勤":"勤","勤":"勤","勵":"勵","⼓":"勹","勺":"勺","勺":"勺","包":"包","匆":"匆","𠣞":"𠣞","⼔":"匕","北":"北","北":"北","⼕":"匚","⼖":"匸","匿":"匿","⼗":"十","〸":"十","〺":"卅","卉":"卉","࿖":"卍","࿕":"卐","卑":"卑","卑":"卑","博":"博","ト":"卜","⼘":"卜","⼙":"卩","⺋":"㔾","即":"即","卵":"卵","卽":"卽","卿":"卿","卿":"卿","卿":"卿","⼚":"厂","𠨬":"𠨬","⼛":"厶","參":"參","⼜":"又","及":"及","叟":"叟","𠭣":"𠭣","ロ":"口","⼝":"口","囗":"口","⼞":"口","句":"句","叫":"叫","叱":"叱","吆":"吆","吏":"吏","吝":"吝","吸":"吸","呂":"呂","呈":"呈","周":"周","咞":"咞","咢":"咢","咽":"咽","䎛":"㖈","哶":"哶","唐":"唐","啓":"啓","啟":"啓","啕":"啕","啣":"啣","善":"善","善":"善","喇":"喇","喙":"喙","喙":"喙","喝":"喝","喝":"喝","喫":"喫","喳":"喳","嗀":"嗀","嗂":"嗂","嗢":"嗢","嘆":"嘆","嘆":"嘆","噑":"噑","噴":"噴","器":"器","囹":"囹","圖":"圖","圗":"圗","⼟":"土","士":"土","⼠":"土","型":"型","城":"城","㦳":"㘽","埴":"埴","堍":"堍","報":"報","堲":"堲","塀":"塀","塚":"塚","塚":"塚","塞":"塞","填":"塡","壿":"墫","墬":"墬","墳":"墳","壘":"壘","壟":"壟","𡓤":"𡓤","壮":"壮","売":"売","壷":"壷","⼡":"夂","夆":"夆","⼢":"夊","タ":"夕","⼣":"夕","多":"多","夢":"夢","⼤":"大","奄":"奄","奈":"奈","契":"契","奔":"奔","奢":"奢","女":"女","⼥":"女","𡚨":"𡚨","𡛪":"𡛪","姘":"姘","姬":"姬","娛":"娛","娧":"娧","婢":"婢","婦":"婦","嬀":"媯","㛮":"㛮","㛼":"㛼","媵":"媵","嬈":"嬈","嬨":"嬨","嬾":"嬾","嬾":"嬾","⼦":"子","⼧":"宀","宅":"宅","𡧈":"𡧈","寃":"寃","寘":"寘","寧":"寧","寧":"寧","寧":"寧","寮":"寮","寳":"寳","𡬘":"𡬘","⼨":"寸","寿":"寿","将":"将","⼩":"小","尢":"尢","⺐":"尢","⼪":"尢","⺏":"尣","㞁":"㞁","⼫":"尸","尿":"尿","屠":"屠","屢":"屢","層":"層","履":"履","屮":"屮","屮":"屮","⼬":"屮","𡴋":"𡴋","⼭":"山","峀":"峀","岍":"岍","𡷤":"𡷤","𡷦":"𡷦","崙":"崙","嵃":"嵃","嵐":"嵐","嵫":"嵫","嵮":"嵮","嵼":"嵼","嶲":"嶲","嶺":"嶺","⼮":"巛","巢":"巢","エ":"工","⼯":"工","⼰":"己","⺒":"巳","㠯":"㠯","巽":"巽","⼱":"巾","帲":"帡","帨":"帨","帽":"帽","幩":"幩","㡢":"㡢","𢆃":"𢆃","⼲":"干","年":"年","𢆟":"𢆟","⺓":"幺","⼳":"幺","⼴":"广","度":"度","㡼":"㡼","庰":"庰","庳":"庳","庶":"庶","廊":"廊","廊":"廊","廉":"廉","廒":"廒","廓":"廓","廙":"廙","廬":"廬","⼵":"廴","廾":"廾","⼶":"廾","𢌱":"𢌱","𢌱":"𢌱","弄":"弄","⼷":"弋","⼸":"弓","弢":"弢","弢":"弢","⼹":"彐","⺔":"彑","当":"当","㣇":"㣇","⼺":"彡","形":"形","彩":"彩","彫":"彫","⼻":"彳","律":"律","㣣":"㣣","徚":"徚","復":"復","徭":"徭","⼼":"心","⺖":"忄","⺗":"㣺","忍":"忍","志":"志","念":"念","忹":"忹","怒":"怒","怜":"怜","恵":"恵","㤜":"㤜","㤺":"㤺","悁":"悁","悔":"悔","悔":"悔","惇":"惇","惘":"惘","惡":"惡","𢛔":"𢛔","愈":"愈","慨":"慨","慄":"慄","慈":"慈","慌":"慌","慌":"慌","慎":"慎","慎":"慎","慠":"慠","慺":"慺","憎":"憎","憎":"憎","憎":"憎","憐":"憐","憤":"憤","憯":"憯","憲":"憲","𢡄":"𢡄","𢡊":"𢡊","懞":"懞","懲":"懲","懲":"懲","懲":"懲","懶":"懶","懶":"懶","戀":"戀","⼽":"戈","成":"成","戛":"戛","戮":"戮","戴":"戴","⼾":"戶","戸":"戶","⼿":"手","⺘":"扌","扝":"扝","抱":"抱","拉":"拉","拏":"拏","拓":"拓","拔":"拔","拼":"拼","拾":"拾","𢬌":"𢬌","挽":"挽","捐":"捐","捨":"捨","捻":"捻","掃":"掃","掠":"掠","掩":"掩","揄":"揄","揤":"揤","摒":"摒","𢯱":"𢯱","搜":"搜","搢":"搢","揅":"揅","摩":"摩","摷":"摷","摾":"摾","㨮":"㨮","搉":"㩁","撚":"撚","撝":"撝","擄":"擄","㩬":"㩬","⽀":"支","⽁":"攴","⺙":"攵","敏":"敏","敏":"敏","敖":"敖","敬":"敬","數":"數","𣀊":"𣀊","⽂":"文","⻫":"斉","⽃":"斗","料":"料","⽄":"斤","⽅":"方","旅":"旅","⽆":"无","⺛":"旡","既":"既","旣":"旣","⽇":"日","易":"易","曶":"㫚","㫤":"㫤","晉":"晉","晩":"晚","晴":"晴","晴":"晴","暑":"暑","暑":"暑","暈":"暈","㬈":"㬈","暜":"暜","暴":"暴","曆":"曆","㬙":"㬙","𣊸":"𣊸","⽈":"曰","更":"更","書":"書","⽉":"月","𣍟":"𣍟","肦":"朌","胐":"朏","胊":"朐","脁":"朓","胶":"㬵","朗":"朗","朗":"朗","朗":"朗","脧":"朘","望":"望","望":"望","幐":"㬺","䐠":"㬻","𣎓":"𣎓","膧":"朣","𣎜":"𣎜","⽊":"木","李":"李","杓":"杓","杖":"杖","杞":"杞","𣏃":"𣏃","柿":"杮","杻":"杻","枅":"枅","林":"林","㭉":"㭉","𣏕":"𣏕","柳":"柳","柺":"柺","栗":"栗","栟":"栟","桒":"桒","𣑭":"𣑭","梁":"梁","梅":"梅","梅":"梅","梎":"梎","梨":"梨","椔":"椔","楂":"楂","㮝":"㮝","㮝":"㮝","槩":"㮣","樧":"榝","榣":"榣","槪":"槪","樂":"樂","樂":"樂","樂":"樂","樓":"樓","𣚣":"𣚣","檨":"檨","櫓":"櫓","櫛":"櫛","欄":"欄","㰘":"㰘","⽋":"欠","次":"次","𣢧":"𣢧","歔":"歔","㱎":"㱎","⽌":"止","⻭":"歯","歲":"歲","歷":"歷","歹":"歹","⽍":"歹","⺞":"歺","殟":"殟","殮":"殮","⽎":"殳","殺":"殺","殺":"殺","殺":"殺","殻":"殻","𣪍":"𣪍","⽏":"毋","⺟":"母","𣫺":"𣫺","⽐":"比","⽑":"毛","⽒":"氏","⺠":"民","⽓":"气","⽔":"水","⺡":"氵","⺢":"氺","汎":"汎","汧":"汧","沈":"沈","沿":"沿","泌":"泌","泍":"泍","泥":"泥","𣲼":"𣲼","洛":"洛","洞":"洞","洴":"洴","派":"派","流":"流","流":"流","流":"流","洖":"洖","浩":"浩","浪":"浪","海":"海","海":"海","浸":"浸","涅":"涅","𣴞":"𣴞","淋":"淋","淚":"淚","淪":"淪","淹":"淹","渚":"渚","港":"港","湮":"湮","潙":"溈","滋":"滋","滋":"滋","溜":"溜","溺":"溺","滇":"滇","滑":"滑","滛":"滛","㴳":"㴳","漏":"漏","漢":"漢","漢":"漢","漣":"漣","𣻑":"𣻑","潮":"潮","𣽞":"𣽞","𣾎":"𣾎","濆":"濆","濫":"濫","濾":"濾","瀛":"瀛","瀞":"瀞","瀞":"瀞","瀹":"瀹","灊":"灊","㶖":"㶖","⽕":"火","⺣":"灬","灰":"灰","灷":"灷","災":"災","炙":"炙","炭":"炭","烈":"烈","烙":"烙","煮":"煮","煮":"煮","𤉣":"𤉣","煅":"煅","煉":"煉","𤋮":"𤋮","熜":"熜","燎":"燎","燐":"燐","𤎫":"𤎫","爐":"爐","爛":"爛","爨":"爨","⽖":"爪","爫":"爫","⺤":"爫","爵":"爵","爵":"爵","⽗":"父","⽘":"爻","⺦":"丬","⽙":"爿","⽚":"片","牐":"牐","⽛":"牙","𤘈":"𤘈","⽜":"牛","牢":"牢","犀":"犀","犕":"犕","⽝":"犬","⺨":"犭","犯":"犯","狀":"狀","𤜵":"𤜵","狼":"狼","猪":"猪","猪":"猪","𤠔":"𤠔","獵":"獵","獺":"獺","⽞":"玄","率":"率","率":"率","⽟":"玉","王":"王","㺬":"㺬","玥":"玥","玲":"玲","㺸":"㺸","㺸":"㺸","珞":"珞","琉":"琉","理":"理","琢":"琢","瑇":"瑇","瑜":"瑜","瑩":"瑩","瑱":"瑱","瑱":"瑱","璅":"璅","璉":"璉","璘":"璘","瓊":"瓊","⽠":"瓜","⽡":"瓦","㼛":"㼛","甆":"甆","⽢":"甘","⽣":"生","甤":"甤","⽤":"用","⽥":"田","画":"画","甾":"甾","𤰶":"𤰶","留":"留","略":"略","異":"異","異":"異","𤲒":"𤲒","⽦":"疋","⽧":"疒","痢":"痢","瘐":"瘐","瘟":"瘟","瘝":"瘝","療":"療","癩":"癩","⽨":"癶","⽩":"白","𤾡":"𤾡","𤾸":"𤾸","⽪":"皮","⽫":"皿","𥁄":"𥁄","㿼":"㿼","益":"益","益":"益","盛":"盛","盧":"盧","䀈":"䀈","⽬":"目","直":"直","直":"直","𥃲":"𥃲","𥃳":"𥃳","省":"省","䀘":"䀘","𥄙":"𥄙","眞":"眞","真":"真","真":"真","𥄳":"𥄳","着":"着","睊":"睊","睊":"睊","鿃":"䀹","䀹":"䀹","䀹":"䀹","晣":"䀿","䁆":"䁆","瞋":"瞋","𥉉":"𥉉","瞧":"瞧","⽭":"矛","⽮":"矢","⽯":"石","䂖":"䂖","𥐝":"𥐝","硏":"研","硎":"硎","硫":"硫","碌":"碌","碌":"碌","碑":"碑","磊":"磊","磌":"磌","磌":"磌","磻":"磻","䃣":"䃣","礪":"礪","⽰":"示","⺭":"礻","礼":"礼","社":"社","祈":"祈","祉":"祉","𥘦":"𥘦","祐":"祐","祖":"祖","祖":"祖","祝":"祝","神":"神","祥":"祥","視":"視","視":"視","祿":"祿","𥚚":"𥚚","禍":"禍","禎":"禎","福":"福","福":"福","𥛅":"𥛅","禮":"禮","⽱":"禸","⽲":"禾","秊":"秊","䄯":"䄯","秫":"秫","稜":"稜","穊":"穊","穀":"穀","穀":"穀","穏":"穏","⽳":"穴","突":"突","𥥼":"𥥼","窱":"窱","立":"立","⽴":"立","⻯":"竜","𥪧":"𥪧","𥪧":"𥪧","竮":"竮","⽵":"竹","笠":"笠","節":"節","節":"節","䈂":"䈂","𥮫":"𥮫","篆":"篆","䈧":"䈧","築":"築","𥲀":"𥲀","𥳐":"𥳐","簾":"簾","籠":"籠","⽶":"米","类":"类","粒":"粒","精":"精","糒":"糒","糖":"糖","糨":"糨","䊠":"䊠","糣":"糣","糧":"糧","⽷":"糸","⺯":"糹","𥾆":"𥾆","紀":"紀","紐":"紐","索":"索","累":"累","絶":"絕","絣":"絣","絛":"絛","綠":"綠","綾":"綾","緇":"緇","練":"練","練":"練","練":"練","縂":"縂","䌁":"䌁","縉":"縉","縷":"縷","繁":"繁","繅":"繅","𦇚":"𦇚","䌴":"䌴","⽸":"缶","𦈨":"𦈨","缾":"缾","𦉇":"𦉇","⽹":"网","⺫":"罒","⺲":"罒","⺱":"罓","䍙":"䍙","署":"署","𦋙":"𦋙","罹":"罹","罺":"罺","羅":"羅","𦌾":"𦌾","⽺":"羊","羕":"羕","羚":"羚","羽":"羽","⽻":"羽","翺":"翺","老":"老","⽼":"老","⺹":"耂","者":"者","者":"者","者":"者","⽽":"而","𦓚":"𦓚","⽾":"耒","𦔣":"𦔣","⽿":"耳","聆":"聆","聠":"聠","𦖨":"𦖨","聯":"聯","聰":"聰","聾":"聾","⾀":"聿","⺺":"肀","⾁":"肉","肋":"肋","肭":"肭","育":"育","䏕":"䏕","䏙":"䏙","腁":"胼","脃":"脃","脾":"脾","䐋":"䐋","朡":"朡","𦞧":"𦞧","𦞵":"𦞵","朦":"䑃","臘":"臘","⾂":"臣","臨":"臨","⾃":"自","臭":"臭","⾄":"至","⾅":"臼","舁":"舁","舁":"舁","舄":"舄","⾆":"舌","舘":"舘","⾇":"舛","⾈":"舟","䑫":"䑫","⾉":"艮","良":"良","⾊":"色","⾋":"艸","艹":"艹","艹":"艹","⺾":"艹","⺿":"艹","⻀":"艹","芋":"芋","芑":"芑","芝":"芝","花":"花","芳":"芳","芽":"芽","若":"若","若":"若","苦":"苦","𦬼":"𦬼","茶":"茶","荒":"荒","荣":"荣","茝":"茝","茣":"茣","莽":"莽","荓":"荓","菉":"菉","菊":"菊","菌":"菌","菜":"菜","菧":"菧","華":"華","菱":"菱","著":"著","著":"著","𦰶":"𦰶","莭":"莭","落":"落","葉":"葉","蔿":"蒍","𦳕":"𦳕","𦵫":"𦵫","蓮":"蓮","蓱":"蓱","蓳":"蓳","蓼":"蓼","蔖":"蔖","䔫":"䔫","蕤":"蕤","𦼬":"𦼬","藍":"藍","䕝":"䕝","𦾱":"𦾱","䕡":"䕡","藺":"藺","蘆":"蘆","䕫":"䕫","蘒":"蘒","蘭":"蘭","𧃒":"𧃒","虁":"蘷","蘿":"蘿","⾌":"虍","⻁":"虎","虐":"虐","虜":"虜","虜":"虜","虧":"虧","虩":"虩","⾍":"虫","蚩":"蚩","蚈":"蚈","蛢":"蛢","蜎":"蜎","蜨":"蜨","蝫":"蝫","蟡":"蟡","蝹":"蝹","蝹":"蝹","螆":"螆","䗗":"䗗","𧏊":"𧏊","螺":"螺","蠁":"蠁","䗹":"䗹","蠟":"蠟","⾎":"血","行":"行","⾏":"行","衠":"衠","衣":"衣","⾐":"衣","⻂":"衤","裂":"裂","𧙧":"𧙧","裏":"裏","裗":"裗","裞":"裞","裡":"裡","裸":"裸","裺":"裺","䘵":"䘵","褐":"褐","襁":"襁","襤":"襤","⾑":"襾","⻄":"西","⻃":"覀","覆":"覆","見":"見","⾒":"見","𧢮":"𧢮","⻅":"见","⾓":"角","⾔":"言","𧥦":"𧥦","詽":"訮","訞":"䚶","䚾":"䚾","䛇":"䛇","誠":"誠","說":"說","說":"說","調":"調","請":"請","諒":"諒","論":"論","諭":"諭","諭":"諭","諸":"諸","諸":"諸","諾":"諾","諾":"諾","謁":"謁","謁":"謁","謹":"謹","謹":"謹","識":"識","讀":"讀","讏":"讆","變":"變","變":"變","⻈":"讠","⾕":"谷","⾖":"豆","豈":"豈","豕":"豕","⾗":"豕","豣":"豜","⾘":"豸","𧲨":"𧲨","⾙":"貝","貫":"貫","賁":"賁","賂":"賂","賈":"賈","賓":"賓","贈":"贈","贈":"贈","贛":"贛","⻉":"贝","⾚":"赤","⾛":"走","起":"起","趆":"赿","𧻓":"𧻓","𧼯":"𧼯","⾜":"足","跋":"跋","趼":"趼","跺":"跥","路":"路","跰":"跰","躛":"躗","⾝":"身","車":"車","⾞":"車","軔":"軔","輧":"軿","輦":"輦","輪":"輪","輸":"輸","輸":"輸","輻":"輻","轢":"轢","⻋":"车","⾟":"辛","辞":"辞","辰":"辰","⾠":"辰","⾡":"辵","辶":"辶","⻌":"辶","⻍":"辶","巡":"巡","連":"連","逸":"逸","逸":"逸","遲":"遲","遼":"遼","𨗒":"𨗒","𨗭":"𨗭","邏":"邏","⾢":"邑","邔":"邔","郎":"郎","郞":"郎","郞":"郎","郱":"郱","都":"都","𨜮":"𨜮","鄑":"鄑","鄛":"鄛","⾣":"酉","酪":"酪","醙":"醙","醴":"醴","⾤":"釆","里":"里","⾥":"里","量":"量","金":"金","⾦":"金","鈴":"鈴","鈸":"鈸","鉶":"鉶","鋗":"鋗","鋘":"鋘","鉼":"鉼","錄":"錄","鍊":"鍊","鎮":"鎭","鏹":"鏹","鐕":"鐕","𨯺":"𨯺","⻐":"钅","⻑":"長","⾧":"長","⻒":"镸","⻓":"长","⾨":"門","開":"開","䦕":"䦕","閭":"閭","閷":"閷","𨵷":"𨵷","⻔":"门","⾩":"阜","⻏":"阝","⻖":"阝","阮":"阮","陋":"陋","降":"降","陵":"陵","陸":"陸","陼":"陼","隆":"隆","隣":"隣","䧦":"䧦","⾪":"隶","隷":"隷","隸":"隷","隸":"隷","⾫":"隹","雃":"雃","離":"離","難":"難","難":"難","⾬":"雨","零":"零","雷":"雷","霣":"霣","𩅅":"𩅅","露":"露","靈":"靈","⾭":"靑","⻘":"青","靖":"靖","靖":"靖","𩇟":"𩇟","⾮":"非","⾯":"面","𩈚":"𩈚","⾰":"革","䩮":"䩮","䩶":"䩶","⾱":"韋","韛":"韛","韠":"韠","⻙":"韦","⾲":"韭","𩐊":"𩐊","⾳":"音","響":"響","響":"響","⾴":"頁","䪲":"䪲","頋":"頋","頋":"頋","頋":"頋","領":"領","頩":"頩","𩒖":"𩒖","頻":"頻","頻":"頻","類":"類","⻚":"页","⾵":"風","𩖶":"𩖶","⻛":"风","⾶":"飛","⻜":"飞","⻝":"食","⾷":"食","⻟":"飠","飢":"飢","飯":"飯","飼":"飼","䬳":"䬳","館":"館","餩":"餩","⻠":"饣","⾸":"首","⾹":"香","馧":"馧","⾺":"馬","駂":"駂","駱":"駱","駾":"駾","驪":"驪","⻢":"马","⾻":"骨","䯎":"䯎","⾼":"高","⾽":"髟","𩬰":"𩬰","鬒":"鬒","鬒":"鬒","⾾":"鬥","⾿":"鬯","⿀":"鬲","⿁":"鬼","⻤":"鬼","⿂":"魚","魯":"魯","鱀":"鱀","鱗":"鱗","⻥":"鱼","⿃":"鳥","鳽":"鳽","䳎":"䳎","鵧":"鵧","䳭":"䳭","𪃎":"𪃎","鶴":"鶴","𪄅":"𪄅","䳸":"䳸","鷺":"鷺","𪈎":"𪈎","鸞":"鸞","鹃":"鹂","⿄":"鹵","鹿":"鹿","⿅":"鹿","𪊑":"𪊑","麗":"麗","麟":"麟","⿆":"麥","⻨":"麦","麻":"麻","⿇":"麻","𪎒":"𪎒","⿈":"黃","⻩":"黄","⿉":"黍","黎":"黎","䵖":"䵖","⿊":"黑","黒":"黑","墨":"墨","黹":"黹","⿋":"黹","⿌":"黽","鼅":"鼅","黾":"黾","⿍":"鼎","鼏":"鼏","⿎":"鼓","鼖":"鼖","⿏":"鼠","鼻":"鼻","⿐":"鼻","齃":"齃","⿑":"齊","⻬":"齐","⿒":"齒","𪘀":"𪘀","⻮":"齿","龍":"龍","⿓":"龍","龎":"龎","⻰":"龙","龜":"龜","龜":"龜","龜":"龜","⿔":"龜","⻳":"龟","⿕":"龠"}},{}],282:[function(e,t,i){"use strict";var n=e("./data.json");var r=RegExp(Object.keys(n).map((function(e){return e.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")})).join("|"),"g");function o(e){return n[e]}t.exports=function(e){return e.replace(r,o)}},{"./data.json":281}],283:[function(e,t,i){(function(e){(function(){function i(t){try{if(!e.localStorage)return!1}catch(e){return!1}var i=e.localStorage[t];return null!=i&&"true"===String(i).toLowerCase()}t.exports=function(e,t){if(i("noDeprecation"))return e;var n=!1;return function(){if(!n){if(i("throwDeprecation"))throw new Error(t);i("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],284:[function(e,t,i){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],285:[function(e,t,i){"use strict";var n=e("is-arguments"),r=e("is-generator-function"),o=e("which-typed-array"),s=e("is-typed-array");function a(e){return e.call.bind(e)}var c="undefined"!=typeof BigInt,d="undefined"!=typeof Symbol,l=a(Object.prototype.toString),u=a(Number.prototype.valueOf),h=a(String.prototype.valueOf),f=a(Boolean.prototype.valueOf);if(c)var p=a(BigInt.prototype.valueOf);if(d)var g=a(Symbol.prototype.valueOf);function v(e,t){if("object"!=typeof e)return!1;try{return t(e),!0}catch(e){return!1}}function m(e){return"[object Map]"===l(e)}function y(e){return"[object Set]"===l(e)}function b(e){return"[object WeakMap]"===l(e)}function S(e){return"[object WeakSet]"===l(e)}function _(e){return"[object ArrayBuffer]"===l(e)}function E(e){return"undefined"!=typeof ArrayBuffer&&(_.working?_(e):e instanceof ArrayBuffer)}function w(e){return"[object DataView]"===l(e)}function T(e){return"undefined"!=typeof DataView&&(w.working?w(e):e instanceof DataView)}i.isArgumentsObject=n,i.isGeneratorFunction=r,i.isTypedArray=s,i.isPromise=function(e){return"undefined"!=typeof Promise&&e instanceof Promise||null!==e&&"object"==typeof e&&"function"==typeof e.then&&"function"==typeof e.catch},i.isArrayBufferView=function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):s(e)||T(e)},i.isUint8Array=function(e){return"Uint8Array"===o(e)},i.isUint8ClampedArray=function(e){return"Uint8ClampedArray"===o(e)},i.isUint16Array=function(e){return"Uint16Array"===o(e)},i.isUint32Array=function(e){return"Uint32Array"===o(e)},i.isInt8Array=function(e){return"Int8Array"===o(e)},i.isInt16Array=function(e){return"Int16Array"===o(e)},i.isInt32Array=function(e){return"Int32Array"===o(e)},i.isFloat32Array=function(e){return"Float32Array"===o(e)},i.isFloat64Array=function(e){return"Float64Array"===o(e)},i.isBigInt64Array=function(e){return"BigInt64Array"===o(e)},i.isBigUint64Array=function(e){return"BigUint64Array"===o(e)},m.working="undefined"!=typeof Map&&m(new Map),i.isMap=function(e){return"undefined"!=typeof Map&&(m.working?m(e):e instanceof Map)},y.working="undefined"!=typeof Set&&y(new Set),i.isSet=function(e){return"undefined"!=typeof Set&&(y.working?y(e):e instanceof Set)},b.working="undefined"!=typeof WeakMap&&b(new WeakMap),i.isWeakMap=function(e){return"undefined"!=typeof WeakMap&&(b.working?b(e):e instanceof WeakMap)},S.working="undefined"!=typeof WeakSet&&S(new WeakSet),i.isWeakSet=function(e){return S(e)},_.working="undefined"!=typeof ArrayBuffer&&_(new ArrayBuffer),i.isArrayBuffer=E,w.working="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView&&w(new DataView(new ArrayBuffer(1),0,1)),i.isDataView=T;var I="undefined"!=typeof SharedArrayBuffer?SharedArrayBuffer:void 0;function R(e){return"[object SharedArrayBuffer]"===l(e)}function M(e){return void 0!==I&&(void 0===R.working&&(R.working=R(new I)),R.working?R(e):e instanceof I)}function k(e){return v(e,u)}function C(e){return v(e,h)}function O(e){return v(e,f)}function A(e){return c&&v(e,p)}function P(e){return d&&v(e,g)}i.isSharedArrayBuffer=M,i.isAsyncFunction=function(e){return"[object AsyncFunction]"===l(e)},i.isMapIterator=function(e){return"[object Map Iterator]"===l(e)},i.isSetIterator=function(e){return"[object Set Iterator]"===l(e)},i.isGeneratorObject=function(e){return"[object Generator]"===l(e)},i.isWebAssemblyCompiledModule=function(e){return"[object WebAssembly.Module]"===l(e)},i.isNumberObject=k,i.isStringObject=C,i.isBooleanObject=O,i.isBigIntObject=A,i.isSymbolObject=P,i.isBoxedPrimitive=function(e){return k(e)||C(e)||O(e)||A(e)||P(e)},i.isAnyArrayBuffer=function(e){return"undefined"!=typeof Uint8Array&&(E(e)||M(e))},["isProxy","isExternal","isModuleNamespaceObject"].forEach((function(e){Object.defineProperty(i,e,{enumerable:!1,value:function(){throw new Error(e+" is not supported in userland")}})}))},{"is-arguments":147,"is-generator-function":149,"is-typed-array":150,"which-typed-array":303}],286:[function(e,t,i){(function(t){(function(){var n=Object.getOwnPropertyDescriptors||function(e){for(var t=Object.keys(e),i={},n=0;n=o)return e;switch(e){case"%s":return String(n[i++]);case"%d":return Number(n[i++]);case"%j":try{return JSON.stringify(n[i++])}catch(e){return"[Circular]"}default:return e}})),a=n[i];i=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),g(t)?n.showHidden=t:t&&i._extend(n,t),b(n.showHidden)&&(n.showHidden=!1),b(n.depth)&&(n.depth=2),b(n.colors)&&(n.colors=!1),b(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=d),u(n,e,n.depth)}function d(e,t){var i=c.styles[t];return i?"["+c.colors[i][0]+"m"+e+"["+c.colors[i][1]+"m":e}function l(e,t){return e}function u(e,t,n){if(e.customInspect&&t&&T(t.inspect)&&t.inspect!==i.inspect&&(!t.constructor||t.constructor.prototype!==t)){var r=t.inspect(n,e);return y(r)||(r=u(e,r,n)),r}var o=function(e,t){if(b(t))return e.stylize("undefined","undefined");if(y(t)){var i="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(i,"string")}if(m(t))return e.stylize(""+t,"number");if(g(t))return e.stylize(""+t,"boolean");if(v(t))return e.stylize("null","null")}(e,t);if(o)return o;var s=Object.keys(t),a=function(e){var t={};return e.forEach((function(e,i){t[e]=!0})),t}(s);if(e.showHidden&&(s=Object.getOwnPropertyNames(t)),w(t)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return h(t);if(0===s.length){if(T(t)){var c=t.name?": "+t.name:"";return e.stylize("[Function"+c+"]","special")}if(S(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(E(t))return e.stylize(Date.prototype.toString.call(t),"date");if(w(t))return h(t)}var d,l="",_=!1,I=["{","}"];(p(t)&&(_=!0,I=["[","]"]),T(t))&&(l=" [Function"+(t.name?": "+t.name:"")+"]");return S(t)&&(l=" "+RegExp.prototype.toString.call(t)),E(t)&&(l=" "+Date.prototype.toUTCString.call(t)),w(t)&&(l=" "+h(t)),0!==s.length||_&&0!=t.length?n<0?S(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),d=_?function(e,t,i,n,r){for(var o=[],s=0,a=t.length;s=0&&0,e+t.replace(/\u001b\[\d\d?m/g,"").length+1}),0);if(n>60)return i[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+i[1];return i[0]+t+" "+e.join(", ")+" "+i[1]}(d,l,I)):I[0]+l+I[1]}function h(e){return"["+Error.prototype.toString.call(e)+"]"}function f(e,t,i,n,r,o){var s,a,c;if((c=Object.getOwnPropertyDescriptor(t,r)||{value:t[r]}).get?a=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(a=e.stylize("[Setter]","special")),k(n,r)||(s="["+r+"]"),a||(e.seen.indexOf(c.value)<0?(a=v(i)?u(e,c.value,null):u(e,c.value,i-1)).indexOf("\n")>-1&&(a=o?a.split("\n").map((function(e){return" "+e})).join("\n").slice(2):"\n"+a.split("\n").map((function(e){return" "+e})).join("\n")):a=e.stylize("[Circular]","special")),b(s)){if(o&&r.match(/^\d+$/))return a;(s=JSON.stringify(""+r)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.slice(1,-1),s=e.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=e.stylize(s,"string"))}return s+": "+a}function p(e){return Array.isArray(e)}function g(e){return"boolean"==typeof e}function v(e){return null===e}function m(e){return"number"==typeof e}function y(e){return"string"==typeof e}function b(e){return void 0===e}function S(e){return _(e)&&"[object RegExp]"===I(e)}function _(e){return"object"==typeof e&&null!==e}function E(e){return _(e)&&"[object Date]"===I(e)}function w(e){return _(e)&&("[object Error]"===I(e)||e instanceof Error)}function T(e){return"function"==typeof e}function I(e){return Object.prototype.toString.call(e)}function R(e){return e<10?"0"+e.toString(10):e.toString(10)}i.debuglog=function(e){if(e=e.toUpperCase(),!o[e])if(s.test(e)){var n=t.pid;o[e]=function(){var t=i.format.apply(i,arguments);console.error("%s %d: %s",e,n,t)}}else o[e]=function(){};return o[e]},i.inspect=c,c.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},c.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},i.types=e("./support/types"),i.isArray=p,i.isBoolean=g,i.isNull=v,i.isNullOrUndefined=function(e){return null==e},i.isNumber=m,i.isString=y,i.isSymbol=function(e){return"symbol"==typeof e},i.isUndefined=b,i.isRegExp=S,i.types.isRegExp=S,i.isObject=_,i.isDate=E,i.types.isDate=E,i.isError=w,i.types.isNativeError=w,i.isFunction=T,i.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},i.isBuffer=e("./support/isBuffer");var M=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function k(e,t){return Object.prototype.hasOwnProperty.call(e,t)}i.log=function(){var e,t;console.log("%s - %s",(e=new Date,t=[R(e.getHours()),R(e.getMinutes()),R(e.getSeconds())].join(":"),[e.getDate(),M[e.getMonth()],t].join(" ")),i.format.apply(i,arguments))},i.inherits=e("inherits"),i._extend=function(e,t){if(!t||!_(t))return e;for(var i=Object.keys(t),n=i.length;n--;)e[i[n]]=t[i[n]];return e};var C="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function O(e,t){if(!e){var i=new Error("Promise was rejected with a falsy value");i.reason=e,e=i}return t(e)}i.promisify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');if(C&&e[C]){var t;if("function"!=typeof(t=e[C]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(t,C,{value:t,enumerable:!1,writable:!1,configurable:!0}),t}function t(){for(var t,i,n=new Promise((function(e,n){t=e,i=n})),r=[],o=0;o>>9<<4)+1}function r(e,t){const i=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(i>>16)<<16|65535&i}function o(e,t,i,n,o,s){return r((a=r(r(t,e),r(n,s)))<<(c=o)|a>>>32-c,i);var a,c}function s(e,t,i,n,r,s,a){return o(t&i|~t&n,e,t,r,s,a)}function a(e,t,i,n,r,s,a){return o(t&n|i&~n,e,t,r,s,a)}function c(e,t,i,n,r,s,a){return o(t^i^n,e,t,r,s,a)}function d(e,t,i,n,r,s,a){return o(i^(t|~n),e,t,r,s,a)}Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0;var l=function(e){if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=new Uint8Array(t.length);for(let i=0;i>5]>>>r%32&255,o=parseInt(n.charAt(i>>>4&15)+n.charAt(15&i),16);t.push(o)}return t}(function(e,t){e[t>>5]|=128<>5]|=(255&e[n/8])<>>24,i[1]=t>>>16&255,i[2]=t>>>8&255,i[3]=255&t,i[4]=(t=parseInt(e.slice(9,13),16))>>>8,i[5]=255&t,i[6]=(t=parseInt(e.slice(14,18),16))>>>8,i[7]=255&t,i[8]=(t=parseInt(e.slice(19,23),16))>>>8,i[9]=255&t,i[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,i[11]=t/4294967296&255,i[12]=t>>>24&255,i[13]=t>>>16&255,i[14]=t>>>8&255,i[15]=255&t,i};i.default=o},{"./validate.js":301}],292:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0;i.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i},{}],293:[function(e,t,i){"use strict";let n;Object.defineProperty(i,"__esModule",{value:!0}),i.default=function(){if(!n&&(n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!n))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return n(r)};const r=new Uint8Array(16)},{}],294:[function(e,t,i){"use strict";function n(e,t,i,n){switch(e){case 0:return t&i^~t&n;case 1:case 3:return t^i^n;case 2:return t&i^t&n^i&n}}function r(e,t){return e<>>32-t}Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0;var o=function(e){const t=[1518500249,1859775393,2400959708,3395469782],i=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){const t=unescape(encodeURIComponent(e));e=[];for(let i=0;i>>0;u=l,l=d,d=r(c,30)>>>0,c=s,s=a}i[0]=i[0]+s>>>0,i[1]=i[1]+c>>>0,i[2]=i[2]+d>>>0,i[3]=i[3]+l>>>0,i[4]=i[4]+u>>>0}return[i[0]>>24&255,i[0]>>16&255,i[0]>>8&255,255&i[0],i[1]>>24&255,i[1]>>16&255,i[1]>>8&255,255&i[1],i[2]>>24&255,i[2]>>16&255,i[2]>>8&255,255&i[2],i[3]>>24&255,i[3]>>16&255,i[3]>>8&255,255&i[3],i[4]>>24&255,i[4]>>16&255,i[4]>>8&255,255&i[4]]};i.default=o},{}],295:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0,i.unsafeStringify=s;var n,r=(n=e("./validate.js"))&&n.__esModule?n:{default:n};const o=[];for(let e=0;e<256;++e)o.push((e+256).toString(16).slice(1));function s(e,t=0){return(o[e[t+0]]+o[e[t+1]]+o[e[t+2]]+o[e[t+3]]+"-"+o[e[t+4]]+o[e[t+5]]+"-"+o[e[t+6]]+o[e[t+7]]+"-"+o[e[t+8]]+o[e[t+9]]+"-"+o[e[t+10]]+o[e[t+11]]+o[e[t+12]]+o[e[t+13]]+o[e[t+14]]+o[e[t+15]]).toLowerCase()}var a=function(e,t=0){const i=s(e,t);if(!(0,r.default)(i))throw TypeError("Stringified UUID is invalid");return i};i.default=a},{"./validate.js":301}],296:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0;var n,r=(n=e("./rng.js"))&&n.__esModule?n:{default:n},o=e("./stringify.js");let s,a,c=0,d=0;var l=function(e,t,i){let n=t&&i||0;const l=t||new Array(16);let u=(e=e||{}).node||s,h=void 0!==e.clockseq?e.clockseq:a;if(null==u||null==h){const t=e.random||(e.rng||r.default)();null==u&&(u=s=[1|t[0],t[1],t[2],t[3],t[4],t[5]]),null==h&&(h=a=16383&(t[6]<<8|t[7]))}let f=void 0!==e.msecs?e.msecs:Date.now(),p=void 0!==e.nsecs?e.nsecs:d+1;const g=f-c+(p-d)/1e4;if(g<0&&void 0===e.clockseq&&(h=h+1&16383),(g<0||f>c)&&void 0===e.nsecs&&(p=0),p>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");c=f,d=p,a=h,f+=122192928e5;const v=(1e4*(268435455&f)+p)%4294967296;l[n++]=v>>>24&255,l[n++]=v>>>16&255,l[n++]=v>>>8&255,l[n++]=255&v;const m=f/4294967296*1e4&268435455;l[n++]=m>>>8&255,l[n++]=255&m,l[n++]=m>>>24&15|16,l[n++]=m>>>16&255,l[n++]=h>>>8|128,l[n++]=255&h;for(let e=0;e<6;++e)l[n+e]=u[e];return t||(0,o.unsafeStringify)(l)};i.default=l},{"./rng.js":293,"./stringify.js":295}],297:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0;var n=o(e("./v35.js")),r=o(e("./md5.js"));function o(e){return e&&e.__esModule?e:{default:e}}var s=(0,n.default)("v3",48,r.default);i.default=s},{"./md5.js":288,"./v35.js":298}],298:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.URL=i.DNS=void 0,i.default=function(e,t,i){function n(e,n,s,a){var c;if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));const t=[];for(let i=0;i",e.GreaterThanOrEqual=">=",e.LessThanOrEqual="<="}(i.ConditionOperator||(i.ConditionOperator={})),i.DMMemberCountCondition="2",i.isDmMemberCountCondition=function(e){return"==2"===e||"2"===e},function(e){e.EventMatch="event_match",e.EventPropertyIs="event_property_is",e.EventPropertyContains="event_property_contains",e.ContainsDisplayName="contains_display_name",e.RoomMemberCount="room_member_count",e.SenderNotificationPermission="sender_notification_permission",e.CallStarted="call_started",e.CallStartedPrefix="org.matrix.msc3914.call_started"}(i.ConditionKind||(i.ConditionKind={})),function(e){e.Override="override",e.ContentSpecific="content",e.RoomSpecific="room",e.SenderSpecific="sender",e.Underride="underride"}(i.PushRuleKind||(i.PushRuleKind={})),function(e){e.Master=".m.rule.master",e.IsUserMention=".org.matrix.msc3952.is_user_mention",e.IsRoomMention=".org.matrix.msc3952.is_room_mention",e.ContainsDisplayName=".m.rule.contains_display_name",e.ContainsUserName=".m.rule.contains_user_name",e.AtRoomNotification=".m.rule.roomnotif",e.DM=".m.rule.room_one_to_one",e.EncryptedDM=".m.rule.encrypted_room_one_to_one",e.Message=".m.rule.message",e.EncryptedMessage=".m.rule.encrypted",e.InviteToSelf=".m.rule.invite_for_me",e.MemberEvent=".m.rule.member_event",e.IncomingCall=".m.rule.call",e.SuppressNotices=".m.rule.suppress_notices",e.Tombstone=".m.rule.tombstone",e.PollStart=".m.rule.poll_start",e.PollStartUnstable=".org.matrix.msc3930.rule.poll_start",e.PollEnd=".m.rule.poll_end",e.PollEndUnstable=".org.matrix.msc3930.rule.poll_end",e.PollStartOneToOne=".m.rule.poll_start_one_to_one",e.PollStartOneToOneUnstable=".org.matrix.msc3930.rule.poll_start_one_to_one",e.PollEndOneToOne=".m.rule.poll_end_one_to_one",e.PollEndOneToOneUnstable=".org.matrix.msc3930.rule.poll_end_one_to_one"}(i.RuleId||(i.RuleId={}))},{}],305:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.M_BEACON=i.M_BEACON_INFO=void 0;const n=e("../NamespacedValue");i.M_BEACON_INFO=new n.UnstableValue("m.beacon_info","org.matrix.msc3672.beacon_info"),i.M_BEACON=new n.UnstableValue("m.beacon","org.matrix.msc3672.beacon")},{"../NamespacedValue":316}],306:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.LOCAL_NOTIFICATION_SETTINGS_PREFIX=i.PUSHER_DEVICE_ID=i.PUSHER_ENABLED=i.EVENT_VISIBILITY_CHANGE_TYPE=i.UNSTABLE_ELEMENT_FUNCTIONAL_USERS=i.MSC3912_RELATION_BASED_REDACTIONS_PROP=i.UNSTABLE_MSC2716_MARKER=i.UNSTABLE_MSC3089_BRANCH=i.UNSTABLE_MSC3089_LEAF=i.UNSTABLE_MSC3089_TREE_SUBTYPE=i.UNSTABLE_MSC3088_ENABLED=i.UNSTABLE_MSC3088_PURPOSE=i.ToDeviceMessageId=i.RoomType=i.RoomCreateTypeField=i.MsgType=i.RelationType=i.EventType=void 0;const n=e("../NamespacedValue");!function(e){e.RoomCanonicalAlias="m.room.canonical_alias",e.RoomCreate="m.room.create",e.RoomJoinRules="m.room.join_rules",e.RoomMember="m.room.member",e.RoomThirdPartyInvite="m.room.third_party_invite",e.RoomPowerLevels="m.room.power_levels",e.RoomName="m.room.name",e.RoomTopic="m.room.topic",e.RoomAvatar="m.room.avatar",e.RoomPinnedEvents="m.room.pinned_events",e.RoomEncryption="m.room.encryption",e.RoomHistoryVisibility="m.room.history_visibility",e.RoomGuestAccess="m.room.guest_access",e.RoomServerAcl="m.room.server_acl",e.RoomTombstone="m.room.tombstone",e.RoomPredecessor="org.matrix.msc3946.room_predecessor",e.SpaceChild="m.space.child",e.SpaceParent="m.space.parent",e.RoomRedaction="m.room.redaction",e.RoomMessage="m.room.message",e.RoomMessageEncrypted="m.room.encrypted",e.Sticker="m.sticker",e.CallInvite="m.call.invite",e.CallCandidates="m.call.candidates",e.CallAnswer="m.call.answer",e.CallHangup="m.call.hangup",e.CallReject="m.call.reject",e.CallSelectAnswer="m.call.select_answer",e.CallNegotiate="m.call.negotiate",e.CallSDPStreamMetadataChanged="m.call.sdp_stream_metadata_changed",e.CallSDPStreamMetadataChangedPrefix="org.matrix.call.sdp_stream_metadata_changed",e.CallReplaces="m.call.replaces",e.CallAssertedIdentity="m.call.asserted_identity",e.CallAssertedIdentityPrefix="org.matrix.call.asserted_identity",e.KeyVerificationRequest="m.key.verification.request",e.KeyVerificationStart="m.key.verification.start",e.KeyVerificationCancel="m.key.verification.cancel",e.KeyVerificationMac="m.key.verification.mac",e.KeyVerificationDone="m.key.verification.done",e.KeyVerificationKey="m.key.verification.key",e.KeyVerificationAccept="m.key.verification.accept",e.KeyVerificationReady="m.key.verification.ready",e.RoomMessageFeedback="m.room.message.feedback",e.Reaction="m.reaction",e.PollStart="org.matrix.msc3381.poll.start",e.Typing="m.typing",e.Receipt="m.receipt",e.Presence="m.presence",e.FullyRead="m.fully_read",e.Tag="m.tag",e.SpaceOrder="org.matrix.msc3230.space_order",e.PushRules="m.push_rules",e.Direct="m.direct",e.IgnoredUserList="m.ignored_user_list",e.RoomKey="m.room_key",e.RoomKeyRequest="m.room_key_request",e.ForwardedRoomKey="m.forwarded_room_key",e.Dummy="m.dummy",e.GroupCallPrefix="org.matrix.msc3401.call",e.GroupCallMemberPrefix="org.matrix.msc3401.call.member"}(i.EventType||(i.EventType={})),function(e){e.Annotation="m.annotation",e.Replace="m.replace",e.Reference="m.reference",e.Thread="m.thread"}(i.RelationType||(i.RelationType={})),function(e){e.Text="m.text",e.Emote="m.emote",e.Notice="m.notice",e.Image="m.image",e.File="m.file",e.Audio="m.audio",e.Location="m.location",e.Video="m.video",e.KeyVerificationRequest="m.key.verification.request"}(i.MsgType||(i.MsgType={})),i.RoomCreateTypeField="type",function(e){e.Space="m.space",e.UnstableCall="org.matrix.msc3417.call",e.ElementVideo="io.element.video"}(i.RoomType||(i.RoomType={})),i.ToDeviceMessageId="org.matrix.msgid",i.UNSTABLE_MSC3088_PURPOSE=new n.UnstableValue("m.room.purpose","org.matrix.msc3088.purpose"),i.UNSTABLE_MSC3088_ENABLED=new n.UnstableValue("m.enabled","org.matrix.msc3088.enabled"),i.UNSTABLE_MSC3089_TREE_SUBTYPE=new n.UnstableValue("m.data_tree","org.matrix.msc3089.data_tree"),i.UNSTABLE_MSC3089_LEAF=new n.UnstableValue("m.leaf","org.matrix.msc3089.leaf"),i.UNSTABLE_MSC3089_BRANCH=new n.UnstableValue("m.branch","org.matrix.msc3089.branch"),i.UNSTABLE_MSC2716_MARKER=new n.UnstableValue("m.room.marker","org.matrix.msc2716.marker"),i.MSC3912_RELATION_BASED_REDACTIONS_PROP=new n.UnstableValue("with_relations","org.matrix.msc3912.with_relations"),i.UNSTABLE_ELEMENT_FUNCTIONAL_USERS=new n.UnstableValue("io.element.functional_members","io.element.functional_members"),i.EVENT_VISIBILITY_CHANGE_TYPE=new n.UnstableValue("m.visibility","org.matrix.msc3531.visibility"),i.PUSHER_ENABLED=new n.UnstableValue("enabled","org.matrix.msc3881.enabled"),i.PUSHER_DEVICE_ID=new n.UnstableValue("device_id","org.matrix.msc3881.device_id"),i.LOCAL_NOTIFICATION_SETTINGS_PREFIX=new n.UnstableValue("m.local_notification_settings","org.matrix.msc3890.local_notification_settings")},{"../NamespacedValue":316}],307:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.isEventTypeSame=i.REFERENCE_RELATION=i.M_HTML=i.M_TEXT=i.M_MESSAGE=void 0;const n=e("matrix-events-sdk"),r=e("../extensible_events_v1/utilities");i.M_MESSAGE=new n.UnstableValue("m.message","org.matrix.msc1767.message"),i.M_TEXT=new n.UnstableValue("m.text","org.matrix.msc1767.text"),i.M_HTML=new n.UnstableValue("m.html","org.matrix.msc1767.html"),i.REFERENCE_RELATION=new n.NamespacedValue("m.reference"),i.isEventTypeSame=function(e,t){if("string"==typeof e)return"string"==typeof t?t===e:t.matches(e);if("string"==typeof t)return e.matches(t);{const i=t,n=e;return i.matches(n.name)||(0,r.isProvided)(n.altName)&&i.matches(n.altName)}}},{"../extensible_events_v1/utilities":361,"matrix-events-sdk":167}],308:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.M_LOCATION=i.M_TIMESTAMP=i.M_ASSET=i.LocationAssetType=void 0;const n=e("../NamespacedValue");e("./extensible_events");!function(e){e.Self="m.self",e.Pin="m.pin"}(i.LocationAssetType||(i.LocationAssetType={})),i.M_ASSET=new n.UnstableValue("m.asset","org.matrix.msc3488.asset"),i.M_TIMESTAMP=new n.UnstableValue("m.ts","org.matrix.msc3488.ts"),i.M_LOCATION=new n.UnstableValue("m.location","org.matrix.msc3488.location")},{"../NamespacedValue":316,"./extensible_events":307}],309:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.HistoryVisibility=i.GuestAccess=i.RestrictedAllowType=i.JoinRule=i.Preset=i.Visibility=void 0,function(e){e.Public="public",e.Private="private"}(i.Visibility||(i.Visibility={})),function(e){e.PrivateChat="private_chat",e.TrustedPrivateChat="trusted_private_chat",e.PublicChat="public_chat"}(i.Preset||(i.Preset={})),function(e){e.Public="public",e.Invite="invite",e.Private="private",e.Knock="knock",e.Restricted="restricted"}(i.JoinRule||(i.JoinRule={})),function(e){e.RoomMembership="m.room_membership"}(i.RestrictedAllowType||(i.RestrictedAllowType={})),function(e){e.CanJoin="can_join",e.Forbidden="forbidden"}(i.GuestAccess||(i.GuestAccess={})),function(e){e.Invited="invited",e.Joined="joined",e.Shared="shared",e.WorldReadable="world_readable"}(i.HistoryVisibility||(i.HistoryVisibility={}))},{}],310:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.M_POLL_END=i.M_POLL_RESPONSE=i.M_POLL_START=i.M_POLL_KIND_UNDISCLOSED=i.M_POLL_KIND_DISCLOSED=void 0;const n=e("matrix-events-sdk");i.M_POLL_KIND_DISCLOSED=new n.UnstableValue("m.poll.disclosed","org.matrix.msc3381.poll.disclosed"),i.M_POLL_KIND_UNDISCLOSED=new n.UnstableValue("m.poll.undisclosed","org.matrix.msc3381.poll.undisclosed"),i.M_POLL_START=new n.UnstableValue("m.poll.start","org.matrix.msc3381.poll.start"),i.M_POLL_RESPONSE=new n.UnstableValue("m.poll.response","org.matrix.msc3381.poll.response"),i.M_POLL_END=new n.UnstableValue("m.poll.end","org.matrix.msc3381.poll.end")},{"matrix-events-sdk":167}],311:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MAIN_ROOM_TIMELINE=i.ReceiptType=void 0,function(e){e.Read="m.read",e.FullyRead="m.fully_read",e.ReadPrivate="m.read.private"}(i.ReceiptType||(i.ReceiptType={})),i.MAIN_ROOM_TIMELINE="main"},{}],312:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0})},{}],313:[function(e,t,i){"use strict";var n;Object.defineProperty(i,"__esModule",{value:!0}),i.SearchOrderBy=void 0,function(e){e.RoomId="room_id",e.Sender="sender"}(n||(n={})),function(e){e.Recent="recent",e.Rank="rank"}(i.SearchOrderBy||(i.SearchOrderBy={}))},{}],314:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.UNREAD_THREAD_NOTIFICATIONS=void 0;const n=e("../NamespacedValue");i.UNREAD_THREAD_NOTIFICATIONS=new n.ServerControlledNamespacedValue("unread_thread_notifications","org.matrix.msc3773.unread_thread_notifications")},{"../NamespacedValue":316}],315:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.M_TOPIC=void 0;const n=e("../NamespacedValue");i.M_TOPIC=new n.UnstableValue("m.topic","org.matrix.msc3765.topic")},{"../NamespacedValue":316}],316:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.UnstableValue=i.ServerControlledNamespacedValue=i.NamespacedValue=void 0;class n{constructor(e,t){if(this.stable=e,this.unstable=t,!this.unstable&&!this.stable)throw new Error("One of stable or unstable values must be supplied")}get name(){return this.stable?this.stable:this.unstable}get altName(){return this.stable?this.unstable:null}get names(){const e=[this.name],t=this.altName;return t&&e.push(t),e}matches(e){return this.name===e||this.altName===e}findIn(e){let t;return this.name&&(t=null==e?void 0:e[this.name]),!t&&this.altName&&(t=null==e?void 0:e[this.altName]),t}includedIn(e){let t=!1;return this.name&&(t=e.includes(this.name)),!t&&this.altName&&(t=e.includes(this.altName)),t}}i.NamespacedValue=n;i.ServerControlledNamespacedValue=class extends n{constructor(){super(...arguments),this.preferUnstable=!1}setPreferUnstable(e){this.preferUnstable=e}get name(){return this.stable&&!this.preferUnstable?this.stable:this.unstable}};i.UnstableValue=class extends n{constructor(e,t){if(super(e,t),!this.unstable)throw new Error("Unstable value must be supplied")}get name(){return this.unstable}get altName(){return this.stable}}},{}],317:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TypedReEmitter=i.ReEmitter=void 0;class n{constructor(e){this.target=e,this.reEmitters=new Map}reEmit(e,t){let i=this.reEmitters.get(e);i||(i=new Map,this.reEmitters.set(e,i));for(const n of t){const t=(...t)=>{"error"===n&&0===this.target.listenerCount("error")||this.target.emit(n,...t,e)};e.on(n,t),i.set(n,t)}}stopReEmitting(e,t){const i=this.reEmitters.get(e);if(i){for(const n of t)e.off(n,i.get(n)),i.delete(n);0===i.size&&this.reEmitters.delete(e)}}}i.ReEmitter=n;i.TypedReEmitter=class extends n{constructor(e){super(e)}reEmit(e,t){super.reEmit(e,t)}stopReEmitting(e,t){super.stopReEmitting(e,t)}}},{}],318:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.ToDeviceMessageQueue=void 0;const r=e("./@types/event"),o=e("./logger"),s=e("./client"),a=e("./scheduler"),c=e("./sync"),d=e("./utils");i.ToDeviceMessageQueue=class{constructor(e){this.client=e,this.sending=!1,this.running=!0,this.retryTimeout=null,this.retryAttempts=0,this.sendQueue=()=>n(this,void 0,void 0,(function*(){if(null!==this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null,this.sending||!this.running)return;let e;o.logger.debug("Attempting to send queued to-device messages"),this.sending=!0;try{for(;this.running&&(e=yield this.client.store.getOldestToDeviceBatch(),null!==e);)yield this.sendBatch(e),yield this.client.store.removeToDeviceBatch(e.id),this.retryAttempts=0;if(!this.running)return;o.logger.debug("All queued to-device messages sent")}catch(t){++this.retryAttempts;const i=a.MatrixScheduler.RETRY_BACKOFF_RATELIMIT(null,this.retryAttempts,t);if(-1===i)return void(4===Math.floor(t.httpStatus/100)?(o.logger.error("Fatal error when sending to-device message - dropping to-device batch!",t),yield this.client.store.removeToDeviceBatch(e.id)):o.logger.info("Automatic retry limit reached for to-device messages."));o.logger.info(`Failed to send batch of to-device messages. Will retry in ${i}ms`,t),this.retryTimeout=setTimeout(this.sendQueue,i)}finally{this.sending=!1}})),this.onResumedSync=(e,t)=>{e===c.SyncState.Syncing&&t!==c.SyncState.Syncing&&(o.logger.info("Resuming queue after resumed sync"),this.sendQueue())}}start(){this.running=!0,this.sendQueue(),this.client.on(s.ClientEvent.Sync,this.onResumedSync)}stop(){this.running=!1,null!==this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null,this.client.removeListener(s.ClientEvent.Sync,this.onResumedSync)}queueBatch(e){return n(this,void 0,void 0,(function*(){const t=[];for(let i=0;i`${e.userId}/${e.deviceId} (msgid ${e.payload[r.ToDeviceMessageId]})`));o.logger.info(`Enqueuing batch of to-device messages. type=${e.eventType} txnid=${n.txnId}`,s)}yield this.client.store.saveToDeviceBatches(t),this.sendQueue()}))}sendBatch(e){return n(this,void 0,void 0,(function*(){const t=new d.MapWithDefault((()=>new Map));for(const i of e.batch)t.getOrCreate(i.userId).set(i.deviceId,i.payload);o.logger.info(`Sending batch of ${e.batch.length} to-device messages with ID ${e.id} and txnId ${e.txnId}`),yield this.client.sendToDevice(e.eventType,t,e.txnId)}))}}},{"./@types/event":306,"./client":321,"./logger":374,"./scheduler":403,"./sync":414,"./utils":416}],319:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.AutoDiscovery=i.AutoDiscoveryAction=void 0;const r=e("./logger"),o=e("./http-api");var s,a;!function(e){e.SUCCESS="SUCCESS",e.IGNORE="IGNORE",e.PROMPT="PROMPT",e.FAIL_PROMPT="FAIL_PROMPT",e.FAIL_ERROR="FAIL_ERROR"}(s=i.AutoDiscoveryAction||(i.AutoDiscoveryAction={})),function(e){e.Invalid="Invalid homeserver discovery response",e.GenericFailure="Failed to get autodiscovery configuration from server",e.InvalidHsBaseUrl="Invalid base_url for m.homeserver",e.InvalidHomeserver="Homeserver URL does not appear to be a valid Matrix homeserver",e.InvalidIsBaseUrl="Invalid base_url for m.identity_server",e.InvalidIdentityServer="Identity server URL does not appear to be a valid identity server",e.InvalidIs="Invalid identity server discovery response",e.MissingWellknown="No .well-known JSON file found",e.InvalidJson="Invalid JSON"}(a||(a={}));class c{static fromDiscoveryConfig(e){var t;return n(this,void 0,void 0,(function*(){const i={"m.homeserver":{state:c.FAIL_ERROR,error:c.ERROR_INVALID,base_url:null},"m.identity_server":{state:c.PROMPT,error:null,base_url:null}};if(!e||!e["m.homeserver"])return r.logger.error("No m.homeserver key in config"),i["m.homeserver"].state=c.FAIL_PROMPT,i["m.homeserver"].error=c.ERROR_INVALID,Promise.resolve(i);if(!e["m.homeserver"].base_url)return r.logger.error("No m.homeserver base_url in config"),i["m.homeserver"].state=c.FAIL_PROMPT,i["m.homeserver"].error=c.ERROR_INVALID_HS_BASE_URL,Promise.resolve(i);const n=this.sanitizeWellKnownUrl(e["m.homeserver"].base_url);if(!n)return r.logger.error("Invalid base_url for m.homeserver"),i["m.homeserver"].error=c.ERROR_INVALID_HS_BASE_URL,Promise.resolve(i);const o=yield this.fetchWellKnownObject(`${n}/_matrix/client/versions`);if(!o||!(null===(t=o.raw)||void 0===t?void 0:t.versions))return r.logger.error("Invalid /versions response"),i["m.homeserver"].error=c.ERROR_INVALID_HOMESERVER,i["m.homeserver"].base_url=n,Promise.resolve(i);i["m.homeserver"]={state:c.SUCCESS,error:null,base_url:n};let a="";if(e["m.identity_server"]){const t={"m.homeserver":i["m.homeserver"],"m.identity_server":{state:c.FAIL_PROMPT,error:c.ERROR_INVALID_IS,base_url:null}};if(a=this.sanitizeWellKnownUrl(e["m.identity_server"].base_url),!a)return r.logger.error("Invalid base_url for m.identity_server"),t["m.identity_server"].error=c.ERROR_INVALID_IS_BASE_URL,Promise.resolve(t);const n=yield this.fetchWellKnownObject(`${a}/_matrix/identity/v2`);if(!(null==n?void 0:n.raw)||n.action!==s.SUCCESS)return r.logger.error("Invalid /v2 response"),t["m.identity_server"].error=c.ERROR_INVALID_IDENTITY_SERVER,t["m.identity_server"].base_url=a,Promise.resolve(t)}return a&&a.toString().length>0&&(i["m.identity_server"]={state:c.SUCCESS,error:null,base_url:a}),Object.keys(e).forEach((t=>{if("m.homeserver"===t||"m.identity_server"===t){const n=["error","state","base_url"];for(const r of Object.keys(e[t]))n.includes(r)||(i[t][r]=e[t][r])}else i[t]=e[t]})),Promise.resolve(i)}))}static findClientConfig(e){return n(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||0===e.length)throw new Error("'domain' must be a string of non-zero length");const t={"m.homeserver":{state:c.FAIL_ERROR,error:c.ERROR_INVALID,base_url:null},"m.identity_server":{state:c.PROMPT,error:null,base_url:null}},i=yield this.fetchWellKnownObject(`https://${e}/.well-known/matrix/client`);return i&&i.action===s.SUCCESS?c.fromDiscoveryConfig(i.raw):(r.logger.error("No response or error when parsing .well-known"),i.reason&&r.logger.error(i.reason),i.action===s.IGNORE?t["m.homeserver"]={state:c.PROMPT,error:null,base_url:null}:(t["m.homeserver"].state=c.FAIL_PROMPT,t["m.homeserver"].error=c.ERROR_INVALID),Promise.resolve(t))}))}static getRawClientConfig(e){return n(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||0===e.length)throw new Error("'domain' must be a string of non-zero length");const t=yield this.fetchWellKnownObject(`https://${e}/.well-known/matrix/client`);return t&&t.raw||{}}))}static sanitizeWellKnownUrl(e){if(!e)return!1;try{let t;try{t=new URL(e)}catch(e){r.logger.error("Could not parse url",e)}if(!(null==t?void 0:t.hostname))return!1;if("http:"!==t.protocol&&"https:"!==t.protocol)return!1;const i=t.port?`:${t.port}`:"",n=t.pathname?t.pathname:"";let o=`${t.protocol}//${t.hostname}${i}${n}`;return o.endsWith("/")&&(o=o.substring(0,o.length-1)),o}catch(e){return r.logger.error(e),!1}}static fetch(e,i){return this.fetchFn?this.fetchFn(e,i):t.fetch(e,i)}static setFetchFn(e){c.fetchFn=e}static fetchWellKnownObject(e){return n(this,void 0,void 0,(function*(){let t;try{if(t=yield c.fetch(e,{method:o.Method.Get,signal:(0,o.timeoutSignal)(5e3)}),404===t.status)return{raw:{},action:s.IGNORE,reason:c.ERROR_MISSING_WELLKNOWN};if(!t.ok)return{raw:{},action:s.FAIL_PROMPT,reason:"General failure"}}catch(e){const t=e;let i="";return"object"==typeof t&&(i=null==t?void 0:t.message),{error:t,raw:{},action:s.FAIL_PROMPT,reason:i||"General failure"}}try{return{raw:yield t.json(),action:s.SUCCESS}}catch(e){const t=e;return{error:t,raw:{},action:s.FAIL_PROMPT,reason:"SyntaxError"===(null==t?void 0:t.name)?c.ERROR_INVALID_JSON:c.ERROR_INVALID}}}))}}i.AutoDiscovery=c,c.ERROR_INVALID=a.Invalid,c.ERROR_GENERIC_FAILURE=a.GenericFailure,c.ERROR_INVALID_HS_BASE_URL=a.InvalidHsBaseUrl,c.ERROR_INVALID_HOMESERVER=a.InvalidHomeserver,c.ERROR_INVALID_IS_BASE_URL=a.InvalidIsBaseUrl,c.ERROR_INVALID_IDENTITY_SERVER=a.InvalidIdentityServer,c.ERROR_INVALID_IS=a.InvalidIs,c.ERROR_MISSING_WELLKNOWN=a.MissingWellknown,c.ERROR_INVALID_JSON=a.InvalidJson,c.ALL_ERRORS=Object.keys(a),c.FAIL_ERROR=s.FAIL_ERROR,c.FAIL_PROMPT=s.FAIL_PROMPT,c.PROMPT=s.PROMPT,c.SUCCESS=s.SUCCESS}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./http-api":367,"./logger":374}],320:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0});const a=o(e("./matrix"));if(t.__js_sdk_entrypoint)throw new Error("Multiple matrix-js-sdk entrypoints detected!");let c;t.__js_sdk_entrypoint=!0;try{c=t.indexedDB}catch(e){}c&&a.setCryptoStoreFactory((()=>new a.IndexedDBCryptoStore(c,"matrix-js-sdk:crypto"))),s(e("./matrix"),i),i.default=a,t.matrixcs=a}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./matrix":375}],321:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},a=this&&this.__rest||function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r{this.isInitialSyncComplete()&&(this.callEventHandler.start(),this.groupCallEventHandler.start(),this.off(ae.Sync,this.startCallEventHandler))},this.fixupRoomNotifications=()=>{var e;if(this.isInitialSyncComplete()){const t=(null!==(e=this.getRooms())&&void 0!==e?e:[]).filter((e=>e.getUnreadNotificationCount(L.NotificationCountType.Total)>0));for(const e of t){const t=this.getSafeUserId();e.fixupNotifications(t)}this.off(ae.Sync,this.fixupRoomNotifications)}},e.baseUrl=p.ensureNoTrailingSlash(e.baseUrl),e.idBaseUrl=p.ensureNoTrailingSlash(e.idBaseUrl),this.baseUrl=e.baseUrl,this.idBaseUrl=e.idBaseUrl,this.identityServer=e.identityServer,this.usingExternalCrypto=null!==(t=e.usingExternalCrypto)&&void 0!==t&&t,this.store=e.store||new l.StubStore,this.deviceId=e.deviceId||null,this.sessionId=(0,F.randomString)(10);const i=e.userId||null;this.credentials={userId:i},this.http=new I.MatrixHttpApi(this,{fetchFn:e.fetchFn,baseUrl:e.baseUrl,idBaseUrl:e.idBaseUrl,accessToken:e.accessToken,prefix:I.ClientPrefix.R0,onlyData:!0,extraParams:e.queryParams,localTimeoutMs:e.localTimeoutMs,useAuthorizationHeader:e.useAuthorizationHeader}),e.deviceToImport?this.deviceId?w.logger.warn("not importing device because device ID is provided to constructor independently of exported data"):this.credentials.userId?w.logger.warn("not importing device because user ID is provided to constructor independently of exported data"):e.deviceToImport.deviceId?(this.deviceId=e.deviceToImport.deviceId,this.credentials.userId=e.deviceToImport.userId,this.exportedOlmDeviceToImport=e.deviceToImport.olmDevice):w.logger.warn("not importing device because no device ID in exported data"):e.pickleKey&&(this.pickleKey=e.pickleKey),this.scheduler=e.scheduler,this.scheduler&&this.scheduler.setProcessFunction((e=>s(this,void 0,void 0,(function*(){const t=this.getRoom(e.getRoomId());e.status!==d.EventStatus.SENDING&&this.updatePendingEventStatus(t,e,d.EventStatus.SENDING);const i=yield this.sendEventHttpRequest(e);return t&&t.updatePendingEvent(e,d.EventStatus.SENT,i.event_id),i})))),(0,u.supportsMatrixCall)()&&(this.callEventHandler=new f.CallEventHandler(this),this.groupCallEventHandler=new G.GroupCallEventHandler(this),this.canSupportVoip=!0,this.on(ae.Sync,this.startCallEventHandler)),this.on(ae.Sync,this.fixupRoomNotifications),this.timelineSupport=Boolean(e.timelineSupport),this.cryptoStore=e.cryptoStore,this.verificationMethods=e.verificationMethods,this.cryptoCallbacks=e.cryptoCallbacks||{},this.forceTURN=e.forceTURN||!1,this.iceCandidatePoolSize=void 0===e.iceCandidatePoolSize?0:e.iceCandidatePoolSize,this.supportsCallTransfer=e.supportsCallTransfer||!1,this.fallbackICEServerAllowed=e.fallbackICEServerAllowed||!1,this.isVoipWithNoMediaAllowed=e.isVoipWithNoMediaAllowed||!1,void 0!==e.useE2eForGroupCall&&(this.useE2eForGroupCall=e.useE2eForGroupCall),this.roomList=new E.RoomList(this.cryptoStore),this.roomNameGenerator=e.roomNameGenerator,this.toDeviceMessageQueue=new ee.ToDeviceMessageQueue(this),this.on(d.MatrixEventEvent.Decrypted,(e=>{le(this,e)})),this.on(L.RoomEvent.Receipt,((e,t)=>{var i;if(t&&this.isRoomEncrypted(t.roomId)){const n=e.getContent();if(!(Object.keys(n).filter((e=>{for(const[t,i]of Object.entries(n[e]))if(p.isSupportedReceiptType(t)&&i&&Object.keys(i).includes(this.getUserId()))return!0;return!1})).length>0))return;const r=20,o=t.getLiveTimeline().getEvents();let s=0;for(let e=o.length-1;e>=0;e--){if(e===o.length-r)return;const n=o[e];if(t.hasUserReadEvent(this.getUserId(),n.getId()))break;const a=this.getPushActionsForEvent(n);s+=(null===(i=null==a?void 0:a.tweaks)||void 0===i?void 0:i.highlight)?1:0}t.setUnreadNotificationCount(L.NotificationCountType.Highlight,s)}})),this.ignoredInvites=new te.IgnoredInvites(this)}startClient(e){return s(this,void 0,void 0,(function*(){if(this.clientRunning)return;this.clientRunning=!0,"number"==typeof e&&(e={initialSyncLimit:e});const t=this.getUserId();t&&this.store.storeUser(new C.User(t)),this.canSupportVoip&&(this.checkTurnServersIntervalID=setInterval((()=>{this.checkTurnServers()}),re),this.checkTurnServers()),this.syncApi&&(w.logger.error("Still have sync object whilst not running: stopping old one"),this.syncApi.stop());try{yield this.getVersions();const{threads:e,list:t,fwdPagination:i}=yield this.doesServerSupportThread();Q.Thread.setServerSideSupport(e),Q.Thread.setServerSideListSupport(t),Q.Thread.setServerSideFwdPaginationSupport(i)}catch(e){w.logger.error("Can't fetch server versions, continuing to initialise sync, this will be retried later",e)}this.clientOpts=null!=e?e:{},this.clientOpts.slidingSync?this.syncApi=new J.SlidingSyncSdk(this.clientOpts.slidingSync,this,this.clientOpts,this.buildSyncApiOptions()):this.syncApi=new c.SyncApi(this,this.clientOpts,this.buildSyncApiOptions()),this.clientOpts.hasOwnProperty("experimentalThreadSupport")&&w.logger.warn("`experimentalThreadSupport` has been deprecated, use `threadSupport` instead"),!this.clientOpts.hasOwnProperty("threadSupport")&&this.clientOpts.hasOwnProperty("experimentalThreadSupport")&&(this.clientOpts.threadSupport=this.clientOpts.experimentalThreadSupport),this.syncApi.sync(),void 0!==this.clientOpts.clientWellKnownPollPeriod&&(this.clientWellKnownIntervalID=setInterval((()=>{this.fetchClientWellKnown()}),1e3*this.clientOpts.clientWellKnownPollPeriod),this.fetchClientWellKnown()),this.toDeviceMessageQueue.start()}))}buildSyncApiOptions(){return{crypto:this.crypto,cryptoCallbacks:this.cryptoBackend,canResetEntireTimeline:e=>!!this.canResetTimelineCallback&&this.canResetTimelineCallback(e)}}stopClient(){var e,i,n,r,o;null===(e=this.cryptoBackend)||void 0===e||e.stop(),this.clientRunning&&(w.logger.log("stopping MatrixClient"),this.clientRunning=!1,null===(i=this.syncApi)||void 0===i||i.stop(),this.syncApi=void 0,null===(n=this.peekSync)||void 0===n||n.stopPeeking(),null===(r=this.callEventHandler)||void 0===r||r.stop(),null===(o=this.groupCallEventHandler)||void 0===o||o.stop(),this.callEventHandler=void 0,this.groupCallEventHandler=void 0,t.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=void 0,void 0!==this.clientWellKnownIntervalID&&t.clearInterval(this.clientWellKnownIntervalID),this.toDeviceMessageQueue.stop())}rehydrateDevice(){return s(this,void 0,void 0,(function*(){if(this.crypto)throw new Error("Cannot rehydrate device after crypto is initialized");if(!this.cryptoCallbacks.getDehydrationKey)return;const e=yield this.getDehydratedDevice();if(!e)return;if(!e.device_data||!e.device_id)return void w.logger.info("no dehydrated device found");const i=new t.Olm.Account;try{const t=e.device_data;if(t.algorithm!==P.DEHYDRATION_ALGORITHM)return void w.logger.warn("Wrong algorithm for dehydrated device");w.logger.log("unpickling dehydrated device");const n=yield this.cryptoCallbacks.getDehydrationKey(t,(e=>{i.unpickle(new Uint8Array(e),t.account)}));i.unpickle(n,t.account),w.logger.log("unpickled device");if((yield this.http.authedRequest(I.Method.Post,"/dehydrated_device/claim",void 0,{device_id:e.device_id},{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})).success){this.deviceId=e.device_id,w.logger.info("using dehydrated device");const t=this.pickleKey||"DEFAULT_KEY";return this.exportedOlmDeviceToImport={pickledAccount:i.pickle(t),sessions:[],pickleKey:t},i.free(),this.deviceId}return i.free(),void w.logger.info("not using dehydrated device")}catch(e){i.free(),w.logger.warn("could not unpickle",e)}}))}getDehydratedDevice(){return s(this,void 0,void 0,(function*(){try{return yield this.http.authedRequest(I.Method.Get,"/dehydrated_device",void 0,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})}catch(e){return void w.logger.info("could not get dehydrated device",e)}}))}setDehydrationKey(e,t,i){return s(this,void 0,void 0,(function*(){if(this.crypto)return this.crypto.dehydrationManager.setKeyAndQueueDehydration(e,t,i);w.logger.warn("not dehydrating device if crypto is not enabled")}))}createDehydratedDevice(e,t,i){return s(this,void 0,void 0,(function*(){if(this.crypto)return yield this.crypto.dehydrationManager.setKey(e,t,i),this.crypto.dehydrationManager.dehydrateDevice();w.logger.warn("not dehydrating device if crypto is not enabled")}))}exportDevice(){return s(this,void 0,void 0,(function*(){if(this.crypto)return{userId:this.credentials.userId,deviceId:this.deviceId,olmDevice:yield this.crypto.olmDevice.export()};w.logger.warn("not exporting device if crypto is not enabled")}))}clearStores(){if(this.clientRunning)throw new Error("Cannot clear stores while client is running");const e=[];e.push(this.store.deleteAllData()),this.cryptoStore&&e.push(this.cryptoStore.deleteAllData());return e.push((()=>s(this,void 0,void 0,(function*(){let e;try{e=t.indexedDB}catch(e){return}for(const t of[`${ne.RUST_SDK_STORE_PREFIX}::matrix-sdk-crypto`,`${ne.RUST_SDK_STORE_PREFIX}::matrix-sdk-crypto-meta`]){const i=new Promise(((i,n)=>{w.logger.info(`Removing IndexedDB instance ${t}`);const r=e.deleteDatabase(t);r.onsuccess=e=>{w.logger.info(`Removed IndexedDB instance ${t}`),i(0)},r.onerror=e=>{w.logger.warn(`Failed to remove IndexedDB instance ${t}:`,e),i(0)},r.onblocked=e=>{w.logger.info(`cannot yet remove IndexedDB instance ${t}`)}}));yield i}})))()),Promise.all(e).then()}getUserId(){return this.credentials&&this.credentials.userId?this.credentials.userId:null}getSafeUserId(){const e=this.getUserId();if(!e)throw new Error("Expected logged in user but found none.");return e}getDomain(){return this.credentials&&this.credentials.userId?this.credentials.userId.replace(/^.*?:/,""):null}getUserIdLocalpart(){return this.credentials&&this.credentials.userId?this.credentials.userId.split(":")[0].substring(1):null}getDeviceId(){return this.deviceId}getSessionId(){return this.sessionId}supportsVoip(){return this.canSupportVoip}getMediaHandler(){return this.mediaHandler}setForceTURN(e){this.forceTURN=e}setSupportsCallTransfer(e){this.supportsCallTransfer=e}getUseE2eForGroupCall(){return this.useE2eForGroupCall}createCall(e){return(0,u.createNewMatrixCall)(this,e)}createGroupCall(e,t,i,n,r,o){return s(this,void 0,void 0,(function*(){if(this.getGroupCallForRoom(e))throw new Error(`${e} already has an existing group call`);const s=this.getRoom(e);if(!s)throw new Error(`Cannot find room ${e}`);return new H.GroupCall(this,s,t,i,n,void 0,r||this.isVoipWithNoMediaAllowed,o,this.isVoipWithNoMediaAllowed).create()}))}waitUntilRoomReadyForGroupCalls(e){return this.groupCallEventHandler.waitUntilRoomReadyForGroupCalls(e)}getGroupCallForRoom(e){return this.groupCallEventHandler.groupCalls.get(e)||null}getSyncState(){var e,t;return null!==(t=null===(e=this.syncApi)||void 0===e?void 0:e.getSyncState())&&void 0!==t?t:null}getSyncStateData(){return this.syncApi?this.syncApi.getSyncStateData():null}isInitialSyncComplete(){const e=this.getSyncState();return!!e&&(e===c.SyncState.Prepared||e===c.SyncState.Syncing)}isGuest(){return this.isGuestAccount}setGuest(e){this.isGuestAccount=e}getScheduler(){return this.scheduler}retryImmediately(){var e,t;return this.toDeviceMessageQueue.sendQueue(),null!==(t=null===(e=this.syncApi)||void 0===e?void 0:e.retryImmediately())&&void 0!==t&&t}getNotifTimelineSet(){return this.notifTimelineSet}setNotifTimelineSet(e){this.notifTimelineSet=e}getCapabilities(e=!1){const t=(new Date).getTime();return this.cachedCapabilities&&!e&&t(w.logger.error(e),{}))).then(((e={})=>{const i=e.capabilities||{},n=Object.keys(i).length?216e5:6e4+5e3*Math.random();return this.cachedCapabilities={capabilities:i,expiration:t+n},w.logger.log("Caching capabilities: ",i),i}))}initCrypto(){return s(this,void 0,void 0,(function*(){if(!(0,R.isCryptoAvailable)())throw new Error("End-to-end encryption not supported in this js-sdk build: did you remember to load the olm library?");if(this.cryptoBackend)return void w.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");if(!this.cryptoStore)throw new Error("Cannot enable encryption: no cryptoStore provided");w.logger.log("Crypto: Starting up crypto store..."),yield this.cryptoStore.startup(),w.logger.log("Crypto: initialising roomlist..."),yield this.roomList.init();const e=this.getUserId();if(null===e)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");if(null===this.deviceId)throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");const t=new R.Crypto(this,e,this.deviceId,this.store,this.cryptoStore,this.roomList,this.verificationMethods);this.reEmitter.reEmit(t,[R.CryptoEvent.KeyBackupFailed,R.CryptoEvent.KeyBackupSessionsRemaining,R.CryptoEvent.RoomKeyRequest,R.CryptoEvent.RoomKeyRequestCancellation,R.CryptoEvent.Warning,R.CryptoEvent.DevicesUpdated,R.CryptoEvent.WillUpdateDevices,R.CryptoEvent.DeviceVerificationChanged,R.CryptoEvent.UserTrustStatusChanged,R.CryptoEvent.KeysChanged]),w.logger.log("Crypto: initialising crypto object..."),yield t.init({exportedOlmDevice:this.exportedOlmDeviceToImport,pickleKey:this.pickleKey}),delete this.exportedOlmDeviceToImport,this.olmVersion=R.Crypto.getOlmVersion(),t.registerEventHandlers(this),this.cryptoBackend=this.crypto=t,this.crypto.uploadDeviceKeys().catch((e=>{w.logger.error("Error uploading device keys",e)}))}))}initRustCrypto(){return s(this,void 0,void 0,(function*(){if(this.cryptoBackend)return void w.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");const t=this.getUserId();if(null===t)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");const i=this.getDeviceId();if(null===i)throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");const n=yield Promise.resolve().then((()=>o(e("./rust-crypto")))),r=yield n.initRustCrypto(this.http,t,i);this.cryptoBackend=r,this.on(U.RoomMemberEvent.Membership,r.onRoomMembership.bind(r))}))}getCrypto(){return this.cryptoBackend}isCryptoEnabled(){return!!this.cryptoBackend}getDeviceEd25519Key(){var e,t;return null!==(t=null===(e=this.crypto)||void 0===e?void 0:e.getDeviceEd25519Key())&&void 0!==t?t:null}getDeviceCurve25519Key(){var e,t;return null!==(t=null===(e=this.crypto)||void 0===e?void 0:e.getDeviceCurve25519Key())&&void 0!==t?t:null}uploadKeys(){return s(this,void 0,void 0,(function*(){w.logger.warn("MatrixClient.uploadKeys is deprecated")}))}downloadKeys(e,t){return this.crypto?this.crypto.downloadKeys(e,t):Promise.reject(new Error("End-to-end encryption disabled"))}getStoredDevicesForUser(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredDevicesForUser(e)||[]}getStoredDevice(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredDevice(e,t)||null}setDeviceVerified(e,t,i=!0){const n=this.setDeviceVerification(e,t,i,null,null);return e==this.credentials.userId&&this.checkKeyBackup(),n}setDeviceBlocked(e,t,i=!0){return this.setDeviceVerification(e,t,null,i,null)}setDeviceKnown(e,t,i=!0){return this.setDeviceVerification(e,t,null,null,i)}setDeviceVerification(e,t,i,n,r){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");yield this.crypto.setDeviceVerification(e,t,i,n,r)}))}requestVerificationDM(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestVerificationDM(e,t)}findVerificationRequestDMInProgress(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.findVerificationRequestDMInProgress(e)}getVerificationRequestsToDeviceInProgress(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getVerificationRequestsToDeviceInProgress(e)}requestVerification(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestVerification(e,t)}beginKeyVerification(e,t,i){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.beginKeyVerification(e,t,i)}checkSecretStorageKey(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkSecretStorageKey(e,t)}setGlobalBlacklistUnverifiedDevices(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.globalBlacklistUnverifiedDevices=e,e}getGlobalBlacklistUnverifiedDevices(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.globalBlacklistUnverifiedDevices}setGlobalErrorOnUnknownDevices(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");this.cryptoBackend.globalErrorOnUnknownDevices=e}getGlobalErrorOnUnknownDevices(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.globalErrorOnUnknownDevices}getCrossSigningId(e=D.CrossSigningKey.Master){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getCrossSigningId(e)}getStoredCrossSigningForUser(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredCrossSigningForUser(e)}checkUserTrust(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.checkUserTrust(e)}checkDeviceTrust(e,t){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.checkDeviceTrust(e,t)}checkIfOwnDeviceCrossSigned(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkIfOwnDeviceCrossSigned(e)}checkOwnCrossSigningTrust(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkOwnCrossSigningTrust(e)}checkCrossSigningPrivateKey(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkCrossSigningPrivateKey(e,t)}legacyDeviceVerification(e,t,i){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.legacyDeviceVerification(e,t,i)}prepareToEncrypt(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");this.cryptoBackend.prepareToEncrypt(e)}userHasCrossSigningKeys(){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.userHasCrossSigningKeys()}isCrossSigningReady(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.isCrossSigningReady()}bootstrapCrossSigning(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.bootstrapCrossSigning(e)}getCryptoTrustCrossSignedDevices(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getCryptoTrustCrossSignedDevices()}setCryptoTrustCrossSignedDevices(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");this.crypto.setCryptoTrustCrossSignedDevices(e)}countSessionsNeedingBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.countSessionsNeedingBackup()}getEventEncryptionInfo(e){if(!this.cryptoBackend)throw new Error("End-to-end encryption disabled");return this.cryptoBackend.getEventEncryptionInfo(e)}createRecoveryKeyFromPassphrase(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.createRecoveryKeyFromPassphrase(e)}isSecretStorageReady(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.isSecretStorageReady()}bootstrapSecretStorage(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.bootstrapSecretStorage(e)}addSecretStorageKey(e,t,i){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.addSecretStorageKey(e,t,i)}hasSecretStorageKey(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.hasSecretStorageKey(e)}storeSecret(e,t,i){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.storeSecret(e,t,i)}getSecret(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getSecret(e)}isSecretStored(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.isSecretStored(e)}requestSecret(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestSecret(e,t)}getDefaultSecretStorageKeyId(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getDefaultSecretStorageKeyId()}setDefaultSecretStorageKeyId(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.setDefaultSecretStorageKeyId(e)}checkSecretStoragePrivateKey(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkSecretStoragePrivateKey(e,t)}getEventSenderDeviceInfo(e){return s(this,void 0,void 0,(function*(){return this.crypto?this.crypto.getEventSenderDeviceInfo(e):null}))}isEventSenderVerified(e){return s(this,void 0,void 0,(function*(){const t=yield this.getEventSenderDeviceInfo(e);return!!t&&t.isVerified()}))}getOutgoingRoomKeyRequest(e){if(!this.crypto)throw new Error("End-to-End encryption disabled");const t=e.getWireContent(),i={session_id:t.session_id,sender_key:t.sender_key,algorithm:t.algorithm,room_id:e.getRoomId()};return i.session_id&&i.sender_key&&i.algorithm&&i.room_id?this.crypto.cryptoStore.getOutgoingRoomKeyRequest(i):Promise.resolve(null)}cancelAndResendEventRoomKeyRequest(e){if(!this.crypto)throw new Error("End-to-End encryption disabled");return e.cancelAndResendKeyRequest(this.crypto,this.getUserId())}setRoomEncryption(e,t){if(!this.crypto)throw new Error("End-to-End encryption disabled");return this.crypto.setRoomEncryption(e,t)}isRoomEncrypted(e){const t=this.getRoom(e);if(!t)return!1;return!!t.currentState.getStateEvents(B.EventType.RoomEncryption,"")||this.roomList.isRoomEncrypted(e)}encryptAndSendToDevices(e,t){if(!this.crypto)throw new Error("End-to-End encryption disabled");return this.crypto.encryptAndSendToDevices(e,t)}forceDiscardSession(e){if(!this.cryptoBackend)throw new Error("End-to-End encryption disabled");this.cryptoBackend.forceDiscardSession(e)}exportRoomKeys(){return this.cryptoBackend?this.cryptoBackend.exportRoomKeys():Promise.reject(new Error("End-to-end encryption disabled"))}importRoomKeys(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.importRoomKeys(e,t)}checkKeyBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.checkKeyBackup()}getKeyBackupVersion(){return s(this,void 0,void 0,(function*(){let e;try{e=yield this.http.authedRequest(I.Method.Get,"/room_keys/version",void 0,void 0,{prefix:I.ClientPrefix.V3})}catch(e){if("M_NOT_FOUND"===e.errcode)return null;throw e}return K.BackupManager.checkBackupVersion(e),e}))}isKeyBackupTrusted(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.isKeyBackupTrusted(e)}getKeyBackupEnabled(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.getKeyBackupEnabled()}enableKeyBackup(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.enableKeyBackup(e)}disableKeyBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");this.crypto.backupManager.disableKeyBackup()}prepareKeyBackupVersion(e,t={secureSecretStorage:!1}){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");const{algorithm:i,auth_data:n,recovery_key:r,privateKey:o}=yield this.crypto.backupManager.prepareKeyBackupVersion(e);return t.secureSecretStorage&&(yield this.storeSecret("m.megolm_backup.v1",(0,S.encodeBase64)(o)),w.logger.info("Key backup private key stored in secret storage")),{algorithm:i,auth_data:n,recovery_key:r}}))}isKeyBackupKeyStored(){return Promise.resolve(this.isSecretStored("m.megolm_backup.v1"))}createKeyBackupVersion(e){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");yield this.crypto.backupManager.createKeyBackupVersion(e);const t={algorithm:e.algorithm,auth_data:e.auth_data};yield this.crypto.signObject(t.auth_data),this.cryptoCallbacks.getCrossSigningKey&&this.crypto.crossSigningInfo.getId()&&(yield this.crypto.crossSigningInfo.signObject(t.auth_data,"master"));const i=yield this.http.authedRequest(I.Method.Post,"/room_keys/version",void 0,t,{prefix:I.ClientPrefix.V3});return yield this.checkKeyBackup(),this.getKeyBackupEnabled()||w.logger.error("Key backup not usable even though we just created it"),i}))}deleteKeyBackupVersion(e){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");this.crypto.backupManager.version&&this.crypto.backupManager.disableKeyBackup();const t=p.encodeUri("/room_keys/version/$version",{$version:e});yield this.http.authedRequest(I.Method.Delete,t,void 0,void 0,{prefix:I.ClientPrefix.V3})}))}makeKeyBackupPath(e,t,i){let n;n=void 0!==t?p.encodeUri("/room_keys/keys/$roomId/$sessionId",{$roomId:e,$sessionId:t}):void 0!==e?p.encodeUri("/room_keys/keys/$roomId",{$roomId:e}):"/room_keys/keys";return{path:n,queryData:void 0===i?void 0:{version:i}}}sendKeyBackup(e,t,i,n){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");const r=this.makeKeyBackupPath(e,t,i);yield this.http.authedRequest(I.Method.Put,r.path,r.queryData,n,{prefix:I.ClientPrefix.V3})}))}scheduleAllGroupSessionsForBackup(){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");yield this.crypto.backupManager.scheduleAllGroupSessionsForBackup()}))}flagAllGroupSessionsForBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.flagAllGroupSessionsForBackup()}isValidRecoveryKey(e){try{return(0,M.decodeRecoveryKey)(e),!0}catch(e){return!1}}keyBackupKeyFromPassword(e,t){return(0,k.keyFromAuthData)(t.auth_data,e)}keyBackupKeyFromRecoveryKey(e){return(0,M.decodeRecoveryKey)(e)}restoreKeyBackupWithPassword(e,t,i,n,r){return s(this,void 0,void 0,(function*(){const o=yield(0,k.keyFromAuthData)(n.auth_data,e);return this.restoreKeyBackup(o,t,i,n,r)}))}restoreKeyBackupWithSecretStorage(e,t,i,n){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");const r=yield this.getSecret("m.megolm_backup.v1"),o=(0,R.fixBackupKey)(r);if(o){const e=yield this.crypto.getSecretStorageKey();yield this.storeSecret("m.megolm_backup.v1",o,[e[0]])}const s=(0,S.decodeBase64)(o||r);return this.restoreKeyBackup(s,t,i,e,n)}))}restoreKeyBackupWithRecoveryKey(e,t,i,n,r){const o=(0,M.decodeRecoveryKey)(e);return this.restoreKeyBackup(o,t,i,n,r)}restoreKeyBackupWithCache(e,t,i,n){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");const r=yield this.crypto.getSessionBackupPrivateKey();if(!r)throw new Error("Couldn't get key");return this.restoreKeyBackup(r,e,t,i,n)}))}restoreKeyBackup(e,t,i,n,r){return s(this,void 0,void 0,(function*(){const o=null==r?void 0:r.cacheCompleteCallback,a=null==r?void 0:r.progressCallback;if(!this.crypto)throw new Error("End-to-end encryption disabled");let c=0,d=[];const l=this.makeKeyBackupPath(t,i,n.version),u=yield K.BackupManager.makeAlgorithm(n,(()=>s(this,void 0,void 0,(function*(){return e})))),h=u.untrusted;try{if(!(yield u.keyMatches(e)))return Promise.reject(new I.MatrixError({errcode:de.RESTORE_BACKUP_ERROR_BAD_KEY}));this.crypto.storeSessionBackupPrivateKey(e).catch((e=>{w.logger.warn("Error caching session backup key:",e)})).then(o),a&&a({stage:"fetch"});const n=yield this.http.authedRequest(I.Method.Get,l.path,l.queryData,void 0,{prefix:I.ClientPrefix.V3});if(n.rooms){const e=n.rooms;for(const[t,i]of Object.entries(e)){if(!i.sessions)continue;c+=Object.keys(i.sessions).length;const e=yield u.decryptSessions(i.sessions);for(const i of e)i.room_id=t,d.push(i)}}else if(n.sessions){const e=n.sessions;c=Object.keys(e).length,d=yield u.decryptSessions(e);for(const e of d)e.room_id=t}else{c=1;try{const[e]=yield u.decryptSessions({[i]:n});e.room_id=t,e.session_id=i,d.push(e)}catch(e){w.logger.log("Failed to decrypt megolm session from backup",e)}}}finally{u.free()}return yield this.importRoomKeys(d,{progressCallback:a,untrusted:h,source:"backup"}),yield this.checkKeyBackup(),{total:c,imported:d.length}}))}deleteKeysFromBackup(e,t,i){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");const n=this.makeKeyBackupPath(e,t,i);yield this.http.authedRequest(I.Method.Delete,n.path,n.queryData,void 0,{prefix:I.ClientPrefix.V3})}))}sendSharedHistoryKeys(e,t){return s(this,void 0,void 0,(function*(){if(!this.crypto)throw new Error("End-to-end encryption disabled");const i=this.roomList.getRoomEncryption(e);if(!i)return void w.logger.error("Unknown room. Not sharing decryption keys");const n=yield this.crypto.downloadKeys(t),r=new Map;for(const[e,t]of n)r.set(e,Array.from(t.values()));const o=this.crypto.getRoomDecryptor(e,i.algorithm);o.sendSharedHistoryInboundSessions?yield o.sendSharedHistoryInboundSessions(r):w.logger.warn("Algorithm does not support sharing previous keys",i.algorithm)}))}getMediaConfig(){return this.http.authedRequest(I.Method.Get,"/config",void 0,void 0,{prefix:I.MediaPrefix.R0})}getRoom(e){return e?this.store.getRoom(e):null}getRooms(){return this.store.getRooms()}getVisibleRooms(e=!1){var t;const i=this.store.getRooms(),n=new Set;for(const r of i){const i=null===(t=r.findPredecessor(e))||void 0===t?void 0:t.roomId;i&&n.add(i)}return i.filter((e=>!e.currentState.getStateEvents(B.EventType.RoomTombstone,"")||!n.has(e.roomId)))}getUser(e){return this.store.getUser(e)}getUsers(){return this.store.getUsers()}setAccountData(e,t){const i=p.encodeUri("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});return(0,I.retryNetworkOperation)(5,(()=>this.http.authedRequest(I.Method.Put,i,void 0,t)))}getAccountData(e){return this.store.getAccountData(e)}getAccountDataFromServer(e){var t;return s(this,void 0,void 0,(function*(){if(this.isInitialSyncComplete()){const t=this.store.getAccountData(e);return t?t.getContent():null}const i=p.encodeUri("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});try{return yield this.http.authedRequest(I.Method.Get,i)}catch(e){if("M_NOT_FOUND"===(null===(t=e.data)||void 0===t?void 0:t.errcode))return null;throw e}}))}deleteAccountData(e){return s(this,void 0,void 0,(function*(){const t=this.canSupport.get(ie.Feature.AccountDataDeletion);if(t===ie.ServerSupport.Unsupported)return void(yield this.setAccountData(e,{}));const i=p.encodeUri("/user/$userId/account_data/$type",{$userId:this.getSafeUserId(),$type:e}),n=t===ie.ServerSupport.Unstable?{prefix:"/_matrix/client/unstable/org.matrix.msc3391"}:void 0;return yield this.http.authedRequest(I.Method.Delete,i,void 0,void 0,n)}))}getIgnoredUsers(){const e=this.getAccountData("m.ignored_user_list");return e&&e.getContent()&&e.getContent().ignored_users?Object.keys(e.getContent().ignored_users):[]}setIgnoredUsers(e){const t={ignored_users:{}};return e.forEach((e=>{t.ignored_users[e]={}})),this.setAccountData("m.ignored_user_list",t)}isUserIgnored(e){return this.getIgnoredUsers().includes(e)}joinRoom(e,t={}){return s(this,void 0,void 0,(function*(){void 0===t.syncRoom&&(t.syncRoom=!0);const i=this.getRoom(e);if(null==i?void 0:i.hasMembershipState(this.credentials.userId,"join"))return Promise.resolve(i);let n=Promise.resolve();if(t.inviteSignUrl){const e=new URL(t.inviteSignUrl);e.searchParams.set("mxid",this.credentials.userId),n=this.http.requestOtherUrl(I.Method.Post,e)}const r={};t.viaServers&&(r.server_name=t.viaServers);try{const i={},o=yield n;o&&(i.third_party_signed=o);const s=p.encodeUri("/join/$roomid",{$roomid:e}),a=(yield this.http.authedRequest(I.Method.Post,s,r,i)).room_id,d=new c.SyncApi(this,this.clientOpts,this.buildSyncApiOptions()).createRoom(a);return t.syncRoom,d}catch(e){throw e}}))}resendEvent(e,t){return this.toDeviceMessageQueue.sendQueue(),this.updatePendingEventStatus(t,e,d.EventStatus.SENDING),this.encryptAndSendEvent(t,e)}cancelPendingEvent(e){if(![d.EventStatus.QUEUED,d.EventStatus.NOT_SENT,d.EventStatus.ENCRYPTING].includes(e.status))throw new Error("cannot cancel an event with status "+e.status);e.status===d.EventStatus.ENCRYPTING?this.pendingEventEncryption.delete(e.getId()):this.scheduler&&e.status===d.EventStatus.QUEUED&&this.scheduler.removeEventFromQueue(e);const t=this.getRoom(e.getRoomId());this.updatePendingEventStatus(t,e,d.EventStatus.CANCELLED)}setRoomName(e,t){return this.sendStateEvent(e,B.EventType.RoomName,{name:t})}setRoomTopic(e,t,i){const n=x.makeTopicContent(t,i);return this.sendStateEvent(e,B.EventType.RoomTopic,n)}getRoomTags(e){const t=p.encodeUri("/user/$userId/rooms/$roomId/tags",{$userId:this.credentials.userId,$roomId:e});return this.http.authedRequest(I.Method.Get,t)}setRoomTag(e,t,i){const n=p.encodeUri("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(I.Method.Put,n,void 0,i)}deleteRoomTag(e,t){const i=p.encodeUri("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(I.Method.Delete,i)}setRoomAccountData(e,t,i){const n=p.encodeUri("/user/$userId/rooms/$roomId/account_data/$type",{$userId:this.credentials.userId,$roomId:e,$type:t});return this.http.authedRequest(I.Method.Put,n,void 0,i)}setPowerLevel(e,t,i,n){let r={users:{}};(null==n?void 0:n.getType())===B.EventType.RoomPowerLevels&&(r=p.deepCopy(n.getContent()));const o=Array.isArray(t)?t:[t];for(const e of o)null==i?delete r.users[e]:r.users[e]=i;const s=p.encodeUri("/rooms/$roomId/state/m.room.power_levels",{$roomId:e});return this.http.authedRequest(I.Method.Put,s,void 0,r)}unstable_createLiveBeacon(e,t){return s(this,void 0,void 0,(function*(){return this.unstable_setLiveBeacon(e,t)}))}unstable_setLiveBeacon(e,t){return s(this,void 0,void 0,(function*(){return this.sendStateEvent(e,X.M_BEACON_INFO.name,t,this.getUserId())}))}sendEvent(e,t,i,n,r){var o,s,a,c,d;let l,u,h,f;if((null==t?void 0:t.startsWith(se))||null===t?(f=r,h=n,u=i,l=t):(f=n,h=i,u=t,l=null),l&&!(null===(o=h["m.relates_to"])||void 0===o?void 0:o.rel_type)){const t=!!(null===(s=h["m.relates_to"])||void 0===s?void 0:s["m.in_reply_to"]);h["m.relates_to"]=Object.assign(Object.assign({},h["m.relates_to"]),{rel_type:Q.THREAD_RELATION_TYPE.name,event_id:l,is_falling_back:!t});const i=null===(a=this.getRoom(e))||void 0===a?void 0:a.getThread(l);i&&!t&&(h["m.relates_to"]["m.in_reply_to"]={event_id:null!==(d=null===(c=i.lastReply((e=>e.isRelation(Q.THREAD_RELATION_TYPE.name)&&!e.status)))||void 0===c?void 0:c.getId())&&void 0!==d?d:l})}return this.sendCompleteEvent(e,l,{type:u,content:h},f)}sendCompleteEvent(e,t,i,n){n||(n=this.makeTxnId());const r=new d.MatrixEvent(Object.assign(i,{event_id:"~"+e+":"+n,user_id:this.credentials.userId,sender:this.credentials.userId,room_id:e,origin_server_ts:(new Date).getTime()})),o=this.getRoom(e),s=t?null==o?void 0:o.getThread(t):void 0;s&&r.setThread(s),this.reEmitter.reEmit(r,[d.MatrixEventEvent.Replaced,d.MatrixEventEvent.VisibilityChange]),null==o||o.reEmitter.reEmit(r,[d.MatrixEventEvent.BeforeRedaction]);const a=r.getAssociatedId();if(null==a?void 0:a.startsWith("~")){const e=null==o?void 0:o.getPendingEvents().find((e=>e.getId()===a));null==e||e.once(d.MatrixEventEvent.LocalEventIdReplaced,(()=>{r.updateAssociatedId(e.getId())}))}const c=r.getType();return w.logger.log(`sendEvent of type ${c} in ${e} with txnId ${n}`),r.setTxnId(n),r.setStatus(d.EventStatus.SENDING),null==o||o.addPendingEvent(r,n),r.status===d.EventStatus.NOT_SENT?Promise.reject(new Error("Event blocked by other events not yet sent")):this.encryptAndSendEvent(o,r)}encryptAndSendEvent(e,t){let i=!1;return Promise.resolve().then((()=>{const n=this.encryptEventIfNeeded(t,null!=e?e:void 0);return n?(this.pendingEventEncryption.set(t.getId(),n),this.updatePendingEventStatus(e,t,d.EventStatus.ENCRYPTING),n.then((()=>{this.pendingEventEncryption.has(t.getId())?this.updatePendingEventStatus(e,t,d.EventStatus.SENDING):i=!0}))):null})).then((()=>{if(i)return{};let n=null;return this.scheduler&&(n=this.scheduler.queueEvent(t),n&&this.scheduler.getQueueForEvent(t).length>1&&this.updatePendingEventStatus(e,t,d.EventStatus.QUEUED)),n||(n=this.sendEventHttpRequest(t),e&&(n=n.then((i=>(e.updatePendingEvent(t,d.EventStatus.SENT,i.event_id),i))))),n})).catch((i=>{w.logger.error("Error sending event",i.stack||i);try{t.error=i,this.updatePendingEventStatus(e,t,d.EventStatus.NOT_SENT)}catch(e){w.logger.error("Exception in error handler!",e.stack||i)}throw i instanceof I.MatrixError&&(i.event=t),i}))}encryptEventIfNeeded(e,t){if(e.isEncrypted())return null;if(e.isRedaction())return null;if(!t||!this.isRoomEncrypted(e.getRoomId()))return null;if(!this.cryptoBackend&&this.usingExternalCrypto)return null;if(e.getType()===B.EventType.Reaction)return null;if(!this.cryptoBackend)throw new Error("This room is configured to use encryption, but your client does not support encryption.");return this.cryptoBackend.encryptEvent(e,t)}getEncryptedIfNeededEventType(e,t){return t===B.EventType.Reaction?t:this.isRoomEncrypted(e)?B.EventType.RoomMessageEncrypted:t}updatePendingEventStatus(e,t,i){e?e.updatePendingEvent(t,i):t.setStatus(i)}sendEventHttpRequest(e){let t=e.getTxnId();t||(t=this.makeTxnId(),e.setTxnId(t));const i={$roomId:e.getRoomId(),$eventType:e.getWireType(),$stateKey:e.getStateKey(),$txnId:t};let n;if(e.isState()){let t="/rooms/$roomId/state/$eventType";e.getStateKey()&&e.getStateKey().length>0&&(t="/rooms/$roomId/state/$eventType/$stateKey"),n=p.encodeUri(t,i)}else if(e.isRedaction()){const t="/rooms/$roomId/redact/$redactsEventId/$txnId";n=p.encodeUri(t,Object.assign({$redactsEventId:e.event.redacts},i))}else n=p.encodeUri("/rooms/$roomId/send/$eventType/$txnId",i);return this.http.authedRequest(I.Method.Put,n,void 0,e.getWireContent()).then((t=>(w.logger.log(`Event sent to ${e.getRoomId()} with event id ${t.event_id}`),t)))}redactEvent(e,t,i,n,r){(null==i?void 0:i.startsWith(se))||(r=n,n=i,i=t,t=null);const o=null==r?void 0:r.reason;if((null==r?void 0:r.with_relations)&&this.canSupport.get(ie.Feature.RelationBasedRedactions)===ie.ServerSupport.Unsupported)throw new Error(`Server does not support relation based redactions roomId ${e} eventId ${i} txnId: ${n} threadId ${t}`);const s=(null==r?void 0:r.with_relations)?{[this.canSupport.get(ie.Feature.RelationBasedRedactions)===ie.ServerSupport.Stable?B.MSC3912_RELATION_BASED_REDACTIONS_PROP.stable:B.MSC3912_RELATION_BASED_REDACTIONS_PROP.unstable]:null==r?void 0:r.with_relations}:{};return this.sendCompleteEvent(e,t,{type:B.EventType.RoomRedaction,content:Object.assign(Object.assign({},s),{reason:o}),redacts:i},n)}sendMessage(e,t,i,n){"string"!=typeof t&&null!==t&&(n=i,i=t,t=null);const r=B.EventType.RoomMessage,o=i;return this.sendEvent(e,t,r,o,n)}sendTextMessage(e,t,i,n){(null==t?void 0:t.startsWith(se))||null===t||(n=i,i=t,t=null);const r=x.makeTextMessage(i);return this.sendMessage(e,t,r,n)}sendNotice(e,t,i,n){(null==t?void 0:t.startsWith(se))||null===t||(n=i,i=t,t=null);const r=x.makeNotice(i);return this.sendMessage(e,t,r,n)}sendEmoteMessage(e,t,i,n){(null==t?void 0:t.startsWith(se))||null===t||(n=i,i=t,t=null);const r=x.makeEmoteMessage(i);return this.sendMessage(e,t,r,n)}sendImageMessage(e,t,i,n,r="Image"){(null==t?void 0:t.startsWith(se))||null===t||(r=n||"Image",n=i,i=t,t=null);const o={msgtype:B.MsgType.Image,url:i,info:n,body:r};return this.sendMessage(e,t,o)}sendStickerMessage(e,t,i,n,r="Sticker"){(null==t?void 0:t.startsWith(se))||null===t||(r=n||"Sticker",n=i,i=t,t=null);const o={url:i,info:n,body:r};return this.sendEvent(e,t,B.EventType.Sticker,o)}sendHtmlMessage(e,t,i,n){(null==t?void 0:t.startsWith(se))||null===t||(n=i,i=t,t=null);const r=x.makeHtmlMessage(i,n);return this.sendMessage(e,t,r)}sendHtmlNotice(e,t,i,n){(null==t?void 0:t.startsWith(se))||null===t||(n=i,i=t,t=null);const r=x.makeHtmlNotice(i,n);return this.sendMessage(e,t,r)}sendHtmlEmote(e,t,i,n){(null==t?void 0:t.startsWith(se))||null===t||(n=i,i=t,t=null);const r=x.makeHtmlEmote(i,n);return this.sendMessage(e,t,r)}sendReceipt(e,t,i,n=!1){return s(this,void 0,void 0,(function*(){if(this.isGuest())return Promise.resolve({});const r=p.encodeUri("/rooms/$roomId/receipt/$receiptType/$eventId",{$roomId:e.getRoomId(),$receiptType:t,$eventId:e.getId()});if(!n){const t=!!e.threadRootId;i=Object.assign(Object.assign({},i),{thread_id:t?e.threadRootId:Y.MAIN_ROOM_TIMELINE})}const o=this.http.authedRequest(I.Method.Post,r,void 0,i||{}),s=this.getRoom(e.getRoomId());return s&&this.credentials.userId&&s.addLocalEchoReceipt(this.credentials.userId,e,t),o}))}sendReadReceipt(e,t=Y.ReceiptType.Read,i=!1){return s(this,void 0,void 0,(function*(){if(!e)return;const n=e.getId(),r=this.getRoom(e.getRoomId());if(null==r?void 0:r.hasPendingEvent(n))throw new Error(`Cannot set read receipt to a pending event (${n})`);return this.sendReceipt(e,t,{},i)}))}setRoomReadMarkers(e,t,i,n){return s(this,void 0,void 0,(function*(){const r=this.getRoom(e);if(r&&r.hasPendingEvent(t))throw new Error(`Cannot set read marker to a pending event (${t})`);let o,s;if(i){if(o=i.getId(),null==r?void 0:r.hasPendingEvent(o))throw new Error(`Cannot set read receipt to a pending event (${o})`);null==r||r.addLocalEchoReceipt(this.credentials.userId,i,Y.ReceiptType.Read)}if(n){if(s=n.getId(),null==r?void 0:r.hasPendingEvent(s))throw new Error(`Cannot set read receipt to a pending event (${s})`);null==r||r.addLocalEchoReceipt(this.credentials.userId,n,Y.ReceiptType.ReadPrivate)}return yield this.setRoomReadMarkersHttpRequest(e,t,o,s)}))}getUrlPreview(e,t){t=6e4*Math.floor(t/6e4);const i=new URL(e);i.hash="";const n=t+"_"+(e=i.toString()),r=this.urlPreviewCache[n];if(r)return r;const o=this.http.authedRequest(I.Method.Get,"/preview_url",{url:e,ts:t.toString()},void 0,{prefix:I.MediaPrefix.R0});return this.urlPreviewCache[n]=o,o}sendTyping(e,t,i){if(this.isGuest())return Promise.resolve({});const n=p.encodeUri("/rooms/$roomId/typing/$userId",{$roomId:e,$userId:this.getUserId()}),r={typing:t};return t&&(r.timeout=i||2e4),this.http.authedRequest(I.Method.Put,n,void 0,r)}getRoomUpgradeHistory(e,t=!1,i=!1){const n=this.getRoom(e);if(!n)return[];return[...this.findPredecessorRooms(n,t,i),n,...this.findSuccessorRooms(n,t,i)]}findPredecessorRooms(e,t,i){var n,r;const o=[];let s=null===(n=e.findPredecessor(i))||void 0===n?void 0:n.roomId;for(;null!==s;){const n=this.getRoom(s);if(null===n)break;if(t){const t=n.currentState.getStateEvents(B.EventType.RoomTombstone,"");if(!t||t.getContent().replacement_room!==e.roomId)break}o.splice(0,0,n),s=null===(r=(e=n).findPredecessor(i))||void 0===r?void 0:r.roomId}return o}findSuccessorRooms(e,t,i){var n;const r=[];let o=e.currentState.getStateEvents(B.EventType.RoomTombstone,"");for(;o;){const s=this.getRoom(o.getContent().replacement_room);if(!s)break;if(s.roomId===e.roomId)break;if(t){const t=null===(n=s.findPredecessor(i))||void 0===n?void 0:n.roomId;if(!t||t!==e.roomId)break}r.push(s);if(new Set(r.map((e=>e.roomId))).sizethis.leave(e).then((()=>{delete r[e]})).catch((t=>{r[e]=t}));for(const e of n)o.push(s(e.roomId));return Promise.all(o).then((()=>r))}ban(e,t,i){return this.membershipChange(e,t,"ban",i)}forget(e,t=!0){const i=this.membershipChange(e,void 0,"forget");return t?i.then((t=>(this.store.removeRoom(e),this.emit(ae.DeleteRoom,e),t))):i}unban(e,t){const i=p.encodeUri("/rooms/$roomId/unban",{$roomId:e}),n={user_id:t};return this.http.authedRequest(I.Method.Post,i,void 0,n)}kick(e,t,i){const n=p.encodeUri("/rooms/$roomId/kick",{$roomId:e}),r={user_id:t,reason:i};return this.http.authedRequest(I.Method.Post,n,void 0,r)}membershipChange(e,t,i,n){const r=p.encodeUri("/rooms/$room_id/$membership",{$room_id:e,$membership:i});return this.http.authedRequest(I.Method.Post,r,void 0,{user_id:t,reason:n})}getPushActionsForEvent(e,t=!1){return e.getPushActions()&&!t||e.setPushActions(this.pushProcessor.actionsForEvent(e)),e.getPushActions()}setProfileInfo(e,t){const i=p.encodeUri("/profile/$userId/$info",{$userId:this.credentials.userId,$info:e});return this.http.authedRequest(I.Method.Put,i,void 0,t)}setDisplayName(e){return s(this,void 0,void 0,(function*(){const t=yield this.setProfileInfo("displayname",{displayname:e}),i=this.getUser(this.getUserId());return i&&(i.displayName=e,i.emit(C.UserEvent.DisplayName,i.events.presence,i)),t}))}setAvatarUrl(e){return s(this,void 0,void 0,(function*(){const t=yield this.setProfileInfo("avatar_url",{avatar_url:e}),i=this.getUser(this.getUserId());return i&&(i.avatarUrl=e,i.emit(C.UserEvent.AvatarUrl,i.events.presence,i)),t}))}mxcUrlToHttp(e,t,i,n,r){return(0,O.getHttpUriForMxc)(this.baseUrl,e,t,i,n,r)}setPresence(e){return s(this,void 0,void 0,(function*(){const t=p.encodeUri("/presence/$userId/status",{$userId:this.credentials.userId});if(-1===["offline","online","unavailable"].indexOf(e.presence))throw new Error("Bad presence value: "+e.presence);yield this.http.authedRequest(I.Method.Put,t,void 0,e)}))}getPresence(e){const t=p.encodeUri("/presence/$userId/status",{$userId:e});return this.http.authedRequest(I.Method.Get,t)}scrollback(e,t=30){let i=0,n=this.ongoingScrollbacks[e.roomId]||{};if(n.promise)return n.promise;if(n.errorTs){const e=Date.now()-n.errorTs;i=Math.max(3e3-e,0)}if(null===e.oldState.paginationToken)return Promise.resolve(e);const r=this.store.scrollback(e,t).length;if(r===t)return Promise.resolve(e);t-=r;const o=new Promise(((n,r)=>{(0,g.sleep)(i).then((()=>this.createMessagesRequest(e.roomId,e.oldState.paginationToken,t,v.Direction.Backward))).then((t=>{var i,r;const o=t.chunk.map(this.getEventMapper());if(t.state){const i=t.state.map(this.getEventMapper());e.currentState.setUnknownStateEvents(i)}const[s,a]=e.partitionThreadedEvents(o);this.processAggregatedTimelineEvents(e,s),e.addEventsToTimeline(s,!0,e.getLiveTimeline()),this.processThreadEvents(e,a,!0),e.oldState.paginationToken=null!==(i=t.end)&&void 0!==i?i:null,0===t.chunk.length&&(e.oldState.paginationToken=null),this.store.storeEvents(e,o,null!==(r=t.end)&&void 0!==r?r:null,!0),delete this.ongoingScrollbacks[e.roomId],n(e)})).catch((t=>{this.ongoingScrollbacks[e.roomId]={errorTs:Date.now()},r(t)}))}));return n={promise:o},this.ongoingScrollbacks[e.roomId]=n,o}getEventMapper(e){return(0,j.eventMapperFor)(this,e||{})}getEventTimeline(e,t){var i,n,r,o;return s(this,void 0,void 0,(function*(){if(!this.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");if(!(null==e?void 0:e.room))throw new Error("getEventTimeline only supports room timelines");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);if(e.thread&&this.supportsThreads())return this.getThreadTimeline(e,t);const s=p.encodeUri("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t});let a;(null===(i=this.clientOpts)||void 0===i?void 0:i.lazyLoadMembers)&&(a={filter:JSON.stringify(h.Filter.LAZY_LOADING_MESSAGES_FILTER)});const c=yield this.http.authedRequest(I.Method.Get,s,a);if(!c.event)throw new Error("'event' not in '/context' result - homeserver too old?");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);const d=this.getEventMapper(),l=d(c.event);if(l.isRelation(Q.THREAD_RELATION_TYPE.name))return void w.logger.warn("Tried loading a regular timeline at the position of a thread event");const u=[...c.events_after.reverse().map(d),l,...c.events_before.map(d)];let f=e.getTimelineForEvent(u[0].getId());f?f.getState(v.EventTimeline.BACKWARDS).setUnknownStateEvents(c.state.map(d)):(f=e.addTimeline(),f.initialiseState(c.state.map(d)),f.getState(v.EventTimeline.FORWARDS).paginationToken=c.end);const[g,m]=e.room.partitionThreadedEvents(u);return e.addEventsToTimeline(g,!0,f,c.start),this.processThreadEvents(e.room,m,!0),this.processAggregatedTimelineEvents(e.room,g),null!==(o=null!==(n=e.getTimelineForEvent(t))&&void 0!==n?n:null===(r=e.room.findThreadForEvent(l))||void 0===r?void 0:r.liveTimeline)&&void 0!==o?o:f}))}getThreadTimeline(e,t){var i,n,r,o,a,c,d,l;return s(this,void 0,void 0,(function*(){if(!this.supportsThreads())throw new Error("could not get thread timeline: no client support");if(!e.room)throw new Error("could not get thread timeline: not a room timeline");if(!e.thread)throw new Error("could not get thread timeline: not a thread timeline");const s=p.encodeUri("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t}),u={limit:"0"};(null===(i=this.clientOpts)||void 0===i?void 0:i.lazyLoadMembers)&&(u.filter=JSON.stringify(h.Filter.LAZY_LOADING_MESSAGES_FILTER));const f=yield this.http.authedRequest(I.Method.Get,s,u),g=this.getEventMapper(),m=g(f.event);if(e.canContain(m)&&Q.Thread.hasServerSideSupport){if(Q.Thread.hasServerSideFwdPaginationSupport){if(!e.thread)throw new Error("could not get thread timeline: not a thread timeline");const i=e.thread,s=yield this.fetchRelations(e.room.roomId,i.id,Q.THREAD_RELATION_TYPE.name,null,{dir:v.Direction.Backward,from:f.start}),c=yield this.fetchRelations(e.room.roomId,i.id,Q.THREAD_RELATION_TYPE.name,null,{dir:v.Direction.Forward,from:f.end}),d=[...c.chunk.reverse().map(g),m,...s.chunk.map(g)];for(const t of d)yield null===(n=e.thread)||void 0===n?void 0:n.processEvent(t);let l=e.getTimelineForEvent(m.getId());if(l?l.getState(v.EventTimeline.BACKWARDS).setUnknownStateEvents(f.state.map(g)):(l=e.addTimeline(),l.initialiseState(f.state.map(g))),e.addEventsToTimeline(d,!0,l,c.next_batch),!s.next_batch){const t=yield this.fetchRoomEvent(e.room.roomId,i.id);e.addEventsToTimeline([g(t)],!0,l,null)}return l.setPaginationToken(null!==(r=s.next_batch)&&void 0!==r?r:null,v.Direction.Backward),l.setPaginationToken(null!==(o=c.next_batch)&&void 0!==o?o:null,v.Direction.Forward),this.processAggregatedTimelineEvents(e.room,d),null!==(a=e.getTimelineForEvent(t))&&void 0!==a?a:l}{const t=e.thread,i=yield this.fetchRelations(e.room.roomId,t.id,Q.THREAD_RELATION_TYPE.name,null,{dir:v.Direction.Backward,from:f.start}),n=[];let r=f.end;for(;r;){const i=yield this.fetchRelations(e.room.roomId,t.id,Q.THREAD_RELATION_TYPE.name,null,{dir:v.Direction.Forward,from:r});r=null!==(c=i.next_batch)&&void 0!==c?c:null,n.push(...i.chunk)}const o=[...n.reverse().map(g),m,...i.chunk.map(g)];for(const t of o)yield null===(d=e.thread)||void 0===d?void 0:d.processEvent(t);const s=e.getLiveTimeline();if(s.getState(v.EventTimeline.BACKWARDS).setUnknownStateEvents(f.state.map(g)),e.addEventsToTimeline(o,!0,s,null),!i.next_batch){const i=yield this.fetchRoomEvent(e.room.roomId,t.id);e.addEventsToTimeline([g(i)],!0,s,null)}return s.setPaginationToken(null!==(l=i.next_batch)&&void 0!==l?l:null,v.Direction.Backward),s.setPaginationToken(null,v.Direction.Forward),this.processAggregatedTimelineEvents(e.room,o),s}}}))}getLatestTimeline(e){var t,i,n,r;return s(this,void 0,void 0,(function*(){if(!this.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");if(!e.room)throw new Error("getLatestTimeline only supports room timelines");let o;if(null!==e.threadListType){const i=yield this.createThreadListMessagesRequest(e.room.roomId,null,1,v.Direction.Backward,e.threadListType,e.getFilter());o=null===(t=i.chunk)||void 0===t?void 0:t[0]}else if(e.thread&&Q.Thread.hasServerSideSupport){const t=yield this.fetchRelations(e.room.roomId,e.thread.id,Q.THREAD_RELATION_TYPE.name,null,{dir:v.Direction.Backward,limit:1});o=null===(i=t.chunk)||void 0===i?void 0:i[0]}else{const t=p.encodeUri("/rooms/$roomId/messages",{$roomId:e.room.roomId}),i={dir:"b"};(null===(n=this.clientOpts)||void 0===n?void 0:n.lazyLoadMembers)&&(i.filter=JSON.stringify(h.Filter.LAZY_LOADING_MESSAGES_FILTER));const s=yield this.http.authedRequest(I.Method.Get,t,i);o=null===(r=s.chunk)||void 0===r?void 0:r[0]}if(!o)throw new Error("No message returned when trying to construct getLatestTimeline");return this.getEventTimeline(e,o.event_id)}))}createMessagesRequest(e,t,i=30,n,r){var o,s;const a=p.encodeUri("/rooms/$roomId/messages",{$roomId:e}),c={limit:i.toString(),dir:n};t&&(c.from=t);let d=null;return(null===(o=this.clientOpts)||void 0===o?void 0:o.lazyLoadMembers)&&(d=Object.assign({},h.Filter.LAZY_LOADING_MESSAGES_FILTER)),r&&(d=d||{},Object.assign(d,null===(s=r.getRoomTimelineFilterComponent())||void 0===s?void 0:s.toJSON())),d&&(c.filter=JSON.stringify(d)),this.http.authedRequest(I.Method.Get,a,c)}createThreadListMessagesRequest(e,t,i=30,n=v.Direction.Backward,r=Q.ThreadFilterType.All,o){var s,a;const c=p.encodeUri("/rooms/$roomId/threads",{$roomId:e}),d={limit:i.toString(),dir:n,include:(0,Q.threadFilterTypeToFilter)(r)};t&&(d.from=t);let l={};(null===(s=this.clientOpts)||void 0===s?void 0:s.lazyLoadMembers)&&(l=Object.assign({},h.Filter.LAZY_LOADING_MESSAGES_FILTER)),o&&(l=Object.assign(Object.assign({},l),null===(a=o.getRoomTimelineFilterComponent())||void 0===a?void 0:a.toJSON())),Object.keys(l).length&&(d.filter=JSON.stringify(l));const u={prefix:Q.Thread.hasServerSideListSupport===Q.FeatureSupport.Stable?"/_matrix/client/v1":"/_matrix/client/unstable/org.matrix.msc3856"};return this.http.authedRequest(I.Method.Get,c,d,void 0,u).then((e=>{var t;return Object.assign(Object.assign({},e),{chunk:null===(t=e.chunk)||void 0===t?void 0:t.reverse(),start:e.prev_batch,end:e.next_batch})}))}paginateEventTimeline(e,t){var i,n,r;const o=e.getTimelineSet()===this.notifTimelineSet,a=this.getRoom(e.getRoomId()),c=e.getTimelineSet().threadListType,d=e.getTimelineSet().thread,l=(t=t||{}).backwards||!1;if(o&&!l)throw new Error("paginateNotifTimeline can only paginate backwards");const u=l?v.EventTimeline.BACKWARDS:v.EventTimeline.FORWARDS,h=e.getPaginationToken(u),f=e.paginationRequests[u];if(f)return f;let p,y,b;if(o)p="/notifications",y={limit:(null!==(i=t.limit)&&void 0!==i?i:30).toString(),only:"highlight"},h&&"end"!==h&&(y.from=h),b=this.http.authedRequest(I.Method.Get,"/notifications",y).then((t=>s(this,void 0,void 0,(function*(){const i=t.next_token,n=[];t.notifications=t.notifications.filter(g.noUnsafeEventProps);for(let e=0;e{e.paginationRequests[u]=null})),e.paginationRequests[u]=b;else if(null!==c){if(!a)throw new Error("Unknown room "+e.getRoomId());if(!Q.Thread.hasServerSideFwdPaginationSupport&&u===v.Direction.Forward)throw new Error("Cannot paginate threads forwards without server-side support for MSC 3715");b=this.createThreadListMessagesRequest(e.getRoomId(),h,t.limit,u,c,e.getFilter()).then((t=>{if(t.state){const i=e.getState(u),n=t.state.filter(g.noUnsafeEventProps).map(this.getEventMapper());i.setUnknownStateEvents(n)}const i=t.end,n=t.chunk.filter(g.noUnsafeEventProps).map(this.getEventMapper());return e.getTimelineSet().addEventsToTimeline(n,l,e,i),this.processAggregatedTimelineEvents(a,n),this.processThreadRoots(a,n,l),l&&t.end==t.start&&e.setPaginationToken(null,u),t.end!==t.start})).finally((()=>{e.paginationRequests[u]=null})),e.paginationRequests[u]=b}else if(d){const i=this.getRoom(null!==(n=e.getRoomId())&&void 0!==n?n:void 0);if(!i)throw new Error("Unknown room "+e.getRoomId());b=this.fetchRelations(null!==(r=e.getRoomId())&&void 0!==r?r:"",d.id,Q.THREAD_RELATION_TYPE.name,null,{dir:u,limit:t.limit,from:null!=h?h:void 0}).then((t=>s(this,void 0,void 0,(function*(){var n;const r=this.getEventMapper(),o=t.chunk.filter(g.noUnsafeEventProps).map(r);for(const e of o.slice().reverse()){yield null==d?void 0:d.processEvent(e);const t=e.getSender();l&&null!==(null==d?void 0:d.getEventReadUpTo(t))||i.addLocalEchoReceipt(t,e,Y.ReceiptType.Read)}const s=t.next_batch,a=e.getTimelineSet();if(a.addEventsToTimeline(o,l,e,null!=s?s:null),!s&&l){const t=yield this.fetchRoomEvent(null!==(n=e.getRoomId())&&void 0!==n?n:"",d.id);a.addEventsToTimeline([r(t)],!0,e,null)}return this.processAggregatedTimelineEvents(a.room,o),l&&!s&&e.setPaginationToken(null,u),Boolean(s)})))).finally((()=>{e.paginationRequests[u]=null})),e.paginationRequests[u]=b}else{if(!a)throw new Error("Unknown room "+e.getRoomId());b=this.createMessagesRequest(e.getRoomId(),h,t.limit,u,e.getFilter()).then((t=>{if(t.state){const i=e.getState(u),n=t.state.filter(g.noUnsafeEventProps).map(this.getEventMapper());i.setUnknownStateEvents(n)}const i=t.end,n=t.chunk.filter(g.noUnsafeEventProps).map(this.getEventMapper()),r=e.getTimelineSet(),[o]=a.partitionThreadedEvents(n);r.addEventsToTimeline(o,l,e,i),this.processAggregatedTimelineEvents(a,o),this.processThreadRoots(a,o.filter((e=>e.getServerAggregatedRelation(Q.THREAD_RELATION_TYPE.name))),!1);const s=void 0===t.end||t.end===t.start;return l&&s&&e.setPaginationToken(null,u),!s})).finally((()=>{e.paginationRequests[u]=null})),e.paginationRequests[u]=b}return b}resetNotifTimelineSet(){this.notifTimelineSet&&this.notifTimelineSet.resetLiveTimeline("end")}peekInRoom(e){var t;return null===(t=this.peekSync)||void 0===t||t.stopPeeking(),this.peekSync=new c.SyncApi(this,this.clientOpts,this.buildSyncApiOptions()),this.peekSync.peek(e)}stopPeeking(){this.peekSync&&(this.peekSync.stopPeeking(),this.peekSync=null)}setGuestAccess(e,t){const i=this.sendStateEvent(e,B.EventType.RoomGuestAccess,{guest_access:t.allowJoin?"can_join":"forbidden"},"");let n=Promise.resolve(void 0);return t.allowRead&&(n=this.sendStateEvent(e,B.EventType.RoomHistoryVisibility,{history_visibility:"world_readable"},"")),Promise.all([n,i]).then()}requestRegisterEmailToken(e,t,i,n){return this.requestTokenFromEndpoint("/register/email/requestToken",{email:e,client_secret:t,send_attempt:i,next_link:n})}requestRegisterMsisdnToken(e,t,i,n,r){return this.requestTokenFromEndpoint("/register/msisdn/requestToken",{country:e,phone_number:t,client_secret:i,send_attempt:n,next_link:r})}requestAdd3pidEmailToken(e,t,i,n){return this.requestTokenFromEndpoint("/account/3pid/email/requestToken",{email:e,client_secret:t,send_attempt:i,next_link:n})}requestAdd3pidMsisdnToken(e,t,i,n,r){return this.requestTokenFromEndpoint("/account/3pid/msisdn/requestToken",{country:e,phone_number:t,client_secret:i,send_attempt:n,next_link:r})}requestPasswordEmailToken(e,t,i,n){return this.requestTokenFromEndpoint("/account/password/email/requestToken",{email:e,client_secret:t,send_attempt:i,next_link:n})}requestPasswordMsisdnToken(e,t,i,n,r){return this.requestTokenFromEndpoint("/account/password/msisdn/requestToken",{country:e,phone_number:t,client_secret:i,send_attempt:n,next_link:r})}requestTokenFromEndpoint(e,t){var i;return s(this,void 0,void 0,(function*(){const n=Object.assign({},t);if(!(yield this.doesServerSupportSeparateAddAndBind())&&this.idBaseUrl){const e=new URL(this.idBaseUrl);if(n.id_server=e.host,(null===(i=this.identityServer)||void 0===i?void 0:i.getAccessToken)&&(yield this.doesServerAcceptIdentityAccessToken())){const e=yield this.identityServer.getAccessToken();e&&(n.id_access_token=e)}}return this.http.request(I.Method.Post,e,void 0,n)}))}getRoomPushRule(e,t){var i,n;if(this.pushRules)return null===(n=null===(i=this.pushRules[e])||void 0===i?void 0:i.room)||void 0===n?void 0:n.find((e=>e.rule_id===t));throw new Error("SyncApi.sync() must be done before accessing to push rules.")}setRoomMutePushRule(e,t,i){let n,r=!1;const o=this.getRoomPushRule(e,t);if((null==o?void 0:o.actions.includes(V.PushRuleActionName.DontNotify))&&(r=!0),i)if(o){if(!r){const i=p.defer();this.deletePushRule(e,V.PushRuleKind.RoomSpecific,o.rule_id).then((()=>{this.addPushRule(e,V.PushRuleKind.RoomSpecific,t,{actions:[V.PushRuleActionName.DontNotify]}).then((()=>{i.resolve()})).catch((e=>{i.reject(e)}))})).catch((e=>{i.reject(e)})),n=i.promise}}else n=this.addPushRule(e,V.PushRuleKind.RoomSpecific,t,{actions:[V.PushRuleActionName.DontNotify]});else r&&(n=this.deletePushRule(e,V.PushRuleKind.RoomSpecific,o.rule_id));if(n)return new Promise(((e,t)=>{n.then((()=>{this.getPushRules().then((t=>{this.pushRules=t,e()})).catch((e=>{t(e)}))})).catch((e=>{this.getPushRules().then((i=>{this.pushRules=i,t(e)})).catch((i=>{t(e)}))}))}))}searchMessageText(e){const t={search_term:e.query};return"keys"in e&&(t.keys=e.keys),this.search({body:{search_categories:{room_events:t}}})}searchRoomEvents(e){const t={search_categories:{room_events:{search_term:e.term,filter:e.filter,order_by:$.SearchOrderBy.Recent,event_context:{before_limit:1,after_limit:1,include_profile:!0}}}},i={_query:t,results:[],highlights:[]};return this.search({body:t}).then((e=>this.processRoomEventsSearch(i,e)))}backPaginateRoomEventsSearch(e){if(!e.next_batch)return Promise.reject(new Error("Cannot backpaginate event search any further"));if(e.pendingRequest)return e.pendingRequest;const t={body:e._query,next_batch:e.next_batch},i=this.search(t,e.abortSignal).then((t=>this.processRoomEventsSearch(e,t))).finally((()=>{e.pendingRequest=void 0}));return e.pendingRequest=i,i}processRoomEventsSearch(e,t){var i,n;const r=t.search_categories.room_events;e.count=r.count,e.next_batch=r.next_batch;const o=new Set(r.highlights);e.highlights.forEach((e=>{o.add(e)})),e.highlights=Array.from(o);const s=this.getEventMapper(),a=null!==(n=null===(i=r.results)||void 0===i?void 0:i.length)&&void 0!==n?n:0;for(let t=0;t{w.logger.log("Marking success of sync left room request"),this.syncedLeftRooms=!0})).finally((()=>{this.syncLeftRoomsPromise=void 0})),this.syncLeftRoomsPromise}createFilter(e){const t=p.encodeUri("/user/$userId/filter",{$userId:this.credentials.userId});return this.http.authedRequest(I.Method.Post,t,void 0,e).then((t=>{const i=h.Filter.fromJson(this.credentials.userId,t.filter_id,e);return this.store.storeFilter(i),i}))}getFilter(e,t,i){if(i){const i=this.store.getFilter(e,t);if(i)return Promise.resolve(i)}const n=p.encodeUri("/user/$userId/filter/$filterId",{$userId:e,$filterId:t});return this.http.authedRequest(I.Method.Get,n).then((i=>{const n=h.Filter.fromJson(e,t,i);return this.store.storeFilter(n),n}))}getOrCreateFilter(e,t){return s(this,void 0,void 0,(function*(){const i=this.store.getFilterIdByName(e);let n;if(i){try{const e=yield this.getFilter(this.credentials.userId,i,!0);if(e){const r=e.getDefinition(),o=t.getDefinition();p.deepCompare(r,o)&&(n=i)}}catch(e){if("M_UNKNOWN"!==e.errcode&&"M_NOT_FOUND"!==e.errcode)throw e}n||this.store.setFilterIdByName(e,void 0)}if(n)return n;const r=yield this.createFilter(t.getDefinition());return this.store.setFilterIdByName(e,r.filterId),r.filterId}))}getOpenIdToken(){const e=p.encodeUri("/user/$userId/openid/request_token",{$userId:this.credentials.userId});return this.http.authedRequest(I.Method.Post,e,void 0,{})}turnServer(){return this.http.authedRequest(I.Method.Get,"/voip/turnServer")}getTurnServers(){return this.turnServers||[]}getTurnServersExpiry(){return this.turnServersExpiry}get pollingTurnServers(){return void 0!==this.checkTurnServersIntervalID}checkTurnServers(){return s(this,void 0,void 0,(function*(){if(!this.canSupportVoip)return;let e=!1;const i=this.turnServersExpiry-Date.now();if(i>re)w.logger.debug("TURN creds are valid for another "+i+" ms: not fetching new ones."),e=!0;else{w.logger.debug("Fetching new TURN credentials");try{const t=yield this.turnServer();if(t.uris){w.logger.log("Got TURN URIs: "+t.uris+" refresh in "+t.ttl+" secs");const i={urls:t.uris,username:t.username,credential:t.password};this.turnServers=[i],this.turnServersExpiry=Date.now()+1e3*t.ttl,e=!0,this.emit(ae.TurnServers,this.turnServers)}}catch(e){w.logger.error("Failed to get TURN URIs",e),403===e.httpStatus?(w.logger.info("TURN access unavailable for this account: stopping credentials checks"),null!==this.checkTurnServersIntervalID&&t.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=void 0,this.emit(ae.TurnServersError,e,!0)):this.emit(ae.TurnServersError,e,!1)}}return e}))}setFallbackICEServerAllowed(e){this.fallbackICEServerAllowed=e}isFallbackICEServerAllowed(){return this.fallbackICEServerAllowed}isSynapseAdministrator(){const e=p.encodeUri("/_synapse/admin/v1/users/$userId/admin",{$userId:this.getUserId()});return this.http.authedRequest(I.Method.Get,e,void 0,void 0,{prefix:""}).then((e=>e.admin))}whoisSynapseUser(e){const t=p.encodeUri("/_synapse/admin/v1/whois/$userId",{$userId:e});return this.http.authedRequest(I.Method.Get,t,void 0,void 0,{prefix:""})}deactivateSynapseUser(e){const t=p.encodeUri("/_synapse/admin/v1/deactivate/$userId",{$userId:e});return this.http.authedRequest(I.Method.Post,t,void 0,void 0,{prefix:""})}fetchClientWellKnown(){var e;return s(this,void 0,void 0,(function*(){this.clientWellKnownPromise=y.AutoDiscovery.getRawClientConfig(null!==(e=this.getDomain())&&void 0!==e?e:void 0),this.clientWellKnown=yield this.clientWellKnownPromise,this.emit(ae.ClientWellKnown,this.clientWellKnown)}))}getClientWellKnown(){return this.clientWellKnown}waitForClientWellKnown(){if(!this.clientRunning)throw new Error("Client is not running");return this.clientWellKnownPromise}storeClientOptions(){const e=["boolean","string","number"],t=Object.entries(this.clientOpts).filter((([t,i])=>e.includes(typeof i))).reduce(((e,[t,i])=>(e[t]=i,e)),{});return this.store.storeClientOptions(t)}_unstable_getSharedRooms(e){return s(this,void 0,void 0,(function*(){const t=yield this.doesServerSupportUnstableFeature("uk.half-shot.msc2666"),i=yield this.doesServerSupportUnstableFeature("uk.half-shot.msc2666.mutual_rooms");if(!t&&!i)throw Error("Server does not support mutual_rooms API");const n=p.encodeUri(`/uk.half-shot.msc2666/user/${i?"mutual_rooms":"shared_rooms"}/$userId`,{$userId:e});return(yield this.http.authedRequest(I.Method.Get,n,void 0,void 0,{prefix:I.ClientPrefix.Unstable})).joined}))}getVersions(){return s(this,void 0,void 0,(function*(){if(this.serverVersionsPromise)return this.serverVersionsPromise;this.serverVersionsPromise=this.http.request(I.Method.Get,"/_matrix/client/versions",void 0,void 0,{prefix:""}).catch((e=>{throw this.serverVersionsPromise=void 0,e}));const e=yield this.serverVersionsPromise;return this.canSupport=yield(0,ie.buildFeatureSupportMap)(e),this.serverVersionsPromise}))}isVersionSupported(e){return s(this,void 0,void 0,(function*(){const{versions:t}=yield this.getVersions();return t&&t.includes(e)}))}doesServerSupportLazyLoading(){return s(this,void 0,void 0,(function*(){const e=yield this.getVersions();if(!e)return!1;const t=e.versions,i=e.unstable_features;return t&&t.includes("r0.5.0")||i&&i["m.lazy_load_members"]}))}doesServerRequireIdServerParam(){return s(this,void 0,void 0,(function*(){const e=yield this.getVersions();if(!e)return!0;const t=e.versions;if(t&&t.includes("r0.6.0"))return!1;const i=e.unstable_features;return!i||(void 0===i["m.require_identity_server"]||i["m.require_identity_server"])}))}doesServerAcceptIdentityAccessToken(){return s(this,void 0,void 0,(function*(){const e=yield this.getVersions();if(!e)return!1;const t=e.versions,i=e.unstable_features;return t&&t.includes("r0.6.0")||i&&i["m.id_access_token"]}))}doesServerSupportSeparateAddAndBind(){return s(this,void 0,void 0,(function*(){const e=yield this.getVersions();if(!e)return!1;const t=e.versions,i=e.unstable_features;return(null==t?void 0:t.includes("r0.6.0"))||(null==i?void 0:i["m.separate_add_and_bind"])}))}doesServerSupportUnstableFeature(e){return s(this,void 0,void 0,(function*(){const t=yield this.getVersions();if(!t)return!1;const i=t.unstable_features;return i&&!!i[e]}))}doesServerForceEncryptionForPreset(e){return s(this,void 0,void 0,(function*(){const t=yield this.getVersions();if(!t)return!1;const i=t.unstable_features,n=e.includes("_chat")?e.substring(0,e.indexOf("_chat")):e;return i&&!!i[`io.element.e2ee_forced.${n}`]}))}doesServerSupportThread(){return s(this,void 0,void 0,(function*(){if(yield this.isVersionSupported("v1.4"))return{threads:Q.FeatureSupport.Stable,list:Q.FeatureSupport.Stable,fwdPagination:Q.FeatureSupport.Stable};try{const[e,t,i,n,r,o]=yield Promise.all([this.doesServerSupportUnstableFeature("org.matrix.msc3440"),this.doesServerSupportUnstableFeature("org.matrix.msc3440.stable"),this.doesServerSupportUnstableFeature("org.matrix.msc3856"),this.doesServerSupportUnstableFeature("org.matrix.msc3856.stable"),this.doesServerSupportUnstableFeature("org.matrix.msc3715"),this.doesServerSupportUnstableFeature("org.matrix.msc3715.stable")]);return{threads:(0,Q.determineFeatureSupport)(t,e),list:(0,Q.determineFeatureSupport)(n,i),fwdPagination:(0,Q.determineFeatureSupport)(o,r)}}catch(e){return{threads:Q.FeatureSupport.None,list:Q.FeatureSupport.None,fwdPagination:Q.FeatureSupport.None}}}))}doesServerSupportLogoutDevices(){return this.isVersionSupported("r0.6.1")}hasLazyLoadMembersEnabled(){var e;return!!(null===(e=this.clientOpts)||void 0===e?void 0:e.lazyLoadMembers)}setCanResetTimelineCallback(e){this.canResetTimelineCallback=e}getCanResetTimelineCallback(){return this.canResetTimelineCallback}relations(e,t,i,n,r={dir:v.Direction.Backward}){var o,a;return s(this,void 0,void 0,(function*(){const s=n?this.getEncryptedIfNeededEventType(e,n):null,[c,d]=yield Promise.all([this.fetchRoomEvent(e,t),this.fetchRelations(e,t,i,s,r)]),l=this.getEventMapper(),u=c?l(c):void 0;let h=d.chunk.map(l);if(s===B.EventType.RoomMessageEncrypted){const e=u?h.concat(u):h;yield Promise.all(e.map((e=>this.decryptEventIfNeeded(e)))),null!==n&&(h=h.filter((e=>e.getType()===n)))}return u&&i===B.RelationType.Replace&&(h=h.filter((e=>e.getSender()===u.getSender()))),{originalEvent:null!=u?u:null,events:h,nextBatch:null!==(o=d.next_batch)&&void 0!==o?o:null,prevBatch:null!==(a=d.prev_batch)&&void 0!==a?a:null}}))}getCrossSigningCacheCallbacks(){var e;return null===(e=this.crypto)||void 0===e?void 0:e.crossSigningInfo.getCacheCallbacks()}generateClientSecret(){return(0,F.randomString)(32)}decryptEventIfNeeded(e,t){return e.shouldAttemptDecryption()&&this.isCryptoEnabled()&&e.attemptDecryption(this.cryptoBackend,t),e.isBeingDecrypted()?e.getDecryptionPromise():Promise.resolve()}termsUrlForService(e,t){switch(e){case T.SERVICE_TYPES.IS:return this.http.getUrl("/terms",void 0,I.IdentityPrefix.V2,t);case T.SERVICE_TYPES.IM:return this.http.getUrl("/terms",void 0,"/_matrix/integrations/v1",t);default:throw new Error("Unsupported service type")}}getHomeserverUrl(){return this.baseUrl}getIdentityServerUrl(e=!1){var t,i;return e&&((null===(t=this.idBaseUrl)||void 0===t?void 0:t.startsWith("http://"))||(null===(i=this.idBaseUrl)||void 0===i?void 0:i.startsWith("https://")))?this.idBaseUrl.split("://")[1]:this.idBaseUrl}setIdentityServerUrl(e){this.idBaseUrl=p.ensureNoTrailingSlash(e),this.http.setIdBaseUrl(this.idBaseUrl)}getAccessToken(){return this.http.opts.accessToken||null}setAccessToken(e){this.http.opts.accessToken=e}isLoggedIn(){return void 0!==this.http.opts.accessToken}makeTxnId(){return"m"+(new Date).getTime()+"."+this.txnCtr++}isUsernameAvailable(e){return this.http.authedRequest(I.Method.Get,"/register/available",{username:e}).then((e=>e.available)).catch((e=>"M_USER_IN_USE"!==e.errcode&&Promise.reject(e)))}register(e,t,i,n,r,o,s){!0===r?r={email:!0}:null!=r&&!1!==r||(r={}),i&&(n.session=i);const a={auth:n,refresh_token:!0};return null!=e&&(a.username=e),null!=t&&(a.password=t),r.email&&(a.bind_email=!0),r.msisdn&&(a.bind_msisdn=!0),null!=o&&(a.guest_access_token=o),null!=s&&(a.inhibit_login=s),null!=t&&(a.x_show_msisdn=!0),this.registerRequest(a)}registerGuest({body:e}={}){return this.registerRequest(e||{},"guest")}registerRequest(e,t){const i={};return t&&(i.kind=t),this.http.request(I.Method.Post,"/register",i,e)}refreshToken(e){return this.http.authedRequest(I.Method.Post,"/refresh",void 0,{refresh_token:e},{prefix:I.ClientPrefix.V1,inhibitLogoutEmit:!0})}loginFlows(){return this.http.request(I.Method.Get,"/login")}login(e,t){const i={type:e};return Object.assign(i,t),this.http.authedRequest(I.Method.Post,"/login",void 0,i).then((e=>(e.access_token&&e.user_id&&(this.http.opts.accessToken=e.access_token,this.credentials={userId:e.user_id}),e)))}loginWithPassword(e,t){return this.login("m.login.password",{user:e,password:t})}loginWithSAML2(e){return this.login("m.login.saml2",{relay_state:e})}getCasLoginUrl(e){return this.getSsoLoginUrl(e,"cas")}getSsoLoginUrl(e,t="sso",i,n){let r="/login/"+t+"/redirect";i&&(r+="/"+i);const o={redirectUrl:e,[ce.unstable]:n};return this.http.getUrl(r,o,I.ClientPrefix.R0).href}loginWithToken(e){return this.login("m.login.token",{token:e})}logout(e=!1){var t,i;return s(this,void 0,void 0,(function*(){if(null===(i=null===(t=this.crypto)||void 0===t?void 0:t.backupManager)||void 0===i?void 0:i.getKeyBackupEnabled())try{for(;(yield this.crypto.backupManager.backupPendingKeys(200))>0;);}catch(e){w.logger.error("Key backup request failed when logging out. Some keys may be missing from backup",e)}return e&&(this.stopClient(),this.http.abort()),this.http.authedRequest(I.Method.Post,"/logout")}))}deactivateAccount(e,t){const i={};return e&&(i.auth=e),void 0!==t&&(i.erase=t),this.http.authedRequest(I.Method.Post,"/account/deactivate",void 0,i)}requestLoginToken(e){const t={auth:e};return this.http.authedRequest(I.Method.Post,"/org.matrix.msc3882/login/token",void 0,t,{prefix:I.ClientPrefix.Unstable})}getFallbackAuthUrl(e,t){const i=p.encodeUri("/auth/$loginType/fallback/web",{$loginType:e});return this.http.getUrl(i,{session:t},I.ClientPrefix.R0).href}createRoom(e){var t;return s(this,void 0,void 0,(function*(){const i=(e.invite_3pid||[]).filter((e=>!e.id_access_token));if(i.length>0&&(null===(t=this.identityServer)||void 0===t?void 0:t.getAccessToken)&&(yield this.doesServerAcceptIdentityAccessToken())){const e=yield this.identityServer.getAccessToken();if(e)for(const t of i)t.id_access_token=e}return this.http.authedRequest(I.Method.Post,"/createRoom",void 0,e)}))}fetchRelations(e,t,i,n,r={dir:v.Direction.Backward}){let o=r;Q.Thread.hasServerSideFwdPaginationSupport===Q.FeatureSupport.Experimental&&(o=(0,g.replaceParam)("dir","org.matrix.msc3715.dir",o));const s=p.encodeParams(o);let a="/rooms/$roomId/relations/$eventId";null!==i?(a+="/$relationType",null!==n&&(a+="/$eventType")):null!==n&&(w.logger.warn(`eventType: ${n} ignored when fetching\n relations as relationType is null`),n=null);const c=p.encodeUri(a+"?"+s,{$roomId:e,$eventId:t,$relationType:i,$eventType:n});return this.http.authedRequest(I.Method.Get,c,void 0,void 0,{prefix:I.ClientPrefix.V1})}roomState(e){const t=p.encodeUri("/rooms/$roomId/state",{$roomId:e});return this.http.authedRequest(I.Method.Get,t)}fetchRoomEvent(e,t){const i=p.encodeUri("/rooms/$roomId/event/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(I.Method.Get,i)}members(e,t,i,n){const r={};t&&(r.membership=t),i&&(r.not_membership=i),n&&(r.at=n);const o=p.encodeParams(r),s=p.encodeUri("/rooms/$roomId/members?"+o,{$roomId:e});return this.http.authedRequest(I.Method.Get,s)}upgradeRoom(e,t){const i=p.encodeUri("/rooms/$roomId/upgrade",{$roomId:e});return this.http.authedRequest(I.Method.Post,i,void 0,{new_version:t})}getStateEvent(e,t,i){const n={$roomId:e,$eventType:t,$stateKey:i};let r=p.encodeUri("/rooms/$roomId/state/$eventType",n);return void 0!==i&&(r=p.encodeUri(r+"/$stateKey",n)),this.http.authedRequest(I.Method.Get,r)}sendStateEvent(e,t,i,n="",r={}){const o={$roomId:e,$eventType:t,$stateKey:n};let s=p.encodeUri("/rooms/$roomId/state/$eventType",o);return void 0!==n&&(s=p.encodeUri(s+"/$stateKey",o)),this.http.authedRequest(I.Method.Put,s,void 0,i,r)}roomInitialSync(e,t){var i;const n=p.encodeUri("/rooms/$roomId/initialSync",{$roomId:e});return this.http.authedRequest(I.Method.Get,n,{limit:null!==(i=null==t?void 0:t.toString())&&void 0!==i?i:"30"})}setRoomReadMarkersHttpRequest(e,t,i,n){return s(this,void 0,void 0,(function*(){const r=p.encodeUri("/rooms/$roomId/read_markers",{$roomId:e}),o={[Y.ReceiptType.FullyRead]:t,[Y.ReceiptType.Read]:i};return((yield this.doesServerSupportUnstableFeature("org.matrix.msc2285.stable"))||(yield this.isVersionSupported("v1.4")))&&(o[Y.ReceiptType.ReadPrivate]=n),this.http.authedRequest(I.Method.Post,r,void 0,o)}))}getJoinedRooms(){const e=p.encodeUri("/joined_rooms",{});return this.http.authedRequest(I.Method.Get,e)}getJoinedRoomMembers(e){const t=p.encodeUri("/rooms/$roomId/joined_members",{$roomId:e});return this.http.authedRequest(I.Method.Get,t)}publicRooms(e={}){var{server:t,limit:i,since:n}=e,r=a(e,["server","limit","since"]);const o={server:t,limit:i,since:n};return 0===Object.keys(r).length?this.http.authedRequest(I.Method.Get,"/publicRooms",o):this.http.authedRequest(I.Method.Post,"/publicRooms",o,r)}createAlias(e,t){const i=p.encodeUri("/directory/room/$alias",{$alias:e}),n={room_id:t};return this.http.authedRequest(I.Method.Put,i,void 0,n)}deleteAlias(e){const t=p.encodeUri("/directory/room/$alias",{$alias:e});return this.http.authedRequest(I.Method.Delete,t)}getLocalAliases(e){const t=p.encodeUri("/rooms/$roomId/aliases",{$roomId:e}),i=I.ClientPrefix.V3;return this.http.authedRequest(I.Method.Get,t,void 0,void 0,{prefix:i})}getRoomIdForAlias(e){const t=p.encodeUri("/directory/room/$alias",{$alias:e});return this.http.authedRequest(I.Method.Get,t)}resolveRoomAlias(e){const t=p.encodeUri("/directory/room/$alias",{$alias:e});return this.http.request(I.Method.Get,t)}getRoomDirectoryVisibility(e){const t=p.encodeUri("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(I.Method.Get,t)}setRoomDirectoryVisibility(e,t){const i=p.encodeUri("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(I.Method.Put,i,void 0,{visibility:t})}setRoomDirectoryVisibilityAppService(e,t,i){const n=p.encodeUri("/directory/list/appservice/$networkId/$roomId",{$networkId:e,$roomId:t});return this.http.authedRequest(I.Method.Put,n,void 0,{visibility:i})}searchUserDirectory({term:e,limit:t}){const i={search_term:e};return void 0!==t&&(i.limit=t),this.http.authedRequest(I.Method.Post,"/user_directory/search",void 0,i)}uploadContent(e,t){return this.http.uploadContent(e,t)}cancelUpload(e){return this.http.cancelUpload(e)}getCurrentUploads(){return this.http.getCurrentUploads()}getProfileInfo(e,t){const i=t?p.encodeUri("/profile/$userId/$info",{$userId:e,$info:t}):p.encodeUri("/profile/$userId",{$userId:e});return this.http.authedRequest(I.Method.Get,i)}getThreePids(){return this.http.authedRequest(I.Method.Get,"/account/3pid")}addThreePid(e,t){const i={threePidCreds:e,bind:t};return this.http.authedRequest(I.Method.Post,"/account/3pid",void 0,i)}addThreePidOnly(e){return s(this,void 0,void 0,(function*(){const t=(yield this.isVersionSupported("r0.6.0"))?I.ClientPrefix.R0:I.ClientPrefix.Unstable;return this.http.authedRequest(I.Method.Post,"/account/3pid/add",void 0,e,{prefix:t})}))}bindThreePid(e){return s(this,void 0,void 0,(function*(){const t=(yield this.isVersionSupported("r0.6.0"))?I.ClientPrefix.R0:I.ClientPrefix.Unstable;return this.http.authedRequest(I.Method.Post,"/account/3pid/bind",void 0,e,{prefix:t})}))}unbindThreePid(e,t){return s(this,void 0,void 0,(function*(){const i={medium:e,address:t,id_server:this.getIdentityServerUrl(!0)},n=(yield this.isVersionSupported("r0.6.0"))?I.ClientPrefix.R0:I.ClientPrefix.Unstable;return this.http.authedRequest(I.Method.Post,"/account/3pid/unbind",void 0,i,{prefix:n})}))}deleteThreePid(e,t){return this.http.authedRequest(I.Method.Post,"/account/3pid/delete",void 0,{medium:e,address:t})}setPassword(e,t,i){const n={auth:e,new_password:t,logout_devices:i};return this.http.authedRequest(I.Method.Post,"/account/password",void 0,n)}getDevices(){return this.http.authedRequest(I.Method.Get,"/devices")}getDevice(e){const t=p.encodeUri("/devices/$device_id",{$device_id:e});return this.http.authedRequest(I.Method.Get,t)}setDeviceDetails(e,t){const i=p.encodeUri("/devices/$device_id",{$device_id:e});return this.http.authedRequest(I.Method.Put,i,void 0,t)}deleteDevice(e,t){const i=p.encodeUri("/devices/$device_id",{$device_id:e}),n={};return t&&(n.auth=t),this.http.authedRequest(I.Method.Delete,i,void 0,n)}deleteMultipleDevices(e,t){const i={devices:e};t&&(i.auth=t);return this.http.authedRequest(I.Method.Post,"/delete_devices",void 0,i)}getPushers(){return s(this,void 0,void 0,(function*(){const e=yield this.http.authedRequest(I.Method.Get,"/pushers");return(yield this.doesServerSupportUnstableFeature("org.matrix.msc3881"))||(e.pushers=e.pushers.map((e=>(e.hasOwnProperty(B.PUSHER_ENABLED.name)||(e[B.PUSHER_ENABLED.name]=!0),e)))),e}))}setPusher(e){return this.http.authedRequest(I.Method.Post,"/pushers/set",void 0,e)}setLocalNotificationSettings(e,t){const i=`${B.LOCAL_NOTIFICATION_SETTINGS_PREFIX.name}.${e}`;return this.setAccountData(i,t)}getPushRules(){return this.http.authedRequest(I.Method.Get,"/pushrules/").then((e=>(this.setPushRules(e),this.pushRules)))}setPushRules(e){this.pushRules=m.PushProcessor.rewriteDefaultRules(e,this.getUserId()),this.pushProcessor.updateCachedPushRuleKeys(this.pushRules)}addPushRule(e,t,i,n){const r=p.encodeUri("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:i});return this.http.authedRequest(I.Method.Put,r,void 0,n)}deletePushRule(e,t,i){const n=p.encodeUri("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:i});return this.http.authedRequest(I.Method.Delete,n)}setPushRuleEnabled(e,t,i,n){const r=p.encodeUri("/pushrules/"+e+"/$kind/$ruleId/enabled",{$kind:t,$ruleId:i});return this.http.authedRequest(I.Method.Put,r,void 0,{enabled:n})}setPushRuleActions(e,t,i,n){const r=p.encodeUri("/pushrules/"+e+"/$kind/$ruleId/actions",{$kind:t,$ruleId:i});return this.http.authedRequest(I.Method.Put,r,void 0,{actions:n})}search({body:e,next_batch:t},i){const n={};return t&&(n.next_batch=t),this.http.authedRequest(I.Method.Post,"/search",n,e,{abortSignal:i})}uploadKeysRequest(e,t){return this.http.authedRequest(I.Method.Post,"/keys/upload",void 0,e)}uploadKeySignatures(e){return this.http.authedRequest(I.Method.Post,"/keys/signatures/upload",void 0,e,{prefix:I.ClientPrefix.V3})}downloadKeysForUsers(e,{token:t}={}){const i={device_keys:{}};return void 0!==t&&(i.token=t),e.forEach((e=>{i.device_keys[e]=[]})),this.http.authedRequest(I.Method.Post,"/keys/query",void 0,i)}claimOneTimeKeys(e,t="signed_curve25519",i){const n={};void 0===t&&(t="signed_curve25519");for(const[i,r]of e){const e=n[i]||{};n[i]=e,e[r]=t}const r={one_time_keys:n};i&&(r.timeout=i);return this.http.authedRequest(I.Method.Post,"/keys/claim",void 0,r)}getKeyChanges(e,t){const i={from:e,to:t};return this.http.authedRequest(I.Method.Get,"/keys/changes",i)}uploadDeviceSigningKeys(e,t){const i=Object.assign({},t);return e&&Object.assign(i,{auth:e}),this.http.authedRequest(I.Method.Post,"/keys/device_signing/upload",void 0,i,{prefix:I.ClientPrefix.Unstable})}registerWithIdentityServer(e){if(!this.idBaseUrl)throw new Error("No identity server base URL set");const t=this.http.getUrl("/account/register",void 0,I.IdentityPrefix.V2,this.idBaseUrl);return this.http.requestOtherUrl(I.Method.Post,t,e)}requestEmailToken(e,t,i,n,r){const o={client_secret:t,email:e,send_attempt:null==i?void 0:i.toString()};return n&&(o.next_link=n),this.http.idServerRequest(I.Method.Post,"/validate/email/requestToken",o,I.IdentityPrefix.V2,r)}requestMsisdnToken(e,t,i,n,r,o){const s={client_secret:i,country:e,phone_number:t,send_attempt:null==n?void 0:n.toString()};return r&&(s.next_link=r),this.http.idServerRequest(I.Method.Post,"/validate/msisdn/requestToken",s,I.IdentityPrefix.V2,o)}submitMsisdnToken(e,t,i,n){const r={sid:e,client_secret:t,token:i};return this.http.idServerRequest(I.Method.Post,"/validate/msisdn/submitToken",r,I.IdentityPrefix.V2,n)}submitMsisdnTokenOtherUrl(e,t,i,n){const r={sid:t,client_secret:i,token:n};return this.http.requestOtherUrl(I.Method.Post,e,r)}getIdentityHashDetails(e){return this.http.idServerRequest(I.Method.Get,"/hash_details",void 0,I.IdentityPrefix.V2,e)}identityHashedLookup(e,i){return s(this,void 0,void 0,(function*(){const n={},r=yield this.getIdentityHashDetails(i);if(!r||!r.lookup_pepper||!r.algorithms)throw new Error("Unsupported identity server: bad response");n.pepper=r.lookup_pepper;const o={};if(r.algorithms.includes("sha256")){const i=new t.Olm.Utility;n.addresses=e.map((e=>{const t=e[0].toLowerCase(),r=e[1].toLowerCase(),s=i.sha256(`${t} ${r} ${n.pepper}`).replace(/\+/g,"-").replace(/\//g,"_");return o[s]=e[0],s})),n.algorithm="sha256"}else{if(!r.algorithms.includes("none"))throw new Error("Unsupported identity server: unknown hash algorithm");n.addresses=e.map((e=>{const t=`${e[0].toLowerCase()} ${e[1].toLowerCase()}`;return o[t]=e[0],t})),n.algorithm="none"}const s=yield this.http.idServerRequest(I.Method.Post,"/lookup",n,I.IdentityPrefix.V2,i);if(!(null==s?void 0:s.mappings))return[];const a=[];for(const e of Object.keys(s.mappings)){const t=s.mappings[e],i=o[e];if(!i)throw new Error("Identity server returned more results than expected");a.push({address:i,mxid:t})}return a}))}lookupThreePid(e,t,i){return s(this,void 0,void 0,(function*(){const n=(yield this.identityHashedLookup([[t,e]],i)).find((e=>e.address===t));if(!n)return{};return{address:t,medium:e,mxid:n.mxid}}))}bulkLookupThreePids(e,t){return s(this,void 0,void 0,(function*(){const i=yield this.identityHashedLookup(e.map((e=>[e[1],e[0]])),t),n=[];for(const t of i){const i=e.find((e=>e[1]===t.address));if(!i)throw new Error("Identity sever returned unexpected results");n.push([i[0],t.address,t.mxid])}return{threepids:n}}))}getIdentityAccount(e){return this.http.idServerRequest(I.Method.Get,"/account",void 0,I.IdentityPrefix.V2,e)}sendToDevice(e,t,i){const n=p.encodeUri("/sendToDevice/$eventType/$txnId",{$eventType:e,$txnId:i||this.makeTxnId()}),r={messages:p.recursiveMapToObject(t)},o=new Map;for(const[e,i]of t)o.set(e,Array.from(i.keys()));return w.logger.log(`PUT ${n}`,o),this.http.authedRequest(I.Method.Put,n,void 0,r)}queueToDevice(e){return this.toDeviceMessageQueue.queueBatch(e)}getThirdpartyProtocols(){return this.http.authedRequest(I.Method.Get,"/thirdparty/protocols").then((e=>{if(!e||"object"!=typeof e)throw new Error(`/thirdparty/protocols did not return an object: ${e}`);return e}))}getThirdpartyLocation(e,t){const i=p.encodeUri("/thirdparty/location/$protocol",{$protocol:e});return this.http.authedRequest(I.Method.Get,i,t)}getThirdpartyUser(e,t){const i=p.encodeUri("/thirdparty/user/$protocol",{$protocol:e});return this.http.authedRequest(I.Method.Get,i,t)}getTerms(e,t){const i=this.termsUrlForService(e,t);return this.http.requestOtherUrl(I.Method.Get,i)}agreeToTerms(e,t,i,n){const r=this.termsUrlForService(e,t),o={Authorization:"Bearer "+i};return this.http.requestOtherUrl(I.Method.Post,r,{user_accepts:n},{headers:o})}reportEvent(e,t,i,n){const r=p.encodeUri("/rooms/$roomId/report/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(I.Method.Post,r,void 0,{score:i,reason:n})}getRoomHierarchy(e,t,i,n=!1,r){const o=p.encodeUri("/rooms/$roomId/hierarchy",{$roomId:e}),s={suggested_only:String(n),max_depth:null==i?void 0:i.toString(),from:r,limit:null==t?void 0:t.toString()};return this.http.authedRequest(I.Method.Get,o,s,void 0,{prefix:I.ClientPrefix.V1}).catch((e=>{if("M_UNRECOGNIZED"===e.errcode)return this.http.authedRequest(I.Method.Get,o,s,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2946"});throw e}))}unstableCreateFileTree(e){return s(this,void 0,void 0,(function*(){const{room_id:t}=yield this.createRoom({name:e,preset:N.Preset.PrivateChat,power_level_content_override:Object.assign(Object.assign({},q.DEFAULT_TREE_POWER_LEVELS_TEMPLATE),{users:{[this.getUserId()]:100}}),creation_content:{[B.RoomCreateTypeField]:B.RoomType.Space},initial_state:[{type:B.UNSTABLE_MSC3088_PURPOSE.name,state_key:B.UNSTABLE_MSC3089_TREE_SUBTYPE.name,content:{[B.UNSTABLE_MSC3088_ENABLED.name]:!0}},{type:B.EventType.RoomEncryption,state_key:"",content:{algorithm:b.MEGOLM_ALGORITHM}}]});return new q.MSC3089TreeSpace(this,t)}))}unstableGetFileTreeSpace(e){var t,i;const n=this.getRoom(e);if("join"!==(null==n?void 0:n.getMyMembership()))return null;const r=n.currentState.getStateEvents(B.EventType.RoomCreate,""),o=n.currentState.getStateEvents(B.UNSTABLE_MSC3088_PURPOSE.name,B.UNSTABLE_MSC3089_TREE_SUBTYPE.name);if(!r)throw new Error("Expected single room create event");return(null===(t=null==o?void 0:o.getContent())||void 0===t?void 0:t[B.UNSTABLE_MSC3088_ENABLED.name])?(null===(i=r.getContent())||void 0===i?void 0:i[B.RoomCreateTypeField])!==B.RoomType.Space?null:new q.MSC3089TreeSpace(this,e):null}slidingSync(e,t,i){const n={};e.pos&&(n.pos=e.pos,delete e.pos),e.timeout&&(n.timeout=e.timeout,delete e.timeout);const r=e.clientTimeout;return delete e.clientTimeout,this.http.authedRequest(I.Method.Post,"/sync",n,e,{prefix:"/_matrix/client/unstable/org.matrix.msc3575",baseUrl:t,localTimeoutMs:r,abortSignal:i})}supportsExperimentalThreads(){var e;return w.logger.warn("supportsExperimentalThreads() is deprecated, use supportThreads() instead"),(null===(e=this.clientOpts)||void 0===e?void 0:e.experimentalThreadSupport)||!1}supportsThreads(){var e;return(null===(e=this.clientOpts)||void 0===e?void 0:e.threadSupport)||!1}supportsIntentionalMentions(){var e;return(null===(e=this.clientOpts)||void 0===e?void 0:e.intentionalMentions)||!1}getRoomSummary(e,t){return s(this,void 0,void 0,(function*(){const i=p.encodeUri("/rooms/$roomid/summary",{$roomid:e});return this.http.authedRequest(I.Method.Get,i,{via:t},void 0,{prefix:"/_matrix/client/unstable/im.nheko.summary"})}))}processThreadEvents(e,t,i){e.processThreadedEvents(t,i)}processThreadRoots(e,t,i){e.processThreadRoots(t,i)}processBeaconEvents(e,t){this.processAggregatedTimelineEvents(e,t)}processAggregatedTimelineEvents(e,t){(null==t?void 0:t.length)&&e&&(e.currentState.processBeaconEvents(t,this),e.processPollEvents(t))}whoami(){return s(this,void 0,void 0,(function*(){return this.http.authedRequest(I.Method.Get,"/account/whoami")}))}timestampToEvent(e,t,i){return s(this,void 0,void 0,(function*(){const n=p.encodeUri("/rooms/$roomId/timestamp_to_event",{$roomId:e}),r={ts:t.toString(),dir:i};try{return yield this.http.authedRequest(I.Method.Get,n,r,void 0,{prefix:I.ClientPrefix.V1})}catch(e){if("M_UNRECOGNIZED"===e.errcode&&(400===e.httpStatus||404===e.httpStatus||405===e.httpStatus))return yield this.http.authedRequest(I.Method.Get,n,r,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc3030"});throw e}}))}}function le(e,t){var i,n;const r=e.getUserId(),o=t.getId(),s=e.getRoom(t.getRoomId());if(!s||!r||!o)return;const a=t.getPushActions(),c=e.getPushActionsForEvent(t,!0),d=!!t.threadRootId&&!t.isThreadRoot,l=s.getUnreadCountForEventContext(L.NotificationCountType.Highlight,t),u=!!(null===(i=null==a?void 0:a.tweaks)||void 0===i?void 0:i.highlight),h=!!(null===(n=null==c?void 0:c.tweaks)||void 0===n?void 0:n.highlight);let f;if(d){const e=s.getThread(t.threadRootId);f=!e||e.hasUserReadEvent(r,o)}else f=s.hasUserReadEvent(r,o);if(f)return;if(u!==h||l>0){let e=l;h&&!u&&e++,!h&&u&&e--,d?s.setThreadUnreadNotificationCount(t.threadRootId,L.NotificationCountType.Highlight,e):s.setUnreadNotificationCount(L.NotificationCountType.Highlight,e)}const p=s.getUnreadCountForEventContext(L.NotificationCountType.Total,t);!!(null==c?void 0:c.notify)&&(d?s.setThreadUnreadNotificationCount(t.threadRootId,L.NotificationCountType.Total,p+1):s.setUnreadNotificationCount(L.NotificationCountType.Total,p+1))}i.MatrixClient=de,de.RESTORE_BACKUP_ERROR_BAD_KEY="RESTORE_BACKUP_ERROR_BAD_KEY",i.fixNotificationCountOnDecryption=le}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./@types/PushRules":304,"./@types/beacon":305,"./@types/event":306,"./@types/partials":309,"./@types/read_receipts":311,"./@types/search":313,"./NamespacedValue":316,"./ReEmitter":317,"./ToDeviceMessageQueue":318,"./autodiscovery":319,"./content-helpers":322,"./content-repo":323,"./crypto":341,"./crypto/RoomList":329,"./crypto/api":336,"./crypto/backup":337,"./crypto/dehydration":339,"./crypto/key_passphrase":342,"./crypto/olmlib":343,"./crypto/recoverykey":344,"./event-mapper":360,"./feature":362,"./filter":364,"./http-api":367,"./logger":374,"./models/MSC3089TreeSpace":377,"./models/event":383,"./models/event-timeline":382,"./models/invites-ignorer":384,"./models/room":392,"./models/room-member":389,"./models/search-result":393,"./models/thread":394,"./models/typed-event-emitter":395,"./models/user":396,"./pushprocessor":397,"./randomstring":398,"./rust-crypto":402,"./rust-crypto/constants":401,"./service-types":405,"./sliding-sync-sdk":406,"./store/stub":412,"./sync":414,"./utils":416,"./webrtc/call":418,"./webrtc/callEventHandler":419,"./webrtc/groupCall":422,"./webrtc/groupCallEventHandler":423,"./webrtc/mediaHandler":424}],322:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.parseBeaconContent=i.makeBeaconContent=i.parseBeaconInfoContent=i.makeBeaconInfoContent=i.parseTopicContent=i.makeTopicContent=i.parseLocationEvent=i.makeLocationContent=i.getTextForLocationEvent=i.makeEmoteMessage=i.makeNotice=i.makeTextMessage=i.makeHtmlEmote=i.makeHtmlNotice=i.makeHtmlMessage=void 0;const n=e("./@types/event"),r=e("./@types/extensible_events"),o=e("./extensible_events_v1/utilities"),s=e("./@types/location"),a=e("./@types/topic");i.makeHtmlMessage=function(e,t){return{msgtype:n.MsgType.Text,format:"org.matrix.custom.html",body:e,formatted_body:t}},i.makeHtmlNotice=function(e,t){return{msgtype:n.MsgType.Notice,format:"org.matrix.custom.html",body:e,formatted_body:t}},i.makeHtmlEmote=function(e,t){return{msgtype:n.MsgType.Emote,format:"org.matrix.custom.html",body:e,formatted_body:t}},i.makeTextMessage=function(e){return{msgtype:n.MsgType.Text,body:e}},i.makeNotice=function(e){return{msgtype:n.MsgType.Notice,body:e}},i.makeEmoteMessage=function(e){return{msgtype:n.MsgType.Emote,body:e}};i.getTextForLocationEvent=(e,t,i,n)=>{const r=`at ${new Date(i).toISOString()}`;return[t===s.LocationAssetType.Self?"User":void 0,"Location",n?`"${n}"`:void 0,e,r].filter(Boolean).join(" ")};i.makeLocationContent=(e,t,o,a,c)=>{const d=null!=e?e:(0,i.getTextForLocationEvent)(t,c||s.LocationAssetType.Self,o,a),l=o?{[s.M_TIMESTAMP.name]:o}:{};return Object.assign({msgtype:n.MsgType.Location,body:d,geo_uri:t,[s.M_LOCATION.name]:{description:a,uri:t},[s.M_ASSET.name]:{type:c||s.LocationAssetType.Self},[r.M_TEXT.name]:d},l)};i.parseLocationEvent=e=>{var t,n;const o=s.M_LOCATION.findIn(e),a=s.M_ASSET.findIn(e),c=s.M_TIMESTAMP.findIn(e),d=r.M_TEXT.findIn(e),l=null!==(t=null==o?void 0:o.uri)&&void 0!==t?t:null==e?void 0:e.geo_uri,u=null==o?void 0:o.description,h=null!==(n=null==a?void 0:a.type)&&void 0!==n?n:s.LocationAssetType.Self,f=null!=d?d:e.body;return(0,i.makeLocationContent)(f,l,null!=c?c:void 0,u,h)};i.makeTopicContent=(e,t)=>{const i=[{body:e,mimetype:"text/plain"}];return(0,o.isProvided)(t)&&i.push({body:t,mimetype:"text/html"}),{topic:e,[a.M_TOPIC.name]:i}};i.parseTopicContent=e=>{var t,i,n;const r=a.M_TOPIC.findIn(e);if(!Array.isArray(r))return{text:e.topic};return{text:null!==(i=null===(t=null==r?void 0:r.find((e=>!(0,o.isProvided)(e.mimetype)||"text/plain"===e.mimetype)))||void 0===t?void 0:t.body)&&void 0!==i?i:e.topic,html:null===(n=null==r?void 0:r.find((e=>"text/html"===e.mimetype)))||void 0===n?void 0:n.body}};i.makeBeaconInfoContent=(e,t,i,n,r)=>({description:i,timeout:e,live:t,[s.M_TIMESTAMP.name]:r||Date.now(),[s.M_ASSET.name]:{type:null!=n?n:s.LocationAssetType.Self}});i.parseBeaconInfoContent=e=>{var t;const{description:i,timeout:n,live:r}=e,o=null!==(t=s.M_TIMESTAMP.findIn(e))&&void 0!==t?t:void 0,a=s.M_ASSET.findIn(e);return{description:i,timeout:n,live:r,assetType:null==a?void 0:a.type,timestamp:o}};i.makeBeaconContent=(e,t,i,n)=>({[s.M_LOCATION.name]:{description:n,uri:e},[s.M_TIMESTAMP.name]:t,"m.relates_to":{rel_type:r.REFERENCE_RELATION.name,event_id:i}});i.parseBeaconContent=e=>{var t;const i=s.M_LOCATION.findIn(e),n=null!==(t=s.M_TIMESTAMP.findIn(e))&&void 0!==t?t:void 0;return{description:null==i?void 0:i.description,uri:null==i?void 0:i.uri,timestamp:n}}},{"./@types/event":306,"./@types/extensible_events":307,"./@types/location":308,"./@types/topic":315,"./extensible_events_v1/utilities":361}],323:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(i,"__esModule",{value:!0}),i.getHttpUriForMxc=void 0;const s=o(e("./utils"));i.getHttpUriForMxc=function(e,t,i,n,r,o=!1){if("string"!=typeof t||!t)return"";if(0!==t.indexOf("mxc://"))return o?t:"";let a=t.slice(6),c="/_matrix/media/r0/download/";const d={};i&&(d.width=Math.round(i).toString()),n&&(d.height=Math.round(n).toString()),r&&(d.method=r),Object.keys(d).length>0&&(c="/_matrix/media/r0/thumbnail/");const l=a.indexOf("#");let u="";return l>=0&&(u=a.slice(l),a=a.slice(0,l)),e+c+a+(0===Object.keys(d).length?"":"?"+s.encodeParams(d))+u}},{"./utils":416}],324:[function(e,t,i){(function(t,n){(function(){"use strict";var r=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.requestKeysDuringVerification=i.createCryptoStoreCacheCallbacks=i.DeviceTrustLevel=i.UserTrustLevel=i.CrossSigningLevel=i.CrossSigningInfo=void 0;const o=e("./olmlib"),s=e("../logger"),a=e("../crypto/store/indexeddb-crypto-store"),c=e("./aes"),d=6e4;function l(e){return Object.values(e.keys)[0]}class u{constructor(e,t={},i={}){this.userId=e,this.callbacks=t,this.cacheCallbacks=i,this.keys={},this.firstUse=!0,this.crossSigningVerifiedBefore=!1}static fromStorage(e,t){const i=new u(t);for(const t in e)e.hasOwnProperty(t)&&(i[t]=e[t]);return i}toStorage(){return{keys:this.keys,firstUse:this.firstUse,crossSigningVerifiedBefore:this.crossSigningVerifiedBefore}}getCrossSigningKey(e,i){return r(this,void 0,void 0,(function*(){const n=["master","self_signing","user_signing"].indexOf(e)>=0;if(!this.callbacks.getCrossSigningKey)throw new Error("No getCrossSigningKey callback supplied");function r(e){if(!e)return;const n=new t.Olm.PkSigning,r=n.init_with_seed(e);if(r===i)return[r,n];n.free()}void 0===i&&(i=this.getId(e));let o=null;this.cacheCallbacks.getCrossSigningKeyCache&&n&&(o=yield this.cacheCallbacks.getCrossSigningKeyCache(e,i));const s=r(o);if(s)return s;o=yield this.callbacks.getCrossSigningKey(e,i);const a=r(o);if(a)return this.cacheCallbacks.storeCrossSigningKeyCache&&n&&(yield this.cacheCallbacks.storeCrossSigningKeyCache(e,o)),a;if(!o)throw new Error("getCrossSigningKey callback for "+e+" returned falsey");throw new Error("Key type "+e+" from getCrossSigningKey callback did not match")}))}isStoredInSecretStorage(e){return r(this,void 0,void 0,(function*(){const t=(yield e.isStored("m.cross_signing.master"))||{};function i(e){for(const i of Object.keys(t))e[i]||delete t[i]}for(const t of["self_signing","user_signing"])i((yield e.isStored(`m.cross_signing.${t}`))||{});return Object.keys(t).length?t:null}))}static storeInSecretStorage(e,t){return r(this,void 0,void 0,(function*(){for(const[i,n]of e){const e=(0,o.encodeBase64)(n);yield t.store(`m.cross_signing.${i}`,e)}}))}static getFromSecretStorage(e,t){return r(this,void 0,void 0,(function*(){const i=yield t.get(`m.cross_signing.${e}`);return i?(0,o.decodeBase64)(i):null}))}isStoredInKeyCache(e){var t;return r(this,void 0,void 0,(function*(){const i=this.cacheCallbacks;if(!i)return!1;const n=e?[e]:["master","self_signing","user_signing"];for(const e of n)if(!(yield null===(t=i.getCrossSigningKeyCache)||void 0===t?void 0:t.call(i,e)))return!1;return!0}))}getCrossSigningKeysFromCache(){var e;return r(this,void 0,void 0,(function*(){const t=new Map,i=this.cacheCallbacks;if(!i)return t;for(const n of["master","self_signing","user_signing"]){const r=yield null===(e=i.getCrossSigningKeyCache)||void 0===e?void 0:e.call(i,n);r&&t.set(n,r)}return t}))}getId(e="master"){if(!this.keys[e])return null;return l(this.keys[e])}resetKeys(e){return r(this,void 0,void 0,(function*(){if(!this.callbacks.saveCrossSigningKeys)throw new Error("No saveCrossSigningKeys callback supplied");if(void 0===e||e&h.MASTER||!this.keys.master)e=h.MASTER|h.USER_SIGNING|h.SELF_SIGNING;else if(0===e)return;const i={},n={};let r,s;try{if(e&h.MASTER?(r=new t.Olm.PkSigning,i.master=r.generate_seed(),s=r.init_with_seed(i.master),n.master={user_id:this.userId,usage:["master"],keys:{["ed25519:"+s]:s}}):[s,r]=yield this.getCrossSigningKey("master"),e&h.SELF_SIGNING){const e=new t.Olm.PkSigning;try{i.self_signing=e.generate_seed();const t=e.init_with_seed(i.self_signing);n.self_signing={user_id:this.userId,usage:["self_signing"],keys:{["ed25519:"+t]:t}},(0,o.pkSign)(n.self_signing,r,this.userId,s)}finally{e.free()}}if(e&h.USER_SIGNING){const e=new t.Olm.PkSigning;try{i.user_signing=e.generate_seed();const t=e.init_with_seed(i.user_signing);n.user_signing={user_id:this.userId,usage:["user_signing"],keys:{["ed25519:"+t]:t}},(0,o.pkSign)(n.user_signing,r,this.userId,s)}finally{e.free()}}Object.assign(this.keys,n),this.callbacks.saveCrossSigningKeys(i)}finally{r&&r.free()}}))}clearKeys(){this.keys={}}setKeys(e){const t={};if(e.master){if(e.master.user_id!==this.userId){const t="Mismatched user ID "+e.master.user_id+" in master key from "+this.userId;throw s.logger.error(t),new Error(t)}this.keys.master?l(e.master)!==this.getId()&&(this.firstUse=!1):this.firstUse=!0,t.master=e.master}else{if(!this.keys.master)throw new Error("Tried to set cross-signing keys without a master key");t.master=this.keys.master}const i=l(t.master);if(e.user_signing){if(e.user_signing.user_id!==this.userId){const t="Mismatched user ID "+e.master.user_id+" in user_signing key from "+this.userId;throw s.logger.error(t),new Error(t)}try{(0,o.pkVerify)(e.user_signing,i,this.userId)}catch(e){throw s.logger.error("invalid signature on user-signing key"),e}}if(e.self_signing){if(e.self_signing.user_id!==this.userId){const t="Mismatched user ID "+e.master.user_id+" in self_signing key from "+this.userId;throw s.logger.error(t),new Error(t)}try{(0,o.pkVerify)(e.self_signing,i,this.userId)}catch(e){throw s.logger.error("invalid signature on self-signing key"),e}}e.master&&(this.keys.master=e.master,delete this.keys.self_signing,delete this.keys.user_signing),e.self_signing&&(this.keys.self_signing=e.self_signing),e.user_signing&&(this.keys.user_signing=e.user_signing)}updateCrossSigningVerifiedBefore(e){!this.crossSigningVerifiedBefore&&e&&(this.crossSigningVerifiedBefore=!0)}signObject(e,t){return r(this,void 0,void 0,(function*(){if(!this.keys[t])throw new Error("Attempted to sign with "+t+" key but no such key present");const[i,n]=yield this.getCrossSigningKey(t);try{return(0,o.pkSign)(e,n,this.userId,i),e}finally{n.free()}}))}signUser(e){return r(this,void 0,void 0,(function*(){if(this.keys.user_signing)return this.signObject(e.keys.master,"user_signing");s.logger.info("No user signing key: not signing user")}))}signDevice(e,t){return r(this,void 0,void 0,(function*(){if(e!==this.userId)throw new Error(`Trying to sign ${e}'s device; can only sign our own device`);if(this.keys.self_signing)return this.signObject({algorithms:t.algorithms,keys:t.keys,device_id:t.deviceId,user_id:e},"self_signing");s.logger.info("No self signing key: not signing device")}))}checkUserTrust(e){if(this.userId===e.userId&&this.getId()&&this.getId()===e.getId()&&this.getId("self_signing")&&this.getId("self_signing")===e.getId("self_signing"))return new f(!0,!0,this.firstUse);if(!this.keys.user_signing)return new f(!1,!1,e.firstUse);let t;const i=e.keys.master,n=this.getId("user_signing");try{(0,o.pkVerify)(i,n,this.userId),t=!0}catch(e){t=!1}return new f(t,e.crossSigningVerifiedBefore,e.firstUse)}checkDeviceTrust(e,t,i,n){const r=this.checkUserTrust(e),s=e.keys.self_signing;if(!s)return new p(!1,!1,i,n);const a=function(e,t){return{algorithms:e.algorithms,keys:e.keys,device_id:e.deviceId,user_id:t,signatures:e.signatures}}(t,e.userId);try{return(0,o.pkVerify)(s,e.getId(),e.userId),(0,o.pkVerify)(a,l(s),e.userId),p.fromUserTrustLevel(r,i,n)}catch(e){return new p(!1,!1,i,n)}}getCacheCallbacks(){return this.cacheCallbacks}}var h;i.CrossSigningInfo=u,function(e){e[e.MASTER=4]="MASTER",e[e.USER_SIGNING=2]="USER_SIGNING",e[e.SELF_SIGNING=1]="SELF_SIGNING"}(h=i.CrossSigningLevel||(i.CrossSigningLevel={}));class f{constructor(e,t,i){this.crossSigningVerified=e,this.crossSigningVerifiedBefore=t,this.tofu=i}isVerified(){return this.isCrossSigningVerified()}isCrossSigningVerified(){return this.crossSigningVerified}wasCrossSigningVerified(){return this.crossSigningVerifiedBefore}isTofu(){return this.tofu}}i.UserTrustLevel=f;class p{constructor(e,t,i,n){this.crossSigningVerified=e,this.tofu=t,this.localVerified=i,this.trustCrossSignedDevices=n}static fromUserTrustLevel(e,t,i){return new p(e.isCrossSigningVerified(),e.isTofu(),t,i)}isVerified(){return Boolean(this.isLocallyVerified()||this.trustCrossSignedDevices&&this.isCrossSigningVerified())}isCrossSigningVerified(){return this.crossSigningVerified}isLocallyVerified(){return this.localVerified}isTofu(){return this.tofu}}i.DeviceTrustLevel=p,i.createCryptoStoreCacheCallbacks=function(e,t){return{getCrossSigningKeyCache:function(i,s){return r(this,void 0,void 0,(function*(){const r=yield new Promise((t=>e.doTxn("readonly",[a.IndexedDBCryptoStore.STORE_ACCOUNT],(n=>{e.getSecretStorePrivateKey(n,t,i)}))));if(r&&r.ciphertext){const e=n.from(t.pickleKey),s=yield(0,c.decryptAES)(r,e,i);return(0,o.decodeBase64)(s)}return r}))},storeCrossSigningKeyCache:function(i,s){return r(this,void 0,void 0,(function*(){if(!(s instanceof Uint8Array))throw new Error(`storeCrossSigningKeyCache expects Uint8Array, got ${s}`);const r=n.from(t.pickleKey),d=yield(0,c.encryptAES)((0,o.encodeBase64)(s),r,i);return e.doTxn("readwrite",[a.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{e.storeSecretStorePrivateKey(t,i,d)}))}))}}},i.requestKeysDuringVerification=function(e,t,i){return r(this,void 0,void 0,(function*(){if(e.getUserId()===t)return s.logger.log("Cross-signing: Self-verification done; requesting keys"),new Promise(((t,n)=>{const a=e,c=a.crypto.crossSigningInfo,l=new u(c.userId,{getCrossSigningKey:e=>r(this,void 0,void 0,(function*(){s.logger.debug("Cross-signing: requesting secret",e,i);const{promise:t}=a.requestSecret(`m.cross_signing.${e}`,[i]),n=yield t,r=(0,o.decodeBase64)(n);return Uint8Array.from(r)}))},c.getCacheCallbacks());l.keys=c.keys;const h=new Promise((e=>{setTimeout(e,d,new Error("Timeout"))})),f=(()=>r(this,void 0,void 0,(function*(){if(!(yield a.crypto.getSessionBackupPrivateKey())){s.logger.info("No cached backup key found. Requesting...");const e=a.requestSecret("m.megolm_backup.v1",[i]),t=yield e.promise;s.logger.info("Got key backup key, decoding...");const n=(0,o.decodeBase64)(t);s.logger.info("Decoded backup key, storing..."),yield a.crypto.storeSessionBackupPrivateKey(Uint8Array.from(n)),s.logger.info("Backup key stored. Starting backup restore...");const r=yield a.getKeyBackupVersion();a.restoreKeyBackupWithCache(void 0,void 0,r).then((()=>{s.logger.info("Backup restored.")}))}})))();return Promise.race([Promise.all([l.getCrossSigningKey("master"),l.getCrossSigningKey("self_signing"),l.getCrossSigningKey("user_signing"),f]),h]).then(t,n)})).catch((e=>{s.logger.warn("Cross-signing: failure while requesting keys:",e)}))}))}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"../crypto/store/indexeddb-crypto-store":346,"../logger":374,"./aes":331,"./olmlib":343,buffer:68}],325:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.DeviceList=i.TrackingStatus=void 0;const a=e("../logger"),c=e("./deviceinfo"),d=e("./CrossSigning"),l=o(e("./olmlib")),u=e("./store/indexeddb-crypto-store"),h=e("../utils"),f=e("../models/typed-event-emitter"),p=e("./index");var g;!function(e){e[e.NotTracked=0]="NotTracked",e[e.PendingDownload=1]="PendingDownload",e[e.DownloadInProgress=2]="DownloadInProgress",e[e.UpToDate=3]="UpToDate"}(g=i.TrackingStatus||(i.TrackingStatus={}));class v extends f.TypedEventEmitter{constructor(e,t,i,n=250){super(),this.cryptoStore=t,this.keyDownloadChunkSize=n,this.devices={},this.crossSigningInfo={},this.userByIdentityKey={},this.deviceTrackingStatus={},this.syncToken=null,this.keyDownloadsInProgressByUser=new Map,this.dirty=!1,this.savePromise=null,this.resolveSavePromise=null,this.savePromiseTime=null,this.saveTimer=null,this.hasFetched=null,this.serialiser=new m(e,i,this)}load(){return s(this,void 0,void 0,(function*(){yield this.cryptoStore.doTxn("readonly",[u.IndexedDBCryptoStore.STORE_DEVICE_DATA],(e=>{this.cryptoStore.getEndToEndDeviceData(e,(e=>{var t;this.hasFetched=Boolean(e&&e.devices),this.devices=e?e.devices:{},this.crossSigningInfo=e&&e.crossSigningInfo||{},this.deviceTrackingStatus=e?e.trackingStatus:{},this.syncToken=null!==(t=null==e?void 0:e.syncToken)&&void 0!==t?t:null,this.userByIdentityKey={};for(const e of Object.keys(this.devices)){const t=this.devices[e];for(const i of Object.keys(t)){const n=t[i].keys["curve25519:"+i];void 0!==n&&(this.userByIdentityKey[n]=e)}}}))}));for(const e of Object.keys(this.deviceTrackingStatus))this.deviceTrackingStatus[e]==g.DownloadInProgress&&(this.deviceTrackingStatus[e]=g.PendingDownload)}))}stop(){null!==this.saveTimer&&clearTimeout(this.saveTimer)}saveIfDirty(e=500){return s(this,void 0,void 0,(function*(){if(!this.dirty)return Promise.resolve(!1);const t=Date.now()+e;this.savePromiseTime&&t{this.resolveSavePromise=e})),this.savePromise=i),null===this.saveTimer){const i=this.resolveSavePromise;this.savePromiseTime=t,this.saveTimer=setTimeout((()=>{a.logger.log("Saving device tracking data",this.syncToken),this.savePromiseTime=null,this.saveTimer=null,this.savePromise=null,this.resolveSavePromise=null,this.cryptoStore.doTxn("readwrite",[u.IndexedDBCryptoStore.STORE_DEVICE_DATA],(e=>{var t;this.cryptoStore.storeEndToEndDeviceData({devices:this.devices,crossSigningInfo:this.crossSigningInfo,trackingStatus:this.deviceTrackingStatus,syncToken:null!==(t=this.syncToken)&&void 0!==t?t:void 0},e)})).then((()=>{this.dirty=!1,null==i||i(!0)}),(e=>{a.logger.error("Failed to save device tracking data",this.syncToken),a.logger.error(e)}))}),e)}return i}))}getSyncToken(){return this.syncToken}setSyncToken(e){this.syncToken=e}downloadKeys(e,t){const i=[],n=[];if(e.forEach((e=>{const r=this.deviceTrackingStatus[e];this.keyDownloadsInProgressByUser.has(e)?(a.logger.log(`downloadKeys: already have a download in progress for ${e}: awaiting its result`),n.push(this.keyDownloadsInProgressByUser.get(e))):(t||r!=g.UpToDate)&&i.push(e)})),0!=i.length){a.logger.log("downloadKeys: downloading for",i);const e=this.doKeyDownload(i);n.push(e)}return 0===n.length&&a.logger.log("downloadKeys: already have all necessary keys"),Promise.all(n).then((()=>this.getDevicesFromStore(e)))}getDevicesFromStore(e){const t=new Map;return e.forEach((e=>{var i;const n=new Map;null===(i=this.getStoredDevicesForUser(e))||void 0===i||i.forEach((function(e){n.set(e.deviceId,e)})),t.set(e,n)})),t}getKnownUserIds(){return Object.keys(this.devices)}getStoredDevicesForUser(e){const t=this.devices[e];if(!t)return null;const i=[];for(const e in t)t.hasOwnProperty(e)&&i.push(c.DeviceInfo.fromStorage(t[e],e));return i}getRawStoredDevicesForUser(e){return this.devices[e]}getStoredCrossSigningForUser(e){return this.crossSigningInfo[e]?d.CrossSigningInfo.fromStorage(this.crossSigningInfo[e],e):null}storeCrossSigningForUser(e,t){this.crossSigningInfo[e]=t,this.dirty=!0}getStoredDevice(e,t){const i=this.devices[e];if(null==i?void 0:i[t])return c.DeviceInfo.fromStorage(i[t],t)}getUserByIdentityKey(e,t){return e!==l.OLM_ALGORITHM&&e!==l.MEGOLM_ALGORITHM?null:this.userByIdentityKey[t]}getDeviceByIdentityKey(e,t){const i=this.getUserByIdentityKey(e,t);if(!i)return null;const n=this.devices[i];if(!n)return null;for(const e in n){if(!n.hasOwnProperty(e))continue;const i=n[e];for(const n in i.keys){if(!i.keys.hasOwnProperty(n))continue;if(0!==n.indexOf("curve25519:"))continue;if(i.keys[n]==t)return c.DeviceInfo.fromStorage(i,e)}}return null}storeDevicesForUser(e,t){this.setRawStoredDevicesForUser(e,t),this.dirty=!0}startTrackingDeviceList(e){if("string"!=typeof e)throw new Error("userId must be a string; was "+e);this.deviceTrackingStatus[e]||(a.logger.log("Now tracking device list for "+e),this.deviceTrackingStatus[e]=g.PendingDownload,this.dirty=!0)}stopTrackingDeviceList(e){this.deviceTrackingStatus[e]&&(a.logger.log("No longer tracking device list for "+e),this.deviceTrackingStatus[e]=g.NotTracked,this.dirty=!0)}stopTrackingAllDeviceLists(){for(const e of Object.keys(this.deviceTrackingStatus))this.deviceTrackingStatus[e]=g.NotTracked;this.dirty=!0}invalidateUserDeviceList(e){this.deviceTrackingStatus[e]&&(a.logger.log("Marking device list outdated for",e),this.deviceTrackingStatus[e]=g.PendingDownload,this.dirty=!0)}refreshOutdatedDeviceLists(){this.saveIfDirty();const e=[];for(const t of Object.keys(this.deviceTrackingStatus)){this.deviceTrackingStatus[t]==g.PendingDownload&&e.push(t)}return this.doKeyDownload(e)}setRawStoredDevicesForUser(e,t){if(void 0!==this.devices[e])for(const[t,i]of Object.entries(this.devices[e])){const e=i.keys["curve25519:"+t];delete this.userByIdentityKey[e]}this.devices[e]=t;for(const[i,n]of Object.entries(t)){const t=n.keys["curve25519:"+i];this.userByIdentityKey[t]=e}}setRawStoredCrossSigningForUser(e,t){this.crossSigningInfo[e]=t}doKeyDownload(e){if(0===e.length)return Promise.resolve();const t=this.serialiser.updateDevicesForUsers(e,this.syncToken).then((()=>{i(!0)}),(t=>{throw a.logger.error("Error downloading keys for "+e+":",t),i(!1),t}));e.forEach((e=>{this.keyDownloadsInProgressByUser.set(e,t);this.deviceTrackingStatus[e]==g.PendingDownload&&(this.deviceTrackingStatus[e]=g.DownloadInProgress)}));const i=i=>{this.emit(p.CryptoEvent.WillUpdateDevices,e,!this.hasFetched),e.forEach((e=>{if(this.dirty=!0,this.keyDownloadsInProgressByUser.get(e)!==t)return void a.logger.log("Another update in the queue for",e,"- not marking up-to-date");this.keyDownloadsInProgressByUser.delete(e);this.deviceTrackingStatus[e]==g.DownloadInProgress&&(i?(this.deviceTrackingStatus[e]=g.UpToDate,a.logger.log("Device list for",e,"now up to date")):this.deviceTrackingStatus[e]=g.PendingDownload)})),this.saveIfDirty(),this.emit(p.CryptoEvent.DevicesUpdated,e,!this.hasFetched),this.hasFetched=!0};return t}}i.DeviceList=v;class m{constructor(e,t,i){this.baseApis=e,this.olmDevice=t,this.deviceList=i,this.downloadInProgress=!1,this.keyDownloadsQueuedByUser={}}updateDevicesForUsers(e,t){return e.forEach((e=>{this.keyDownloadsQueuedByUser[e]=!0})),this.queuedQueryDeferred||(this.queuedQueryDeferred=(0,h.defer)()),this.syncToken=t,this.downloadInProgress?(a.logger.log("Queued key download for",e),this.queuedQueryDeferred.promise):this.doQueuedQueries()}doQueuedQueries(){if(this.downloadInProgress)throw new Error("DeviceListUpdateSerialiser.doQueuedQueries called with request active");const e=Object.keys(this.keyDownloadsQueuedByUser);this.keyDownloadsQueuedByUser={};const t=this.queuedQueryDeferred;this.queuedQueryDeferred=void 0,a.logger.log("Starting key download for",e),this.downloadInProgress=!0;const i={};this.syncToken&&(i.token=this.syncToken);const n=[];for(let t=0;tthis.baseApis.downloadKeysForUsers(r,i)))}return(0,h.chunkPromises)(n,3).then((t=>s(this,void 0,void 0,(function*(){const i=Object.assign({},...t.map((e=>e.device_keys||{}))),n=Object.assign({},...t.map((e=>e.master_keys||{}))),r=Object.assign({},...t.map((e=>e.self_signing_keys||{}))),o=Object.assign({},...t.map((e=>e.user_signing_keys||{})));for(const t of e){yield(0,h.sleep)(5);try{yield this.processQueryResponseForUser(t,i[t],{master:null==n?void 0:n[t],self_signing:null==r?void 0:r[t],user_signing:null==o?void 0:o[t]})}catch(e){a.logger.error(`Error processing keys for ${t}:`,e)}}})))).then((()=>{a.logger.log("Completed key download for "+e),this.downloadInProgress=!1,null==t||t.resolve(),this.queuedQueryDeferred&&this.doQueuedQueries()}),(i=>{a.logger.warn("Error downloading keys for "+e+":",i),this.downloadInProgress=!1,null==t||t.reject(i)})),t.promise}processQueryResponseForUser(e,t,i){return s(this,void 0,void 0,(function*(){a.logger.log("got device keys for "+e+":",t),a.logger.log("got cross-signing keys for "+e+":",i);{const i={},n=this.deviceList.getRawStoredDevicesForUser(e);n&&Object.keys(n).forEach((e=>{const t=c.DeviceInfo.fromStorage(n[e],e);i[e]=t})),yield function(e,t,i,n,r,o){return s(this,void 0,void 0,(function*(){let s=!1;for(const e in i)if(i.hasOwnProperty(e)&&!(e in n)){if(t===r&&e===o){a.logger.warn(`Local device ${e} missing from sync, skipping removal`);continue}a.logger.log("Device "+t+":"+e+" has been removed"),delete i[e],s=!0}for(const r in n){if(!n.hasOwnProperty(r))continue;const o=n[r];o.user_id===t?o.device_id===r?(yield y(e,i,o))&&(s=!0):a.logger.warn("Mismatched device_id "+o.device_id+" in keys from "+t+":"+r):a.logger.warn("Mismatched user_id "+o.user_id+" in keys from "+t+":"+r)}return s}))}(this.olmDevice,e,i,t||{},this.baseApis.getUserId(),this.baseApis.deviceId);const r={};Object.keys(i).forEach((e=>{r[e]=i[e].toStorage()})),this.deviceList.setRawStoredDevicesForUser(e,r)}if(i&&(i.master||i.self_signing||i.user_signing)){const t=this.deviceList.getStoredCrossSigningForUser(e)||new d.CrossSigningInfo(e);t.setKeys(i),this.deviceList.setRawStoredCrossSigningForUser(e,t.toStorage()),this.deviceList.emit(p.CryptoEvent.UserCrossSigningUpdated,e)}}))}}function y(e,t,i){return s(this,void 0,void 0,(function*(){if(!i.keys)return!1;const n=i.device_id,r=i.user_id,o="ed25519:"+n,s=i.keys[o];if(!s)return a.logger.warn("Device "+r+":"+n+" has no ed25519 key"),!1;const d=i.unsigned||{},u=i.signatures||{};try{yield l.verifySignature(e,i,r,n,s)}catch(e){return a.logger.warn("Unable to verify signature on device "+r+":"+n+":"+e),!1}let h;if(n in t){if(h=t[n],h.getFingerprint()!=s)return a.logger.warn("Ed25519 key for device "+r+":"+n+" has changed"),!1}else t[n]=h=new c.DeviceInfo(n);return h.keys=i.keys||{},h.algorithms=i.algorithms||[],h.unsigned=d,h.signatures=u,!0}))}},{"../logger":374,"../models/typed-event-emitter":395,"../utils":416,"./CrossSigning":324,"./deviceinfo":340,"./index":341,"./olmlib":343,"./store/indexeddb-crypto-store":346}],326:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.EncryptionSetupOperation=i.EncryptionSetupBuilder=void 0;const r=e("../logger"),o=e("../models/event"),s=e("./CrossSigning"),a=e("./store/indexeddb-crypto-store"),c=e("../http-api"),d=e("../client"),l=e("../models/typed-event-emitter");i.EncryptionSetupBuilder=class{constructor(e,t){this.accountDataClientAdapter=new h(e),this.crossSigningCallbacks=new f,this.ssssCryptoCallbacks=new p(t)}addCrossSigningKeys(e,t){this.crossSigningKeys={authUpload:e,keys:t}}addSessionBackup(e){this.keyBackupInfo=e}addSessionBackupPrivateKeyToCache(e){this.sessionBackupPrivateKey=e}addKeySignature(e,t,i){this.keySignatures||(this.keySignatures={});const n=this.keySignatures[e]||{};this.keySignatures[e]=n,n[t]=i}setAccountData(e,t){return n(this,void 0,void 0,(function*(){yield this.accountDataClientAdapter.setAccountData(e,t)}))}buildOperation(){const e=this.accountDataClientAdapter.values;return new u(e,this.crossSigningKeys,this.keyBackupInfo,this.keySignatures)}persist(e){var t;return n(this,void 0,void 0,(function*(){if(this.crossSigningKeys){const i=(0,s.createCryptoStoreCacheCallbacks)(e.cryptoStore,e.olmDevice);for(const e of["master","self_signing","user_signing"]){r.logger.log(`Cache ${e} cross-signing private key locally`);const n=this.crossSigningCallbacks.privateKeys.get(e);yield null===(t=i.storeCrossSigningKeyCache)||void 0===t?void 0:t.call(i,e,n)}yield e.cryptoStore.doTxn("readwrite",[a.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{e.cryptoStore.storeCrossSigningKeys(t,this.crossSigningKeys.keys)}))}this.sessionBackupPrivateKey&&(yield e.storeSessionBackupPrivateKey(this.sessionBackupPrivateKey))}))}};class u{constructor(e,t,i,n){this.accountData=e,this.crossSigningKeys=t,this.keyBackupInfo=i,this.keySignatures=n}apply(e){var t,i;return n(this,void 0,void 0,(function*(){const n=e.baseApis;if(this.crossSigningKeys){const r={};for(const[e,t]of Object.entries(this.crossSigningKeys.keys))r[e+"_key"]=t;yield null===(i=(t=this.crossSigningKeys).authUpload)||void 0===i?void 0:i.call(t,(e=>n.uploadDeviceSigningKeys(e,r))),e.crossSigningInfo.setKeys(this.crossSigningKeys.keys)}if(this.accountData)for(const[e,t]of this.accountData)yield n.setAccountData(e,t);this.keySignatures&&(yield n.uploadKeySignatures(this.keySignatures)),this.keyBackupInfo&&(this.keyBackupInfo.version?yield n.http.authedRequest(c.Method.Put,"/room_keys/version/"+this.keyBackupInfo.version,void 0,{algorithm:this.keyBackupInfo.algorithm,auth_data:this.keyBackupInfo.auth_data},{prefix:c.ClientPrefix.V3}):yield n.http.authedRequest(c.Method.Post,"/room_keys/version",void 0,this.keyBackupInfo,{prefix:c.ClientPrefix.V3}))}))}}i.EncryptionSetupOperation=u;class h extends l.TypedEventEmitter{constructor(e){super(),this.existingValues=e,this.values=new Map}getAccountDataFromServer(e){return Promise.resolve(this.getAccountData(e))}getAccountData(e){const t=this.values.get(e);if(t)return t;const i=this.existingValues.get(e);return i?i.getContent():null}setAccountData(e,t){const i=this.values.get(e);return this.values.set(e,t),Promise.resolve().then((()=>{const n=new o.MatrixEvent({type:e,content:t});return this.emit(d.ClientEvent.AccountData,n,i),{}}))}}class f{constructor(){this.privateKeys=new Map}getCrossSigningKeyCache(e,t){return this.getCrossSigningKey(e,t)}storeCrossSigningKeyCache(e,t){return this.privateKeys.set(e,t),Promise.resolve()}getCrossSigningKey(e,t){var i;return Promise.resolve(null!==(i=this.privateKeys.get(e))&&void 0!==i?i:null)}saveCrossSigningKeys(e){for(const[t,i]of Object.entries(e))this.privateKeys.set(t,i)}}class p{constructor(e){this.delegateCryptoCallbacks=e,this.privateKeys=new Map}getSecretStorageKey({keys:e},t){var i;return n(this,void 0,void 0,(function*(){for(const t of Object.keys(e)){const e=this.privateKeys.get(t);if(e)return[t,e]}if(null===(i=null==this?void 0:this.delegateCryptoCallbacks)||void 0===i?void 0:i.getSecretStorageKey){const i=yield this.delegateCryptoCallbacks.getSecretStorageKey({keys:e},t);if(i){const[e,t]=i;this.privateKeys.set(e,t)}return i}return null}))}addPrivateKey(e,t,i){var n,r;this.privateKeys.set(e,i),null===(r=null===(n=this.delegateCryptoCallbacks)||void 0===n?void 0:n.cacheSecretStorageKey)||void 0===r||r.call(n,e,t,i)}}},{"../client":321,"../http-api":367,"../logger":374,"../models/event":383,"../models/typed-event-emitter":395,"./CrossSigning":324,"./store/indexeddb-crypto-store":346}],327:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.WITHHELD_MESSAGES=i.OlmDevice=i.PayloadTooLargeError=void 0;const a=e("../logger"),c=e("./store/indexeddb-crypto-store"),d=o(e("./algorithms")),l=49152;class u extends Error{constructor(){super(...arguments),this.data={errcode:"M_TOO_LARGE",error:"Payload too large for encrypted message"}}}function h(e){if(void 0===e)throw new Error("payloadString undefined");if(e.length>l)throw new u(`Message too long (${e.length} bytes). The maximum for an encrypted message is ${l} bytes.`)}i.PayloadTooLargeError=u;function f(e){return e.code&&e.code in i.WITHHELD_MESSAGES?i.WITHHELD_MESSAGES[e.code]:e.reason?e.reason:"decryption key withheld"}i.OlmDevice=class{constructor(e){this.cryptoStore=e,this.pickleKey="DEFAULT_KEY",this.deviceCurve25519Key=null,this.deviceEd25519Key=null,this.maxOneTimeKeys=null,this.outboundGroupSessionStore={},this.inboundGroupSessionMessageIndexes={},this.sessionsInProgress={},this.olmPrekeyPromise=Promise.resolve()}static getOlmVersion(){return t.Olm.get_library_version()}init({pickleKey:e,fromExportedDevice:i}={}){return s(this,void 0,void 0,(function*(){let n;const r=new t.Olm.Account;try{i?(e&&a.logger.warn("ignoring opts.pickleKey because opts.fromExportedDevice is present."),this.pickleKey=i.pickleKey,yield this.initialiseFromExportedDevice(i,r)):(e&&(this.pickleKey=e),yield this.initialiseAccount(r)),n=JSON.parse(r.identity_keys()),this.maxOneTimeKeys=r.max_number_of_one_time_keys()}finally{r.free()}this.deviceCurve25519Key=n.curve25519,this.deviceEd25519Key=n.ed25519}))}initialiseFromExportedDevice(e,t){return s(this,void 0,void 0,(function*(){yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT,c.IndexedDBCryptoStore.STORE_SESSIONS],(t=>{this.cryptoStore.storeAccount(t,e.pickledAccount),e.sessions.forEach((e=>{const{deviceKey:i,sessionId:n}=e,r={session:e.session,lastReceivedMessageTs:e.lastReceivedMessageTs};this.cryptoStore.storeEndToEndSession(i,n,r,t)}))})),t.unpickle(this.pickleKey,e.pickledAccount)}))}initialiseAccount(e){return s(this,void 0,void 0,(function*(){yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{this.cryptoStore.getAccount(t,(i=>{null!==i?e.unpickle(this.pickleKey,i):(e.create(),i=e.pickle(this.pickleKey),this.cryptoStore.storeAccount(t,i))}))}))}))}getAccount(e,i){this.cryptoStore.getAccount(e,(e=>{const n=new t.Olm.Account;try{n.unpickle(this.pickleKey,e),i(n)}finally{n.free()}}))}storeAccount(e,t){this.cryptoStore.storeAccount(e,t.pickle(this.pickleKey))}export(){return s(this,void 0,void 0,(function*(){const e={pickleKey:this.pickleKey};return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_ACCOUNT,c.IndexedDBCryptoStore.STORE_SESSIONS],(t=>{this.cryptoStore.getAccount(t,(t=>{e.pickledAccount=t})),e.sessions=[],this.cryptoStore.getAllEndToEndSessions(t,(t=>{e.sessions.push(t)}))})),e}))}getSession(e,t,i,n){this.cryptoStore.getEndToEndSession(e,t,i,(e=>{this.unpickleSession(e,n)}))}unpickleSession(e,i){const n=new t.Olm.Session;try{n.unpickle(this.pickleKey,e.session);i(Object.assign({},e,{session:n}))}finally{n.free()}}saveSession(e,t,i){const n=t.session.session_id();a.logger.debug(`Saving Olm session ${n} with device ${e}: ${t.session.describe()}`);const r=Object.assign(t,{session:t.session.pickle(this.pickleKey)});this.cryptoStore.storeEndToEndSession(e,n,r,i)}getUtility(e){const i=new t.Olm.Utility;try{return e(i)}finally{i.free()}}sign(e){return s(this,void 0,void 0,(function*(){let t;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(i=>{this.getAccount(i,(i=>{t=i.sign(e)}))})),t}))}getOneTimeKeys(){return s(this,void 0,void 0,(function*(){let e;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{this.getAccount(t,(t=>{e=JSON.parse(t.one_time_keys())}))})),e}))}maxNumberOfOneTimeKeys(){var e;return null!==(e=this.maxOneTimeKeys)&&void 0!==e?e:-1}markKeysAsPublished(){return s(this,void 0,void 0,(function*(){yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.getAccount(e,(t=>{t.mark_keys_as_published(),this.storeAccount(e,t)}))}))}))}generateOneTimeKeys(e){return this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{this.getAccount(t,(i=>{i.generate_one_time_keys(e),this.storeAccount(t,i)}))}))}generateFallbackKey(){return s(this,void 0,void 0,(function*(){yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.getAccount(e,(t=>{t.generate_fallback_key(),this.storeAccount(e,t)}))}))}))}getFallbackKey(){return s(this,void 0,void 0,(function*(){let e;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{this.getAccount(t,(t=>{e=JSON.parse(t.unpublished_fallback_key())}))})),e}))}forgetOldFallbackKey(){return s(this,void 0,void 0,(function*(){yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.getAccount(e,(t=>{t.forget_old_fallback_key(),this.storeAccount(e,t)}))}))}))}createOutboundSession(e,i){return s(this,void 0,void 0,(function*(){let n;return yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT,c.IndexedDBCryptoStore.STORE_SESSIONS],(r=>{this.getAccount(r,(o=>{const s=new t.Olm.Session;try{s.create_outbound(o,e,i),n=s.session_id(),this.storeAccount(r,o);const t={session:s,lastReceivedMessageTs:Date.now()};this.saveSession(e,t,r)}finally{s.free()}}))}),a.logger.withPrefix("[createOutboundSession]")),n}))}createInboundSession(e,i,n){return s(this,void 0,void 0,(function*(){if(0!==i)throw new Error("Need messageType == 0 to create inbound session");let r;return yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT,c.IndexedDBCryptoStore.STORE_SESSIONS],(o=>{this.getAccount(o,(s=>{const a=new t.Olm.Session;try{a.create_inbound_from(s,e,n),s.remove_one_time_keys(a),this.storeAccount(o,s);const t=a.decrypt(i,n),c={session:a,lastReceivedMessageTs:Date.now()};this.saveSession(e,c,o),r={payload:t,session_id:a.session_id()}}finally{a.free()}}))}),a.logger.withPrefix("[createInboundSession]")),r}))}getSessionIdsForDevice(e){return s(this,void 0,void 0,(function*(){const t=a.logger.withPrefix("[getSessionIdsForDevice]");if(e in this.sessionsInProgress){t.debug(`Waiting for Olm session for ${e} to be created`);try{yield this.sessionsInProgress[e]}catch(e){}}let i;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_SESSIONS],(t=>{this.cryptoStore.getEndToEndSessions(e,t,(e=>{i=Object.keys(e)}))}),t),i}))}getSessionIdForDevice(e,t=!1,i){return s(this,void 0,void 0,(function*(){const n=yield this.getSessionInfoForDevice(e,t,i);if(0===n.length)return null;let r=0;for(let e=1;es||i===s&&t.sessionId{this.cryptoStore.getEndToEndSessions(e,t,(e=>{const t=Object.keys(e).sort();for(const i of t)this.unpickleSession(e[i],(e=>{n.push({lastReceivedMessageTs:e.lastReceivedMessageTs,hasReceivedMessage:e.session.has_received_message(),sessionId:i})}))}))}),i),n}))}encryptMessage(e,t,i){return s(this,void 0,void 0,(function*(){let n;return h(i),yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_SESSIONS],(r=>{this.getSession(e,t,r,(o=>{const s=o.session.describe();a.logger.log("encryptMessage: Olm Session ID "+t+" to "+e+": "+s),n=o.session.encrypt(i),this.saveSession(e,o,r)}))}),a.logger.withPrefix("[encryptMessage]")),n}))}decryptMessage(e,t,i,n){return s(this,void 0,void 0,(function*(){let r;return yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_SESSIONS],(o=>{this.getSession(e,t,o,(s=>{const c=s.session.describe();a.logger.log("decryptMessage: Olm Session ID "+t+" from "+e+": "+c),r=s.session.decrypt(i,n),s.lastReceivedMessageTs=Date.now(),this.saveSession(e,s,o)}))}),a.logger.withPrefix("[decryptMessage]")),r}))}matchesSession(e,t,i,n){return s(this,void 0,void 0,(function*(){if(0!==i)return!1;let r;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_SESSIONS],(i=>{this.getSession(e,t,i,(e=>{r=e.session.matches_inbound(n)}))}),a.logger.withPrefix("[matchesSession]")),r}))}recordSessionProblem(e,t,i){return s(this,void 0,void 0,(function*(){a.logger.info(`Recording problem on olm session with ${e} of type ${t}. Recreating: ${i}`),yield this.cryptoStore.storeEndToEndSessionProblem(e,t,i)}))}sessionMayHaveProblems(e,t){return this.cryptoStore.getEndToEndSessionProblem(e,t)}filterOutNotifiedErrorDevices(e){return this.cryptoStore.filterOutNotifiedErrorDevices(e)}saveOutboundGroupSession(e){this.outboundGroupSessionStore[e.session_id()]=e.pickle(this.pickleKey)}getOutboundGroupSession(e,i){const n=this.outboundGroupSessionStore[e];if(void 0===n)throw new Error("Unknown outbound group session "+e);const r=new t.Olm.OutboundGroupSession;try{return r.unpickle(this.pickleKey,n),i(r)}finally{r.free()}}createOutboundGroupSession(){const e=new t.Olm.OutboundGroupSession;try{return e.create(),this.saveOutboundGroupSession(e),e.session_id()}finally{e.free()}}encryptGroupMessage(e,t){return a.logger.log(`encrypting msg with megolm session ${e}`),h(t),this.getOutboundGroupSession(e,(e=>{const i=e.encrypt(t);return this.saveOutboundGroupSession(e),i}))}getOutboundGroupSessionKey(e){return this.getOutboundGroupSession(e,(function(e){return{chain_index:e.message_index(),key:e.session_key()}}))}unpickleInboundGroupSession(e,i){const n=new t.Olm.InboundGroupSession;try{return n.unpickle(this.pickleKey,e.session),i(n)}finally{n.free()}}getInboundGroupSession(e,t,i,n,r){this.cryptoStore.getEndToEndInboundGroupSession(t,i,n,((t,i)=>{if(null!==t){if(null!==e&&e!==t.room_id)throw new Error("Mismatched room_id for inbound group session (expected "+t.room_id+", was "+e+")");this.unpickleInboundGroupSession(t,(e=>{r(e,t,i)}))}else r(null,null,i)}))}addInboundGroupSession(e,i,n,r,o,d,l,u={}){return s(this,void 0,void 0,(function*(){yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD,c.IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS],(s=>{this.getInboundGroupSession(e,i,r,s,((c,h)=>{const f=new t.Olm.InboundGroupSession;try{if(l?f.import_session(o):f.create(o),r!=f.session_id())throw new Error("Mismatched group session ID from senderKey: "+i);if(c&&(a.logger.log(`Update for megolm session ${i}|${r}`),c.first_known_index()<=f.first_known_index())){if(!h.untrusted||u.untrusted)return void a.logger.log(`Keeping existing megolm session ${i}|${r}`);if(c.first_known_index(){this.cryptoStore.storeEndToEndInboundGroupSessionWithheld(t,i,{room_id:e,code:n,reason:r},o)}))}))}decryptGroupMessage(e,t,i,n,r,o){return s(this,void 0,void 0,(function*(){let s,l=null;if(yield this.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],(a=>{this.getInboundGroupSession(e,t,i,a,((e,c,u)=>{if(null===e||null===c)return u&&(s=new d.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID",f(u),{session:t+"|"+i})),void(l=null);let h;try{h=e.decrypt(n)}catch(e){return void(s="OLM.UNKNOWN_MESSAGE_INDEX"===(null==e?void 0:e.message)&&u?new d.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID",f(u),{session:t+"|"+i}):e)}let p=h.plaintext;if(void 0===p)p=h;else{const e=t+"|"+i+"|"+h.message_index;if(e in this.inboundGroupSessionMessageIndexes){const t=this.inboundGroupSessionMessageIndexes[e];if(t.id!==r||t.timestamp!==o)return void(s=new Error("Duplicate message index, possible replay attack: "+e))}this.inboundGroupSessionMessageIndexes[e]={id:r,timestamp:o}}c.session=e.pickle(this.pickleKey),this.cryptoStore.storeEndToEndInboundGroupSession(t,i,c,a),l={result:p,keysClaimed:c.keysClaimed||{},senderKey:t,forwardingCurve25519KeyChain:c.forwardingCurve25519KeyChain||[],untrusted:!!c.untrusted}}))}),a.logger.withPrefix("[decryptGroupMessage]")),s)throw s;return l}))}hasInboundSessionKeys(e,t,i){return s(this,void 0,void 0,(function*(){let n;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],(r=>{this.cryptoStore.getEndToEndInboundGroupSession(t,i,r,(r=>{null!==r?e!==r.room_id?(a.logger.warn(`requested keys for inbound group session ${t}|${i}, with incorrect room_id (expected ${r.room_id}, was ${e})`),n=!1):n=!0:n=!1}))}),a.logger.withPrefix("[hasInboundSessionKeys]")),n}))}getInboundGroupSessionKey(e,t,i,n){return s(this,void 0,void 0,(function*(){let r=null;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,c.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],(o=>{this.getInboundGroupSession(e,t,i,o,((e,t)=>{if(null===e||null===t)return void(r=null);void 0===n&&(n=e.first_known_index());const i=e.export_session(n),o=(t.keysClaimed||{}).ed25519||null,s=t.forwardingCurve25519KeyChain||[],a="untrusted"in t?t.untrusted:s.length>0;r={chain_index:n,key:i,forwarding_curve25519_key_chain:s,sender_claimed_ed25519_key:o,shared_history:t.sharedHistory||!1,untrusted:a}}))}),a.logger.withPrefix("[getInboundGroupSessionKey]")),r}))}exportInboundGroupSession(e,t,i){return this.unpickleInboundGroupSession(i,(n=>{const r=n.first_known_index();return{sender_key:e,sender_claimed_keys:i.keysClaimed,room_id:i.room_id,session_id:t,session_key:n.export_session(r),forwarding_curve25519_key_chain:i.forwardingCurve25519KeyChain||[],first_known_index:n.first_known_index(),"org.matrix.msc3061.shared_history":i.sharedHistory||!1}}))}getSharedHistoryInboundGroupSessions(e){return s(this,void 0,void 0,(function*(){let t;return yield this.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS],(i=>{t=this.cryptoStore.getSharedHistoryInboundGroupSessions(e,i)}),a.logger.withPrefix("[getSharedHistoryInboundGroupSessionsForRoom]")),t}))}verifySignature(e,t,i){this.getUtility((function(n){n.ed25519_verify(e,t,i)}))}},i.WITHHELD_MESSAGES={"m.unverified":"The sender has disabled encrypting to unverified devices.","m.blacklisted":"The sender has blocked you.","m.unauthorised":"You are not authorised to read the message.","m.no_olm":"Unable to establish a secure channel."}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../logger":374,"./algorithms":333,"./store/indexeddb-crypto-store":346}],328:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.OutgoingRoomKeyRequestManager=i.RoomKeyRequestState=void 0;const r=e("uuid"),o=e("../logger"),s=e("../@types/event"),a=e("../utils");var c;!function(e){e[e.Unsent=0]="Unsent",e[e.Sent=1]="Sent",e[e.CancellationPending=2]="CancellationPending",e[e.CancellationPendingAndWillResend=3]="CancellationPendingAndWillResend"}(c=i.RoomKeyRequestState||(i.RoomKeyRequestState={}));function d(e){return e.room_id+" / "+e.session_id}function l(e){return`[${e.map((e=>`${e.userId}:${e.deviceId}`)).join(",")}]`}i.OutgoingRoomKeyRequestManager=class{constructor(e,t,i){this.baseApis=e,this.deviceId=t,this.cryptoStore=i,this.sendOutgoingRoomKeyRequestsRunning=!1,this.clientRunning=!0}stop(){o.logger.log("stopping OutgoingRoomKeyRequestManager"),this.clientRunning=!1}sendQueuedRequests(){this.startTimer()}queueRoomKeyRequest(e,t,i=!1){return n(this,void 0,void 0,(function*(){const n=yield this.cryptoStore.getOutgoingRoomKeyRequest(e);if(n)switch(n.state){case c.CancellationPendingAndWillResend:case c.Unsent:return;case c.CancellationPending:{const e=i?c.CancellationPendingAndWillResend:c.Sent;yield this.cryptoStore.updateOutgoingRoomKeyRequest(n.requestId,c.CancellationPending,{state:e,cancellationTxnId:this.baseApis.makeTxnId()});break}case c.Sent:if(i){const r=c.CancellationPendingAndWillResend,s=yield this.cryptoStore.updateOutgoingRoomKeyRequest(n.requestId,c.Sent,{state:r,cancellationTxnId:this.baseApis.makeTxnId(),requestTxnId:this.baseApis.makeTxnId()});if(!s)return this.queueRoomKeyRequest(e,t,i);try{yield this.sendOutgoingRoomKeyRequestCancellation(s,!0)}catch(e){o.logger.error("Error sending room key request cancellation; will retry later.",e)}}break;default:throw new Error("unhandled state: "+n.state)}else yield this.cryptoStore.getOrAddOutgoingRoomKeyRequest({requestBody:e,recipients:t,requestId:this.baseApis.makeTxnId(),state:c.Unsent})}))}cancelRoomKeyRequest(e){return this.cryptoStore.getOutgoingRoomKeyRequest(e).then((t=>{if(t)switch(t.state){case c.CancellationPending:case c.CancellationPendingAndWillResend:return;case c.Unsent:return o.logger.log("deleting unnecessary room key request for "+d(e)),this.cryptoStore.deleteOutgoingRoomKeyRequest(t.requestId,c.Unsent);case c.Sent:return this.cryptoStore.updateOutgoingRoomKeyRequest(t.requestId,c.Sent,{state:c.CancellationPending,cancellationTxnId:this.baseApis.makeTxnId()}).then((t=>{t?this.sendOutgoingRoomKeyRequestCancellation(t).catch((e=>{o.logger.error("Error sending room key request cancellation; will retry later.",e),this.startTimer()})):o.logger.log("Tried to cancel room key request for "+d(e)+" but it was already cancelled in another tab")}));default:throw new Error("unhandled state: "+t.state)}}))}getOutgoingSentRoomKeyRequest(e,t){return this.cryptoStore.getOutgoingRoomKeyRequestsByTarget(e,t,[c.Sent])}cancelAndResendAllOutgoingRequests(){return n(this,void 0,void 0,(function*(){const e=yield this.cryptoStore.getAllOutgoingRoomKeyRequestsByState(c.Sent);return Promise.all(e.map((({requestBody:e,recipients:t})=>this.queueRoomKeyRequest(e,t,!0))))}))}startTimer(){if(this.sendOutgoingRoomKeyRequestsTimer)return;this.sendOutgoingRoomKeyRequestsTimer=setTimeout((()=>{if(this.sendOutgoingRoomKeyRequestsRunning)throw new Error("RoomKeyRequestSend already in progress!");this.sendOutgoingRoomKeyRequestsRunning=!0,this.sendOutgoingRoomKeyRequests().finally((()=>{this.sendOutgoingRoomKeyRequestsRunning=!1})).catch((e=>{o.logger.warn(`error in OutgoingRoomKeyRequestManager: ${e}`)}))}),500)}sendOutgoingRoomKeyRequests(){return n(this,void 0,void 0,(function*(){if(!this.clientRunning)return void(this.sendOutgoingRoomKeyRequestsTimer=void 0);const e=yield this.cryptoStore.getOutgoingRoomKeyRequestByState([c.CancellationPending,c.CancellationPendingAndWillResend,c.Unsent]);if(e)try{switch(e.state){case c.Unsent:yield this.sendOutgoingRoomKeyRequest(e);break;case c.CancellationPending:yield this.sendOutgoingRoomKeyRequestCancellation(e);break;case c.CancellationPendingAndWillResend:yield this.sendOutgoingRoomKeyRequestCancellation(e,!0)}return this.sendOutgoingRoomKeyRequests()}catch(e){o.logger.error("Error sending room key request; will retry later.",e),this.sendOutgoingRoomKeyRequestsTimer=void 0}else this.sendOutgoingRoomKeyRequestsTimer=void 0}))}sendOutgoingRoomKeyRequest(e){o.logger.log(`Requesting keys for ${d(e.requestBody)} from ${l(e.recipients)}(id ${e.requestId})`);const t={action:"request",requesting_device_id:this.deviceId,request_id:e.requestId,body:e.requestBody};return this.sendMessageToDevices(t,e.recipients,e.requestTxnId||e.requestId).then((()=>this.cryptoStore.updateOutgoingRoomKeyRequest(e.requestId,c.Unsent,{state:c.Sent})))}sendOutgoingRoomKeyRequestCancellation(e,t=!1){o.logger.log(`Sending cancellation for key request for ${d(e.requestBody)} to ${l(e.recipients)} (cancellation id ${e.cancellationTxnId})`);const i={action:"request_cancellation",requesting_device_id:this.deviceId,request_id:e.requestId};return this.sendMessageToDevices(i,e.recipients,e.cancellationTxnId).then((()=>t?this.cryptoStore.updateOutgoingRoomKeyRequest(e.requestId,c.CancellationPendingAndWillResend,{state:c.Unsent}):this.cryptoStore.deleteOutgoingRoomKeyRequest(e.requestId,c.CancellationPending)))}sendMessageToDevices(e,t,i){const n=new a.MapWithDefault((()=>new Map));for(const i of t){n.getOrCreate(i.userId).set(i.deviceId,Object.assign(Object.assign({},e),{[s.ToDeviceMessageId]:(0,r.v4)()}))}return this.baseApis.sendToDevice(s.EventType.RoomKeyRequest,n,i)}}},{"../@types/event":306,"../logger":374,"../utils":416,uuid:287}],329:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.RoomList=void 0;const r=e("./store/indexeddb-crypto-store");i.RoomList=class{constructor(e){this.cryptoStore=e,this.roomEncryption={}}init(){return n(this,void 0,void 0,(function*(){yield this.cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_ROOMS],(e=>{this.cryptoStore.getEndToEndRooms(e,(e=>{this.roomEncryption=e}))}))}))}getRoomEncryption(e){return this.roomEncryption[e]||null}isRoomEncrypted(e){return Boolean(this.getRoomEncryption(e))}setRoomEncryption(e,t){return n(this,void 0,void 0,(function*(){this.roomEncryption[e]=t,yield this.cryptoStore.doTxn("readwrite",[r.IndexedDBCryptoStore.STORE_ROOMS],(i=>{this.cryptoStore.storeEndToEndRoom(e,t,i)}))}))}}},{"./store/indexeddb-crypto-store":346}],330:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.SecretStorage=i.SECRET_STORAGE_ALGORITHM_V1_AES=void 0;const a=e("uuid"),c=e("../logger"),d=o(e("./olmlib")),l=e("../randomstring"),u=e("./aes"),h=e("../client"),f=e("../utils"),p=e("../@types/event");i.SECRET_STORAGE_ALGORITHM_V1_AES="m.secret_storage.v1.aes-hmac-sha2";i.SecretStorage=class{constructor(e,t,i){this.accountDataAdapter=e,this.cryptoCallbacks=t,this.baseApis=i,this.requests=new Map}getDefaultKeyId(){return s(this,void 0,void 0,(function*(){const e=yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.default_key");return e?e.key:null}))}setDefaultKeyId(e){return new Promise(((t,i)=>{const n=i=>{"m.secret_storage.default_key"===i.getType()&&i.getContent().key===e&&(this.accountDataAdapter.removeListener(h.ClientEvent.AccountData,n),t())};this.accountDataAdapter.on(h.ClientEvent.AccountData,n),this.accountDataAdapter.setAccountData("m.secret_storage.default_key",{key:e}).catch((e=>{this.accountDataAdapter.removeListener(h.ClientEvent.AccountData,n),i(e)}))}))}addKey(e,t={},n){return s(this,void 0,void 0,(function*(){if(e!==i.SECRET_STORAGE_ALGORITHM_V1_AES)throw new Error(`Unknown key algorithm ${e}`);const r={algorithm:e};if(t.name&&(r.name=t.name),t.passphrase&&(r.passphrase=t.passphrase),t.key){const{iv:e,mac:i}=yield(0,u.calculateKeyCheck)(t.key);r.iv=e,r.mac=i}if(!n)do{n=(0,l.randomString)(32)}while(yield this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${n}`));return yield this.accountDataAdapter.setAccountData(`m.secret_storage.key.${n}`,r),{keyId:n,keyInfo:r}}))}getKey(e){return s(this,void 0,void 0,(function*(){if(e||(e=yield this.getDefaultKeyId()),!e)return null;const t=yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+e);return t?[e,t]:null}))}hasKey(e){return s(this,void 0,void 0,(function*(){return Boolean(yield this.getKey(e))}))}checkKey(e,t){return s(this,void 0,void 0,(function*(){if(t.algorithm===i.SECRET_STORAGE_ALGORITHM_V1_AES){if(t.mac){const{mac:i}=yield(0,u.calculateKeyCheck)(e,t.iv);return t.mac.replace(/=+$/g,"")===i.replace(/=+$/g,"")}return!0}throw new Error("Unknown algorithm")}))}store(e,t,n){return s(this,void 0,void 0,(function*(){const r={};if(!n){const e=yield this.getDefaultKeyId();if(!e)throw new Error("No keys specified and no default key present");n=[e]}if(0===n.length)throw new Error("Zero keys given to encrypt with!");for(const o of n){const n=yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+o);if(!n)throw new Error("Unknown key: "+o);if(n.algorithm===i.SECRET_STORAGE_ALGORITHM_V1_AES){const i={[o]:n},[,s]=yield this.getSecretStorageKey(i,e);r[o]=yield s.encrypt(t)}else c.logger.warn("unknown algorithm for secret storage key "+o+": "+n.algorithm)}yield this.accountDataAdapter.setAccountData(e,{encrypted:r})}))}get(e){return s(this,void 0,void 0,(function*(){const t=yield this.accountDataAdapter.getAccountDataFromServer(e);if(!t)return;if(!t.encrypted)throw new Error("Content is not encrypted!");const n={};for(const e of Object.keys(t.encrypted)){const r=yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+e),o=t.encrypted[e];r.algorithm===i.SECRET_STORAGE_ALGORITHM_V1_AES&&o.iv&&o.ciphertext&&o.mac&&(n[e]=r)}if(0===Object.keys(n).length)throw new Error(`Could not decrypt ${e} because none of the keys it is encrypted with are for a supported algorithm`);const[r,o]=yield this.getSecretStorageKey(n,e),s=t.encrypted[r];return o.decrypt(s)}))}isStored(e){return s(this,void 0,void 0,(function*(){const t=yield this.accountDataAdapter.getAccountDataFromServer(e);if(!(null==t?void 0:t.encrypted))return null;const n={};for(const e of Object.keys(t.encrypted)){const r=yield this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+e);if(!r)continue;const o=t.encrypted[e];r.algorithm===i.SECRET_STORAGE_ALGORITHM_V1_AES&&o.iv&&o.ciphertext&&o.mac&&(n[e]=r)}return Object.keys(n).length?n:null}))}request(e,t){const i=this.baseApis.makeTxnId(),n=(0,f.defer)();this.requests.set(i,{name:e,devices:t,deferred:n});const r={name:e,action:"request",requesting_device_id:this.baseApis.deviceId,request_id:i,[p.ToDeviceMessageId]:(0,a.v4)()},o=new Map;for(const e of t)o.set(e,r);return c.logger.info(`Request secret ${e} from ${t}, id ${i}`),this.baseApis.sendToDevice("m.secret.request",new Map([[this.baseApis.getUserId(),o]])),{requestId:i,promise:n.promise,cancel:e=>{const r={action:"request_cancellation",requesting_device_id:this.baseApis.deviceId,request_id:i},o=new Map;for(const e of t)o.set(e,r);this.baseApis.sendToDevice("m.secret.request",new Map([[this.baseApis.getUserId(),o]])),n.reject(new Error(e||"Cancelled"))}}}onRequestReceived(e){return s(this,void 0,void 0,(function*(){const t=e.getSender(),i=e.getContent();if(t!==this.baseApis.getUserId()||!(i.name&&i.action&&i.requesting_device_id&&i.request_id))return;const n=i.requesting_device_id;if("request_cancellation"===i.action);else if("request"===i.action){if(n===this.baseApis.deviceId)return;if(c.logger.info("received request for secret ("+t+", "+n+", "+i.request_id+")"),!this.cryptoCallbacks.onSecretRequested)return;const e=yield this.cryptoCallbacks.onSecretRequested(t,n,i.request_id,i.name,this.baseApis.checkDeviceTrust(t,n));if(e){c.logger.info(`Preparing ${i.name} secret for ${n}`);const r={type:"m.secret.send",content:{request_id:i.request_id,secret:e}},o={algorithm:d.OLM_ALGORITHM,sender_key:this.baseApis.crypto.olmDevice.deviceCurve25519Key,ciphertext:{},[p.ToDeviceMessageId]:(0,a.v4)()};yield d.ensureOlmSessionsForDevices(this.baseApis.crypto.olmDevice,this.baseApis,new Map([[t,[this.baseApis.getStoredDevice(t,n)]]])),yield d.encryptMessageForDevice(o.ciphertext,this.baseApis.getUserId(),this.baseApis.deviceId,this.baseApis.crypto.olmDevice,t,this.baseApis.getStoredDevice(t,n),r);const s=new Map([[t,new Map([[n,o]])]]);c.logger.info(`Sending ${i.name} secret for ${n}`),this.baseApis.sendToDevice("m.room.encrypted",s)}else c.logger.info(`Request denied for ${i.name} secret for ${n}`)}}))}onSecretReceived(e){if(e.getSender()!==this.baseApis.getUserId())return;if(!d.isOlmEncrypted(e))return void c.logger.error("secret event not properly encrypted");const t=e.getContent();if(this.baseApis.crypto.deviceList.getUserByIdentityKey(d.OLM_ALGORITHM,e.getSenderKey()||"")!==e.getSender())return void c.logger.error("sending device does not belong to the user it claims to be from");c.logger.log("got secret share for request",t.request_id);const i=this.requests.get(t.request_id);if(i){const n=this.baseApis.crypto.deviceList.getDeviceByIdentityKey(d.OLM_ALGORITHM,e.getSenderKey());if(!n)return void c.logger.log("secret share from unknown device with key",e.getSenderKey());if(!i.devices.includes(n.deviceId))return void c.logger.log("unsolicited secret share from device",n.deviceId);if(!this.baseApis.crypto.checkDeviceInfoTrust(e.getSender(),n).isVerified())return void c.logger.log("secret share from unverified device");c.logger.log(`Successfully received secret ${i.name} from ${n.deviceId}`),i.deferred.resolve(t.secret)}}getSecretStorageKey(e,t){return s(this,void 0,void 0,(function*(){if(!this.cryptoCallbacks.getSecretStorageKey)throw new Error("No getSecretStorageKey callback supplied");const n=yield this.cryptoCallbacks.getSecretStorageKey({keys:e},t);if(!n)throw new Error("getSecretStorageKey callback returned falsey");if(n.length<2)throw new Error("getSecretStorageKey callback returned invalid data");const[r,o]=n;if(!e[r])throw new Error("App returned unknown key from getSecretStorageKey!");if(e[r].algorithm===i.SECRET_STORAGE_ALGORITHM_V1_AES){return[r,{encrypt:function(e){return(0,u.encryptAES)(e,o,t)},decrypt:function(e){return(0,u.decryptAES)(e,o,t)}}]}throw new Error("Unknown key type: "+e[r].algorithm)}))}}},{"../@types/event":306,"../client":321,"../logger":374,"../randomstring":398,"../utils":416,"./aes":331,"./olmlib":343,uuid:287}],331:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.calculateKeyCheck=i.decryptAES=i.encryptAES=void 0;const r=e("./olmlib"),o=e("./crypto"),s=new Uint8Array(8);function a(e,t,i,s){return n(this,void 0,void 0,(function*(){let n;s?n=(0,r.decodeBase64)(s):(n=new Uint8Array(16),o.crypto.getRandomValues(n),n[8]&=127);const[a,d]=yield c(t,i),l=(new o.TextEncoder).encode(e),u=yield o.subtleCrypto.encrypt({name:"AES-CTR",counter:n,length:64},a,l),h=yield o.subtleCrypto.sign({name:"HMAC"},d,u);return{iv:(0,r.encodeBase64)(n),ciphertext:(0,r.encodeBase64)(u),mac:(0,r.encodeBase64)(h)}}))}function c(e,t){return n(this,void 0,void 0,(function*(){const i=yield o.subtleCrypto.importKey("raw",e,{name:"HKDF"},!1,["deriveBits"]),n=yield o.subtleCrypto.deriveBits({name:"HKDF",salt:s,info:(new o.TextEncoder).encode(t),hash:"SHA-256"},i,512),r=n.slice(0,32),a=n.slice(32),c=o.subtleCrypto.importKey("raw",r,{name:"AES-CTR"},!1,["encrypt","decrypt"]),d=o.subtleCrypto.importKey("raw",a,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"]);return Promise.all([c,d])}))}i.encryptAES=a,i.decryptAES=function(e,t,i){return n(this,void 0,void 0,(function*(){const[n,s]=yield c(t,i),a=(0,r.decodeBase64)(e.ciphertext);if(!(yield o.subtleCrypto.verify({name:"HMAC"},s,(0,r.decodeBase64)(e.mac),a)))throw new Error(`Error decrypting secret ${i}: bad MAC`);const d=yield o.subtleCrypto.decrypt({name:"AES-CTR",counter:(0,r.decodeBase64)(e.iv),length:64},n,a);return(new TextDecoder).decode(new Uint8Array(d))}))};const d="\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";i.calculateKeyCheck=function(e,t){return a(d,e,"",t)}},{"./crypto":338,"./olmlib":343}],332:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.registerAlgorithm=i.UnknownDeviceError=i.DecryptionError=i.DecryptionAlgorithm=i.EncryptionAlgorithm=i.DECRYPTION_CLASSES=i.ENCRYPTION_CLASSES=void 0,i.ENCRYPTION_CLASSES=new Map,i.DECRYPTION_CLASSES=new Map;i.EncryptionAlgorithm=class{constructor(e){this.userId=e.userId,this.deviceId=e.deviceId,this.crypto=e.crypto,this.olmDevice=e.olmDevice,this.baseApis=e.baseApis,this.roomId=e.roomId}prepareToEncrypt(e){}onRoomMembership(e,t,i){}};i.DecryptionAlgorithm=class{constructor(e){this.userId=e.userId,this.crypto=e.crypto,this.olmDevice=e.olmDevice,this.baseApis=e.baseApis,this.roomId=e.roomId}onRoomKeyEvent(e){return n(this,void 0,void 0,(function*(){}))}importRoomKey(e,t){return n(this,void 0,void 0,(function*(){}))}hasKeysForKeyRequest(e){return Promise.resolve(!1)}shareKeysWithDevice(e){throw new Error("shareKeysWithDevice not supported for this DecryptionAlgorithm")}retryDecryptionFromSender(e){return n(this,void 0,void 0,(function*(){return!1}))}};class r extends Error{constructor(e,t,i){super(t),this.code=e,this.code=e,this.name="DecryptionError",this.detailedString=function(e,t){let i=e.name+"[msg: "+e.message;t&&(i+=", "+Object.keys(t).map((e=>e+": "+t[e])).join(", "));return i+="]",i}(this,i)}}i.DecryptionError=r;class o extends Error{constructor(e,t,i){super(e),this.devices=t,this.event=i,this.name="UnknownDeviceError",this.devices=t}}i.UnknownDeviceError=o,i.registerAlgorithm=function(e,t,n){i.ENCRYPTION_CLASSES.set(e,t),i.DECRYPTION_CLASSES.set(e,n)}},{}],333:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),e("./olm"),e("./megolm"),r(e("./base"),i)},{"./base":332,"./megolm":334,"./olm":335}],334:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.MegolmDecryption=i.MegolmEncryption=i.isRoomSharedHistory=void 0;const a=e("uuid"),c=e("../../logger"),d=o(e("../olmlib")),l=e("./base"),u=e("../OlmDevice"),h=e("../../@types/event"),f=e("../OutgoingRoomKeyRequestManager"),p=e("../../utils");function g(e){var t,i;const n=null===(t=null==e?void 0:e.currentState)||void 0===t?void 0:t.getStateEvents("m.room.history_visibility",""),r=null===(i=null==n?void 0:n.getContent())||void 0===i?void 0:i.history_visibility;return["world_readable","shared"].includes(r)}i.isRoomSharedHistory=g;const v=e=>"string"==typeof e.ciphertext?!!e.ciphertext.length:!!Object.keys(e.ciphertext).length;class m{constructor(e,t=!1){this.sessionId=e,this.sharedHistory=t,this.useCount=0,this.sharedWithDevices=new p.MapWithDefault((()=>new Map)),this.blockedDevicesNotified=new p.MapWithDefault((()=>new Map)),this.creationTime=(new Date).getTime()}needsRotation(e,t){const i=(new Date).getTime()-this.creationTime;return(this.useCount>=e||i>=t)&&(c.logger.log("Rotating megolm session after "+this.useCount+" messages, "+i+"ms"),!0)}markSharedWithDevice(e,t,i,n){this.sharedWithDevices.getOrCreate(e).set(t,{deviceKey:i,messageIndex:n})}markNotifiedBlockedDevice(e,t){this.blockedDevicesNotified.getOrCreate(e).set(t,!0)}sharedWithTooManyDevices(e){var t;for(const[i,n]of this.sharedWithDevices){if(!e.has(i))return c.logger.log("Starting new megolm session because we shared with "+i),!0;for(const[r]of n)if(!(null===(t=e.get(i))||void 0===t?void 0:t.get(r)))return c.logger.log("Starting new megolm session because we shared with "+i+":"+r),!0}return!1}}class y extends l.EncryptionAlgorithm{constructor(e){var t,i,n,r;super(e),this.setupPromise=Promise.resolve(null),this.outboundSessions={},this.roomId=e.roomId,this.prefixedLogger=c.logger.withPrefix(`[${this.roomId} encryption]`),this.sessionRotationPeriodMsgs=null!==(i=null===(t=e.config)||void 0===t?void 0:t.rotation_period_msgs)&&void 0!==i?i:100,this.sessionRotationPeriodMs=null!==(r=null===(n=e.config)||void 0===n?void 0:n.rotation_period_ms)&&void 0!==r?r:6048e5}ensureOutboundSession(e,t,i,n=!1){return s(this,void 0,void 0,(function*(){const r=this.setupPromise.then((r=>s(this,void 0,void 0,(function*(){const o=g(e),s=yield this.prepareSession(t,o,r);return yield this.shareSession(t,o,n,i,s),s}))));return this.setupPromise=r.catch((e=>(this.prefixedLogger.error("Failed to setup outbound session",e),null))),r}))}prepareSession(e,t,i){return s(this,void 0,void 0,(function*(){return i&&t!==i.sharedHistory&&(i=null),(null==i?void 0:i.needsRotation(this.sessionRotationPeriodMsgs,this.sessionRotationPeriodMs))&&(this.prefixedLogger.log("Starting new megolm session because we need to rotate."),i=null),(null==i?void 0:i.sharedWithTooManyDevices(e))&&(i=null),i||(this.prefixedLogger.log("Starting new megolm session"),i=yield this.prepareNewSession(t),this.prefixedLogger.log(`Started new megolm session ${i.sessionId}`),this.outboundSessions[i.sessionId]=i),i}))}shareSession(e,t,i,n,r){var o;return s(this,void 0,void 0,(function*(){const a={};for(const[t,i]of e)for(const[e,n]of i){n.getIdentityKey()!=this.olmDevice.deviceCurve25519Key&&((null===(o=r.sharedWithDevices.get(t))||void 0===o?void 0:o.get(e))||(a[t]=a[t]||[],a[t].push(n)))}const c=this.olmDevice.getOutboundGroupSessionKey(r.sessionId),l={type:"m.room_key",content:{algorithm:d.MEGOLM_ALGORITHM,room_id:this.roomId,session_id:r.sessionId,session_key:c.key,chain_index:c.chain_index,"org.matrix.msc3061.shared_history":t}},[u,h]=yield d.getExistingOlmSessions(this.olmDevice,this.baseApis,a);yield Promise.all([(()=>s(this,void 0,void 0,(function*(){const e=Array.from(h.entries()).map((([e,t])=>Array.from(t.entries()).map((([t,i])=>`${e}/${t}: ${i.sessionId}`)))).flat(1);this.prefixedLogger.debug("Sharing keys with devices with existing Olm sessions:",e),yield this.shareKeyWithOlmSessions(r,c,l,h),this.prefixedLogger.debug("Shared keys with existing Olm sessions")})))(),(()=>s(this,void 0,void 0,(function*(){const e=Array.from(u.entries()).map((([e,t])=>t.map((t=>`${e}/${t.deviceId}`)))).flat(1);this.prefixedLogger.debug("Sharing keys (start phase 1) with devices without existing Olm sessions:",e);const t=[],n=Date.now(),o=[];yield this.shareKeyWithDevices(r,c,l,u,t,i?1e4:2e3,o),this.prefixedLogger.debug("Shared keys (end phase 1) with devices without existing Olm sessions"),!i&&Date.now()-n<1e4?(()=>{s(this,void 0,void 0,(function*(){const e=new p.MapWithDefault((()=>[])),i=new Set;for(const e of o)i.add(e);const n=[];for(const{userId:r,deviceInfo:o}of t){const t=r.slice(r.indexOf(":")+1);i.has(t)?e.getOrCreate(r).push(o):n.push({userId:r,deviceInfo:o})}const s=Array.from(e.entries()).map((([e,t])=>t.map((t=>`${e}/${t.deviceId}`)))).flat(1);s.length>0&&(this.prefixedLogger.debug("Sharing keys (start phase 2) with devices without existing Olm sessions:",s),yield this.shareKeyWithDevices(r,c,l,e,n,3e4),this.prefixedLogger.debug("Shared keys (end phase 2) with devices without existing Olm sessions")),yield this.notifyFailedOlmDevices(r,c,n)}))})():yield this.notifyFailedOlmDevices(r,c,t)})))(),(()=>s(this,void 0,void 0,(function*(){var e;this.prefixedLogger.debug(`There are ${n.size} blocked devices:`,Array.from(n.entries()).map((([e,t])=>Array.from(t.entries()).map((([t,i])=>`${e}/${t}`)))).flat(1));const t=new p.MapWithDefault((()=>new Map));let i=0;for(const[o,s]of n)for(const[n,a]of s)void 0===(null===(e=r.blockedDevicesNotified.get(o))||void 0===e?void 0:e.get(n))&&(t.getOrCreate(o).set(n,{device:a}),i++);i&&(this.prefixedLogger.debug(`Notifying ${i} newly blocked devices:`,Array.from(t.entries()).map((([e,t])=>Object.entries(t).map((([t,i])=>`${e}/${t}`)))).flat(1)),yield this.notifyBlockedDevices(r,t),this.prefixedLogger.debug(`Notified ${i} newly blocked devices`))})))()])}))}prepareNewSession(e){return s(this,void 0,void 0,(function*(){const t=this.olmDevice.createOutboundGroupSession(),i=this.olmDevice.getOutboundGroupSessionKey(t);return yield this.olmDevice.addInboundGroupSession(this.roomId,this.olmDevice.deviceCurve25519Key,[],t,i.key,{ed25519:this.olmDevice.deviceEd25519Key},!1,{sharedHistory:e}),this.crypto.backupManager.backupGroupSession(this.olmDevice.deviceCurve25519Key,t),new m(t,e)}))}getDevicesWithoutSessions(e,t,i=[]){for(const[n,r]of t){const t=e.get(n);for(const e of r){const r=e.deviceId,o=null==t?void 0:t.get(r);(null==o?void 0:o.sessionId)||(i.push({userId:n,deviceInfo:e}),null==t||t.delete(r))}}return i}splitDevices(e){let t=[];const i=[t];for(const[n,r]of e){for(const e of r.values())t.push({userId:n,deviceInfo:e.device});t.length>20&&(t=[],i.push(t))}return 0===t.length&&i.pop(),i}encryptAndSendKeysToDevices(e,t,i,n){return this.crypto.encryptAndSendToDevices(i,n).then((()=>{for(const n of i)e.markSharedWithDevice(n.userId,n.deviceInfo.deviceId,n.deviceInfo.getIdentityKey(),t)})).catch((e=>{throw this.prefixedLogger.error("failed to encryptAndSendToDevices",e),e}))}sendBlockedNotificationsToDevices(e,t,i){return s(this,void 0,void 0,(function*(){const n=new p.MapWithDefault((()=>new Map));for(const e of t){const t=e.userId,r=e.deviceInfo,o=r.deviceInfo.deviceId,s=Object.assign(Object.assign({},i),{code:r.code,reason:r.reason,[h.ToDeviceMessageId]:(0,a.v4)()});"m.no_olm"===s.code&&(delete s.room_id,delete s.session_id),n.getOrCreate(t).set(o,s)}yield this.baseApis.sendToDevice("m.room_key.withheld",n);for(const[t,i]of n)for(const n of i.keys())e.markNotifiedBlockedDevice(t,n)}))}reshareKeyWithDevice(e,t,i,n){var r;return s(this,void 0,void 0,(function*(){const o=this.outboundSessions[t];if(!o)return void this.prefixedLogger.debug(`megolm session ${e}|${t} not found: not re-sharing keys`);if(!o.sharedWithDevices.has(i))return void this.prefixedLogger.debug(`megolm session ${e}|${t} never shared with user ${i}`);const s=null===(r=o.sharedWithDevices.get(i))||void 0===r?void 0:r.get(n.deviceId);if(void 0===s)return void this.prefixedLogger.debug(`megolm session ${e}|${t} never shared with device ${i}:${n.deviceId}`);if(s.deviceKey!==n.getIdentityKey())return void this.prefixedLogger.warn(`Megolm session ${e}|${t} has been shared with device ${n.deviceId} but with identity key ${s.deviceKey}. Key is now ${n.getIdentityKey()}!`);const c=yield this.olmDevice.getInboundGroupSessionKey(this.roomId,e,t,s.messageIndex);if(!c)return void this.prefixedLogger.warn(`No inbound session key found for megolm session ${e}|${t}: not re-sharing keys`);yield d.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,new Map([[i,[n]]]));const l={type:"m.forwarded_room_key",content:{algorithm:d.MEGOLM_ALGORITHM,room_id:this.roomId,session_id:t,session_key:c.key,chain_index:c.chain_index,sender_key:e,sender_claimed_ed25519_key:c.sender_claimed_ed25519_key,forwarding_curve25519_key_chain:c.forwarding_curve25519_key_chain,"org.matrix.msc3061.shared_history":c.shared_history||!1}},u={algorithm:d.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[h.ToDeviceMessageId]:(0,a.v4)()};yield d.encryptMessageForDevice(u.ciphertext,this.userId,this.deviceId,this.olmDevice,i,n,l),yield this.baseApis.sendToDevice("m.room.encrypted",new Map([[i,new Map([[n.deviceId,u]])]])),this.prefixedLogger.debug(`Re-shared key for megolm session ${e}|${t} with ${i}:${n.deviceId}`)}))}shareKeyWithDevices(e,t,i,n,r,o,a){return s(this,void 0,void 0,(function*(){const s=yield d.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,n,!1,o,a,this.prefixedLogger);this.getDevicesWithoutSessions(s,n,r),yield this.shareKeyWithOlmSessions(e,t,i,s)}))}shareKeyWithOlmSessions(e,t,i,n){return s(this,void 0,void 0,(function*(){const r=this.splitDevices(n);for(let n=0;n`${e.userId}/${e.deviceInfo.deviceId}`))),yield this.encryptAndSendKeysToDevices(e,t.chain_index,r[n],i),this.prefixedLogger.debug(`Shared ${o}`)}catch(e){throw this.prefixedLogger.error(`Failed to share ${o}`),e}}}))}notifyFailedOlmDevices(e,t,i){return s(this,void 0,void 0,(function*(){this.prefixedLogger.debug(`Notifying ${i.length} devices we failed to create Olm sessions`);for(const{userId:n,deviceInfo:r}of i){const i=r.deviceId;e.markSharedWithDevice(n,i,r.getIdentityKey(),t.chain_index)}const n=yield this.olmDevice.filterOutNotifiedErrorDevices(i);this.prefixedLogger.debug(`Need to notify ${n.length} failed devices which haven't been notified before`);const r=new p.MapWithDefault((()=>new Map));for(const{userId:e,deviceInfo:t}of n)r.getOrCreate(e).set(t.deviceId,{device:{code:"m.no_olm",reason:u.WITHHELD_MESSAGES["m.no_olm"],deviceInfo:t}});yield this.notifyBlockedDevices(e,r),this.prefixedLogger.debug(`Notified ${n.length} devices we failed to create Olm sessions`)}))}notifyBlockedDevices(e,t){return s(this,void 0,void 0,(function*(){const i={room_id:this.roomId,session_id:e.sessionId,algorithm:d.MEGOLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key},n=this.splitDevices(t);for(let t=0;tt;return this.encryptionPreparation={startTime:Date.now(),promise:(()=>s(this,void 0,void 0,(function*(){try{const t=yield this.getDevicesInRoom(e,!1,i);if(null===t)return;const[n,r]=t;this.crypto.globalErrorOnUnknownDevices&&this.removeUnknownDevices(n),this.prefixedLogger.debug("Ensuring outbound megolm session"),yield this.ensureOutboundSession(e,n,r,!0),this.prefixedLogger.debug("Ready to encrypt events")}catch(e){this.prefixedLogger.error("Failed to prepare to encrypt events",e)}finally{delete this.encryptionPreparation}})))(),cancel:()=>{t=!0,delete this.encryptionPreparation}},this.encryptionPreparation.cancel}encryptMessage(e,t,i){return s(this,void 0,void 0,(function*(){if(this.prefixedLogger.log("Starting to encrypt event"),null!=this.encryptionPreparation)try{yield this.encryptionPreparation.promise}catch(e){}const n=this.isVerificationEvent(t,i),[r,o]=yield this.getDevicesInRoom(e,n);this.crypto.globalErrorOnUnknownDevices&&this.checkForUnknownDevices(r);const s=yield this.ensureOutboundSession(e,r,o),a={room_id:this.roomId,type:t,content:i},c=this.olmDevice.encryptGroupMessage(s.sessionId,JSON.stringify(a)),l={algorithm:d.MEGOLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:c,session_id:s.sessionId,device_id:this.deviceId};return s.useCount++,l}))}isVerificationEvent(e,t){switch(e){case h.EventType.KeyVerificationCancel:case h.EventType.KeyVerificationDone:case h.EventType.KeyVerificationMac:case h.EventType.KeyVerificationStart:case h.EventType.KeyVerificationKey:case h.EventType.KeyVerificationReady:case h.EventType.KeyVerificationAccept:return!0;case h.EventType.RoomMessage:return t.msgtype===h.MsgType.KeyVerificationRequest;default:return!1}}forceDiscardSession(){this.setupPromise=this.setupPromise.then((()=>null))}checkForUnknownDevices(e){const t=new p.MapWithDefault((()=>new Map));for(const[i,n]of e)for(const[e,r]of n)r.isUnverified()&&!r.isKnown()&&t.getOrCreate(i).set(e,r);if(t.size)throw new l.UnknownDeviceError("This room contains unknown devices which have not been verified. We strongly recommend you verify them before continuing.",t)}removeUnknownDevices(e){for(const[t,i]of e){for(const[e,t]of i)t.isUnverified()&&!t.isKnown()&&i.delete(e);0===i.size&&e.delete(t)}}getDevicesInRoom(e,t=!1,i){return s(this,void 0,void 0,(function*(){const n=yield e.getEncryptionTargetMembers();this.prefixedLogger.debug(`Encrypting for users (shouldEncryptForInvitedMembers: ${e.shouldEncryptForInvitedMembers()}):`,n.map((e=>`${e.userId} (${e.membership})`)));const r=n.map((function(e){return e.userId}));let o=this.crypto.globalBlacklistUnverifiedDevices;const s=e.getBlacklistUnverifiedDevices();"boolean"==typeof s&&(o=s);const a=yield this.crypto.downloadKeys(r,!1);if(!0===(null==i?void 0:i()))return null;const c=new p.MapWithDefault((()=>new Map));for(const[e,n]of a)for(const[r,s]of n){if(void 0!==i&&(yield(0,p.immediate)()),!0===(null==i?void 0:i()))return null;const a=this.crypto.checkDeviceTrust(e,r);if(s.isBlocked()||!a.isVerified()&&o&&!t){const t=c.getOrCreate(e),i=s.isBlocked();t.set(r,{code:i?"m.blacklisted":"m.unverified",reason:u.WITHHELD_MESSAGES[i?"m.blacklisted":"m.unverified"],deviceInfo:s}),n.delete(r)}}return[a,c]}))}}i.MegolmEncryption=y;class b extends l.DecryptionAlgorithm{constructor(e){super(e),this.pendingEvents=new Map,this.olmlib=d,this.roomId=e.roomId,this.prefixedLogger=c.logger.withPrefix(`[${this.roomId} decryption]`)}decryptEvent(e){return s(this,void 0,void 0,(function*(){const t=e.getWireContent();if(!t.sender_key||!t.session_id||!t.ciphertext)throw new l.DecryptionError("MEGOLM_MISSING_FIELDS","Missing fields in input");let i;this.addEventToPendingList(e);try{i=yield this.olmDevice.decryptGroupMessage(e.getRoomId(),t.sender_key,t.session_id,t.ciphertext,e.getId(),e.getTs())}catch(i){if("DecryptionError"===i.name)throw i;let n="OLM_DECRYPT_GROUP_MESSAGE_ERROR";throw"OLM.UNKNOWN_MESSAGE_INDEX"===(null==i?void 0:i.message)&&(this.requestKeysForEvent(e),n="OLM_UNKNOWN_MESSAGE_INDEX"),new l.DecryptionError(n,i instanceof Error?i.message:"Unknown Error: Error is undefined",{session:t.sender_key+"|"+t.session_id})}if(null===i){this.crypto.backupManager.queryKeyBackupRateLimited(e.getRoomId(),t.session_id).catch((()=>{})),this.requestKeysForEvent(e);const i=yield this.olmDevice.sessionMayHaveProblems(t.sender_key,e.getTs()-12e4);if(i){this.prefixedLogger.info(`When handling UISI from ${e.getSender()} (sender key ${t.sender_key}): recent session problem with that sender:`,i);let n=S[i.type]||S.unknown;throw i.fixed&&(n+=" Trying to create a new secure channel and re-requesting the keys."),new l.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID",n,{session:t.sender_key+"|"+t.session_id})}throw new l.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID","The sender's device has not sent us the keys for this message.",{session:t.sender_key+"|"+t.session_id})}i.untrusted||this.removeEventFromPendingList(e);const n=JSON.parse(i.result);if(n.room_id!==e.getRoomId())throw new l.DecryptionError("MEGOLM_BAD_ROOM","Message intended for room "+n.room_id);return{clearEvent:n,senderCurve25519Key:i.senderKey,claimedEd25519Key:i.keysClaimed.ed25519,forwardingCurve25519KeyChain:i.forwardingCurve25519KeyChain,untrusted:i.untrusted}}))}requestKeysForEvent(e){const t=e.getWireContent(),i=e.getKeyRequestRecipients(this.userId);this.crypto.requestRoomKey({room_id:e.getRoomId(),algorithm:t.algorithm,sender_key:t.sender_key,session_id:t.session_id},i)}addEventToPendingList(e){var t;const i=e.getWireContent(),n=i.sender_key,r=i.session_id;this.pendingEvents.has(n)||this.pendingEvents.set(n,new Map);const o=this.pendingEvents.get(n);o.has(r)||o.set(r,new Set),null===(t=o.get(r))||void 0===t||t.add(e)}removeEventFromPendingList(e){const t=e.getWireContent(),i=t.sender_key,n=t.session_id,r=this.pendingEvents.get(i),o=null==r?void 0:r.get(n);o&&(o.delete(e),0===o.size&&r.delete(n),0===r.size&&this.pendingEvents.delete(i))}roomKeyFromEvent(e){const t=e.getSenderKey(),i=e.getContent(),n={};if(!(i.room_id&&i.session_key&&i.session_id&&i.algorithm))return void this.prefixedLogger.error("key event is missing fields");if(!d.isOlmEncrypted(e))return void this.prefixedLogger.error("key event not properly encrypted");i["org.matrix.msc3061.shared_history"]&&(n.sharedHistory=!0);return{senderKey:t,sessionId:i.session_id,sessionKey:i.session_key,extraSessionData:n,exportFormat:!1,roomId:i.room_id,algorithm:i.algorithm,forwardingKeyChain:[],keysClaimed:e.getKeysClaimed()}}forwardedRoomKeyFromEvent(e){const t=this.roomKeyFromEvent(e);if(!t)return;const i=e.getSenderKey(),n=e.getContent(),r=this.baseApis.crypto.deviceList.getUserByIdentityKey(d.OLM_ALGORITHM,i),o=n.sender_key,s=n.sender_claimed_ed25519_key;let a=Array.isArray(n.forwarding_curve25519_key_chain)?n.forwarding_curve25519_key_chain:[];if(a=a.slice(),a.push(i),r!==e.getSender())return void this.prefixedLogger.error("sending device does not belong to the user it claims to be from");if(!o)return void this.prefixedLogger.error("forwarded_room_key event is missing sender_key field");if(!s)return void this.prefixedLogger.error("forwarded_room_key_event is missing sender_claimed_ed25519_key field");const c={ed25519:s};return t.senderKey=o,t.keysClaimed=c,t.exportFormat=!0,t.forwardingKeyChain=a,t.extraSessionData.untrusted=!0,t}shouldAcceptForwardedKey(e,t){var i;return s(this,void 0,void 0,(function*(){const n=e.getSenderKey(),r=null!==(i=this.crypto.deviceList.getDeviceByIdentityKey(d.OLM_ALGORITHM,n))&&void 0!==i?i:void 0,o=this.crypto.checkDeviceInfoTrust(e.getSender(),r),s=e.getSender()===this.baseApis.getUserId(),a=o.isVerified()&&s,c=yield this.wasRoomKeyRequested(e,t),l=this.wasRoomKeyForwardedByInviter(e,t),u=this.wasRoomKeyForwardedAsHistory(t);return c&&a||l&&u}))}wasRoomKeyRequested(e,t){return s(this,void 0,void 0,(function*(){return(yield this.crypto.cryptoStore.getOutgoingRoomKeyRequestsByTarget(e.getSender(),"*",[f.RoomKeyRequestState.Sent])).some((e=>e.requestBody.room_id===t.roomId&&e.requestBody.session_id===t.sessionId))}))}wasRoomKeyForwardedByInviter(e,t){var i,n,r;const o=this.baseApis.getRoom(t.roomId),s=e.getSenderKey();if(!s)return!1;const a=this.crypto.deviceList.getUserByIdentityKey(d.OLM_ALGORITHM,s);if(!a)return!1;const c=null===(i=null==o?void 0:o.getMember(this.userId))||void 0===i?void 0:i.events.member,l=(null==c?void 0:c.getSender())===a||(null===(n=null==c?void 0:c.getUnsigned())||void 0===n?void 0:n.prev_sender)===a&&"invite"===(null===(r=null==c?void 0:c.getPrevContent())||void 0===r?void 0:r.membership);return!(!o||!l)}wasRoomKeyForwardedAsHistory(e){return!(!this.baseApis.getRoom(e.roomId)||!e.extraSessionData.sharedHistory)}shouldParkForwardedKey(e){return!(this.baseApis.getRoom(e.roomId)||!e.extraSessionData.sharedHistory)}parkForwardedKey(e,t){return s(this,void 0,void 0,(function*(){const i={senderId:e.getSender(),senderKey:t.senderKey,sessionId:t.sessionId,sessionKey:t.sessionKey,keysClaimed:t.keysClaimed,forwardingCurve25519KeyChain:t.forwardingKeyChain};yield this.crypto.cryptoStore.doTxn("readwrite",["parked_shared_history"],(e=>this.crypto.cryptoStore.addParkedSharedHistory(t.roomId,i,e)),c.logger.withPrefix("[addParkedSharedHistory]"))}))}addRoomKey(e){return s(this,void 0,void 0,(function*(){try{yield this.olmDevice.addInboundGroupSession(e.roomId,e.senderKey,e.forwardingKeyChain,e.sessionId,e.sessionKey,e.keysClaimed,e.exportFormat,e.extraSessionData),(yield this.retryDecryption(e.senderKey,e.sessionId,!e.extraSessionData.untrusted))&&this.crypto.cancelRoomKeyRequest({algorithm:e.algorithm,room_id:e.roomId,session_id:e.sessionId,sender_key:e.senderKey}),yield this.crypto.backupManager.backupGroupSession(e.senderKey,e.sessionId)}catch(e){this.prefixedLogger.error(`Error handling m.room_key_event: ${e}`)}}))}onForwardedRoomKey(e){return s(this,void 0,void 0,(function*(){const t=this.forwardedRoomKeyFromEvent(e);t&&((yield this.shouldAcceptForwardedKey(e,t))?yield this.addRoomKey(t):this.shouldParkForwardedKey(t)&&(yield this.parkForwardedKey(e,t)))}))}onRoomKeyEvent(e){return s(this,void 0,void 0,(function*(){if("m.forwarded_room_key"==e.getType())yield this.onForwardedRoomKey(e);else{const t=this.roomKeyFromEvent(e);if(!t)return;yield this.addRoomKey(t)}}))}onRoomKeyWithheldEvent(e){return s(this,void 0,void 0,(function*(){const t=e.getContent(),i=t.sender_key;"m.no_olm"===t.code?yield this.onNoOlmWithheldEvent(e):"m.unavailable"===t.code||(yield this.olmDevice.addInboundGroupSessionWithheld(t.room_id,i,t.session_id,t.code,t.reason)),t.session_id?yield this.retryDecryption(i,t.session_id):yield this.retryDecryptionFromSender(i)}))}onNoOlmWithheldEvent(e){return s(this,void 0,void 0,(function*(){const t=e.getContent(),i=t.sender_key,n=e.getSender();if(this.prefixedLogger.warn(`${n}:${i} was unable to establish an olm session with us`),yield this.olmDevice.getSessionIdForDevice(i))return this.prefixedLogger.debug("New session already created. Not creating a new one."),void(yield this.olmDevice.recordSessionProblem(i,"no_olm",!0));let r=this.crypto.deviceList.getDeviceByIdentityKey(t.algorithm,i);if(!r&&(yield this.crypto.downloadKeys([n],!1),r=this.crypto.deviceList.getDeviceByIdentityKey(t.algorithm,i),!r))return this.prefixedLogger.info("Couldn't find device for identity key "+i+": not establishing session"),void(yield this.olmDevice.recordSessionProblem(i,"no_olm",!1));yield d.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,new Map([[n,[r]]]),!1);const o={algorithm:d.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[h.ToDeviceMessageId]:(0,a.v4)()};yield d.encryptMessageForDevice(o.ciphertext,this.userId,void 0,this.olmDevice,n,r,{type:"m.dummy"}),yield this.olmDevice.recordSessionProblem(i,"no_olm",!0),yield this.baseApis.sendToDevice("m.room.encrypted",new Map([[n,new Map([[r.deviceId,o]])]]))}))}hasKeysForKeyRequest(e){const t=e.requestBody;return this.olmDevice.hasInboundSessionKeys(t.room_id,t.sender_key,t.session_id)}shareKeysWithDevice(e){const t=e.userId,i=e.deviceId,n=this.crypto.getStoredDevice(t,i),r=e.requestBody;this.olmlib.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,new Map([[t,[n]]])).then((e=>{var n;const o=null===(n=e.get(t))||void 0===n?void 0:n.get(i);return(null==o?void 0:o.sessionId)?(this.prefixedLogger.log("sharing keys for session "+r.sender_key+"|"+r.session_id+" with device "+t+":"+i),this.buildKeyForwardingMessage(r.room_id,r.sender_key,r.session_id)):null})).then((e=>{const r={algorithm:d.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[h.ToDeviceMessageId]:(0,a.v4)()};return this.olmlib.encryptMessageForDevice(r.ciphertext,this.userId,void 0,this.olmDevice,t,n,e).then((()=>this.baseApis.sendToDevice("m.room.encrypted",new Map([[t,new Map([[i,r]])]]))))}))}buildKeyForwardingMessage(e,t,i){return s(this,void 0,void 0,(function*(){const n=yield this.olmDevice.getInboundGroupSessionKey(e,t,i);return{type:"m.forwarded_room_key",content:{algorithm:d.MEGOLM_ALGORITHM,room_id:e,sender_key:t,sender_claimed_ed25519_key:n.sender_claimed_ed25519_key,session_id:i,session_key:n.key,chain_index:n.chain_index,forwarding_curve25519_key_chain:n.forwarding_curve25519_key_chain,"org.matrix.msc3061.shared_history":n.shared_history||!1}}}))}importRoomKey(e,{untrusted:t,source:i}={}){const n={};return(t||e.untrusted)&&(n.untrusted=!0),e["org.matrix.msc3061.shared_history"]&&(n.sharedHistory=!0),this.olmDevice.addInboundGroupSession(e.room_id,e.sender_key,e.forwarding_curve25519_key_chain,e.session_id,e.session_key,e.sender_claimed_keys,!0,n).then((()=>{"backup"!==i&&this.crypto.backupManager.backupGroupSession(e.sender_key,e.session_id).catch((e=>{this.prefixedLogger.log("Failed to back up megolm session",e)})),this.retryDecryption(e.sender_key,e.session_id,!n.untrusted)}))}retryDecryption(e,t,i){var n;return s(this,void 0,void 0,(function*(){const r=this.pendingEvents.get(e);if(!r)return!0;const o=r.get(t);if(!o)return!0;const a=[...o];return this.prefixedLogger.debug("Retrying decryption on events:",a.map((e=>`${e.getId()}`))),yield Promise.all(a.map((e=>s(this,void 0,void 0,(function*(){try{yield e.attemptDecryption(this.crypto,{isRetry:!0,forceRedecryptIfUntrusted:i})}catch(e){}}))))),!(null===(n=this.pendingEvents.get(e))||void 0===n?void 0:n.has(t))}))}retryDecryptionFromSender(e){return s(this,void 0,void 0,(function*(){const t=this.pendingEvents.get(e);return!t||(this.pendingEvents.delete(e),yield Promise.all([...t].map((([e,t])=>s(this,void 0,void 0,(function*(){yield Promise.all([...t].map((e=>s(this,void 0,void 0,(function*(){try{yield e.attemptDecryption(this.crypto)}catch(e){}})))))}))))),!this.pendingEvents.has(e))}))}sendSharedHistoryInboundSessions(e){return s(this,void 0,void 0,(function*(){yield d.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,e);const t=yield this.olmDevice.getSharedHistoryInboundGroupSessions(this.roomId);this.prefixedLogger.log(`Sharing history in with users ${Array.from(e.keys())}`,t.map((([e,t])=>`${e}|${t}`)));for(const[i,n]of t){const t=yield this.buildKeyForwardingMessage(this.roomId,i,n),r=[],o=new Map;for(const[i,n]of e){const e=new Map;o.set(i,e);for(const o of n){const n={algorithm:d.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[h.ToDeviceMessageId]:(0,a.v4)()};e.set(o.deviceId,n),r.push(d.encryptMessageForDevice(n.ciphertext,this.userId,void 0,this.olmDevice,i,o,t))}}yield Promise.all(r);for(const[e,t]of o){for(const[i,n]of t)v(n)||(this.prefixedLogger.log("No ciphertext for device "+e+":"+i+": pruning"),t.delete(i));0===t.size&&(this.prefixedLogger.log("Pruned all devices for user "+e),o.delete(e))}if(0===o.size)return void this.prefixedLogger.log("No users left to send to: aborting");yield this.baseApis.sendToDevice("m.room.encrypted",o)}}))}}i.MegolmDecryption=b;const S={no_olm:"The sender was unable to establish a secure channel.",unknown:"The secure channel with the sender was corrupted."};(0,l.registerAlgorithm)(d.MEGOLM_ALGORITHM,y,b)},{"../../@types/event":306,"../../logger":374,"../../utils":416,"../OlmDevice":327,"../OutgoingRoomKeyRequestManager":328,"../olmlib":343,"./base":332,uuid:287}],335:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0});const a=e("../../logger"),c=o(e("../olmlib")),d=e("../deviceinfo"),l=e("./base"),u=d.DeviceInfo.DeviceVerification;class h extends l.EncryptionAlgorithm{constructor(){super(...arguments),this.sessionPrepared=!1,this.prepPromise=null}ensureSession(e){return this.prepPromise?this.prepPromise:this.sessionPrepared?Promise.resolve():(this.prepPromise=this.crypto.downloadKeys(e).then((()=>this.crypto.ensureOlmSessionsForUsers(e))).then((()=>{this.sessionPrepared=!0})).finally((()=>{this.prepPromise=null})),this.prepPromise)}encryptMessage(e,t,i){return s(this,void 0,void 0,(function*(){const n=(yield e.getEncryptionTargetMembers()).map((function(e){return e.userId}));yield this.ensureSession(n);const r={room_id:e.roomId,type:t,content:i},o={algorithm:c.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{}},s=[];for(const e of n){const t=this.crypto.getStoredDevicesForUser(e)||[];for(const i of t){i.getIdentityKey()!=this.olmDevice.deviceCurve25519Key&&(i.verified!=u.BLOCKED&&s.push(c.encryptMessageForDevice(o.ciphertext,this.userId,this.deviceId,this.olmDevice,e,i,r)))}}return Promise.all(s).then((()=>o))}))}}class f extends l.DecryptionAlgorithm{decryptEvent(e){return s(this,void 0,void 0,(function*(){const t=e.getWireContent(),i=t.sender_key,n=t.ciphertext;if(!n)throw new l.DecryptionError("OLM_MISSING_CIPHERTEXT","Missing ciphertext");if(!(this.olmDevice.deviceCurve25519Key in n))throw new l.DecryptionError("OLM_NOT_INCLUDED_IN_RECIPIENTS","Not included in recipients");const r=n[this.olmDevice.deviceCurve25519Key];let o;try{o=yield this.decryptMessage(i,r)}catch(e){throw new l.DecryptionError("OLM_BAD_ENCRYPTED_MESSAGE","Bad Encrypted Message",{sender:i,err:e})}const s=JSON.parse(o);if(s.recipient!=this.userId)throw new l.DecryptionError("OLM_BAD_RECIPIENT","Message was intented for "+s.recipient);if(s.recipient_keys.ed25519!=this.olmDevice.deviceEd25519Key)throw new l.DecryptionError("OLM_BAD_RECIPIENT_KEY","Message not intended for this device",{intended:s.recipient_keys.ed25519,our_key:this.olmDevice.deviceEd25519Key});yield this.crypto.deviceList.downloadKeys([e.getSender()],!1);const a=this.crypto.deviceList.getUserByIdentityKey(c.OLM_ALGORITHM,i);if(a!==e.getSender()&&null!=a)throw new l.DecryptionError("OLM_BAD_SENDER","Message claimed to be from "+e.getSender(),{real_sender:a});if(s.sender!=e.getSender())throw new l.DecryptionError("OLM_FORWARDED_MESSAGE","Message forwarded from "+s.sender,{reported_sender:e.getSender()});if(s.room_id!==e.getRoomId())throw new l.DecryptionError("OLM_BAD_ROOM","Message intended for room "+s.room_id,{reported_room:e.getRoomId()||"ROOM_ID_UNDEFINED"});return{clearEvent:s,senderCurve25519Key:i,claimedEd25519Key:(s.keys||{}).ed25519||null}}))}decryptMessage(e,t){if(0!==t.type)return this.reallyDecryptMessage(e,t);{const i=this.olmDevice.olmPrekeyPromise.then((()=>this.reallyDecryptMessage(e,t)));return this.olmDevice.olmPrekeyPromise=i.catch((()=>{})),i}}reallyDecryptMessage(e,t){return s(this,void 0,void 0,(function*(){const i=yield this.olmDevice.getSessionIdsForDevice(e),n={};for(const r of i)try{const i=yield this.olmDevice.decryptMessage(e,r,t.type,t.body);return a.logger.log("Decrypted Olm message from "+e+" with session "+r),i}catch(i){if(yield this.olmDevice.matchesSession(e,r,t.type,t.body))throw new Error("Error decrypting prekey message with existing session id "+r+": "+i.message);n[r]=i.message}if(0!==t.type){if(0===i.length)throw new Error("No existing sessions");throw new Error("Error decrypting non-prekey message with existing sessions: "+JSON.stringify(n))}let r;try{r=yield this.olmDevice.createInboundSession(e,t.type,t.body)}catch(e){throw n["(new)"]=e.message,new Error("Error decrypting prekey message: "+JSON.stringify(n))}return a.logger.log("created new inbound Olm session ID "+r.session_id+" with "+e),r.payload}))}}(0,l.registerAlgorithm)(c.OLM_ALGORITHM,h,f)},{"../../logger":374,"../deviceinfo":340,"../olmlib":343,"./base":332}],336:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CrossSigningKey=void 0,function(e){e.Master="master",e.SelfSigning="self_signing",e.UserSigning="user_signing"}(i.CrossSigningKey||(i.CrossSigningKey={}))},{}],337:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.DefaultAlgorithm=i.algorithmsByName=i.Aes256=i.Curve25519=i.BackupManager=void 0;const r=e("../client"),o=e("../logger"),s=e("./olmlib"),a=e("./key_passphrase"),c=e("../utils"),d=e("./store/indexeddb-crypto-store"),l=e("./recoverykey"),u=e("./aes"),h=e("../NamespacedValue"),f=e("./index"),p=e("./crypto"),g=e("../http-api");class v{constructor(e,t){this.baseApis=e,this.getKey=t,this.sessionLastCheckAttemptedTime={},this.checkedForBackup=!1,this.sendingBackups=!1}get version(){return this.backupInfo&&this.backupInfo.version}static checkBackupVersion(e){const t=i.algorithmsByName[e.algorithm];if(!t)throw new Error("Unknown backup algorithm: "+e.algorithm);if("object"!=typeof e.auth_data)throw new Error("Invalid backup data returned");return t.checkBackupVersion(e)}static makeAlgorithm(e,t){const n=i.algorithmsByName[e.algorithm];if(!n)throw new Error("Unknown backup algorithm");return n.init(e.auth_data,t)}enableKeyBackup(e){return n(this,void 0,void 0,(function*(){this.backupInfo=e,this.algorithm&&this.algorithm.free(),this.algorithm=yield v.makeAlgorithm(e,this.getKey),this.baseApis.emit(f.CryptoEvent.KeyBackupStatus,!0),this.scheduleKeyBackupSend()}))}disableKeyBackup(){this.algorithm&&this.algorithm.free(),this.algorithm=void 0,this.backupInfo=void 0,this.baseApis.emit(f.CryptoEvent.KeyBackupStatus,!1)}getKeyBackupEnabled(){return this.checkedForBackup?Boolean(this.algorithm):null}prepareKeyBackupVersion(e,t){return n(this,void 0,void 0,(function*(){const n=t?i.algorithmsByName[t]:i.DefaultAlgorithm;if(!n)throw new Error("Unknown backup algorithm");const[r,o]=yield n.prepare(e),s=(0,l.encodeRecoveryKey)(r);return{algorithm:n.algorithmName,auth_data:o,recovery_key:s,privateKey:r}}))}createKeyBackupVersion(e){return n(this,void 0,void 0,(function*(){this.algorithm=yield v.makeAlgorithm(e,this.getKey)}))}checkAndStart(){var e;return n(this,void 0,void 0,(function*(){if(o.logger.log("Checking key backup status..."),this.baseApis.isGuest())return o.logger.log("Skipping key backup check since user is guest"),this.checkedForBackup=!0,null;let t;try{t=null!==(e=yield this.baseApis.getKeyBackupVersion())&&void 0!==e?e:void 0}catch(e){return o.logger.log("Error checking for active key backup",e),404===e.httpStatus&&(this.checkedForBackup=!0),null}this.checkedForBackup=!0;const i=yield this.isKeyBackupTrusted(t);return i.usable&&!this.backupInfo?(o.logger.log(`Found usable key backup v${t.version}: enabling key backups`),yield this.enableKeyBackup(t)):!i.usable&&this.backupInfo?(o.logger.log("No usable key backup: disabling key backup"),this.disableKeyBackup()):i.usable||this.backupInfo?i.usable&&this.backupInfo&&(t.version!==this.backupInfo.version?(o.logger.log(`On backup version ${this.backupInfo.version} but found version ${t.version}: switching.`),this.disableKeyBackup(),yield this.enableKeyBackup(t),yield this.scheduleAllGroupSessionsForBackup()):o.logger.log(`Backup version ${t.version} still current`)):o.logger.log("No usable key backup: not enabling key backup"),{backupInfo:t,trustInfo:i}}))}checkKeyBackup(){return n(this,void 0,void 0,(function*(){return this.checkedForBackup=!1,this.checkAndStart()}))}queryKeyBackupRateLimited(e,t){return n(this,void 0,void 0,(function*(){if(!this.backupInfo)return;const i=(new Date).getTime();(!this.sessionLastCheckAttemptedTime[t]||i-this.sessionLastCheckAttemptedTime[t]>5e3)&&(this.sessionLastCheckAttemptedTime[t]=i,yield this.baseApis.restoreKeyBackupWithCache(e,t,this.backupInfo,{}))}))}isKeyBackupTrusted(e){return n(this,void 0,void 0,(function*(){const t={usable:!1,trusted_locally:!1,sigs:[]};if(!(e&&e.algorithm&&e.auth_data&&e.auth_data.signatures))return o.logger.info("Key backup is absent or missing required data"),t;const i=this.baseApis.getUserId(),r=yield this.baseApis.crypto.getSessionBackupPrivateKey();if(r){let i=null;try{i=yield v.makeAlgorithm(e,(()=>n(this,void 0,void 0,(function*(){return r})))),(yield i.keyMatches(r))&&(o.logger.info("Backup is trusted locally"),t.trusted_locally=!0)}catch(e){}finally{null==i||i.free()}}const a=e.auth_data.signatures[i]||{};for(const n of Object.keys(a)){const r=n.split(":");if("ed25519"!==r[0]){o.logger.log("Ignoring unknown signature type: "+r[0]);continue}const a={deviceId:r[1]},c=this.baseApis.crypto.crossSigningInfo.getId();if(c===a.deviceId){a.crossSigningId=!0;try{yield(0,s.verifySignature)(this.baseApis.crypto.olmDevice,e.auth_data,i,a.deviceId,c),a.valid=!0}catch(e){o.logger.warn("Bad signature from cross signing key "+c,e),a.valid=!1}t.sigs.push(a);continue}const d=this.baseApis.crypto.deviceList.getStoredDevice(i,a.deviceId);if(d){a.device=d,a.deviceTrust=this.baseApis.checkDeviceTrust(i,a.deviceId);try{yield(0,s.verifySignature)(this.baseApis.crypto.olmDevice,e.auth_data,i,d.deviceId,d.getFingerprint()),a.valid=!0}catch(t){o.logger.info("Bad signature from key ID "+n+" userID "+this.baseApis.getUserId()+" device ID "+d.deviceId+" fingerprint: "+d.getFingerprint(),e.auth_data,t),a.valid=!1}}else a.valid=null,o.logger.info("Ignoring signature from unknown key "+n);t.sigs.push(a)}return t.usable=t.sigs.some((e=>{var t;return e.valid&&(e.device&&(null===(t=e.deviceTrust)||void 0===t?void 0:t.isVerified())||e.crossSigningId)})),t}))}scheduleKeyBackupSend(e=1e4){return n(this,void 0,void 0,(function*(){if(!this.sendingBackups){this.sendingBackups=!0;try{const t=Math.random()*e;yield(0,c.sleep)(t);let i=0;for(;;){if(!this.algorithm)return;try{if(0===(yield this.backupPendingKeys(200)))return;i=0}catch(e){if(i++,o.logger.log("Key backup request failed",e),e.data&&("M_NOT_FOUND"==e.data.errcode||"M_WRONG_ROOM_KEYS_VERSION"==e.data.errcode))throw yield this.checkKeyBackup(),this.baseApis.crypto.emit(f.CryptoEvent.KeyBackupFailed,e.data.errcode),e}i&&(yield(0,c.sleep)(1e3*Math.pow(2,Math.min(i-1,4))))}}finally{this.sendingBackups=!1}}}))}backupPendingKeys(e){var t;return n(this,void 0,void 0,(function*(){const i=yield this.baseApis.crypto.cryptoStore.getSessionsNeedingBackup(e);if(!i.length)return 0;let n=yield this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();this.baseApis.crypto.emit(f.CryptoEvent.KeyBackupSessionsRemaining,n);const r={};for(const e of i){const i=e.sessionData.room_id;(0,c.safeSet)(r,i,r[i]||{sessions:{}});const n=this.baseApis.crypto.olmDevice.exportInboundGroupSession(e.senderKey,e.sessionId,e.sessionData);n.algorithm=s.MEGOLM_ALGORITHM;const o=(n.forwarding_curve25519_key_chain||[]).length,a=this.baseApis.crypto.deviceList.getUserByIdentityKey(s.MEGOLM_ALGORITHM,e.senderKey),d=null!==(t=this.baseApis.crypto.deviceList.getDeviceByIdentityKey(s.MEGOLM_ALGORITHM,e.senderKey))&&void 0!==t?t:void 0,l=this.baseApis.crypto.checkDeviceInfoTrust(a,d).isVerified();(0,c.safeSet)(r[i].sessions,e.sessionId,{first_message_index:n.first_known_index,forwarded_count:o,is_verified:l,session_data:yield this.algorithm.encryptSession(n)})}return yield this.baseApis.sendKeyBackup(void 0,void 0,this.backupInfo.version,{rooms:r}),yield this.baseApis.crypto.cryptoStore.unmarkSessionsNeedingBackup(i),n=yield this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup(),this.baseApis.crypto.emit(f.CryptoEvent.KeyBackupSessionsRemaining,n),i.length}))}backupGroupSession(e,t){return n(this,void 0,void 0,(function*(){yield this.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([{senderKey:e,sessionId:t}]),this.backupInfo&&this.scheduleKeyBackupSend()}))}scheduleAllGroupSessionsForBackup(){return n(this,void 0,void 0,(function*(){yield this.flagAllGroupSessionsForBackup(),this.scheduleKeyBackupSend(0)}))}flagAllGroupSessionsForBackup(){return n(this,void 0,void 0,(function*(){yield this.baseApis.crypto.cryptoStore.doTxn("readwrite",[d.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,d.IndexedDBCryptoStore.STORE_BACKUP],(e=>{this.baseApis.crypto.cryptoStore.getAllEndToEndInboundGroupSessions(e,(t=>{null!==t&&this.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([t],e)}))}));const e=yield this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();return this.baseApis.emit(f.CryptoEvent.KeyBackupSessionsRemaining,e),e}))}countSessionsNeedingBackup(){return this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup()}}i.BackupManager=v;class m{constructor(e,t,i){this.authData=e,this.publicKey=t,this.getKey=i}static init(e,i){return n(this,void 0,void 0,(function*(){if(!e||!("public_key"in e))throw new Error("auth_data missing required information");const n=new t.Olm.PkEncryption;return n.set_recipient_key(e.public_key),new m(e,n,i)}))}static prepare(e){return n(this,void 0,void 0,(function*(){const i=new t.Olm.PkDecryption;try{const n={};if(e)if(e instanceof Uint8Array)n.public_key=i.init_with_private_key(e);else{const t=yield(0,a.keyFromPassphrase)(e);n.private_key_salt=t.salt,n.private_key_iterations=t.iterations,n.public_key=i.init_with_private_key(t.key)}else n.public_key=i.generate_key();return(new t.Olm.PkEncryption).set_recipient_key(n.public_key),[i.get_private_key(),n]}finally{i.free()}}))}static checkBackupVersion(e){if(!("public_key"in e.auth_data))throw new Error("Invalid backup data returned")}get untrusted(){return!0}encryptSession(e){return n(this,void 0,void 0,(function*(){const t=Object.assign({},e);return delete t.session_id,delete t.room_id,delete t.first_known_index,this.publicKey.encrypt(JSON.stringify(t))}))}decryptSessions(e){return n(this,void 0,void 0,(function*(){const i=yield this.getKey(),n=new t.Olm.PkDecryption;try{if(n.init_with_private_key(i)!==this.authData.public_key)throw new g.MatrixError({errcode:r.MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY});const t=[];for(const[i,r]of Object.entries(e))try{const e=JSON.parse(n.decrypt(r.session_data.ephemeral,r.session_data.mac,r.session_data.ciphertext));e.session_id=i,t.push(e)}catch(e){o.logger.log("Failed to decrypt megolm session from backup",e,r)}return t}finally{n.free()}}))}keyMatches(e){return n(this,void 0,void 0,(function*(){const i=new t.Olm.PkDecryption;let n;try{n=i.init_with_private_key(e)}finally{i.free()}return n===this.authData.public_key}))}free(){this.publicKey.free()}}i.Curve25519=m,m.algorithmName="m.megolm_backup.v1.curve25519-aes-sha2";const y=new h.UnstableValue("m.megolm_backup.v1.aes-hmac-sha2","org.matrix.msc3270.v1.aes-hmac-sha2");class b{constructor(e,t){this.authData=e,this.key=t}static init(e,t){return n(this,void 0,void 0,(function*(){if(!e)throw new Error("auth_data missing");const i=yield t();if(e.mac){const{mac:t}=yield(0,u.calculateKeyCheck)(i,e.iv);if(e.mac.replace(/=+$/g,"")!==t.replace(/=+/g,""))throw new Error("Key does not match")}return new b(e,i)}))}static prepare(e){return n(this,void 0,void 0,(function*(){let t;const i={};if(e)if(e instanceof Uint8Array)t=new Uint8Array(e);else{const n=yield(0,a.keyFromPassphrase)(e);i.private_key_salt=n.salt,i.private_key_iterations=n.iterations,t=n.key}else t=function(e){const t=new Uint8Array(e);return p.crypto.getRandomValues(t),t}(32);const{iv:n,mac:r}=yield(0,u.calculateKeyCheck)(t);return i.iv=n,i.mac=r,[t,i]}))}static checkBackupVersion(e){if(!("iv"in e.auth_data)||!("mac"in e.auth_data))throw new Error("Invalid backup data returned")}get untrusted(){return!1}encryptSession(e){const t=Object.assign({},e);return delete t.session_id,delete t.room_id,delete t.first_known_index,(0,u.encryptAES)(JSON.stringify(t),this.key,e.session_id)}decryptSessions(e){return n(this,void 0,void 0,(function*(){const t=[];for(const[i,n]of Object.entries(e))try{const e=JSON.parse(yield(0,u.decryptAES)(n.session_data,this.key,i));e.session_id=i,t.push(e)}catch(e){o.logger.log("Failed to decrypt megolm session from backup",e,n)}return t}))}keyMatches(e){return n(this,void 0,void 0,(function*(){if(this.authData.mac){const{mac:t}=yield(0,u.calculateKeyCheck)(e,this.authData.iv);return this.authData.mac.replace(/=+$/g,"")===t.replace(/=+/g,"")}return!0}))}free(){this.key.fill(0)}}i.Aes256=b,b.algorithmName=y.name,i.algorithmsByName={[m.algorithmName]:m,[b.algorithmName]:b},i.DefaultAlgorithm=m}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../NamespacedValue":316,"../client":321,"../http-api":367,"../logger":374,"../utils":416,"./aes":331,"./crypto":338,"./index":341,"./key_passphrase":342,"./olmlib":343,"./recoverykey":344,"./store/indexeddb-crypto-store":346}],338:[function(e,t,i){(function(t){(function(){"use strict";var n,r,o,s,a,c,d;Object.defineProperty(i,"__esModule",{value:!0}),i.setTextEncoder=i.setCrypto=i.TextEncoder=i.subtleCrypto=i.crypto=void 0;const l=e("../logger");if(i.crypto=null===(n=t.window)||void 0===n?void 0:n.crypto,i.subtleCrypto=null!==(s=null===(o=null===(r=t.window)||void 0===r?void 0:r.crypto)||void 0===o?void 0:o.subtle)&&void 0!==s?s:null===(c=null===(a=t.window)||void 0===a?void 0:a.crypto)||void 0===c?void 0:c.webkitSubtle,i.TextEncoder=null===(d=t.window)||void 0===d?void 0:d.TextEncoder,!i.crypto)try{i.crypto=e("crypto").webcrypto}catch(e){l.logger.error("Failed to load webcrypto",e)}if(i.subtleCrypto||(i.subtleCrypto=null===i.crypto||void 0===i.crypto?void 0:i.crypto.subtle),!i.TextEncoder)try{i.TextEncoder=e("util").TextEncoder}catch(e){l.logger.error("Failed to load TextEncoder util",e)}i.setCrypto=function(e){var t;i.crypto=e,i.subtleCrypto=null!==(t=e.subtle)&&void 0!==t?t:e.webkitSubtle},i.setTextEncoder=function(e){i.TextEncoder=e}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../logger":374,crypto:78,util:286}],339:[function(e,t,i){(function(t,n){(function(){"use strict";var r=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(i,"__esModule",{value:!0}),i.DehydrationManager=i.DEHYDRATION_ALGORITHM=void 0;const s=o(e("another-json")),a=e("./olmlib"),c=e("../crypto/store/indexeddb-crypto-store"),d=e("./aes"),l=e("../logger"),u=e("../http-api");i.DEHYDRATION_ALGORITHM="org.matrix.msc2697.v1.olm.libolm_pickle";const h=6048e5;i.DehydrationManager=class{constructor(e){this.crypto=e,this.inProgress=!1,this.getDehydrationKeyFromCache()}getDehydrationKeyFromCache(){return this.crypto.cryptoStore.doTxn("readonly",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.crypto.cryptoStore.getSecretStorePrivateKey(e,(e=>r(this,void 0,void 0,(function*(){if(e){const{key:r,keyInfo:o,deviceDisplayName:s,time:c}=e,l=n.from(this.crypto.olmDevice.pickleKey),u=yield(0,d.decryptAES)(r,l,i.DEHYDRATION_ALGORITHM);this.key=(0,a.decodeBase64)(u),this.keyInfo=o,this.deviceDisplayName=s;const f=Date.now(),p=Math.max(1,c+h-f);this.timeoutId=t.setTimeout(this.dehydrateDevice.bind(this),p)}}))),"dehydration")}))}setKeyAndQueueDehydration(e,t={},i){return r(this,void 0,void 0,(function*(){(yield this.setKey(e,t,i))||this.dehydrateDevice()}))}setKey(e,i={},n){return r(this,void 0,void 0,(function*(){if(!e)return this.timeoutId&&(t.clearTimeout(this.timeoutId),this.timeoutId=void 0),yield this.crypto.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.crypto.cryptoStore.storeSecretStorePrivateKey(e,"dehydration",null)})),this.key=void 0,void(this.keyInfo=void 0);let r=!!this.key&&e.length==this.key.length;for(let t=0;r&&t{this.crypto.cryptoStore.storeSecretStorePrivateKey(e,"dehydration",{keyInfo:this.keyInfo,key:r,deviceDisplayName:this.deviceDisplayName,time:Date.now()})})),l.logger.log("Attempting to dehydrate device"),l.logger.log("Creating account");const o=new t.Olm.Account;o.create();const f=JSON.parse(o.identity_keys()),p=o.max_number_of_one_time_keys();o.generate_one_time_keys(p/2),o.generate_fallback_key();const g=JSON.parse(o.one_time_keys()),v=JSON.parse(o.fallback_key());o.mark_keys_as_published();const m=o.pickle(new Uint8Array(this.key)),y={algorithm:i.DEHYDRATION_ALGORITHM,account:m};this.keyInfo.passphrase&&(y.passphrase=this.keyInfo.passphrase),l.logger.log("Uploading account to server");const b=(yield this.crypto.baseApis.http.authedRequest(u.Method.Put,"/dehydrated_device",void 0,{device_data:y,initial_device_display_name:this.deviceDisplayName},{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})).device_id;l.logger.log("Preparing device keys",b);const S={algorithms:this.crypto.supportedAlgorithms,device_id:b,user_id:this.crypto.userId,keys:{[`ed25519:${b}`]:f.ed25519,[`curve25519:${b}`]:f.curve25519}},_=o.sign(s.default.stringify(S));S.signatures={[this.crypto.userId]:{[`ed25519:${b}`]:_}},this.crypto.crossSigningInfo.getId("self_signing")&&(yield this.crypto.crossSigningInfo.signObject(S,"self_signing")),l.logger.log("Preparing one-time keys");const E={};for(const[e,t]of Object.entries(g.curve25519)){const i={key:t},n=o.sign(s.default.stringify(i));i.signatures={[this.crypto.userId]:{[`ed25519:${b}`]:n}},E[`signed_curve25519:${e}`]=i}l.logger.log("Preparing fallback keys");const w={};for(const[e,t]of Object.entries(v.curve25519)){const i={key:t,fallback:!0},n=o.sign(s.default.stringify(i));i.signatures={[this.crypto.userId]:{[`ed25519:${b}`]:n}},w[`signed_curve25519:${e}`]=i}return l.logger.log("Uploading keys to server"),yield this.crypto.baseApis.http.authedRequest(u.Method.Post,"/keys/upload/"+encodeURI(b),void 0,{device_keys:S,one_time_keys:E,"org.matrix.msc2732.fallback_keys":w}),l.logger.log("Done dehydrating"),this.timeoutId=t.setTimeout(this.dehydrateDevice.bind(this),h),b}finally{this.inProgress=!1}}}))}stop(){this.timeoutId&&(t.clearTimeout(this.timeoutId),this.timeoutId=void 0)}}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"../crypto/store/indexeddb-crypto-store":346,"../http-api":367,"../logger":374,"./aes":331,"./olmlib":343,"another-json":1,buffer:68}],340:[function(e,t,i){"use strict";var n;Object.defineProperty(i,"__esModule",{value:!0}),i.DeviceInfo=void 0,function(e){e[e.Blocked=-1]="Blocked",e[e.Unverified=0]="Unverified",e[e.Verified=1]="Verified"}(n||(n={}));class r{static fromStorage(e,t){const i=new r(t);for(const t in e)e.hasOwnProperty(t)&&(i[t]=e[t]);return i}constructor(e){this.deviceId=e,this.algorithms=[],this.keys={},this.verified=n.Unverified,this.known=!1,this.unsigned={},this.signatures={}}toStorage(){return{algorithms:this.algorithms,keys:this.keys,verified:this.verified,known:this.known,unsigned:this.unsigned,signatures:this.signatures}}getFingerprint(){return this.keys["ed25519:"+this.deviceId]}getIdentityKey(){return this.keys["curve25519:"+this.deviceId]}getDisplayName(){return this.unsigned.device_display_name||null}isBlocked(){return this.verified==n.Blocked}isVerified(){return this.verified==n.Verified}isUnverified(){return this.verified==n.Unverified}isKnown(){return!0===this.known}}i.DeviceInfo=r,r.DeviceVerification={VERIFIED:n.Verified,UNVERIFIED:n.Unverified,BLOCKED:n.Blocked}},{}],341:[function(e,t,i){(function(t,n){(function(){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return o(t,e),t},a=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(i,"__esModule",{value:!0}),i.IncomingRoomKeyRequest=i.fixBackupKey=i.Crypto=i.CryptoEvent=i.isCryptoAvailable=i.verificationMethods=void 0;const d=c(e("another-json")),l=e("uuid"),u=e("../@types/event"),h=e("../ReEmitter"),f=e("../logger"),p=e("./OlmDevice"),g=s(e("./olmlib")),v=e("./DeviceList"),m=e("./deviceinfo"),y=s(e("./algorithms")),b=e("./CrossSigning"),S=e("./EncryptionSetup"),_=e("./SecretStorage"),E=e("./OutgoingRoomKeyRequestManager"),w=e("./store/indexeddb-crypto-store"),T=e("./verification/QRCode"),I=e("./verification/SAS"),R=e("./key_passphrase"),M=e("./recoverykey"),k=e("./verification/request/VerificationRequest"),C=e("./verification/request/InRoomChannel"),O=e("./verification/request/ToDeviceChannel"),A=e("./verification/IllegalMethod"),P=e("../errors"),D=e("./aes"),x=e("./dehydration"),L=e("./backup"),U=e("../models/room"),B=e("../models/room-member"),N=e("../models/event"),j=e("../client"),F=e("../models/typed-event-emitter"),K=e("../models/room-state"),q=e("../utils"),$=m.DeviceInfo.DeviceVerification,V={[T.ReciprocateQRCode.NAME]:T.ReciprocateQRCode,[I.SAS.NAME]:I.SAS,[T.SHOW_QR_CODE_METHOD]:A.IllegalMethod,[T.SCAN_QR_CODE_METHOD]:A.IllegalMethod};i.verificationMethods={RECIPROCATE_QR_CODE:T.ReciprocateQRCode.NAME,SAS:I.SAS.NAME},i.isCryptoAvailable=function(){return Boolean(t.Olm)};var H;!function(e){e.DeviceVerificationChanged="deviceVerificationChanged",e.UserTrustStatusChanged="userTrustStatusChanged",e.UserCrossSigningUpdated="userCrossSigningUpdated",e.RoomKeyRequest="crypto.roomKeyRequest",e.RoomKeyRequestCancellation="crypto.roomKeyRequestCancellation",e.KeyBackupStatus="crypto.keyBackupStatus",e.KeyBackupFailed="crypto.keyBackupFailed",e.KeyBackupSessionsRemaining="crypto.keyBackupSessionsRemaining",e.KeySignatureUploadFailure="crypto.keySignatureUploadFailure",e.VerificationRequest="crypto.verification.request",e.Warning="crypto.warning",e.WillUpdateDevices="crypto.willUpdateDevices",e.DevicesUpdated="crypto.devicesUpdated",e.KeysChanged="crossSigning.keysChanged"}(H=i.CryptoEvent||(i.CryptoEvent={}));class W extends F.TypedEventEmitter{static getOlmVersion(){return p.OlmDevice.getOlmVersion()}constructor(e,t,i,n,r,o,s){if(super(),this.baseApis=e,this.userId=t,this.deviceId=i,this.clientStore=n,this.cryptoStore=r,this.roomList=o,this.trustCrossSignedDevices=!0,this.lastOneTimeKeyCheck=null,this.oneTimeKeyCheckInProgress=!1,this.roomEncryptors=new Map,this.roomDecryptors=new Map,this.deviceKeys={},this.globalBlacklistUnverifiedDevices=!1,this.globalErrorOnUnknownDevices=!0,this.receivedRoomKeyRequests=[],this.receivedRoomKeyRequestCancellations=[],this.processingRoomKeyRequests=!1,this.lazyLoadMembers=!1,this.roomDeviceTrackingState={},this.lastNewSessionForced=new q.MapWithDefault((()=>new q.MapWithDefault((()=>0)))),this.sendKeyRequestsImmediately=!1,this.onDeviceListUserCrossSigningUpdated=e=>a(this,void 0,void 0,(function*(){if(e===this.userId){const t=this.deviceList.getStoredCrossSigningForUser(e),i=t?t.getId():null,n=this.crossSigningInfo.getId();n&&i&&!(n!==i)?yield this.checkOwnCrossSigningTrust():(this.storeTrustedSelfKeys(null),this.emit(H.KeysChanged,{}),this.emit(H.UserTrustStatusChanged,this.userId,this.checkUserTrust(e)))}else{yield this.checkDeviceVerifications(e);const t=this.deviceList.getStoredCrossSigningForUser(e);t&&(t.updateCrossSigningVerifiedBefore(this.checkUserTrust(e).isCrossSigningVerified()),this.deviceList.setRawStoredCrossSigningForUser(e,t.toStorage())),this.emit(H.UserTrustStatusChanged,e,this.checkUserTrust(e))}})),this.onMembership=(e,t,i)=>{try{this.onRoomMembership(e,t,i)}catch(e){f.logger.error("Error handling membership change:",e)}},this.onToDeviceEvent=e=>{try{f.logger.log(`received to-device ${e.getType()} from: ${e.getSender()} id: ${e.getContent()[u.ToDeviceMessageId]}`),"m.room_key"==e.getType()||"m.forwarded_room_key"==e.getType()?this.onRoomKeyEvent(e):"m.room_key_request"==e.getType()?this.onRoomKeyRequestEvent(e):"m.secret.request"===e.getType()?this.secretStorage.onRequestReceived(e):"m.secret.send"===e.getType()?this.secretStorage.onSecretReceived(e):"m.room_key.withheld"===e.getType()?this.onRoomKeyWithheldEvent(e):e.getContent().transaction_id?this.onKeyVerificationMessage(e):"m.bad.encrypted"===e.getContent().msgtype?this.onToDeviceBadEncrypted(e):(e.isBeingDecrypted()||e.shouldAttemptDecryption())&&(e.isBeingDecrypted()||e.attemptDecryption(this),e.once(N.MatrixEventEvent.Decrypted,(e=>{this.onToDeviceEvent(e)})))}catch(e){f.logger.error("Error handling toDeviceEvent:",e)}},this.onTimelineEvent=(e,t,i,n,{liveEvent:r=!0}={})=>{if(!C.InRoomChannel.validateEvent(e,this.baseApis))return;this.handleVerificationEvent(e,this.inRoomVerificationRequests,(e=>{const t=new C.InRoomChannel(this.baseApis,e.getRoomId());return new k.VerificationRequest(t,this.verificationMethods,this.baseApis)}),r)},this.reEmitter=new h.TypedReEmitter(this),s){this.verificationMethods=new Map;for(const e of s)"string"==typeof e?V[e]&&this.verificationMethods.set(e,V[e]):e.NAME?this.verificationMethods.set(e.NAME,e):f.logger.warn(`Excluding unknown verification method ${e}`)}else this.verificationMethods=new Map(Object.entries(V));this.backupManager=new L.BackupManager(e,(()=>a(this,void 0,void 0,(function*(){const e=yield this.getSessionBackupPrivateKey();if(e)return e;const t=yield this.getSecret("m.megolm_backup.v1");if(t){const e=G(t);if(e){const t=yield this.getSecretStorageKey();yield this.storeSecret("m.megolm_backup.v1",e,[t[0]])}return g.decodeBase64(e||t)}if(this.baseApis.cryptoCallbacks&&this.baseApis.cryptoCallbacks.getBackupKey)return this.baseApis.cryptoCallbacks.getBackupKey();throw new Error("Unable to get private key")})))),this.olmDevice=new p.OlmDevice(r),this.deviceList=new v.DeviceList(e,r,this.olmDevice),this.deviceList.on(H.UserCrossSigningUpdated,this.onDeviceListUserCrossSigningUpdated),this.reEmitter.reEmit(this.deviceList,[H.DevicesUpdated,H.WillUpdateDevices]),this.supportedAlgorithms=Array.from(y.DECRYPTION_CLASSES.keys()),this.outgoingRoomKeyRequestManager=new E.OutgoingRoomKeyRequestManager(e,this.deviceId,this.cryptoStore),this.toDeviceVerificationRequests=new O.ToDeviceRequests,this.inRoomVerificationRequests=new C.InRoomRequests;const c=this.baseApis.cryptoCallbacks||{},d=(0,b.createCryptoStoreCacheCallbacks)(r,this.olmDevice);this.crossSigningInfo=new b.CrossSigningInfo(t,c,d),this.secretStorage=new _.SecretStorage(e,c,e),this.dehydrationManager=new x.DehydrationManager(this),!c.getCrossSigningKey&&c.getSecretStorageKey&&(c.getCrossSigningKey=e=>a(this,void 0,void 0,(function*(){return b.CrossSigningInfo.getFromSecretStorage(e,this.secretStorage)})))}init({exportedOlmDevice:e,pickleKey:i}={}){return a(this,void 0,void 0,(function*(){f.logger.log("Crypto: initialising Olm..."),yield t.Olm.init(),f.logger.log(e?"Crypto: initialising Olm device from exported device...":"Crypto: initialising Olm device..."),yield this.olmDevice.init({fromExportedDevice:e,pickleKey:i}),f.logger.log("Crypto: loading device list..."),yield this.deviceList.load(),this.deviceKeys["ed25519:"+this.deviceId]=this.olmDevice.deviceEd25519Key,this.deviceKeys["curve25519:"+this.deviceId]=this.olmDevice.deviceCurve25519Key,f.logger.log("Crypto: fetching own devices...");let n=this.deviceList.getRawStoredDevicesForUser(this.userId);if(n||(n={}),!n[this.deviceId]){f.logger.log("Crypto: adding this device to the store...");const e={keys:this.deviceKeys,algorithms:this.supportedAlgorithms,verified:$.VERIFIED,known:!0};n[this.deviceId]=e,this.deviceList.storeDevicesForUser(this.userId,n),this.deviceList.saveIfDirty()}yield this.cryptoStore.doTxn("readonly",[w.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.cryptoStore.getCrossSigningKeys(e,(e=>{e&&0!==Object.keys(e).length&&(f.logger.log("Loaded cross-signing public keys from crypto store"),this.crossSigningInfo.setKeys(e))}))})),this.deviceList.startTrackingDeviceList(this.userId),f.logger.log("Crypto: checking for key backup..."),this.backupManager.checkAndStart()}))}getCryptoTrustCrossSignedDevices(){return this.trustCrossSignedDevices}setCryptoTrustCrossSignedDevices(e){this.trustCrossSignedDevices=e;for(const e of this.deviceList.getKnownUserIds()){const t=this.deviceList.getRawStoredDevicesForUser(e);for(const i of Object.keys(t)){const t=this.checkDeviceTrust(e,i);if(!t.isLocallyVerified()&&t.isCrossSigningVerified()){const t=this.deviceList.getStoredDevice(e,i);this.emit(H.DeviceVerificationChanged,e,i,t)}}}}createRecoveryKeyFromPassphrase(e){return a(this,void 0,void 0,(function*(){const i=new t.Olm.PkDecryption;try{const t={};if(e){const n=yield(0,R.keyFromPassphrase)(e);t.passphrase={algorithm:"m.pbkdf2",iterations:n.iterations,salt:n.salt},t.pubkey=i.init_with_private_key(n.key)}else t.pubkey=i.generate_key();const n=i.get_private_key();return{keyInfo:t,encodedPrivateKey:(0,M.encodeRecoveryKey)(n),privateKey:n}}finally{null==i||i.free()}}))}userHasCrossSigningKeys(){return a(this,void 0,void 0,(function*(){return yield this.downloadKeys([this.userId]),null!==this.deviceList.getStoredCrossSigningForUser(this.userId)}))}isCrossSigningReady(){return a(this,void 0,void 0,(function*(){const e=this.crossSigningInfo.getId(),t=(yield this.crossSigningInfo.isStoredInKeyCache())||(yield this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage));return!(!e||!t)}))}isSecretStorageReady(){return a(this,void 0,void 0,(function*(){const e=yield this.secretStorage.hasKey(),t=yield this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage),i=!this.backupManager.getKeyBackupEnabled()||(yield this.baseApis.isKeyBackupKeyStored());return!!(e&&t&&i)}))}bootstrapCrossSigning({authUploadDeviceSigningKeys:e,setupNewCrossSigning:t}={}){return a(this,void 0,void 0,(function*(){f.logger.log("Bootstrapping cross-signing");const i=this.baseApis.cryptoCallbacks,n=new S.EncryptionSetupBuilder(this.baseApis.store.accountData,i),r=new b.CrossSigningInfo(this.userId,n.crossSigningCallbacks,n.crossSigningCallbacks),o=()=>a(this,void 0,void 0,(function*(){r.resetKeys(),yield this.signObject(r.keys.master),n.addCrossSigningKeys(e,r.keys);const t=this.deviceList.getStoredDevice(this.userId,this.deviceId),i=yield r.signDevice(this.userId,t);n.addKeySignature(this.userId,this.deviceId,i),this.backupManager.backupInfo&&(yield r.signObject(this.backupManager.backupInfo.auth_data,"master"),n.addSessionBackup(this.backupManager.backupInfo))})),s=this.crossSigningInfo.getId(),c=yield this.crossSigningInfo.isStoredInKeyCache(),d=yield this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage),l=c||d;f.logger.log({setupNewCrossSigning:t,publicKeysOnDevice:s,privateKeysInCache:c,privateKeysInStorage:d,privateKeysExistSomewhere:l}),!l||t?(f.logger.log("Cross-signing private keys not found locally or in secret storage, creating new keys"),yield o()):s&&c?f.logger.log("Cross-signing public keys trusted and private keys found locally"):d&&(f.logger.log("Cross-signing private keys not found locally, but they are available in secret storage, reading storage and caching locally"),yield this.checkOwnCrossSigningTrust({allowPrivateKeyRequests:!0}));const u=n.crossSigningCallbacks.privateKeys;if(u.size&&!this.baseApis.cryptoCallbacks.saveCrossSigningKeys){const e=new _.SecretStorage(n.accountDataClientAdapter,n.ssssCryptoCallbacks,void 0);(yield e.hasKey())&&(f.logger.log("Storing new cross-signing private keys in secret storage"),yield b.CrossSigningInfo.storeInSecretStorage(u,e))}const h=n.buildOperation();yield h.apply(this),yield n.persist(this),f.logger.log("Cross-signing ready")}))}bootstrapSecretStorage({createSecretStorageKey:e=(()=>a(this,void 0,void 0,(function*(){return{}}))),keyBackupInfo:t,setupNewKeyBackup:i,setupNewSecretStorage:n,getKeyBackupPassphrase:r}={}){return a(this,void 0,void 0,(function*(){f.logger.log("Bootstrapping Secure Secret Storage");const o=this.baseApis.cryptoCallbacks,s=new S.EncryptionSetupBuilder(this.baseApis.store.accountData,o),c=new _.SecretStorage(s.accountDataClientAdapter,s.ssssCryptoCallbacks,void 0);let d=null;const l=(e,t)=>a(this,void 0,void 0,(function*(){t&&(e.key=t);const{keyId:i,keyInfo:n}=yield c.addKey(_.SECRET_STORAGE_ALGORITHM_V1_AES,e);return t&&s.ssssCryptoCallbacks.addPrivateKey(i,n,t),yield c.setDefaultKeyId(i),i})),u=(e,t)=>a(this,void 0,void 0,(function*(){var i,n;if(!t.mac){const r=yield null===(n=(i=this.baseApis.cryptoCallbacks).getSecretStorageKey)||void 0===n?void 0:n.call(i,{keys:{[e]:t}},"");if(r){const i=r[1];s.ssssCryptoCallbacks.addPrivateKey(e,t,i);const{iv:n,mac:o}=yield(0,D.calculateKeyCheck)(i);t.iv=n,t.mac=o,yield s.setAccountData(`m.secret_storage.key.${e}`,t)}}})),h=e=>a(this,void 0,void 0,(function*(){if(this.crossSigningInfo.getId()&&(yield this.crossSigningInfo.isStoredInKeyCache("master")))try{f.logger.log("Adding cross-signing signature to key backup"),yield this.crossSigningInfo.signObject(e,"master")}catch(e){f.logger.error("Signing key backup with cross-signing keys failed",e)}else f.logger.warn("Cross-signing keys not available, skipping signature on key backup")})),p=yield this.getSecretStorageKey(),[v,m]=p||[null,null],y=!n&&m&&m.algorithm===_.SECRET_STORAGE_ALGORITHM_V1_AES;if(f.logger.log({keyBackupInfo:t,setupNewKeyBackup:i,setupNewSecretStorage:n,storageExists:y,oldKeyInfo:m}),y||t)if(!y&&t){f.logger.log("Secret storage does not exist, using key backup key");const e=(yield this.getSessionBackupPrivateKey())||(yield null==r?void 0:r()),i={};t.auth_data.private_key_salt&&t.auth_data.private_key_iterations&&(i.passphrase={algorithm:"m.pbkdf2",iterations:t.auth_data.private_key_iterations,salt:t.auth_data.private_key_salt,bits:256}),d=yield l(i,e),yield c.store("m.megolm_backup.v1",g.encodeBase64(e),[d]),yield h(t.auth_data),s.addSessionBackup(t)}else f.logger.log("Secret storage exists"),m&&m.algorithm===_.SECRET_STORAGE_ALGORITHM_V1_AES&&(yield u(v,m));else{f.logger.log("Secret storage does not exist, creating new storage key");const{keyInfo:t={},privateKey:i}=yield e();d=yield l(t,i)}if(!this.baseApis.cryptoCallbacks.saveCrossSigningKeys&&(yield this.isCrossSigningReady())&&(d||!(yield this.crossSigningInfo.isStoredInSecretStorage(c)))){f.logger.log("Copying cross-signing private keys from cache to secret storage");const e=yield this.crossSigningInfo.getCrossSigningKeysFromCache();yield b.CrossSigningInfo.storeInSecretStorage(e,c)}if(i&&!t){f.logger.log("Creating new message key backup version");const e=yield this.baseApis.prepareKeyBackupVersion(null,{secureSecretStorage:!1}),t=(0,M.decodeRecoveryKey)(e.recovery_key);yield c.store("m.megolm_backup.v1",g.encodeBase64(t));const i={algorithm:e.algorithm,auth_data:e.auth_data};yield h(i.auth_data),yield this.signObject(i.auth_data),s.addSessionBackup(i)}const E=yield c.get("m.megolm_backup.v1");if(E){f.logger.info("Got session backup key from secret storage: caching");const e=G(E);if(e){const t=d||v;yield c.store("m.megolm_backup.v1",e,t?[t]:null)}const t=new Uint8Array(g.decodeBase64(e||E));s.addSessionBackupPrivateKeyToCache(t)}else if(this.backupManager.getKeyBackupEnabled()){const e=(yield this.getSessionBackupPrivateKey())||(yield null==r?void 0:r());if(!e)return void f.logger.error("Key backup is enabled but couldn't get key backup key!");f.logger.info("Got session backup key from cache/user that wasn't in SSSS: saving to SSSS"),yield c.store("m.megolm_backup.v1",g.encodeBase64(e))}const w=s.buildOperation();yield w.apply(this),yield s.persist(this),f.logger.log("Secure Secret Storage ready")}))}addSecretStorageKey(e,t,i){return this.secretStorage.addKey(e,t,i)}hasSecretStorageKey(e){return this.secretStorage.hasKey(e)}getSecretStorageKey(e){return this.secretStorage.getKey(e)}storeSecret(e,t,i){return this.secretStorage.store(e,t,i)}getSecret(e){return this.secretStorage.get(e)}isSecretStored(e){return this.secretStorage.isStored(e)}requestSecret(e,t){return t||(t=Object.keys(this.deviceList.getRawStoredDevicesForUser(this.userId))),this.secretStorage.request(e,t)}getDefaultSecretStorageKeyId(){return this.secretStorage.getDefaultKeyId()}setDefaultSecretStorageKeyId(e){return this.secretStorage.setDefaultKeyId(e)}checkSecretStorageKey(e,t){return this.secretStorage.checkKey(e,t)}checkSecretStoragePrivateKey(e,i){let n=null;try{n=new t.Olm.PkDecryption;return n.init_with_private_key(e)===i}finally{null==n||n.free()}}getSessionBackupPrivateKey(){return a(this,void 0,void 0,(function*(){let e=yield new Promise((e=>{this.cryptoStore.doTxn("readonly",[w.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{this.cryptoStore.getSecretStorePrivateKey(t,e,"m.megolm_backup.v1")}))}));if(e&&"string"==typeof e&&(e=new Uint8Array(g.decodeBase64(G(e)||e)),yield this.storeSessionBackupPrivateKey(e)),e&&e.ciphertext){const t=n.from(this.olmDevice.pickleKey),i=yield(0,D.decryptAES)(e,t,"m.megolm_backup.v1");e=g.decodeBase64(i)}return e}))}storeSessionBackupPrivateKey(e){return a(this,void 0,void 0,(function*(){if(!(e instanceof Uint8Array))throw new Error(`storeSessionBackupPrivateKey expects Uint8Array, got ${e}`);const t=n.from(this.olmDevice.pickleKey),i=yield(0,D.encryptAES)(g.encodeBase64(e),t,"m.megolm_backup.v1");return this.cryptoStore.doTxn("readwrite",[w.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.cryptoStore.storeSecretStorePrivateKey(e,"m.megolm_backup.v1",i)}))}))}checkCrossSigningPrivateKey(e,i){let n=null;try{n=new t.Olm.PkSigning;return n.init_with_seed(e)===i}finally{null==n||n.free()}}afterCrossSigningLocalKeyChange(){return a(this,void 0,void 0,(function*(){f.logger.info("Starting cross-signing key change post-processing");const e=this.deviceList.getStoredDevice(this.userId,this.deviceId),t=yield this.crossSigningInfo.signDevice(this.userId,e);f.logger.info(`Starting background key sig upload for ${this.deviceId}`);const i=({shouldEmit:e=!1})=>this.baseApis.uploadKeySignatures({[this.userId]:{[this.deviceId]:t}}).then((t=>{const{failures:n}=t||{};if(Object.keys(n||[]).length>0)throw e&&this.baseApis.emit(H.KeySignatureUploadFailure,n,"afterCrossSigningLocalKeyChange",i),new P.KeySignatureUploadError("Key upload failed",{failures:n});f.logger.info(`Finished background key sig upload for ${this.deviceId}`)})).catch((e=>{f.logger.error(`Error during background key sig upload for ${this.deviceId}`,e)}));i({shouldEmit:!0});const n=this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;if(n){f.logger.info("Starting device verification upgrade");const e={};for(const[t,i]of Object.entries(this.deviceList.crossSigningInfo)){const n=yield this.checkForDeviceVerificationUpgrade(t,b.CrossSigningInfo.fromStorage(i,t));n&&(e[t]=n)}if(Object.keys(e).length>0){f.logger.info(`Found ${Object.keys(e).length} verif users to upgrade`);try{const t=yield n({users:e});if(t)for(const i of t)i in e&&(yield this.baseApis.setDeviceVerified(i,e[i].crossSigningInfo.getId()))}catch(e){f.logger.log("shouldUpgradeDeviceVerifications threw an error: not upgrading",e)}}f.logger.info("Finished device verification upgrade")}f.logger.info("Finished cross-signing key change post-processing")}))}checkForDeviceVerificationUpgrade(e,t){return a(this,void 0,void 0,(function*(){const i=this.crossSigningInfo.checkUserTrust(t);if(t.firstUse&&!i.isVerified()){const i=this.deviceList.getRawStoredDevicesForUser(e),n=yield this.checkForValidDeviceSignature(e,t.keys.master,i);if(n.length)return{devices:n.map((e=>m.DeviceInfo.fromStorage(i[e],e))),crossSigningInfo:t}}}))}checkForValidDeviceSignature(e,t,i){return a(this,void 0,void 0,(function*(){const n=[];if(i&&t.signatures&&t.signatures[e])for(const r of Object.keys(t.signatures[e])){const[,o]=r.split(":",2);if(o in i&&i[o].verified===$.VERIFIED)try{yield g.verifySignature(this.olmDevice,t,e,o,i[o].keys[r]),n.push(o)}catch(e){}}return n}))}getCrossSigningId(e){return this.crossSigningInfo.getId(e)}getStoredCrossSigningForUser(e){return this.deviceList.getStoredCrossSigningForUser(e)}checkUserTrust(e){const t=this.deviceList.getStoredCrossSigningForUser(e);return t?this.crossSigningInfo.checkUserTrust(t):new b.UserTrustLevel(!1,!1,!1)}checkDeviceTrust(e,t){const i=this.deviceList.getStoredDevice(e,t);return this.checkDeviceInfoTrust(e,i)}checkDeviceInfoTrust(e,t){const i=!!(null==t?void 0:t.isVerified()),n=this.deviceList.getStoredCrossSigningForUser(e);if(t&&n){const r=this.trustCrossSignedDevices||e===this.userId;return this.crossSigningInfo.checkDeviceTrust(n,t,i,r)}return new b.DeviceTrustLevel(!1,!1,i,!1)}checkIfOwnDeviceCrossSigned(e){var t;const i=this.deviceList.getStoredDevice(this.userId,e);if(!i)return!1;const n=this.deviceList.getStoredCrossSigningForUser(this.userId);return null!==(t=null==n?void 0:n.checkDeviceTrust(n,i,!1,!0).isCrossSigningVerified())&&void 0!==t&&t}checkOwnCrossSigningTrust({allowPrivateKeyRequests:e=!1}={}){return a(this,void 0,void 0,(function*(){const t=this.userId;yield this.downloadKeys([this.userId]);const i=yield this.crossSigningInfo.getCrossSigningKeysFromCache(),n=this.deviceList.getStoredCrossSigningForUser(t);if(!n)return void f.logger.error("Got cross-signing update event for user "+t+" but no new cross-signing information found!");const r=n.getId(),o=this.crossSigningInfo.getId()!==r,s=n.getId()&&!i.has("master");if(o&&f.logger.info("Got new master public key",r),e&&(o||s)){f.logger.info("Attempting to retrieve cross-signing master private key");let e=null;try{e=(yield this.crossSigningInfo.getCrossSigningKey("master",r))[1],f.logger.info("Got cross-signing master private key")}finally{null==e||e.free()}}const a=this.crossSigningInfo.getId("self_signing"),c=this.crossSigningInfo.getId("user_signing");this.storeTrustedSelfKeys(n.keys);const d=a!==n.getId("self_signing"),l=c!==n.getId("user_signing"),u=n.getId("self_signing")&&!i.has("self_signing"),h=n.getId("user_signing")&&!i.has("user_signing"),p={};if(d&&f.logger.info("Got new self-signing key",n.getId("self_signing")),e&&(d||u)){f.logger.info("Attempting to retrieve cross-signing self-signing private key");let e=null;try{e=(yield this.crossSigningInfo.getCrossSigningKey("self_signing",n.getId("self_signing")))[1],f.logger.info("Got cross-signing self-signing private key")}finally{null==e||e.free()}const t=this.deviceList.getStoredDevice(this.userId,this.deviceId),i=yield this.crossSigningInfo.signDevice(this.userId,t);p[this.deviceId]=i}if(l&&f.logger.info("Got new user-signing key",n.getId("user_signing")),e&&(l||h)){f.logger.info("Attempting to retrieve cross-signing user-signing private key");let e=null;try{e=(yield this.crossSigningInfo.getCrossSigningKey("user_signing",n.getId("user_signing")))[1],f.logger.info("Got cross-signing user-signing private key")}finally{null==e||e.free()}}if(o){const e=this.crossSigningInfo.keys.master;yield this.signObject(e);const t=e.signatures[this.userId]["ed25519:"+this.deviceId];p[this.crossSigningInfo.getId()]=Object.assign({},e,{signatures:{[this.userId]:{["ed25519:"+this.deviceId]:t}}})}const g=Object.keys(p);if(g.length){const e=({shouldEmit:t=!1})=>(f.logger.info(`Starting background key sig upload for ${g}`),this.baseApis.uploadKeySignatures({[this.userId]:p}).then((i=>{const{failures:n}=i||{};if(f.logger.info(`Finished background key sig upload for ${g}`),Object.keys(n||[]).length>0)throw t&&this.baseApis.emit(H.KeySignatureUploadFailure,n,"checkOwnCrossSigningTrust",e),new P.KeySignatureUploadError("Key upload failed",{failures:n})})).catch((e=>{f.logger.error(`Error during background key sig upload for ${g}`,e)})));e({shouldEmit:!0})}this.emit(H.UserTrustStatusChanged,t,this.checkUserTrust(t)),o&&(this.emit(H.KeysChanged,{}),yield this.afterCrossSigningLocalKeyChange()),yield this.backupManager.checkKeyBackup()}))}storeTrustedSelfKeys(e){return a(this,void 0,void 0,(function*(){e?this.crossSigningInfo.setKeys(e):this.crossSigningInfo.clearKeys(),yield this.cryptoStore.doTxn("readwrite",[w.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.cryptoStore.storeCrossSigningKeys(e,this.crossSigningInfo.keys)}))}))}checkDeviceVerifications(e){return a(this,void 0,void 0,(function*(){const t=this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;if(t){if(f.logger.info(`Starting device verification upgrade for ${e}`),this.crossSigningInfo.keys.user_signing){const i=this.deviceList.getStoredCrossSigningForUser(e);if(i){const n=yield this.checkForDeviceVerificationUpgrade(e,i);if(n){(yield t({users:{[e]:n}})).includes(e)&&(yield this.baseApis.setDeviceVerified(e,i.getId()))}}}f.logger.info(`Finished device verification upgrade for ${e}`)}}))}enableLazyLoading(){this.lazyLoadMembers=!0}registerEventHandlers(e){e.on(B.RoomMemberEvent.Membership,this.onMembership),e.on(j.ClientEvent.ToDeviceEvent,this.onToDeviceEvent),e.on(U.RoomEvent.Timeline,this.onTimelineEvent),e.on(N.MatrixEventEvent.Decrypted,this.onTimelineEvent)}start(){f.logger.warn("MatrixClient.crypto.start() is deprecated")}stop(){this.outgoingRoomKeyRequestManager.stop(),this.deviceList.stop(),this.dehydrationManager.stop()}getDeviceEd25519Key(){return this.olmDevice.deviceEd25519Key}getDeviceCurve25519Key(){return this.olmDevice.deviceCurve25519Key}setGlobalBlacklistUnverifiedDevices(e){this.globalBlacklistUnverifiedDevices=e}getGlobalBlacklistUnverifiedDevices(){return this.globalBlacklistUnverifiedDevices}uploadDeviceKeys(){const e={algorithms:this.supportedAlgorithms,device_id:this.deviceId,keys:this.deviceKeys,user_id:this.userId};return this.signObject(e).then((()=>this.baseApis.uploadKeysRequest({device_keys:e})))}updateOneTimeKeyCount(e){if(!isFinite(e))throw new TypeError("Parameter for updateOneTimeKeyCount has to be a number");this.oneTimeKeyCount=e}setNeedsNewFallback(e){this.needsNewFallback=e}getNeedsNewFallback(){return!!this.needsNewFallback}maybeUploadOneTimeKeys(){if(this.oneTimeKeyCheckInProgress)return;const e=Date.now();if(null!==this.lastOneTimeKeyCheck&&e-this.lastOneTimeKeyCheck<6e4)return;this.lastOneTimeKeyCheck=e;const t=this.olmDevice.maxNumberOfOneTimeKeys(),i=Math.floor(t/2),n=e=>a(this,void 0,void 0,(function*(){for(;i>e||this.getNeedsNewFallback();){if(i>e){f.logger.info("generating oneTimeKeys");const t=Math.min(i-e,5);yield this.olmDevice.generateOneTimeKeys(t)}if(this.getNeedsNewFallback()){const e=yield this.olmDevice.getFallbackKey();e.curve25519&&0!=Object.keys(e.curve25519).length||(f.logger.info("generating fallback key"),this.fallbackCleanup&&(clearTimeout(this.fallbackCleanup),delete this.fallbackCleanup),yield this.olmDevice.generateFallbackKey())}f.logger.info("calling uploadOneTimeKeys");const t=yield this.uploadOneTimeKeys();if(!t.one_time_key_counts||!t.one_time_key_counts.signed_curve25519)throw new Error("response for uploading keys does not contain one_time_key_counts.signed_curve25519");e=t.one_time_key_counts.signed_curve25519}}));this.oneTimeKeyCheckInProgress=!0,Promise.resolve().then((()=>void 0!==this.oneTimeKeyCount?Promise.resolve(this.oneTimeKeyCount):this.baseApis.uploadKeysRequest({}).then((e=>e.one_time_key_counts.signed_curve25519||0)))).then((e=>n(e))).catch((e=>{f.logger.error("Error uploading one-time keys",e.stack||e)})).finally((()=>{this.oneTimeKeyCount=void 0,this.oneTimeKeyCheckInProgress=!1}))}uploadOneTimeKeys(){return a(this,void 0,void 0,(function*(){const e=[];let t;if(this.getNeedsNewFallback()){t={};const i=yield this.olmDevice.getFallbackKey();for(const[n,r]of Object.entries(i.curve25519)){const i={key:r,fallback:!0};t["signed_curve25519:"+n]=i,e.push(this.signObject(i))}this.setNeedsNewFallback(!1)}const i=yield this.olmDevice.getOneTimeKeys(),n={};for(const t in i.curve25519)if(i.curve25519.hasOwnProperty(t)){const r={key:i.curve25519[t]};n["signed_curve25519:"+t]=r,e.push(this.signObject(r))}yield Promise.all(e);const r={one_time_keys:n};t&&(r["org.matrix.msc2732.fallback_keys"]=t,r.fallback_keys=t);const o=yield this.baseApis.uploadKeysRequest(r);return t&&(this.fallbackCleanup=setTimeout((()=>{delete this.fallbackCleanup,this.olmDevice.forgetOldFallbackKey()}),36e5)),yield this.olmDevice.markKeysAsPublished(),o}))}downloadKeys(e,t){return this.deviceList.downloadKeys(e,!!t)}getStoredDevicesForUser(e){return this.deviceList.getStoredDevicesForUser(e)}getStoredDevice(e,t){return this.deviceList.getStoredDevice(e,t)}saveDeviceList(e){return this.deviceList.saveIfDirty(e)}setDeviceVerification(e,t,i=null,n=null,r=null,o){return a(this,void 0,void 0,(function*(){const s=this.deviceList.getStoredCrossSigningForUser(e);if(s&&s.getId()===t){if(null!==n||null!==r)throw new Error("Cannot set blocked or known for a cross-signing key");if(!i)throw new Error("Cannot set a cross-signing key as unverified");const c=o?Object.values(o)[0]:null;if(o&&(1!==Object.values(o).length||c!==s.getId()))throw new Error(`Key did not match expected value: expected ${s.getId()}, got ${c}`);if(this.crossSigningInfo.getId()||e!==this.crossSigningInfo.userId||(this.storeTrustedSelfKeys(s.keys),this.emit(H.UserTrustStatusChanged,this.userId,this.checkUserTrust(e))),e!==this.userId){f.logger.info("Master key "+s.getId()+" for "+e+" marked verified. Signing...");const i=yield this.crossSigningInfo.signUser(s);if(i){const n=({shouldEmit:r=!1})=>a(this,void 0,void 0,(function*(){f.logger.info("Uploading signature for "+e+"...");const o=yield this.baseApis.uploadKeySignatures({[e]:{[t]:i}}),{failures:s}=o||{};if(Object.keys(s||[]).length>0)throw r&&this.baseApis.emit(H.KeySignatureUploadFailure,s,"setDeviceVerification",n),new P.KeySignatureUploadError("Key upload failed",{failures:s})}));yield n({shouldEmit:!0})}return i}return s}const c=this.deviceList.getRawStoredDevicesForUser(e);if(!c||!c[t])throw new Error("Unknown device "+e+":"+t);const d=c[t];let l=d.verified;if(i){if(o)for(const[e,t]of Object.entries(o))if(d.keys[e]!==t)throw new Error(`Key did not match expected value: expected ${t}, got ${d.keys[e]}`);l=$.VERIFIED}else null!==i&&l==$.VERIFIED&&(l=$.UNVERIFIED);n?l=$.BLOCKED:null!==n&&l==$.BLOCKED&&(l=$.UNVERIFIED);let u=d.known;if(null!==r&&(u=r),d.verified===l&&d.known===u||(d.verified=l,d.known=u,this.deviceList.storeDevicesForUser(e,c),this.deviceList.saveIfDirty()),i&&e===this.userId){let i;f.logger.info("Own device "+t+" marked verified: signing");if(this.checkDeviceTrust(e,t).isCrossSigningVerified()?f.logger.log(`Own device ${t} already cross-signing verified`):i=yield this.crossSigningInfo.signDevice(e,m.DeviceInfo.fromStorage(d,t)),i){const n=({shouldEmit:r=!1})=>a(this,void 0,void 0,(function*(){f.logger.info("Uploading signature for "+t);const o=yield this.baseApis.uploadKeySignatures({[e]:{[t]:i}}),{failures:s}=o||{};if(Object.keys(s||[]).length>0)throw r&&this.baseApis.emit(H.KeySignatureUploadFailure,s,"setDeviceVerification",n),new P.KeySignatureUploadError("Key upload failed",{failures:s})}));yield n({shouldEmit:!0})}}const h=m.DeviceInfo.fromStorage(d,t);return this.emit(H.DeviceVerificationChanged,e,t,h),h}))}findVerificationRequestDMInProgress(e){return this.inRoomVerificationRequests.findRequestInProgress(e)}getVerificationRequestsToDeviceInProgress(e){return this.toDeviceVerificationRequests.getRequestsInProgress(e)}requestVerificationDM(e,t){const i=this.inRoomVerificationRequests.findRequestInProgress(t);if(i)return Promise.resolve(i);const n=new C.InRoomChannel(this.baseApis,t,e);return this.requestVerificationWithChannel(e,n,this.inRoomVerificationRequests)}requestVerification(e,t){t||(t=Object.keys(this.deviceList.getRawStoredDevicesForUser(e)));const i=this.toDeviceVerificationRequests.findRequestInProgress(e,t);if(i)return Promise.resolve(i);const n=new O.ToDeviceChannel(this.baseApis,e,t,O.ToDeviceChannel.makeTransactionId());return this.requestVerificationWithChannel(e,n,this.toDeviceVerificationRequests)}requestVerificationWithChannel(e,t,i){return a(this,void 0,void 0,(function*(){let e=new k.VerificationRequest(t,this.verificationMethods,this.baseApis);t.transactionId&&i.setRequestByChannel(t,e),yield e.sendRequest();const n=i.getRequestByChannel(t);return n?e=n:(f.logger.log(`Crypto: adding new request to requestsByTxnId with id ${t.transactionId} ${t.roomId}`),i.setRequestByChannel(t,e)),e}))}beginKeyVerification(e,t,i,n=null){let r;if(n){if(r=this.toDeviceVerificationRequests.getRequestBySenderAndTxnId(t,n),!r)throw new Error(`No request found for user ${t} with transactionId ${n}`)}else{n=O.ToDeviceChannel.makeTransactionId();const e=new O.ToDeviceChannel(this.baseApis,t,[i],n,i);r=new k.VerificationRequest(e,this.verificationMethods,this.baseApis),this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(t,n,r)}return r.beginKeyVerification(e,{userId:t,deviceId:i})}legacyDeviceVerification(e,t,i){return a(this,void 0,void 0,(function*(){const n=O.ToDeviceChannel.makeTransactionId(),r=new O.ToDeviceChannel(this.baseApis,e,[t],n,t),o=new k.VerificationRequest(r,this.verificationMethods,this.baseApis);this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(e,n,o);const s=o.beginKeyVerification(i,{userId:e,deviceId:t});return yield Promise.race([s.verify(),o.waitFor((e=>e.started))]),o}))}getOlmSessionsForUser(e){return a(this,void 0,void 0,(function*(){const t=this.getStoredDevicesForUser(e)||[],i={};for(const e of t){const t=e.getIdentityKey(),n=yield this.olmDevice.getSessionInfoForDevice(t);i[e.deviceId]={deviceIdKey:t,sessions:n}}return i}))}getEventSenderDeviceInfo(e){const t=e.getSenderKey(),i=e.getWireContent().algorithm;if(!t||!i)return null;if(e.isKeySourceUntrusted())return null;const n=this.deviceList.getDeviceByIdentityKey(i,t);if(null===n)return null;const r=e.getClaimedEd25519Key();return r?r!==n.getFingerprint()?(f.logger.warn("Event "+e.getId()+" claims ed25519 key "+r+" but sender device has key "+n.getFingerprint()),null):n:(f.logger.warn("Event "+e.getId()+" claims no ed25519 key: cannot verify sending device"),null)}getEventEncryptionInfo(e){var t,i;const n={};if(n.senderKey=null!==(t=e.getSenderKey())&&void 0!==t?t:void 0,n.algorithm=e.getWireContent().algorithm,!n.senderKey||!n.algorithm)return n.encrypted=!1,n;n.encrypted=!0,e.isKeySourceUntrusted()?n.authenticated=!1:n.authenticated=!0,n.sender=null!==(i=this.deviceList.getDeviceByIdentityKey(n.algorithm,n.senderKey))&&void 0!==i?i:void 0;const r=e.getClaimedEd25519Key();return r||(f.logger.warn("Event "+e.getId()+" claims no ed25519 key: cannot verify sending device"),n.mismatchedSender=!0),n.sender&&r!==n.sender.getFingerprint()&&(f.logger.warn("Event "+e.getId()+" claims ed25519 key "+r+"but sender device has key "+n.sender.getFingerprint()),n.mismatchedSender=!0),n}forceDiscardSession(e){const t=this.roomEncryptors.get(e);if(void 0===t)throw new Error("Room not encrypted");if(void 0===t.forceDiscardSession)throw new Error("Room encryption algorithm doesn't support session discarding");return t.forceDiscardSession(),Promise.resolve()}setRoomEncryption(e,t,i){return a(this,void 0,void 0,(function*(){const n=this.clientStore.getRoom(e);if(!n)throw new Error(`Unable to enable encryption tracking devices in unknown room ${e}`);yield this.setRoomEncryptionImpl(n,t),this.lazyLoadMembers||i||this.deviceList.refreshOutdatedDeviceLists()}))}setRoomEncryptionImpl(e,t){return a(this,void 0,void 0,(function*(){const i=e.roomId;if(!t.algorithm)return void f.logger.log("Ignoring setRoomEncryption with no algorithm");const n=this.roomList.getRoomEncryption(i);if(n&&JSON.stringify(n)!=JSON.stringify(t))return void f.logger.error("Ignoring m.room.encryption event which requests a change of config in "+i);if(this.roomEncryptors.get(i))return;let r=null;n||(r=this.roomList.setRoomEncryption(i,t));const o=y.ENCRYPTION_CLASSES.get(t.algorithm);if(!o)throw new Error("Unable to encrypt with "+t.algorithm);const s=new o({userId:this.userId,deviceId:this.deviceId,crypto:this,olmDevice:this.olmDevice,baseApis:this.baseApis,roomId:i,config:t});if(this.roomEncryptors.set(i,s),r&&(yield r),f.logger.log(`Enabling encryption in ${i}`),e.membersLoaded())yield this.trackRoomDevicesImpl(e);else{const t=n=>{e.off(K.RoomStateEvent.Update,t),e.membersLoaded()&&this.trackRoomDevicesImpl(e).catch((e=>{f.logger.error(`Error enabling device tracking in ${i}`,e)}))};e.on(K.RoomStateEvent.Update,t)}}))}trackRoomDevices(e){const t=this.clientStore.getRoom(e);if(!t)throw new Error(`Unable to start tracking devices in unknown room ${e}`);return this.trackRoomDevicesImpl(t)}trackRoomDevicesImpl(e){const t=e.roomId,i=()=>a(this,void 0,void 0,(function*(){if(!this.roomEncryptors.has(t))return;f.logger.log(`Starting to track devices for room ${t} ...`);(yield e.getEncryptionTargetMembers()).forEach((e=>{this.deviceList.startTrackingDeviceList(e.userId)}))}));let n=this.roomDeviceTrackingState[t];return n||(n=i(),this.roomDeviceTrackingState[t]=n.catch((e=>{throw delete this.roomDeviceTrackingState[t],e}))),n}ensureOlmSessionsForUsers(e,t){const i=new Map;for(const t of e){const e=[];i.set(t,e);const n=this.getStoredDevicesForUser(t)||[];for(const t of n){t.getIdentityKey()!=this.olmDevice.deviceCurve25519Key&&(t.verified!=$.BLOCKED&&e.push(t))}}return g.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,i,t)}exportRoomKeys(){return a(this,void 0,void 0,(function*(){const e=[];return yield this.cryptoStore.doTxn("readonly",[w.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS],(t=>{this.cryptoStore.getAllEndToEndInboundGroupSessions(t,(t=>{if(null===t)return;const i=this.olmDevice.exportInboundGroupSession(t.senderKey,t.sessionId,t.sessionData);delete i.first_known_index,i.algorithm=g.MEGOLM_ALGORITHM,e.push(i)}))})),e}))}importRoomKeys(e,t={}){let i=0,n=0;const r=e.length;function o(){var e;null===(e=t.progressCallback)||void 0===e||e.call(t,{stage:"load_keys",successes:i,failures:n,total:r})}return Promise.all(e.map((e=>{if(!e.room_id||!e.algorithm)return f.logger.warn("ignoring room key entry with missing fields",e),n++,t.progressCallback&&o(),null;return this.getRoomDecryptor(e.room_id,e.algorithm).importRoomKey(e,t).finally((()=>{i++,t.progressCallback&&o()}))}))).then()}countSessionsNeedingBackup(){return this.backupManager.countSessionsNeedingBackup()}prepareToEncrypt(e){const t=this.roomEncryptors.get(e.roomId);t&&t.prepareToEncrypt(e)}encryptEvent(e,t){return a(this,void 0,void 0,(function*(){const i=e.getRoomId(),n=this.roomEncryptors.get(i);if(!n)throw new Error("Room "+i+" was previously configured to use encryption, but is no longer. Perhaps the homeserver is hiding the configuration event.");yield this.trackRoomDevicesImpl(t);let r=e.getContent();const o=r["m.relates_to"];o&&(r=Object.assign({},r),delete r["m.relates_to"]);const s=r["io.element.performance_metrics"];s&&(r=Object.assign({},r),delete r["io.element.performance_metrics"]);const a=yield n.encryptMessage(t,e.getType(),r);o&&(a["m.relates_to"]=o),s&&(a["io.element.performance_metrics"]=s),e.makeEncrypted("m.room.encrypted",a,this.olmDevice.deviceCurve25519Key,this.olmDevice.deviceEd25519Key)}))}decryptEvent(e){return a(this,void 0,void 0,(function*(){if(e.isRedacted()){const t=new N.MatrixEvent(Object.assign({room_id:e.getRoomId()},e.getUnsigned().redacted_because));let i=e.getUnsigned().redacted_because;if(t.isEncrypted())try{i=(yield this.decryptEvent(t)).clearEvent}catch(e){f.logger.warn("Decryption of redaction failed. Falling back to unencrypted event.",e)}return{clearEvent:{room_id:e.getRoomId(),type:"m.room.message",content:{},unsigned:{redacted_because:i}}}}{const t=e.getWireContent();return this.getRoomDecryptor(e.getRoomId(),t.algorithm).decryptEvent(e)}}))}handleDeviceListChanges(e,t){return a(this,void 0,void 0,(function*(){e.oldSyncToken&&(yield this.evalDeviceListChanges(t))}))}requestRoomKey(e,t,i=!1){return this.outgoingRoomKeyRequestManager.queueRoomKeyRequest(e,t,i).then((()=>{this.sendKeyRequestsImmediately&&this.outgoingRoomKeyRequestManager.sendQueuedRequests()})).catch((e=>{f.logger.error("Error requesting key for event",e)}))}cancelRoomKeyRequest(e){this.outgoingRoomKeyRequestManager.cancelRoomKeyRequest(e).catch((e=>{f.logger.warn("Error clearing pending room key requests",e)}))}cancelAndResendAllOutgoingKeyRequests(){return a(this,void 0,void 0,(function*(){yield this.outgoingRoomKeyRequestManager.cancelAndResendAllOutgoingRequests()}))}onCryptoEvent(e,t){return a(this,void 0,void 0,(function*(){const i=t.getContent();yield this.setRoomEncryptionImpl(e,i)}))}onSyncWillProcess(e){return a(this,void 0,void 0,(function*(){e.oldSyncToken||(f.logger.log("Initial sync performed - resetting device tracking state"),this.deviceList.stopTrackingAllDeviceLists(),this.deviceList.startTrackingDeviceList(this.userId),this.roomDeviceTrackingState={}),this.sendKeyRequestsImmediately=!1}))}onSyncCompleted(e){var t;return a(this,void 0,void 0,(function*(){this.deviceList.setSyncToken(null!==(t=e.nextSyncToken)&&void 0!==t?t:null),this.deviceList.saveIfDirty(),this.deviceList.startTrackingDeviceList(this.userId),this.deviceList.refreshOutdatedDeviceLists(),e.catchingUp||(this.maybeUploadOneTimeKeys(),this.processReceivedRoomKeyRequests(),this.outgoingRoomKeyRequestManager.sendQueuedRequests(),this.sendKeyRequestsImmediately=!0)}))}evalDeviceListChanges(e){return a(this,void 0,void 0,(function*(){if(Array.isArray(null==e?void 0:e.changed)&&e.changed.forEach((e=>{this.deviceList.invalidateUserDeviceList(e)})),Array.isArray(null==e?void 0:e.left)&&e.left.length){const t=new Set(yield this.getTrackedE2eUsers());e.left.forEach((e=>{t.has(e)||this.deviceList.stopTrackingDeviceList(e)}))}}))}getTrackedE2eUsers(){return a(this,void 0,void 0,(function*(){const e=[];for(const t of this.getTrackedE2eRooms()){const i=yield t.getEncryptionTargetMembers();for(const t of i)e.push(t.userId)}return e}))}getTrackedE2eRooms(){return this.clientStore.getRooms().filter((e=>{if(!this.roomEncryptors.get(e.roomId))return!1;if(!this.roomDeviceTrackingState[e.roomId])return!1;const t=e.getMyMembership();return"join"===t||"invite"===t}))}encryptAndSendToDevices(e,t){return a(this,void 0,void 0,(function*(){const i={eventType:u.EventType.RoomMessageEncrypted,batch:[]};try{yield Promise.all(e.map((({userId:e,deviceInfo:n})=>a(this,void 0,void 0,(function*(){const r=n.deviceId,o={algorithm:g.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[u.ToDeviceMessageId]:(0,l.v4)()};i.batch.push({userId:e,deviceId:r,payload:o}),yield g.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,new Map([[e,[n]]])),yield g.encryptMessageForDevice(o.ciphertext,this.userId,this.deviceId,this.olmDevice,e,n,t)}))))),i.batch=i.batch.filter((e=>Object.keys(e.payload.ciphertext).length>0||(f.logger.log(`No ciphertext for device ${e.userId}:${e.deviceId}: pruning`),!1)));try{yield this.baseApis.queueToDevice(i)}catch(e){throw f.logger.error("sendToDevice failed",e),e}}catch(e){throw f.logger.error("encryptAndSendToDevices promises failed",e),e}}))}preprocessToDeviceMessages(e){return a(this,void 0,void 0,(function*(){return e.filter((e=>{var t;return!(e.type===u.EventType.RoomMessageEncrypted&&!["m.olm.v1.curve25519-aes-sha2"].includes(null===(t=e.content)||void 0===t?void 0:t.algorithm))||(f.logger.log("Ignoring invalid encrypted to-device event from "+e.sender),!1)}))}))}preprocessOneTimeKeyCounts(e){const t=e.get("signed_curve25519")||0;return this.updateOneTimeKeyCount(t),Promise.resolve()}preprocessUnusedFallbackKeys(e){return this.setNeedsNewFallback(!e.has("signed_curve25519")),Promise.resolve()}onRoomKeyEvent(e){const t=e.getContent();if(!t.room_id||!t.algorithm)return void f.logger.error("key event is missing fields");this.backupManager.checkedForBackup||this.backupManager.checkAndStart();this.getRoomDecryptor(t.room_id,t.algorithm).onRoomKeyEvent(e)}onRoomKeyWithheldEvent(e){const t=e.getContent();if(!(("m.no_olm"===t.code||t.room_id&&t.session_id)&&t.algorithm&&t.sender_key))return void f.logger.error("key withheld event is missing fields");f.logger.info(`Got room key withheld event from ${e.getSender()} for ${t.algorithm} session ${t.sender_key}|${t.session_id} in room ${t.room_id} with code ${t.code} (${t.reason})`);const i=this.getRoomDecryptor(t.room_id,t.algorithm);if(i.onRoomKeyWithheldEvent&&i.onRoomKeyWithheldEvent(e),!t.room_id){const e=this.getRoomDecryptors(t.algorithm);for(const i of e)i.retryDecryptionFromSender(t.sender_key)}}onKeyVerificationMessage(e){if(!O.ToDeviceChannel.validateEvent(e,this.baseApis))return;this.handleVerificationEvent(e,this.toDeviceVerificationRequests,(e=>{if(!O.ToDeviceChannel.canCreateRequest(O.ToDeviceChannel.getEventType(e)))return;const t=e.getContent(),i=t&&t.from_device;if(!i)return;const n=e.getSender(),r=new O.ToDeviceChannel(this.baseApis,n,[i]);return new k.VerificationRequest(r,this.verificationMethods,this.baseApis)}))}handleVerificationEvent(e,t,i,n=!0){return a(this,void 0,void 0,(function*(){if(e.isSending()&&e.status!=N.EventStatus.SENT){let t,i;try{yield new Promise(((n,r)=>{t=n,i=()=>{e.status==N.EventStatus.CANCELLED&&r(new Error("Event status set to CANCELLED."))},e.once(N.MatrixEventEvent.LocalEventIdReplaced,t),e.on(N.MatrixEventEvent.Status,i)}))}catch(e){return void f.logger.error("error while waiting for the verification event to be sent: ",e)}finally{e.removeListener(N.MatrixEventEvent.LocalEventIdReplaced,t),e.removeListener(N.MatrixEventEvent.Status,i)}}let r=t.getRequest(e),o=!1;if(!r){if(r=i(e),!r)return void f.logger.log(`Crypto: could not find VerificationRequest for ${e.getType()}, and could not create one, so ignoring.`);o=!0,t.setRequest(e,r)}e.setVerificationRequest(r);try{yield r.channel.handleEvent(e,r,n)}catch(e){f.logger.error("error while handling verification event",e)}o&&!r.initiatedByMe&&!r.invalid&&!r.observeOnly&&this.baseApis.emit(H.VerificationRequest,r)}))}onToDeviceBadEncrypted(e){return a(this,void 0,void 0,(function*(){const t=e.getWireContent(),i=e.getSender(),n=t.algorithm,r=t.sender_key;this.baseApis.emit(j.ClientEvent.UndecryptableToDeviceEvent,e);const o=()=>{const e=this.getRoomDecryptors(g.MEGOLM_ALGORITHM);for(const t of e)t.retryDecryptionFromSender(r)};if(void 0===i||void 0===r||void 0===r)return;const s=this.lastNewSessionForced.getOrCreate(i),a=s.getOrCreate(r);if(a+36e5>Date.now())return f.logger.debug("New session already forced with device "+i+":"+r+" at "+a+": not forcing another"),yield this.olmDevice.recordSessionProblem(r,"wedged",!0),void o();let c=this.deviceList.getDeviceByIdentityKey(n,r);if(!c&&(yield this.downloadKeys([i],!1),c=this.deviceList.getDeviceByIdentityKey(n,r),!c))return f.logger.info("Couldn't find device for identity key "+r+": not re-establishing session"),yield this.olmDevice.recordSessionProblem(r,"wedged",!1),void o();const d=new Map([[i,[c]]]);yield g.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,d,!0),s.set(r,Date.now());const h={algorithm:g.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{},[u.ToDeviceMessageId]:(0,l.v4)()};yield g.encryptMessageForDevice(h.ciphertext,this.userId,this.deviceId,this.olmDevice,i,c,{type:"m.dummy"}),yield this.olmDevice.recordSessionProblem(r,"wedged",!0),o(),yield this.baseApis.sendToDevice("m.room.encrypted",new Map([[i,new Map([[c.deviceId,h]])]]));const p=yield this.outgoingRoomKeyRequestManager.getOutgoingSentRoomKeyRequest(i,c.deviceId);for(const e of p)this.requestRoomKey(e.requestBody,e.recipients,!0)}))}onRoomMembership(e,t,i){var n;const r=t.roomId,o=this.roomEncryptors.get(r);o&&(r in this.roomDeviceTrackingState&&("join"==t.membership?(f.logger.log("Join event for "+t.userId+" in "+r),this.deviceList.startTrackingDeviceList(t.userId)):"invite"==t.membership&&(null===(n=this.clientStore.getRoom(r))||void 0===n?void 0:n.shouldEncryptForInvitedMembers())&&(f.logger.log("Invite event for "+t.userId+" in "+r),this.deviceList.startTrackingDeviceList(t.userId))),o.onRoomMembership(e,t,i))}onRoomKeyRequestEvent(e){const t=e.getContent();if("request"===t.action){const t=new z(e);this.receivedRoomKeyRequests.push(t)}else if("request_cancellation"===t.action){const t=new Y(e);this.receivedRoomKeyRequestCancellations.push(t)}}processReceivedRoomKeyRequests(){return a(this,void 0,void 0,(function*(){if(!this.processingRoomKeyRequests){this.processingRoomKeyRequests=!0;try{const e=this.receivedRoomKeyRequests;this.receivedRoomKeyRequests=[];const t=this.receivedRoomKeyRequestCancellations;this.receivedRoomKeyRequestCancellations=[],yield Promise.all(e.map((e=>this.processReceivedRoomKeyRequest(e)))),yield Promise.all(t.map((e=>this.processReceivedRoomKeyRequestCancellation(e))))}catch(e){f.logger.error(`Error processing room key requsts: ${e}`)}finally{this.processingRoomKeyRequests=!1}}}))}processReceivedRoomKeyRequest(e){return a(this,void 0,void 0,(function*(){const t=e.userId,i=e.deviceId,n=e.requestBody,r=n.room_id,o=n.algorithm;if(f.logger.log(`m.room_key_request from ${t}:${i} for ${r} / ${n.session_id} (id ${e.requestId})`),t!==this.userId){if(!this.roomEncryptors.get(r))return void f.logger.debug(`room key request for unencrypted room ${r}`);const e=this.roomEncryptors.get(r),o=this.deviceList.getStoredDevice(t,i);if(!o)return void f.logger.debug(`Ignoring keyshare for unknown device ${t}:${i}`);try{yield e.reshareKeyWithDevice(n.sender_key,n.session_id,t,o)}catch(e){f.logger.warn("Failed to re-share keys for session "+n.session_id+" with device "+t+":"+o.deviceId,e)}return}if(i===this.deviceId)return void f.logger.log("Ignoring room key request from ourselves");if(!this.roomDecryptors.has(r))return void f.logger.log(`room key request for unencrypted room ${r}`);const s=this.roomDecryptors.get(r).get(o);if(s)if(yield s.hasKeysForKeyRequest(e)){if(e.share=()=>{s.shareKeysWithDevice(e)},this.checkDeviceTrust(t,i).isVerified())return f.logger.log("device is already verified: sharing keys"),void e.share();this.emit(H.RoomKeyRequest,e)}else f.logger.log(`room key request for unknown session ${r} / `+n.session_id);else f.logger.log(`room key request for unknown alg ${o} in room ${r}`)}))}processReceivedRoomKeyRequestCancellation(e){return a(this,void 0,void 0,(function*(){f.logger.log(`m.room_key_request cancellation for ${e.userId}:${e.deviceId} (id ${e.requestId})`),this.emit(H.RoomKeyRequestCancellation,e)}))}getRoomDecryptor(e,t){let i,n;if(e&&(i=this.roomDecryptors.get(e),i||(i=new Map,this.roomDecryptors.set(e,i)),n=i.get(t),n))return n;const r=y.DECRYPTION_CLASSES.get(t);if(!r)throw new y.DecryptionError("UNKNOWN_ENCRYPTION_ALGORITHM",'Unknown encryption algorithm "'+t+'".');return n=new r({userId:this.userId,crypto:this,olmDevice:this.olmDevice,baseApis:this.baseApis,roomId:null!=e?e:void 0}),i&&i.set(t,n),n}getRoomDecryptors(e){const t=[];for(const i of this.roomDecryptors.values())i.has(e)&&t.push(i.get(e));return t}signObject(e){return a(this,void 0,void 0,(function*(){const t=new Map(Object.entries(e.signatures||{})),i=e.unsigned;delete e.signatures,delete e.unsigned;const n=t.get(this.userId)||{};t.set(this.userId,n),n["ed25519:"+this.deviceId]=yield this.olmDevice.sign(d.default.stringify(e)),e.signatures=(0,q.recursiveMapToObject)(t),void 0!==i&&(e.unsigned=i)}))}}function G(e){if("string"!=typeof e||e.indexOf(",")<0)return null;const t=Uint8Array.from(e.split(","),(e=>parseInt(e)));return g.encodeBase64(t)}i.Crypto=W,i.fixBackupKey=G;class z{constructor(e){const t=e.getContent();this.userId=e.getSender(),this.deviceId=t.requesting_device_id,this.requestId=t.request_id,this.requestBody=t.body||{},this.share=()=>{throw new Error("don't know how to share keys for this request yet")}}}i.IncomingRoomKeyRequest=z;class Y{constructor(e){const t=e.getContent();this.userId=e.getSender(),this.deviceId=t.requesting_device_id,this.requestId=t.request_id}}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"../@types/event":306,"../ReEmitter":317,"../client":321,"../errors":359,"../logger":374,"../models/event":383,"../models/room":392,"../models/room-member":389,"../models/room-state":390,"../models/typed-event-emitter":395,"../utils":416,"./CrossSigning":324,"./DeviceList":325,"./EncryptionSetup":326,"./OlmDevice":327,"./OutgoingRoomKeyRequestManager":328,"./SecretStorage":330,"./aes":331,"./algorithms":333,"./backup":337,"./dehydration":339,"./deviceinfo":340,"./key_passphrase":342,"./olmlib":343,"./recoverykey":344,"./store/indexeddb-crypto-store":346,"./verification/IllegalMethod":351,"./verification/QRCode":352,"./verification/SAS":353,"./verification/request/InRoomChannel":355,"./verification/request/ToDeviceChannel":356,"./verification/request/VerificationRequest":357,"another-json":1,buffer:68,uuid:287}],342:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.deriveKey=i.keyFromPassphrase=i.keyFromAuthData=void 0;const r=e("../randomstring"),o=e("./crypto"),s=5e5,a=256;function c(e,t,i,r=a){return n(this,void 0,void 0,(function*(){if(!o.subtleCrypto||!o.TextEncoder)throw new Error("Password-based backup is not available on this platform");const n=yield o.subtleCrypto.importKey("raw",(new o.TextEncoder).encode(e),{name:"PBKDF2"},!1,["deriveBits"]),s=yield o.subtleCrypto.deriveBits({name:"PBKDF2",salt:(new o.TextEncoder).encode(t),iterations:i,hash:"SHA-512"},n,r);return new Uint8Array(s)}))}i.keyFromAuthData=function(e,i){if(!t.Olm)throw new Error("Olm is not available");if(!e.private_key_salt||!e.private_key_iterations)throw new Error("Salt and/or iterations not found: this backup cannot be restored with a passphrase");return c(i,e.private_key_salt,e.private_key_iterations,e.private_key_bits||a)},i.keyFromPassphrase=function(e){return n(this,void 0,void 0,(function*(){if(!t.Olm)throw new Error("Olm is not available");const i=(0,r.randomString)(32);return{key:yield c(e,i,s,a),salt:i,iterations:s}}))},i.deriveKey=c}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../randomstring":398,"./crypto":338}],343:[function(e,t,i){(function(t,n){(function(){"use strict";var r=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(i,"__esModule",{value:!0}),i.decodeBase64=i.encodeUnpaddedBase64=i.encodeBase64=i.isOlmEncrypted=i.pkVerify=i.pkSign=i.verifySignature=i.ensureOlmSessionsForDevices=i.getExistingOlmSessions=i.encryptMessageForDevice=i.MEGOLM_BACKUP_ALGORITHM=i.MEGOLM_ALGORITHM=i.OLM_ALGORITHM=void 0;const s=o(e("another-json")),a=e("../logger"),c=e("../@types/event"),d=e("../utils");var l;function u(e,t,i,n){return r(this,void 0,void 0,(function*(){const r=n.deviceId;try{yield h(e,t,i,r,n.getFingerprint())}catch(e){return a.logger.error("Unable to verify signature on one-time key for device "+i+":"+r+":",e),null}let o;try{o=yield e.createOutboundSession(n.getIdentityKey(),t.key)}catch(e){return a.logger.error("Error starting olm session with device "+i+":"+r+": "+e),null}return a.logger.log("Started new olm sessionid "+o+" for device "+i+":"+r),o}))}function h(e,t,i,n,o){return r(this,void 0,void 0,(function*(){const r="ed25519:"+n,a=((t.signatures||{})[i]||{})[r];if(!a)throw Error("No signature");const c=Object.assign({},t);"unsigned"in c&&delete c.unsigned,delete c.signatures;const d=s.default.stringify(c);e.verifySignature(o,d,a)}))}function f(e){return n.from(e).toString("base64")}!function(e){e.Olm="m.olm.v1.curve25519-aes-sha2",e.Megolm="m.megolm.v1.aes-sha2",e.MegolmBackup="m.megolm_backup.v1.curve25519-aes-sha2"}(l||(l={})),i.OLM_ALGORITHM=l.Olm,i.MEGOLM_ALGORITHM=l.Megolm,i.MEGOLM_BACKUP_ALGORITHM=l.MegolmBackup,i.encryptMessageForDevice=function(e,t,i,n,o,s,c){return r(this,void 0,void 0,(function*(){const r=s.getIdentityKey(),d=yield n.getSessionIdForDevice(r);if(null===d)return void a.logger.log(`[olmlib.encryptMessageForDevice] Unable to find Olm session for device ${o}:${s.deviceId}`);a.logger.log(`[olmlib.encryptMessageForDevice] Using Olm session ${d} for device ${o}:${s.deviceId}`);const l=Object.assign({sender:t,sender_device:i,keys:{ed25519:n.deviceEd25519Key},recipient:o,recipient_keys:{ed25519:s.getFingerprint()}},c);e[r]=yield n.encryptMessage(r,d,JSON.stringify(l))}))},i.getExistingOlmSessions=function(e,t,i){return r(this,void 0,void 0,(function*(){const t=new d.MapWithDefault((()=>[])),n=new d.MapWithDefault((()=>new Map)),o=[];for(const[s,a]of Object.entries(i))for(const i of a){const a=i.deviceId,c=i.getIdentityKey();o.push((()=>r(this,void 0,void 0,(function*(){const r=yield e.getSessionIdForDevice(c,!0);null===r?t.getOrCreate(s).push(i):n.getOrCreate(s).set(a,{device:i,sessionId:r})})))())}return yield Promise.all(o),[t,n]}))},i.ensureOlmSessionsForDevices=function(e,t,i,n=!1,o,s,c=a.logger){var d,l,h;return r(this,void 0,void 0,(function*(){const r=[],a=new Map,f=new Map;for(const t of i.values())for(const i of t){const t=i.getIdentityKey();t!==e.deviceCurve25519Key&&(e.sessionsInProgress[t]||(e.sessionsInProgress[t]=new Promise((i=>{f.set(t,(n=>{delete e.sessionsInProgress[t],i(n)}))}))))}for(const[t,o]of i){const i=new Map;a.set(t,i);for(const s of o){const o=s.deviceId,a=s.getIdentityKey();if(a===e.deviceCurve25519Key){c.info("Attempted to start session with ourself! Ignoring"),i.set(o,{device:s,sessionId:null});continue}const d=`for ${a} (${t}:${o})`,l=yield e.getSessionIdForDevice(a,!!f.get(a),c),u=f.get(a);null!==l&&u&&u(),(null===l||n)&&(n?c.info(`Forcing new Olm session ${d}`):c.info(`Making new Olm session ${d}`),r.push([t,o])),i.set(o,{device:s,sessionId:l})}}if(0===r.length)return a;const p="signed_curve25519";let g,v=`one-time keys for ${r.length} devices`;try{c.debug(`Claiming ${v}`),g=yield t.claimOneTimeKeys(r,p,o),c.debug(`Claimed ${v}`)}catch(e){for(const e of f.values())e();throw c.log(`Failed to claim ${v}`,e,r),e}s&&"failures"in g&&s.push(...Object.keys(g.failures));const m=g.one_time_keys||{},y=[];for(const[t,r]of i){const i=m[t]||{};for(const o of r){const r=o.deviceId,s=o.getIdentityKey();if(s===e.deviceCurve25519Key)continue;if((null===(l=null===(d=a.get(t))||void 0===d?void 0:d.get(r))||void 0===l?void 0:l.sessionId)&&!n)continue;const g=i[r]||{};let v=null;for(const e in g)0===e.indexOf(p+":")&&(v=g[e]);v?y.push(u(e,v,t,o).then((e=>{var i,n;null===(i=f.get(s))||void 0===i||i(null!=e?e:void 0);const o=null===(n=a.get(t))||void 0===n?void 0:n.get(r);o&&(o.sessionId=e)}),(e=>{var t;throw null===(t=f.get(s))||void 0===t||t(),e}))):(c.warn(`No one-time keys (alg=${p}) for device ${t}:${r}`),null===(h=f.get(s))||void 0===h||h())}}return v=`Olm sessions for ${y.length} devices`,c.debug(`Starting ${v}`),yield Promise.all(y),c.debug(`Started ${v}`),a}))},i.verifySignature=h,i.pkSign=function(e,i,n,r){let o=!1;if(i instanceof Uint8Array){const e=new t.Olm.PkSigning;r=e.init_with_seed(i),i=e,o=!0}const a=e.signatures||{};delete e.signatures;const c=e.unsigned;e.unsigned&&delete e.unsigned;try{const t=a[n]||{};return a[n]=t,t["ed25519:"+r]=i.sign(s.default.stringify(e))}finally{e.signatures=a,c&&(e.unsigned=c),o&&i.free()}},i.pkVerify=function(e,i,n){const r="ed25519:"+i;if(!(e.signatures&&e.signatures[n]&&e.signatures[n][r]))throw new Error("No signature");const o=e.signatures[n][r],a=new t.Olm.Utility,c=e.signatures;delete e.signatures;const d=e.unsigned;e.unsigned&&delete e.unsigned;try{a.ed25519_verify(i,s.default.stringify(e),o)}finally{e.signatures=c,d&&(e.unsigned=d),a.free()}},i.isOlmEncrypted=function(e){return e.getSenderKey()?!(e.getWireType()!==c.EventType.RoomMessageEncrypted||!["m.olm.v1.curve25519-aes-sha2"].includes(e.getWireContent().algorithm))||(a.logger.error("Event was not encrypted using an appropriate algorithm"),!1):(a.logger.error("Event has no sender key (not encrypted?)"),!1)},i.encodeBase64=f,i.encodeUnpaddedBase64=function(e){return f(e).replace(/=+$/g,"")},i.decodeBase64=function(e){return n.from(e,"base64")}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"../@types/event":306,"../logger":374,"../utils":416,"another-json":1,buffer:68}],344:[function(e,t,i){(function(t,n){(function(){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&r(t,e,i);return o(t,e),t};Object.defineProperty(i,"__esModule",{value:!0}),i.decodeRecoveryKey=i.encodeRecoveryKey=void 0;const a=s(e("bs58")),c=[139,1];i.encodeRecoveryKey=function(e){var t;const i=n.alloc(c.length+e.length+1);i.set(c,0),i.set(e,c.length);let r=0;for(let e=0;e{a.logger.log(`versionchange for indexeddb ${this.db.name}: closing`),e.close()}}startup(){return s(this,void 0,void 0,(function*(){return this}))}deleteAllData(){return s(this,void 0,void 0,(function*(){throw Error("This is not implemented, call IDBFactory::deleteDatabase(dbName) instead.")}))}getOrAddOutgoingRoomKeyRequest(e){const t=e.requestBody;return new Promise(((i,n)=>{const r=this.db.transaction("outgoingRoomKeyRequests","readwrite");r.onerror=n,this._getOutgoingRoomKeyRequest(r,t,(n=>{if(n)return a.logger.log(`already have key request outstanding for ${t.room_id} / ${t.session_id}: not sending another`),void i(n);a.logger.log(`enqueueing key request for ${t.room_id} / `+t.session_id),r.oncomplete=()=>{i(e)};r.objectStore("outgoingRoomKeyRequests").add(e)}))}))}getOutgoingRoomKeyRequest(e){return new Promise(((t,i)=>{const n=this.db.transaction("outgoingRoomKeyRequests","readonly");n.onerror=i,this._getOutgoingRoomKeyRequest(n,e,(e=>{t(e)}))}))}_getOutgoingRoomKeyRequest(e,t,i){const n=e.objectStore("outgoingRoomKeyRequests").index("session").openCursor([t.room_id,t.session_id]);n.onsuccess=()=>{const e=n.result;if(!e)return void i(null);const r=e.value;c.deepCompare(r.requestBody,t)?i(r):e.continue()}}getOutgoingRoomKeyRequestByState(e){if(0===e.length)return Promise.resolve(null);let t,i=0;const n=this.db.transaction("outgoingRoomKeyRequests","readonly"),r=n.objectStore("outgoingRoomKeyRequests"),o=e[i];return r.index("state").openCursor(o).onsuccess=function n(){const r=this.result;if(r)return void(t=r.value);if(i++,i>=e.length)return;const o=e[i];this.source.openCursor(o).onsuccess=n},u(n).then((()=>t))}getAllOutgoingRoomKeyRequestsByState(e){return new Promise(((t,i)=>{const n=this.db.transaction("outgoingRoomKeyRequests","readonly").objectStore("outgoingRoomKeyRequests").index("state").getAll(e);n.onsuccess=()=>t(n.result),n.onerror=()=>i(n.error)}))}getOutgoingRoomKeyRequestsByTarget(e,t,i){let n=0;const r=[];const o=this.db.transaction("outgoingRoomKeyRequests","readonly"),s=o.objectStore("outgoingRoomKeyRequests"),a=i[n];return s.index("state").openCursor(a).onsuccess=function o(){const s=this.result;if(s){const i=s.value;i.recipients.some((i=>i.userId===e&&i.deviceId===t))&&r.push(i),s.continue()}else{if(n++,n>=i.length)return;const e=i[n];this.source.openCursor(e).onsuccess=o}},u(o).then((()=>r))}updateOutgoingRoomKeyRequest(e,t,i){let n=null;const r=this.db.transaction("outgoingRoomKeyRequests","readwrite");return r.objectStore("outgoingRoomKeyRequests").openCursor(e).onsuccess=function(){const e=this.result;if(!e)return;const r=e.value;r.state==t?(Object.assign(r,i),e.update(r),n=r):a.logger.warn(`Cannot update room key request from ${t} as it was already updated to ${r.state}`)},u(r).then((()=>n))}deleteOutgoingRoomKeyRequest(e,t){const i=this.db.transaction("outgoingRoomKeyRequests","readwrite"),n=i.objectStore("outgoingRoomKeyRequests").openCursor(e);return n.onsuccess=()=>{const e=n.result;if(!e)return;const i=e.value;i.state==t?e.delete():a.logger.warn(`Cannot delete room key request in state ${i.state} (expected ${t})`)},u(i)}getAccount(e,t){const i=e.objectStore("account").get("-");i.onsuccess=function(){try{t(i.result||null)}catch(t){l(e,t)}}}storeAccount(e,t){e.objectStore("account").put(t,"-")}getCrossSigningKeys(e,t){const i=e.objectStore("account").get("crossSigningKeys");i.onsuccess=function(){try{t(i.result||null)}catch(t){l(e,t)}}}getSecretStorePrivateKey(e,t,i){const n=e.objectStore("account").get(`ssss_cache:${i}`);n.onsuccess=function(){try{t(n.result||null)}catch(t){l(e,t)}}}storeCrossSigningKeys(e,t){e.objectStore("account").put(t,"crossSigningKeys")}storeSecretStorePrivateKey(e,t,i){e.objectStore("account").put(i,`ssss_cache:${t}`)}countEndToEndSessions(e,t){const i=e.objectStore("sessions").count();i.onsuccess=function(){try{t(i.result)}catch(t){l(e,t)}}}getEndToEndSessions(e,t,i){const n=t.objectStore("sessions").index("deviceKey").openCursor(e),r={};n.onsuccess=function(){const e=n.result;if(e)r[e.value.sessionId]={session:e.value.session,lastReceivedMessageTs:e.value.lastReceivedMessageTs},e.continue();else try{i(r)}catch(e){l(t,e)}}}getEndToEndSession(e,t,i,n){const r=i.objectStore("sessions").get([e,t]);r.onsuccess=function(){try{r.result?n({session:r.result.session,lastReceivedMessageTs:r.result.lastReceivedMessageTs}):n(null)}catch(e){l(i,e)}}}getAllEndToEndSessions(e,t){const i=e.objectStore("sessions").openCursor();i.onsuccess=function(){try{const e=i.result;e?(t(e.value),e.continue()):t(null)}catch(t){l(e,t)}}}storeEndToEndSession(e,t,i,n){n.objectStore("sessions").put({deviceKey:e,sessionId:t,session:i.session,lastReceivedMessageTs:i.lastReceivedMessageTs})}storeEndToEndSessionProblem(e,t,i){return s(this,void 0,void 0,(function*(){const n=this.db.transaction("session_problems","readwrite");n.objectStore("session_problems").put({deviceKey:e,type:t,fixed:i,time:Date.now()}),yield u(n)}))}getEndToEndSessionProblem(e,t){return s(this,void 0,void 0,(function*(){let i=null;const n=this.db.transaction("session_problems","readwrite"),r=n.objectStore("session_problems").index("deviceKey").getAll(e);return r.onsuccess=()=>{const e=r.result;if(!e.length)return void(i=null);e.sort(((e,t)=>e.time-t.time));const n=e[e.length-1];for(const r of e)if(r.time>t)return void(i=Object.assign({},r,{fixed:n.fixed}));i=n.fixed?null:n},yield u(n),i}))}filterOutNotifiedErrorDevices(e){return s(this,void 0,void 0,(function*(){const t=this.db.transaction("notified_error_devices","readwrite").objectStore("notified_error_devices"),i=[];return yield Promise.all(e.map((e=>new Promise((n=>{const{userId:r,deviceInfo:o}=e,s=t.get([r,o.deviceId]);s.onsuccess=function(){s.result||(t.put({userId:r,deviceId:o.deviceId}),i.push(e)),n()}}))))),i}))}getEndToEndInboundGroupSession(e,t,i,n){let r=!1,o=!1;const s=i.objectStore("inbound_group_sessions").get([e,t]);s.onsuccess=function(){try{r=s.result?s.result.session:null,!1!==o&&n(r,o)}catch(e){l(i,e)}};const a=i.objectStore("inbound_group_sessions_withheld").get([e,t]);a.onsuccess=function(){try{o=a.result?a.result.session:null,!1!==r&&n(r,o)}catch(e){l(i,e)}}}getAllEndToEndInboundGroupSessions(e,t){const i=e.objectStore("inbound_group_sessions").openCursor();i.onsuccess=function(){const n=i.result;if(n){try{t({senderKey:n.value.senderCurve25519Key,sessionId:n.value.sessionId,sessionData:n.value.session})}catch(t){l(e,t)}n.continue()}else try{t(null)}catch(t){l(e,t)}}}addEndToEndInboundGroupSession(e,t,i,n){const r=n.objectStore("inbound_group_sessions").add({senderCurve25519Key:e,sessionId:t,session:i});r.onerror=i=>{var o;"ConstraintError"===(null===(o=r.error)||void 0===o?void 0:o.name)?(i.stopPropagation(),i.preventDefault(),a.logger.log("Ignoring duplicate inbound group session: "+e+" / "+t)):l(n,new Error("Failed to add inbound group session: "+r.error))}}storeEndToEndInboundGroupSession(e,t,i,n){n.objectStore("inbound_group_sessions").put({senderCurve25519Key:e,sessionId:t,session:i})}storeEndToEndInboundGroupSessionWithheld(e,t,i,n){n.objectStore("inbound_group_sessions_withheld").put({senderCurve25519Key:e,sessionId:t,session:i})}getEndToEndDeviceData(e,t){const i=e.objectStore("device_data").get("-");i.onsuccess=function(){try{t(i.result||null)}catch(t){l(e,t)}}}storeEndToEndDeviceData(e,t){t.objectStore("device_data").put(e,"-")}storeEndToEndRoom(e,t,i){i.objectStore("rooms").put(t,e)}getEndToEndRooms(e,t){const i={},n=e.objectStore("rooms").openCursor();n.onsuccess=function(){const r=n.result;if(r)i[r.key]=r.value,r.continue();else try{t(i)}catch(t){l(e,t)}}}getSessionsNeedingBackup(e){return new Promise(((t,i)=>{const n=[],r=this.db.transaction(["sessions_needing_backup","inbound_group_sessions"],"readonly");r.onerror=i,r.oncomplete=function(){t(n)};const o=r.objectStore("sessions_needing_backup"),s=r.objectStore("inbound_group_sessions"),a=o.openCursor();a.onsuccess=function(){const t=a.result;if(t){const i=s.get(t.key);i.onsuccess=function(){n.push({senderKey:i.result.senderCurve25519Key,sessionId:i.result.sessionId,sessionData:i.result.session})},(!e||n.length{const n=t.count();n.onerror=i,n.onsuccess=()=>e(n.result)}))}unmarkSessionsNeedingBackup(e,t){return s(this,void 0,void 0,(function*(){t||(t=this.db.transaction("sessions_needing_backup","readwrite"));const i=t.objectStore("sessions_needing_backup");yield Promise.all(e.map((e=>new Promise(((t,n)=>{const r=i.delete([e.senderKey,e.sessionId]);r.onsuccess=t,r.onerror=n})))))}))}markSessionsNeedingBackup(e,t){return s(this,void 0,void 0,(function*(){t||(t=this.db.transaction("sessions_needing_backup","readwrite"));const i=t.objectStore("sessions_needing_backup");yield Promise.all(e.map((e=>new Promise(((t,n)=>{const r=i.put({senderCurve25519Key:e.senderKey,sessionId:e.sessionId});r.onsuccess=t,r.onerror=n})))))}))}addSharedHistoryInboundGroupSession(e,t,i,n){n||(n=this.db.transaction("shared_history_inbound_group_sessions","readwrite"));const r=n.objectStore("shared_history_inbound_group_sessions"),o=r.get([e]);o.onsuccess=()=>{const{sessions:n}=o.result||{sessions:[]};n.push([t,i]),r.put({roomId:e,sessions:n})}}getSharedHistoryInboundGroupSessions(e,t){t||(t=this.db.transaction("shared_history_inbound_group_sessions","readonly"));const i=t.objectStore("shared_history_inbound_group_sessions").get([e]);return new Promise(((e,t)=>{i.onsuccess=()=>{const{sessions:t}=i.result||{sessions:[]};e(t)},i.onerror=t}))}addParkedSharedHistory(e,t,i){i||(i=this.db.transaction("parked_shared_history","readwrite"));const n=i.objectStore("parked_shared_history"),r=n.get([e]);r.onsuccess=()=>{const{parked:i}=r.result||{parked:[]};i.push(t),n.put({roomId:e,parked:i})}}takeParkedSharedHistory(e,t){t||(t=this.db.transaction("parked_shared_history","readwrite"));const i=t.objectStore("parked_shared_history").openCursor(e);return new Promise(((e,t)=>{i.onsuccess=()=>{const t=i.result;if(!t)return void e([]);const n=t.value;t.delete(),e(n)},i.onerror=t}))}doTxn(e,t,i,n=a.logger){const r=this.db.transaction(t,e),o=u(r),s=i(r);return o.then((()=>s))}};const d=[e=>{!function(e){const t=e.createObjectStore("outgoingRoomKeyRequests",{keyPath:"requestId"});t.createIndex("session",["requestBody.room_id","requestBody.session_id"]),t.createIndex("state","state")}(e)},e=>{e.createObjectStore("account")},e=>{e.createObjectStore("sessions",{keyPath:["deviceKey","sessionId"]}).createIndex("deviceKey","deviceKey")},e=>{e.createObjectStore("inbound_group_sessions",{keyPath:["senderCurve25519Key","sessionId"]})},e=>{e.createObjectStore("device_data")},e=>{e.createObjectStore("rooms")},e=>{e.createObjectStore("sessions_needing_backup",{keyPath:["senderCurve25519Key","sessionId"]})},e=>{e.createObjectStore("inbound_group_sessions_withheld",{keyPath:["senderCurve25519Key","sessionId"]})},e=>{e.createObjectStore("session_problems",{keyPath:["deviceKey","time"]}).createIndex("deviceKey","deviceKey"),e.createObjectStore("notified_error_devices",{keyPath:["userId","deviceId"]})},e=>{e.createObjectStore("shared_history_inbound_group_sessions",{keyPath:["roomId"]})},e=>{e.createObjectStore("parked_shared_history",{keyPath:["roomId"]})}];function l(e,t){e._mx_abortexception=t;try{e.abort()}catch(t){}}function u(e){return new Promise(((t,i)=>{e.oncomplete=()=>{void 0!==e._mx_abortexception&&i(e._mx_abortexception),t(null)},e.onerror=t=>{void 0!==e._mx_abortexception?i(e._mx_abortexception):(a.logger.log("Error performing indexeddb txn",t),i(e.error))},e.onabort=t=>{void 0!==e._mx_abortexception?i(e._mx_abortexception):(a.logger.log("Error performing indexeddb txn",t),i(e.error))}}))}i.VERSION=d.length,i.upgradeDatabase=function(e,t){a.logger.log(`Upgrading IndexedDBCryptoStore from version ${t} to ${i.VERSION}`),d.forEach(((i,n)=>{t<=n&&i(e)}))}},{"../../logger":374,"../../utils":416}],346:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(i,"__esModule",{value:!0}),i.IndexedDBCryptoStore=void 0;const s=e("../../logger"),a=e("./localStorage-crypto-store"),c=e("./memory-crypto-store"),d=o(e("./indexeddb-crypto-store-backend")),l=e("../../errors"),u=o(e("../../indexeddb-helpers"));class h{static exists(e,t){return u.exists(e,t)}constructor(e,t){this.indexedDB=e,this.dbName=t}startup(){return this.backendPromise||(this.backendPromise=new Promise(((e,t)=>{if(!this.indexedDB)return void t(new Error("no indexeddb support available"));s.logger.log(`connecting to indexeddb ${this.dbName}`);const i=this.indexedDB.open(this.dbName,d.VERSION);i.onupgradeneeded=e=>{const t=i.result,n=e.oldVersion;d.upgradeDatabase(t,n)},i.onblocked=()=>{s.logger.log("can't yet open IndexedDBCryptoStore because it is open elsewhere")},i.onerror=e=>{s.logger.log("Error connecting to indexeddb",e),t(i.error)},i.onsuccess=()=>{const t=i.result;s.logger.log(`connected to indexeddb ${this.dbName}`),e(new d.Backend(t))}})).then((e=>e.doTxn("readonly",[h.STORE_INBOUND_GROUP_SESSIONS,h.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],(t=>{e.getEndToEndInboundGroupSession("","",t,(()=>{}))})).then((()=>e)))).catch((e=>{if("VersionError"===e.name)throw s.logger.warn("Crypto DB is too new for us to use!",e),new l.InvalidCryptoStoreError(l.InvalidCryptoStoreState.TooNew);s.logger.warn(`unable to connect to indexeddb ${this.dbName}: falling back to localStorage store: ${e}`);try{return new a.LocalStorageCryptoStore(t.localStorage)}catch(e){return s.logger.warn(`unable to open localStorage: falling back to in-memory store: ${e}`),new c.MemoryCryptoStore}})).then((e=>(this.backend=e,e)))),this.backendPromise}deleteAllData(){return new Promise(((e,t)=>{if(!this.indexedDB)return void t(new Error("no indexeddb support available"));s.logger.log(`Removing indexeddb instance: ${this.dbName}`);const i=this.indexedDB.deleteDatabase(this.dbName);i.onblocked=()=>{s.logger.log("can't yet delete IndexedDBCryptoStore because it is open elsewhere")},i.onerror=e=>{s.logger.log("Error deleting data from indexeddb",e),t(i.error)},i.onsuccess=()=>{s.logger.log(`Removed indexeddb instance: ${this.dbName}`),e()}})).catch((e=>{s.logger.warn(`unable to delete IndexedDBCryptoStore: ${e}`)}))}getOrAddOutgoingRoomKeyRequest(e){return this.backend.getOrAddOutgoingRoomKeyRequest(e)}getOutgoingRoomKeyRequest(e){return this.backend.getOutgoingRoomKeyRequest(e)}getOutgoingRoomKeyRequestByState(e){return this.backend.getOutgoingRoomKeyRequestByState(e)}getAllOutgoingRoomKeyRequestsByState(e){return this.backend.getAllOutgoingRoomKeyRequestsByState(e)}getOutgoingRoomKeyRequestsByTarget(e,t,i){return this.backend.getOutgoingRoomKeyRequestsByTarget(e,t,i)}updateOutgoingRoomKeyRequest(e,t,i){return this.backend.updateOutgoingRoomKeyRequest(e,t,i)}deleteOutgoingRoomKeyRequest(e,t){return this.backend.deleteOutgoingRoomKeyRequest(e,t)}getAccount(e,t){this.backend.getAccount(e,t)}storeAccount(e,t){this.backend.storeAccount(e,t)}getCrossSigningKeys(e,t){this.backend.getCrossSigningKeys(e,t)}getSecretStorePrivateKey(e,t,i){this.backend.getSecretStorePrivateKey(e,t,i)}storeCrossSigningKeys(e,t){this.backend.storeCrossSigningKeys(e,t)}storeSecretStorePrivateKey(e,t,i){this.backend.storeSecretStorePrivateKey(e,t,i)}countEndToEndSessions(e,t){this.backend.countEndToEndSessions(e,t)}getEndToEndSession(e,t,i,n){this.backend.getEndToEndSession(e,t,i,n)}getEndToEndSessions(e,t,i){this.backend.getEndToEndSessions(e,t,i)}getAllEndToEndSessions(e,t){this.backend.getAllEndToEndSessions(e,t)}storeEndToEndSession(e,t,i,n){this.backend.storeEndToEndSession(e,t,i,n)}storeEndToEndSessionProblem(e,t,i){return this.backend.storeEndToEndSessionProblem(e,t,i)}getEndToEndSessionProblem(e,t){return this.backend.getEndToEndSessionProblem(e,t)}filterOutNotifiedErrorDevices(e){return this.backend.filterOutNotifiedErrorDevices(e)}getEndToEndInboundGroupSession(e,t,i,n){this.backend.getEndToEndInboundGroupSession(e,t,i,n)}getAllEndToEndInboundGroupSessions(e,t){this.backend.getAllEndToEndInboundGroupSessions(e,t)}addEndToEndInboundGroupSession(e,t,i,n){this.backend.addEndToEndInboundGroupSession(e,t,i,n)}storeEndToEndInboundGroupSession(e,t,i,n){this.backend.storeEndToEndInboundGroupSession(e,t,i,n)}storeEndToEndInboundGroupSessionWithheld(e,t,i,n){this.backend.storeEndToEndInboundGroupSessionWithheld(e,t,i,n)}storeEndToEndDeviceData(e,t){this.backend.storeEndToEndDeviceData(e,t)}getEndToEndDeviceData(e,t){this.backend.getEndToEndDeviceData(e,t)}storeEndToEndRoom(e,t,i){this.backend.storeEndToEndRoom(e,t,i)}getEndToEndRooms(e,t){this.backend.getEndToEndRooms(e,t)}getSessionsNeedingBackup(e){return this.backend.getSessionsNeedingBackup(e)}countSessionsNeedingBackup(e){return this.backend.countSessionsNeedingBackup(e)}unmarkSessionsNeedingBackup(e,t){return this.backend.unmarkSessionsNeedingBackup(e,t)}markSessionsNeedingBackup(e,t){return this.backend.markSessionsNeedingBackup(e,t)}addSharedHistoryInboundGroupSession(e,t,i,n){this.backend.addSharedHistoryInboundGroupSession(e,t,i,n)}getSharedHistoryInboundGroupSessions(e,t){return this.backend.getSharedHistoryInboundGroupSessions(e,t)}addParkedSharedHistory(e,t,i){this.backend.addParkedSharedHistory(e,t,i)}takeParkedSharedHistory(e,t){return this.backend.takeParkedSharedHistory(e,t)}doTxn(e,t,i,n){return this.backend.doTxn(e,t,i,n)}}i.IndexedDBCryptoStore=h,h.STORE_ACCOUNT="account",h.STORE_SESSIONS="sessions",h.STORE_INBOUND_GROUP_SESSIONS="inbound_group_sessions",h.STORE_INBOUND_GROUP_SESSIONS_WITHHELD="inbound_group_sessions_withheld",h.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS="shared_history_inbound_group_sessions",h.STORE_PARKED_SHARED_HISTORY="parked_shared_history",h.STORE_DEVICE_DATA="device_data",h.STORE_ROOMS="rooms",h.STORE_BACKUP="sessions_needing_backup"}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../errors":359,"../../indexeddb-helpers":372,"../../logger":374,"./indexeddb-crypto-store-backend":345,"./localStorage-crypto-store":347,"./memory-crypto-store":348}],347:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.LocalStorageCryptoStore=void 0;const r=e("../../logger"),o=e("./memory-crypto-store"),s=e("../../utils"),a="crypto.",c=a+"account",d=a+"cross_signing_keys",l=a+"notified_error_devices",u=a+"device_data",h=a+"inboundgroupsessions/",f=a+"inboundgroupsessions.withheld/",p=a+"rooms/",g=a+"sessionsneedingbackup";function v(e){return a+"sessions/"+e}function m(e){return a+"session.problems/"+e}function y(e,t){return h+e+"/"+t}function b(e,t){return f+e+"/"+t}function S(e){return p+e}class _ extends o.MemoryCryptoStore{static exists(e){var t;const i=e.length;for(let n=0;ne.time-t.time)),w(this.store,n,r)}))}getEndToEndSessionProblem(e,t){return n(this,void 0,void 0,(function*(){const i=m(e),n=E(this.store,i)||[];if(!n.length)return null;const r=n[n.length-1];for(const e of n)if(e.time>t)return Object.assign({},e,{fixed:r.fixed});return r.fixed?null:r}))}filterOutNotifiedErrorDevices(e){return n(this,void 0,void 0,(function*(){const t=E(this.store,l)||{},i=[];for(const n of e){const{userId:e,deviceInfo:r}=n;e in t?r.deviceId in t[e]||(i.push(n),(0,s.safeSet)(t[e],r.deviceId,!0)):(i.push(n),(0,s.safeSet)(t,e,{[r.deviceId]:!0}))}return w(this.store,l,t),i}))}getEndToEndInboundGroupSession(e,t,i,n){n(E(this.store,y(e,t)),E(this.store,b(e,t)))}getAllEndToEndInboundGroupSessions(e,t){for(let e=0;e{i.push({senderKey:t,sessionId:r,sessionData:e})})),e&&i.length>=e)break}return Promise.resolve(i)}countSessionsNeedingBackup(){const e=E(this.store,g)||{};return Promise.resolve(Object.keys(e).length)}unmarkSessionsNeedingBackup(e){const t=E(this.store,g)||{};for(const i of e)delete t[i.senderKey+"/"+i.sessionId];return w(this.store,g,t),Promise.resolve()}markSessionsNeedingBackup(e){const t=E(this.store,g)||{};for(const i of e)t[i.senderKey+"/"+i.sessionId]=!0;return w(this.store,g,t),Promise.resolve()}deleteAllData(){return this.store.removeItem(c),Promise.resolve()}getAccount(e,t){t(E(this.store,c))}storeAccount(e,t){w(this.store,c,t)}getCrossSigningKeys(e,t){t(E(this.store,d))}getSecretStorePrivateKey(e,t,i){t(E(this.store,a+`ssss_cache.${i}`))}storeCrossSigningKeys(e,t){w(this.store,d,t)}storeSecretStorePrivateKey(e,t,i){w(this.store,a+`ssss_cache.${t}`,i)}doTxn(e,t,i){return Promise.resolve(i(null))}}function E(e,t){try{return JSON.parse(e.getItem(t))}catch(e){r.logger.log("Error: Failed to get key %s: %s",t,e.message),r.logger.log(e.stack)}return null}function w(e,t,i){e.setItem(t,JSON.stringify(i))}i.LocalStorageCryptoStore=_},{"../../logger":374,"../../utils":416,"./memory-crypto-store":348}],348:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.MemoryCryptoStore=void 0;const a=e("../../logger"),c=o(e("../../utils")),d=e("../../utils");i.MemoryCryptoStore=class{constructor(){this.outgoingRoomKeyRequests=[],this.account=null,this.crossSigningKeys=null,this.privateKeys={},this.sessions={},this.sessionProblems={},this.notifiedErrorDevices={},this.inboundGroupSessions={},this.inboundGroupSessionsWithheld={},this.deviceData=null,this.rooms={},this.sessionsNeedingBackup={},this.sharedHistoryInboundGroupSessions={},this.parkedSharedHistory=new Map}startup(){return s(this,void 0,void 0,(function*(){return this}))}deleteAllData(){return Promise.resolve()}getOrAddOutgoingRoomKeyRequest(e){const t=e.requestBody;return c.promiseTry((()=>{const i=this._getOutgoingRoomKeyRequest(t);return i?(a.logger.log(`already have key request outstanding for ${t.room_id} / ${t.session_id}: not sending another`),i):(a.logger.log(`enqueueing key request for ${t.room_id} / `+t.session_id),this.outgoingRoomKeyRequests.push(e),e)}))}getOutgoingRoomKeyRequest(e){return Promise.resolve(this._getOutgoingRoomKeyRequest(e))}_getOutgoingRoomKeyRequest(e){for(const t of this.outgoingRoomKeyRequests)if(c.deepCompare(t.requestBody,e))return t;return null}getOutgoingRoomKeyRequestByState(e){for(const t of this.outgoingRoomKeyRequests)for(const i of e)if(t.state===i)return Promise.resolve(t);return Promise.resolve(null)}getAllOutgoingRoomKeyRequestsByState(e){return Promise.resolve(this.outgoingRoomKeyRequests.filter((t=>t.state==e)))}getOutgoingRoomKeyRequestsByTarget(e,t,i){const n=[];for(const r of this.outgoingRoomKeyRequests)for(const o of i)r.state===o&&r.recipients.some((i=>i.userId===e&&i.deviceId===t))&&n.push(r);return Promise.resolve(n)}updateOutgoingRoomKeyRequest(e,t,i){for(const n of this.outgoingRoomKeyRequests)if(n.requestId===e)return n.state!==t?(a.logger.warn(`Cannot update room key request from ${t} as it was already updated to ${n.state}`),Promise.resolve(null)):(Object.assign(n,i),Promise.resolve(n));return Promise.resolve(null)}deleteOutgoingRoomKeyRequest(e,t){for(let i=0;i{Object.entries(i).forEach((([i,n])=>{t(Object.assign(Object.assign({},n),{deviceKey:e,sessionId:i}))}))}))}storeEndToEndSession(e,t,i,n){let r=this.sessions[e];void 0===r&&(r={},this.sessions[e]=r),r[t]=i}storeEndToEndSessionProblem(e,t,i){return s(this,void 0,void 0,(function*(){const n=this.sessionProblems[e]=this.sessionProblems[e]||[];n.push({type:t,fixed:i,time:Date.now()}),n.sort(((e,t)=>e.time-t.time))}))}getEndToEndSessionProblem(e,t){return s(this,void 0,void 0,(function*(){const i=this.sessionProblems[e]||[];if(!i.length)return null;const n=i[i.length-1];for(const e of i)if(e.time>t)return Object.assign({},e,{fixed:n.fixed});return n.fixed?null:n}))}filterOutNotifiedErrorDevices(e){return s(this,void 0,void 0,(function*(){const t=this.notifiedErrorDevices,i=[];for(const n of e){const{userId:e,deviceInfo:r}=n;e in t?r.deviceId in t[e]||(i.push(n),(0,d.safeSet)(t[e],r.deviceId,!0)):(i.push(n),(0,d.safeSet)(t,e,{[r.deviceId]:!0}))}return i}))}getEndToEndInboundGroupSession(e,t,i,n){const r=e+"/"+t;n(this.inboundGroupSessions[r]||null,this.inboundGroupSessionsWithheld[r]||null)}getAllEndToEndInboundGroupSessions(e,t){for(const e of Object.keys(this.inboundGroupSessions))t({senderKey:e.slice(0,43),sessionId:e.slice(44),sessionData:this.inboundGroupSessions[e]});t(null)}addEndToEndInboundGroupSession(e,t,i,n){const r=e+"/"+t;void 0===this.inboundGroupSessions[r]&&(this.inboundGroupSessions[r]=i)}storeEndToEndInboundGroupSession(e,t,i,n){this.inboundGroupSessions[e+"/"+t]=i}storeEndToEndInboundGroupSessionWithheld(e,t,i,n){const r=e+"/"+t;this.inboundGroupSessionsWithheld[r]=i}getEndToEndDeviceData(e,t){t(this.deviceData)}storeEndToEndDeviceData(e,t){this.deviceData=e}storeEndToEndRoom(e,t,i){this.rooms[e]=t}getEndToEndRooms(e,t){t(this.rooms)}getSessionsNeedingBackup(e){const t=[];for(const i in this.sessionsNeedingBackup)if(this.inboundGroupSessions[i]&&(t.push({senderKey:i.slice(0,43),sessionId:i.slice(44),sessionData:this.inboundGroupSessions[i]}),e&&i.length>=e))break;return Promise.resolve(t)}countSessionsNeedingBackup(){return Promise.resolve(Object.keys(this.sessionsNeedingBackup).length)}unmarkSessionsNeedingBackup(e){for(const t of e){const e=t.senderKey+"/"+t.sessionId;delete this.sessionsNeedingBackup[e]}return Promise.resolve()}markSessionsNeedingBackup(e){for(const t of e){const e=t.senderKey+"/"+t.sessionId;this.sessionsNeedingBackup[e]=!0}return Promise.resolve()}addSharedHistoryInboundGroupSession(e,t,i){const n=this.sharedHistoryInboundGroupSessions[e]||[];n.push([t,i]),this.sharedHistoryInboundGroupSessions[e]=n}getSharedHistoryInboundGroupSessions(e){return Promise.resolve(this.sharedHistoryInboundGroupSessions[e]||[])}addParkedSharedHistory(e,t){var i;const n=null!==(i=this.parkedSharedHistory.get(e))&&void 0!==i?i:[];n.push(t),this.parkedSharedHistory.set(e,n)}takeParkedSharedHistory(e){var t;const i=null!==(t=this.parkedSharedHistory.get(e))&&void 0!==t?t:[];return this.parkedSharedHistory.delete(e),Promise.resolve(i)}doTxn(e,t,i){return Promise.resolve(i(null))}}},{"../../logger":374,"../../utils":416}],349:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.VerificationBase=i.VerificationEvent=i.SwitchStartEventError=void 0;const r=e("../../models/event"),o=e("../../@types/event"),s=e("../../logger"),a=e("../deviceinfo"),c=e("./Error"),d=e("../CrossSigning"),l=e("../../models/typed-event-emitter"),u=new Error("Verification timed out");class h extends Error{constructor(e){super(),this.startEvent=e}}var f;i.SwitchStartEventError=h,function(e){e.Cancel="cancel"}(f=i.VerificationEvent||(i.VerificationEvent={}));class p extends l.TypedEventEmitter{constructor(e,t,i,n,r,o){super(),this.channel=e,this.baseApis=t,this.userId=i,this.deviceId=n,this.startEvent=r,this.request=o,this.cancelled=!1,this._done=!1,this.promise=null,this.transactionTimeoutTimer=null}get initiatedByMe(){if(!this.startEvent)return!0;const e=this.startEvent.getSender(),t=this.startEvent.getContent();return e===this.baseApis.getUserId()&&t.from_device===this.baseApis.getDeviceId()}get hasBeenCancelled(){return this.cancelled}resetTimer(){s.logger.info("Refreshing/starting the verification transaction timeout timer"),null!==this.transactionTimeoutTimer&&clearTimeout(this.transactionTimeoutTimer),this.transactionTimeoutTimer=setTimeout((()=>{this._done||this.cancelled||(s.logger.info("Triggering verification timeout"),this.cancel(u))}),6e5)}endTimer(){null!==this.transactionTimeoutTimer&&(clearTimeout(this.transactionTimeoutTimer),this.transactionTimeoutTimer=null)}send(e,t){return this.channel.send(e,t)}waitForEvent(e){if(this._done)return Promise.reject(new Error("Verification is already done"));const t=this.request.getEventFromOtherParty(e);return t?Promise.resolve(t):(this.expectedEvent=e,new Promise(((e,t)=>{this.resolveEvent=e,this.rejectEvent=t})))}canSwitchStartEvent(e){return!1}switchStartEvent(e){if(this.canSwitchStartEvent(e))if(s.logger.log("Verification Base: switching verification start event",{restartingFlow:!!this.rejectEvent}),this.rejectEvent){const t=this.rejectEvent;this.rejectEvent=void 0,t(new h(e))}else this.startEvent=e}handleEvent(e){var t;if(!this._done)if(e.getType()===this.expectedEvent)this.expectedEvent!==o.EventType.KeyVerificationDone&&(this.expectedEvent=void 0,this.rejectEvent=void 0,this.resetTimer(),null===(t=this.resolveEvent)||void 0===t||t.call(this,e));else if(e.getType()===o.EventType.KeyVerificationCancel){const t=this.reject;if(this.reject=void 0,t){const i=e.getContent(),{reason:n,code:r}=i;t(new Error(`Other side cancelled verification because ${n} (${r})`))}}else if(this.expectedEvent){const t=new Error("Unexpected message: expecting "+this.expectedEvent+" but got "+e.getType());if(this.expectedEvent=void 0,this.rejectEvent){const e=this.rejectEvent;this.rejectEvent=void 0,e(t)}this.cancel(t)}}done(){var e;return n(this,void 0,void 0,(function*(){if(this.endTimer(),!this._done)return this.request.onVerifierFinished(),null===(e=this.resolve)||void 0===e||e.call(this),(0,d.requestKeysDuringVerification)(this.baseApis,this.userId,this.deviceId)}))}cancel(e){if(this.endTimer(),!this._done){if(this.cancelled=!0,this.request.onVerifierCancelled(),this.userId&&this.deviceId)if(e===u){const e=(0,c.newTimeoutError)();this.send(e.getType(),e.getContent())}else if(e instanceof r.MatrixEvent){if(e.getSender()!==this.userId){const t=e.getContent();e.getType()===o.EventType.KeyVerificationCancel?(t.code=t.code||"m.unknown",t.reason=t.reason||t.body||"Unknown reason",this.send(o.EventType.KeyVerificationCancel,t)):this.send(o.EventType.KeyVerificationCancel,{code:"m.unknown",reason:t.body||"Unknown reason"})}}else this.send(o.EventType.KeyVerificationCancel,{code:"m.unknown",reason:e.toString()});null!==this.promise?this.reject&&this.reject(e):this.promise=Promise.reject(e),this.emit(f.Cancel,e)}}verify(){return this.promise||(this.promise=new Promise(((e,t)=>{this.resolve=(...t)=>{this._done=!0,this.endTimer(),e(...t)},this.reject=e=>{this._done=!0,this.endTimer(),t(e)}})),this.doVerification&&!this.started&&(this.started=!0,this.resetTimer(),new Promise(((e,t)=>{var i;(null===(i=this.baseApis.crypto.deviceList.getStoredCrossSigningForUser(this.userId))||void 0===i?void 0:i.getId())===this.deviceId&&t(new Error("Device ID is the same as the cross-signing ID")),e()})).then((()=>this.doVerification())).then(this.done.bind(this),this.cancel.bind(this)))),this.promise}verifyKeys(e,t,i){return n(this,void 0,void 0,(function*(){const n=[];for(const[r,o]of Object.entries(t)){const t=r.split(":",2)[1],c=this.baseApis.getStoredDevice(e,t);if(c)i(r,c,o),n.push([t,r,c.keys[r]]);else{const c=this.baseApis.crypto.deviceList.getStoredCrossSigningForUser(e);c&&c.getId()===t?(i(r,a.DeviceInfo.fromStorage({keys:{[r]:t}},t),o),n.push([t,r,t])):s.logger.warn(`verification: Could not find device ${t} to verify`)}}if(!n.length)throw new Error("No devices could be verified");s.logger.info("Verification completed! Marking devices verified: ",n);for(const[t,i,r]of n)yield this.baseApis.crypto.setDeviceVerification(e,t,!0,null,null,{[i]:r});e==this.baseApis.credentials.userId&&(yield this.baseApis.checkKeyBackup())}))}get events(){}}i.VerificationBase=p},{"../../@types/event":306,"../../logger":374,"../../models/event":383,"../../models/typed-event-emitter":395,"../CrossSigning":324,"../deviceinfo":340,"./Error":350}],350:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.errorFromEvent=i.newInvalidMessageError=i.newKeyMismatchError=i.newUnexpectedMessageError=i.newUnknownMethodError=i.newTimeoutError=i.newUserCancelledError=i.errorFactory=i.newVerificationError=void 0;const n=e("../../models/event"),r=e("../../@types/event");function o(e,t,i){const o=Object.assign({},{code:e,reason:t},i);return new n.MatrixEvent({type:r.EventType.KeyVerificationCancel,content:o})}function s(e,t){return function(i){return o(e,t,i)}}i.newVerificationError=o,i.errorFactory=s,i.newUserCancelledError=s("m.user","Cancelled by user"),i.newTimeoutError=s("m.timeout","Timed out"),i.newUnknownMethodError=s("m.unknown_method","Unknown method"),i.newUnexpectedMessageError=s("m.unexpected_message","Unexpected message"),i.newKeyMismatchError=s("m.key_mismatch","Key mismatch"),i.newInvalidMessageError=s("m.invalid_message","Invalid message"),i.errorFromEvent=function(e){const t=e.getContent();if(t){const{code:e,reason:i}=t;return{code:e,reason:i}}return{code:"Unknown error",reason:"m.unknown"}}},{"../../@types/event":306,"../../models/event":383}],351:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.IllegalMethod=void 0;const r=e("./Base");class o extends r.VerificationBase{constructor(){super(...arguments),this.doVerification=()=>n(this,void 0,void 0,(function*(){throw new Error("Verification is not possible with this method")}))}static factory(e,t,i,n,r,s){return new o(e,t,i,n,r,s)}static get NAME(){return"org.matrix.illegal_method"}}i.IllegalMethod=o},{"./Base":349}],352:[function(e,t,i){(function(t,n){(function(){"use strict";var r=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.QRCodeData=i.ReciprocateQRCode=i.QrCodeEvent=i.SCAN_QR_CODE_METHOD=i.SHOW_QR_CODE_METHOD=void 0;const o=e("./Base"),s=e("./Error"),a=e("../olmlib"),c=e("../../logger");var d;i.SHOW_QR_CODE_METHOD="m.qr_code.show.v1",i.SCAN_QR_CODE_METHOD="m.qr_code.scan.v1",function(e){e.ShowReciprocateQr="show_reciprocate_qr"}(d=i.QrCodeEvent||(i.QrCodeEvent={}));class l extends o.VerificationBase{constructor(){super(...arguments),this.doVerification=()=>r(this,void 0,void 0,(function*(){if(!this.startEvent)throw new Error("It is not currently possible to start verificationwith this method yet.");const{qrCodeData:e}=this.request;if(this.startEvent.getContent().secret!==(null==e?void 0:e.encodedSharedSecret))throw(0,s.newKeyMismatchError)();yield new Promise(((e,t)=>{this.reciprocateQREvent={confirm:e,cancel:()=>t((0,s.newUserCancelledError)())},this.emit(d.ShowReciprocateQr,this.reciprocateQREvent)}));const t={};switch(null==e?void 0:e.mode){case u.VerifyOtherUser:{const i=e.otherUserMasterKey;t[`ed25519:${i}`]=i;break}case u.VerifySelfTrusted:{const i=this.request.targetDevice.deviceId;t[`ed25519:${i}`]=e.otherDeviceKey;break}case u.VerifySelfUntrusted:{const i=e.myMasterKey;t[`ed25519:${i}`]=i;break}}yield this.verifyKeys(this.userId,t,((e,i,n)=>{const r=t[e];if(!r)throw(0,s.newKeyMismatchError)();if(n!==r)throw c.logger.error("key ID from key info does not match"),(0,s.newKeyMismatchError)();for(const e in i.keys){if(!e.startsWith("ed25519"))continue;const n=t[e];if(!n)throw(0,s.newKeyMismatchError)();if(i.keys[e]!==n)throw c.logger.error("master key does not match"),(0,s.newKeyMismatchError)()}}))}))}static factory(e,t,i,n,r,o){return new l(e,t,i,n,r,o)}static get NAME(){return"m.reciprocate.v1"}}i.ReciprocateQRCode=l;var u;!function(e){e[e.VerifyOtherUser=0]="VerifyOtherUser",e[e.VerifySelfTrusted=1]="VerifySelfTrusted",e[e.VerifySelfUntrusted=2]="VerifySelfUntrusted"}(u||(u={}));class h{constructor(e,t,i,n,r,o){this.mode=e,this.sharedSecret=t,this.otherUserMasterKey=i,this.otherDeviceKey=n,this.myMasterKey=r,this.buffer=o}static create(e,t){return r(this,void 0,void 0,(function*(){const i=h.generateSharedSecret(),n=h.determineMode(e,t);let r=null,o=null,s=null;if(n===u.VerifyOtherUser){r=t.getStoredCrossSigningForUser(e.otherUserId).getId("master")}else if(n===u.VerifySelfTrusted)o=yield h.getOtherDeviceKey(e,t);else if(n===u.VerifySelfUntrusted){const e=t.getUserId();s=t.getStoredCrossSigningForUser(e).getId("master")}const a=h.generateQrData(e,t,n,i,r,o,s),c=h.generateBuffer(a);return new h(n,i,r,o,s,c)}))}get encodedSharedSecret(){return this.sharedSecret}getBuffer(){return this.buffer}static generateSharedSecret(){const e=new Uint8Array(11);return t.crypto.getRandomValues(e),(0,a.encodeUnpaddedBase64)(e)}static getOtherDeviceKey(e,t){return r(this,void 0,void 0,(function*(){const i=t.getUserId(),n=e.targetDevice,r=n.deviceId?t.getStoredDevice(i,n.deviceId):void 0;if(!r)throw new Error("could not find device "+(null==n?void 0:n.deviceId));return r.getFingerprint()}))}static determineMode(e,t){const i=t.getUserId(),n=e.otherUserId;let r=u.VerifyOtherUser;if(i===n){r=t.checkUserTrust(i).isCrossSigningVerified()?u.VerifySelfTrusted:u.VerifySelfUntrusted}return r}static generateQrData(e,t,i,n,r,o,s){const a=t.getUserId(),c={prefix:"MATRIX",version:2,mode:i,transactionId:e.channel.transactionId,firstKeyB64:"",secondKeyB64:"",secretB64:n},d=t.getStoredCrossSigningForUser(a);return i===u.VerifyOtherUser?(c.firstKeyB64=d.getId("master"),c.secondKeyB64=r):i===u.VerifySelfTrusted?(c.firstKeyB64=d.getId("master"),c.secondKeyB64=o):i===u.VerifySelfUntrusted&&(c.firstKeyB64=t.getDeviceEd25519Key(),c.secondKeyB64=s),c}static generateBuffer(e){let t=n.alloc(0);const i=e=>{const i=n.from([e]);t=n.concat([t,i])},r=(e,i,r=!0)=>{const o=n.from(e,i);r&&(e=>{const i=n.alloc(2);i.writeInt16BE(e,0),t=n.concat([t,i])})(o.byteLength),t=n.concat([t,o])},o=e=>{const i=(0,a.decodeBase64)(e),r=n.from(i);t=n.concat([t,r])};return r(e.prefix,"ascii",!1),i(e.version),i(e.mode),r(e.transactionId,"utf-8"),o(e.firstKeyB64),o(e.secondKeyB64),o(e.secretB64),t}}i.QRCodeData=h}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"../../logger":374,"../olmlib":343,"./Base":349,"./Error":350,buffer:68}],353:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(i,"__esModule",{value:!0}),i.SAS=i.SasEvent=void 0;const o=r(e("another-json")),s=e("./Base"),a=e("./Error"),c=e("../../logger"),d=e("./SASDecimal"),l=e("../../@types/event"),u=l.EventType.KeyVerificationStart,h=[l.EventType.KeyVerificationAccept,l.EventType.KeyVerificationKey,l.EventType.KeyVerificationMac];let f;const p=(0,a.errorFactory)("m.mismatched_sas","Mismatched short authentication string"),g=(0,a.errorFactory)("m.mismatched_commitment","Mismatched commitment"),v=[["🐶","dog"],["🐱","cat"],["🦁","lion"],["🐎","horse"],["🦄","unicorn"],["🐷","pig"],["🐘","elephant"],["🐰","rabbit"],["🐼","panda"],["🐓","rooster"],["🐧","penguin"],["🐢","turtle"],["🐟","fish"],["🐙","octopus"],["🦋","butterfly"],["🌷","flower"],["🌳","tree"],["🌵","cactus"],["🍄","mushroom"],["🌏","globe"],["🌙","moon"],["☁️","cloud"],["🔥","fire"],["🍌","banana"],["🍎","apple"],["🍓","strawberry"],["🌽","corn"],["🍕","pizza"],["🎂","cake"],["❤️","heart"],["🙂","smiley"],["🤖","robot"],["🎩","hat"],["👓","glasses"],["🔧","spanner"],["🎅","santa"],["👍","thumbs up"],["☂️","umbrella"],["⌛","hourglass"],["⏰","clock"],["🎁","gift"],["💡","light bulb"],["📕","book"],["✏️","pencil"],["📎","paperclip"],["✂️","scissors"],["🔒","lock"],["🔑","key"],["🔨","hammer"],["☎️","telephone"],["🏁","flag"],["🚂","train"],["🚲","bicycle"],["✈️","aeroplane"],["🚀","rocket"],["🏆","trophy"],["⚽","ball"],["🎸","guitar"],["🎺","trumpet"],["🔔","bell"],["⚓️","anchor"],["🎧","headphones"],["📁","folder"],["📌","pin"]];const m={decimal:d.generateDecimalSas,emoji:function(e){return[e[0]>>2,(3&e[0])<<4|e[1]>>4,(15&e[1])<<2|e[2]>>6,63&e[2],e[3]>>2,(3&e[3])<<4|e[4]>>4,(15&e[4])<<2|e[5]>>6].map((e=>v[e]))}};function y(e,t){const i={};for(const n of t)n in m&&(i[n]=m[n](Array.from(e)));return i}const b={"hkdf-hmac-sha256":"calculate_mac","org.matrix.msc3783.hkdf-hmac-sha256":"calculate_mac_fixed_base64","hkdf-hmac-sha256.v2":"calculate_mac_fixed_base64","hmac-sha256":"calculate_mac_long_kdf"};function S(e,t){return function(i,n){const r=e[b[t]](i,n);return c.logger.log("SAS calculateMAC:",t,[i,n],r),r}}const _={"curve25519-hkdf-sha256":function(e,t,i){const n=`${e.baseApis.getUserId()}|${e.baseApis.deviceId}|${e.ourSASPubKey}|`,r=`${e.userId}|${e.deviceId}|${e.theirSASPubKey}|`,o="MATRIX_KEY_VERIFICATION_SAS|"+(e.initiatedByMe?n+r:r+n)+e.channel.transactionId;return t.generate_bytes(o,i)},curve25519:function(e,t,i){const n=`${e.baseApis.getUserId()}${e.baseApis.deviceId}`,r=`${e.userId}${e.deviceId}`,o="MATRIX_KEY_VERIFICATION_SAS"+(e.initiatedByMe?n+r:r+n)+e.channel.transactionId;return t.generate_bytes(o,i)}},E=["curve25519-hkdf-sha256","curve25519"],w=["sha256"],T=["hkdf-hmac-sha256.v2","org.matrix.msc3783.hkdf-hmac-sha256","hkdf-hmac-sha256","hmac-sha256"],I=Object.keys(m),R=new Set(E),M=new Set(w),k=new Set(T),C=new Set(I);function O(e,t){return Array.isArray(e)?e.filter((e=>t.has(e))):[]}var A;!function(e){e.ShowSas="show_sas"}(A=i.SasEvent||(i.SasEvent={}));class P extends s.VerificationBase{constructor(){super(...arguments),this.doVerification=()=>n(this,void 0,void 0,(function*(){yield t.Olm.init(),f=f||new t.Olm.Utility,yield this.baseApis.downloadKeys([this.userId]);let e=!1;do{try{return this.initiatedByMe?yield this.doSendVerification():yield this.doRespondVerification()}catch(t){if(!(t instanceof s.SwitchStartEventError))throw t;this.startEvent=t.startEvent,e=!0}}while(e)}))}static get NAME(){return"m.sas.v1"}get events(){return h}canSwitchStartEvent(e){if(e.getType()!==u)return!1;const t=e.getContent();return(null==t?void 0:t.method)===P.NAME&&!!this.waitingForAccept}sendStart(){return n(this,void 0,void 0,(function*(){const e=this.channel.completeContent(u,{method:P.NAME,from_device:this.baseApis.deviceId,key_agreement_protocols:E,hashes:w,message_authentication_codes:T,short_authentication_string:I});return yield this.channel.sendCompleted(u,e),e}))}verifyAndCheckMAC(e,t,i,r){return n(this,void 0,void 0,(function*(){const o=_[e](this,i,6),s=new Promise(((e,s)=>{this.sasEvent={sas:y(o,t),confirm:()=>n(this,void 0,void 0,(function*(){try{yield this.sendMAC(i,r),e()}catch(e){s(e)}})),cancel:()=>s((0,a.newUserCancelledError)()),mismatch:()=>s(p())},this.emit(A.ShowSas,this.sasEvent)})),[c]=yield Promise.all([this.waitForEvent(l.EventType.KeyVerificationMac).then((e=>(this.expectedEvent=l.EventType.KeyVerificationDone,e))),s]),d=c.getContent();yield this.checkMAC(i,d,r)}))}doSendVerification(){return n(this,void 0,void 0,(function*(){let e,i;if(this.waitingForAccept=!0,e=this.startEvent?this.channel.completedContentFromEvent(this.startEvent):yield this.sendStart(),!this.initiatedByMe)throw new s.SwitchStartEventError(this.startEvent);try{i=yield this.waitForEvent(l.EventType.KeyVerificationAccept)}finally{this.waitingForAccept=!1}let n=i.getContent();const r=O(n.short_authentication_string,C);if(!(R.has(n.key_agreement_protocol)&&M.has(n.hash)&&k.has(n.message_authentication_code)&&r.length))throw(0,a.newUnknownMethodError)();if("string"!=typeof n.commitment)throw(0,a.newInvalidMessageError)();const c=n.key_agreement_protocol,d=n.message_authentication_code,u=n.commitment,h=new t.Olm.SAS;try{this.ourSASPubKey=h.get_pubkey(),yield this.send(l.EventType.KeyVerificationKey,{key:this.ourSASPubKey}),i=yield this.waitForEvent(l.EventType.KeyVerificationKey),n=i.getContent();const t=n.key+o.default.stringify(e);if(f.sha256(t)!==u)throw g();this.theirSASPubKey=n.key,h.set_their_key(n.key),yield this.verifyAndCheckMAC(c,r,h,d)}finally{h.free()}}))}doRespondVerification(){return n(this,void 0,void 0,(function*(){let e=this.channel.completedContentFromEvent(this.startEvent);const i=O(E,new Set(e.key_agreement_protocols))[0],n=O(w,new Set(e.hashes))[0],r=O(T,new Set(e.message_authentication_codes))[0],s=O(e.short_authentication_string,C);if(void 0===i||void 0===n||void 0===r||!s.length)throw(0,a.newUnknownMethodError)();const c=new t.Olm.SAS;try{const t=c.get_pubkey()+o.default.stringify(e);yield this.send(l.EventType.KeyVerificationAccept,{key_agreement_protocol:i,hash:n,message_authentication_code:r,short_authentication_string:s,commitment:f.sha256(t)});e=(yield this.waitForEvent(l.EventType.KeyVerificationKey)).getContent(),this.theirSASPubKey=e.key,c.set_their_key(e.key),this.ourSASPubKey=c.get_pubkey(),yield this.send(l.EventType.KeyVerificationKey,{key:this.ourSASPubKey}),yield this.verifyAndCheckMAC(i,s,c,r)}finally{c.free()}}))}sendMAC(e,t){const i={},n=[],r="MATRIX_KEY_VERIFICATION_MAC"+this.baseApis.getUserId()+this.baseApis.deviceId+this.userId+this.deviceId+this.channel.transactionId,o=`ed25519:${this.baseApis.deviceId}`;i[o]=S(e,t)(this.baseApis.getDeviceEd25519Key(),r+o),n.push(o);const s=this.baseApis.getCrossSigningId();if(s){const o=`ed25519:${s}`;i[o]=S(e,t)(s,r+o),n.push(o)}const a=S(e,t)(n.sort().join(","),r+"KEY_IDS");return this.send(l.EventType.KeyVerificationMac,{mac:i,keys:a})}checkMAC(e,t,i){return n(this,void 0,void 0,(function*(){const n="MATRIX_KEY_VERIFICATION_MAC"+this.userId+this.deviceId+this.baseApis.getUserId()+this.baseApis.deviceId+this.channel.transactionId;if(t.keys!==S(e,i)(Object.keys(t.mac).sort().join(","),n+"KEY_IDS"))throw(0,a.newKeyMismatchError)();yield this.verifyKeys(this.userId,t.mac,((t,r,o)=>{if(o!==S(e,i)(r.keys[t],n+t))throw(0,a.newKeyMismatchError)()}))}))}}i.SAS=P}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../../@types/event":306,"../../logger":374,"./Base":349,"./Error":350,"./SASDecimal":354,"another-json":1}],354:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.generateDecimalSas=void 0,i.generateDecimalSas=function(e){return[1e3+(e[0]<<5|e[1]>>3),1e3+((7&e[1])<<10|e[2]<<2|e[3]>>6),1e3+((63&e[3])<<7|e[4]>>1)]}},{}],355:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.InRoomRequests=i.InRoomChannel=void 0;const r=e("./VerificationRequest"),o=e("../../../logger"),s=e("../../../@types/event").EventType.RoomMessage,a="m.reference",c="m.relates_to";class d{constructor(e,t,i){this.client=e,this.roomId=t,this.userId=i}get receiveStartFromOtherDevices(){return!0}get transactionId(){return this.requestEventId}static getOtherPartyUserId(e,t){if(d.getEventType(e)!==r.REQUEST_TYPE)return;const i=t.getUserId(),n=e.getSender(),o=e.getContent().to;return n===i?o:o===i?n:void 0}getTimestamp(e){return e.getTs()}static canCreateRequest(e){return e===r.REQUEST_TYPE}canCreateRequest(e){return d.canCreateRequest(e)}static getTransactionId(e){if(d.getEventType(e)===r.REQUEST_TYPE)return e.getId();{const t=e.getRelation();if((null==t?void 0:t.rel_type)===a)return t.event_id}}static validateEvent(e,t){const i=d.getTransactionId(e);if("string"!=typeof i||0===i.length)return!1;const n=d.getEventType(e),s=e.getContent();if(n===r.REQUEST_TYPE){if(!s||"string"!=typeof s.to||!s.to.length)return o.logger.log("InRoomChannel: validateEvent: no valid to "+(s&&s.to)),!1;if(!d.getOtherPartyUserId(e,t))return o.logger.log(`InRoomChannel: validateEvent: not directed to or sent by me: ${e.getSender()}, ${s&&s.to}`),!1}return r.VerificationRequest.validateEvent(n,e,t)}static getEventType(e){const t=e.getType();if(t===s){const t=e.getContent();if(t){const{msgtype:e}=t;if(e===r.REQUEST_TYPE)return r.REQUEST_TYPE}}return t&&t!==r.REQUEST_TYPE?t:""}handleEvent(e,t,i=!1){return n(this,void 0,void 0,(function*(){if(t.hasEventId(e.getId()))return;const n=d.getEventType(e);if(e.getRoomId()!==this.roomId)return;if(!this.userId){const t=d.getOtherPartyUserId(e,this.client);t&&(this.userId=t)}const r=this.client.getUserId(),s=e.getSender();if(this.userId&&s!==r&&s!==this.userId)return void o.logger.log(`InRoomChannel: ignoring verification event from non-participating sender ${s}`);this.requestEventId||(this.requestEventId=d.getTransactionId(e));const a=!!e.getUnsigned().transaction_id,c=e.getSender()===this.client.getUserId();return t.handleEvent(n,e,i,a,c)}))}completedContentFromEvent(e){const t=Object.assign({},e.getContent());return t[c]=e.getRelation(),t}completeContent(e,t){return t=Object.assign({},t),e!==r.REQUEST_TYPE&&e!==r.READY_TYPE&&e!==r.START_TYPE||(t.from_device=this.client.getDeviceId()),e===r.REQUEST_TYPE?t={body:this.client.getUserId()+" is requesting to verify your key, but your client does not support in-chat key verification. You will need to use legacy key verification to verify keys.",msgtype:r.REQUEST_TYPE,to:this.userId,from_device:t.from_device,methods:t.methods}:t[c]={rel_type:a,event_id:this.transactionId},t}send(e,t){const i=this.completeContent(e,t);return this.sendCompleted(e,i)}sendCompleted(e,t){return n(this,void 0,void 0,(function*(){let i=e;e===r.REQUEST_TYPE&&(i=s);const n=yield this.client.sendEvent(this.roomId,i,t);e===r.REQUEST_TYPE&&(this.requestEventId=n.event_id)}))}}i.InRoomChannel=d;i.InRoomRequests=class{constructor(){this.requestsByRoomId=new Map}getRequest(e){const t=e.getRoomId(),i=d.getTransactionId(e);return this.getRequestByTxnId(t,i)}getRequestByChannel(e){return this.getRequestByTxnId(e.roomId,e.transactionId)}getRequestByTxnId(e,t){const i=this.requestsByRoomId.get(e);if(i)return i.get(t)}setRequest(e,t){this.doSetRequest(e.getRoomId(),d.getTransactionId(e),t)}setRequestByChannel(e,t){this.doSetRequest(e.roomId,e.transactionId,t)}doSetRequest(e,t,i){let n=this.requestsByRoomId.get(e);n||(n=new Map,this.requestsByRoomId.set(e,n)),n.set(t,i)}removeRequest(e){const t=e.getRoomId(),i=this.requestsByRoomId.get(t);i&&(i.delete(d.getTransactionId(e)),0===i.size&&this.requestsByRoomId.delete(t))}findRequestInProgress(e){const t=this.requestsByRoomId.get(e);if(t)for(const e of t.values())if(e.pending)return e}}},{"../../../@types/event":306,"../../../logger":374,"./VerificationRequest":357}],356:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.ToDeviceRequests=i.ToDeviceChannel=void 0;const r=e("../../../randomstring"),o=e("../../../logger"),s=e("./VerificationRequest"),a=e("../Error"),c=e("../../../models/event");class d{constructor(e,t,i,n,r){this.client=e,this.userId=t,this.devices=i,this.transactionId=n,this.deviceId=r}isToDevices(e){if(e.length===this.devices.length){for(const t of e)if(!this.devices.includes(t))return!1;return!0}return!1}static getEventType(e){return e.getType()}static getTransactionId(e){const t=e.getContent();return t&&t.transaction_id}static canCreateRequest(e){return e===s.REQUEST_TYPE||e===s.START_TYPE}canCreateRequest(e){return d.canCreateRequest(e)}static validateEvent(e,t){if(e.isCancelled())return o.logger.warn("Ignoring flagged verification request from "+e.getSender()),!1;const i=e.getContent();if(!i)return o.logger.warn("ToDeviceChannel.validateEvent: invalid: no content"),!1;if(!i.transaction_id)return o.logger.warn("ToDeviceChannel.validateEvent: invalid: no transaction_id"),!1;const n=e.getType();if(n===s.REQUEST_TYPE){if(!Number.isFinite(i.timestamp))return o.logger.warn("ToDeviceChannel.validateEvent: invalid: no timestamp"),!1;if(e.getSender()===t.getUserId()&&i.from_device==t.getDeviceId())return o.logger.warn("ToDeviceChannel.validateEvent: invalid: from own device"),!1}return s.VerificationRequest.validateEvent(n,e,t)}getTimestamp(e){const t=e.getContent();return t&&t.timestamp}handleEvent(e,t,i=!1){return n(this,void 0,void 0,(function*(){const n=e.getType(),r=e.getContent();if(n===s.REQUEST_TYPE||n===s.READY_TYPE||n===s.START_TYPE){this.transactionId||(this.transactionId=r.transaction_id);const e=r.from_device;if(!this.deviceId&&this.devices.includes(e)&&(this.deviceId=e),!this.deviceId||this.deviceId!==e){const t=this.completeContent(s.CANCEL_TYPE,(0,a.errorFromEvent)((0,a.newUnexpectedMessageError)()));return this.sendToDevices(s.CANCEL_TYPE,t,[e])}}const o=t.phase===s.PHASE_STARTED||t.phase===s.PHASE_READY;yield t.handleEvent(e.getType(),e,i,!1,!1);const c=t.phase===s.PHASE_STARTED||t.phase===s.PHASE_READY;if((n===s.START_TYPE||n===s.READY_TYPE)&&!o&&c&&this.deviceId){const e=this.devices.filter((e=>e!==this.deviceId&&e!==this.client.getDeviceId()));if(e.length){const t=this.completeContent(s.CANCEL_TYPE,{code:"m.accepted",reason:"Verification request accepted by another device"});yield this.sendToDevices(s.CANCEL_TYPE,t,e)}}}))}completedContentFromEvent(e){return e.getContent()}completeContent(e,t){return t=Object.assign({},t),this.transactionId&&(t.transaction_id=this.transactionId),e!==s.REQUEST_TYPE&&e!==s.READY_TYPE&&e!==s.START_TYPE||(t.from_device=this.client.getDeviceId()),e===s.REQUEST_TYPE&&(t.timestamp=Date.now()),t}send(e,t={}){e!==s.REQUEST_TYPE&&e!==s.START_TYPE||this.transactionId||(this.transactionId=d.makeTransactionId());const i=this.completeContent(e,t);return this.sendCompleted(e,i)}sendCompleted(e,t){return n(this,void 0,void 0,(function*(){let i;i=e===s.REQUEST_TYPE||e===s.CANCEL_TYPE&&!this.deviceId?yield this.sendToDevices(e,t,this.devices):yield this.sendToDevices(e,t,[this.deviceId]);const n=new c.MatrixEvent({sender:this.client.getUserId(),content:t,type:e});return yield this.request.handleEvent(e,n,!0,!0,!0),i}))}sendToDevices(e,t,i){return n(this,void 0,void 0,(function*(){if(i.length){const n=new Map;for(const e of i)n.set(e,t);yield this.client.sendToDevice(e,new Map([[this.userId,n]]))}}))}static makeTransactionId(){return(0,r.randomString)(32)}}i.ToDeviceChannel=d;i.ToDeviceRequests=class{constructor(){this.requestsByUserId=new Map}getRequest(e){return this.getRequestBySenderAndTxnId(e.getSender(),d.getTransactionId(e))}getRequestByChannel(e){return this.getRequestBySenderAndTxnId(e.userId,e.transactionId)}getRequestBySenderAndTxnId(e,t){const i=this.requestsByUserId.get(e);if(i)return i.get(t)}setRequest(e,t){this.setRequestBySenderAndTxnId(e.getSender(),d.getTransactionId(e),t)}setRequestByChannel(e,t){this.setRequestBySenderAndTxnId(e.userId,e.transactionId,t)}setRequestBySenderAndTxnId(e,t,i){let n=this.requestsByUserId.get(e);n||(n=new Map,this.requestsByUserId.set(e,n)),n.set(t,i)}removeRequest(e){const t=e.getSender(),i=this.requestsByUserId.get(t);i&&(i.delete(d.getTransactionId(e)),0===i.size&&this.requestsByUserId.delete(t))}findRequestInProgress(e,t){const i=this.requestsByUserId.get(e);if(i)for(const e of i.values())if(e.pending&&e.channel.isToDevices(t))return e}getRequestsInProgress(e){const t=this.requestsByUserId.get(e);return t?Array.from(t.values()).filter((e=>e.pending)):[]}}},{"../../../logger":374,"../../../models/event":383,"../../../randomstring":398,"../Error":350,"./VerificationRequest":357}],357:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.VerificationRequest=i.VerificationRequestEvent=i.PHASE_DONE=i.PHASE_CANCELLED=i.PHASE_STARTED=i.PHASE_READY=i.PHASE_REQUESTED=i.PHASE_UNSENT=i.Phase=i.READY_TYPE=i.DONE_TYPE=i.CANCEL_TYPE=i.START_TYPE=i.REQUEST_TYPE=i.EVENT_PREFIX=void 0;const r=e("../../../logger"),o=e("../Error"),s=e("../QRCode"),a=e("../../../@types/event"),c=e("../../../models/typed-event-emitter");var d,l;i.EVENT_PREFIX="m.key.verification.",i.REQUEST_TYPE=i.EVENT_PREFIX+"request",i.START_TYPE=i.EVENT_PREFIX+"start",i.CANCEL_TYPE=i.EVENT_PREFIX+"cancel",i.DONE_TYPE=i.EVENT_PREFIX+"done",i.READY_TYPE=i.EVENT_PREFIX+"ready",function(e){e[e.Unsent=1]="Unsent",e[e.Requested=2]="Requested",e[e.Ready=3]="Ready",e[e.Started=4]="Started",e[e.Cancelled=5]="Cancelled",e[e.Done=6]="Done"}(d=i.Phase||(i.Phase={})),i.PHASE_UNSENT=d.Unsent,i.PHASE_REQUESTED=d.Requested,i.PHASE_READY=d.Ready,i.PHASE_STARTED=d.Started,i.PHASE_CANCELLED=d.Cancelled,i.PHASE_DONE=d.Done,function(e){e.Change="change"}(l=i.VerificationRequestEvent||(i.VerificationRequestEvent={}));class u extends c.TypedEventEmitter{constructor(e,t,o){super(),this.channel=e,this.verificationMethods=t,this.client=o,this.eventsByUs=new Map,this.eventsByThem=new Map,this._observeOnly=!1,this.timeoutTimer=null,this._accepting=!1,this._declining=!1,this.verifierHasFinished=!1,this._cancelled=!1,this._chosenMethod=null,this._qrCodeData=null,this.requestReceivedAt=null,this.commonMethods=[],this.cancelOnTimeout=()=>n(this,void 0,void 0,(function*(){try{this.initiatedByMe?yield this.cancel({reason:"Other party didn't accept in time",code:"m.timeout"}):yield this.cancel({reason:"User didn't accept in time",code:"m.timeout"})}catch(e){r.logger.error("Error while cancelling verification request",e)}})),this.channel.request=this,this.setPhase(i.PHASE_UNSENT,!1)}static validateEvent(e,t,n){const o=t.getContent();return!(!e||!e.startsWith(i.EVENT_PREFIX))&&(o?e!==i.REQUEST_TYPE&&e!==i.READY_TYPE||Array.isArray(o.methods)?e!==i.REQUEST_TYPE&&e!==i.READY_TYPE&&e!==i.START_TYPE||"string"==typeof o.from_device&&0!==o.from_device.length||(r.logger.log("VerificationRequest: validateEvent: fail because from_device"),!1):(r.logger.log("VerificationRequest: validateEvent: fail because methods"),!1):(r.logger.log("VerificationRequest: validateEvent: no content"),!1))}get invalid(){return this.phase===i.PHASE_UNSENT}get requested(){return this.phase===i.PHASE_REQUESTED}get cancelled(){return this.phase===i.PHASE_CANCELLED}get ready(){return this.phase===i.PHASE_READY}get started(){return this.phase===i.PHASE_STARTED}get done(){return this.phase===i.PHASE_DONE}get methods(){return this.commonMethods}get chosenMethod(){return this._chosenMethod}calculateEventTimeout(e){let t=this.channel.getTimestamp(e)+6e5;if(this.requestReceivedAt&&!this.initiatedByMe&&this.phase<=i.PHASE_REQUESTED){const e=this.requestReceivedAt+12e4;t=Math.min(t,e)}return Math.max(0,t-Date.now())}get timeout(){const e=this.getEventByEither(i.REQUEST_TYPE);return e?this.calculateEventTimeout(e):0}get requestEvent(){return this.getEventByEither(i.REQUEST_TYPE)}get phase(){return this._phase}get verifier(){return this._verifier}get canAccept(){return this.phase{const n=()=>{let r=!1;return e(this)?(t(this),r=!0):this.cancelled&&(i(new Error("cancelled")),r=!0),r&&this.off(l.Change,n),r};n()||this.on(l.Change,n)}))}setPhase(e,t=!0){this._phase=e,t&&this.emit(l.Change)}getEventByEither(e){return this.eventsByThem.get(e)||this.eventsByUs.get(e)}getEventBy(e,t=!1){return t?this.eventsByThem.get(e):this.eventsByUs.get(e)}calculatePhaseTransitions(){const e=[{phase:i.PHASE_UNSENT}],t=()=>e[e.length-1].phase,n=this.eventsByThem.has(i.REQUEST_TYPE),r=this.getEventBy(i.REQUEST_TYPE,n);r&&e.push({phase:i.PHASE_REQUESTED,event:r});const o=r&&this.getEventBy(i.READY_TYPE,!n);let s;if(o&&t()===i.PHASE_REQUESTED&&e.push({phase:i.PHASE_READY,event:o}),o||!r){const e=this.eventsByThem.get(i.START_TYPE),t=this.eventsByUs.get(i.START_TYPE);s=e&&t?e.getSender()this.verificationMethods.has(e)))}if(this.observeOnly||t!==i.PHASE_REQUESTED&&t!==i.PHASE_STARTED&&t!==i.PHASE_READY||this.channel.receiveStartFromOtherDevices&&this.wasSentByOwnUser(n)&&!this.wasSentByOwnDevice(n)&&(this._observeOnly=!0),t===i.PHASE_STARTED){const{method:e}=n.getContent();this._verifier||this.observeOnly||(this._verifier=this.createVerifier(e,n),this._verifier?this._chosenMethod=e:this.cancel({code:"m.unknown_method",reason:`Unknown method: ${e}`}))}}applyPhaseTransitions(){const e=this.calculatePhaseTransitions(),t=e.findIndex((e=>e.phase===this.phase)),i=e.slice(t+1);for(const e of i)this.transitionToPhase(e);return i}isWinningStartRace(e){if(e.getType()!==i.START_TYPE)return!1;const t=this._verifier.startEvent;let n,r;if(this.isSelfVerification)if(t){const e=t.getContent();n=e&&e.from_device}else n=this.client.getDeviceId();else n=t?t.getSender():this.client.getUserId();if(this.isSelfVerification){const t=e.getContent();r=t&&t.from_device}else r=e.getSender();return re.phase===i.PHASE_READY))){this.otherPartySupportsMethod(s.SCAN_QR_CODE_METHOD,!0)&&(this._qrCodeData=yield s.QRCodeData.create(this,this.client))}const e=h[h.length-1],{phase:t}=e;this.setupTimeout(t),this.setPhase(t)}else this._observeOnly!==n&&this.emit(l.Change)}finally{r.logger.log(`Verification request ${this.channel.transactionId}: ${e} event with id:${t.getId()}, content:${JSON.stringify(t.getContent())} deviceId:${this.channel.deviceId}, sender:${t.getSender()}, isSentByUs:${c}, isLiveEvent:${o}, isRemoteEcho:${a}, phase:${u}=>${this.phase}, observeOnly:${n}=>${this._observeOnly}`)}}))}setupTimeout(e){if(!this.timeoutTimer&&!this.observeOnly&&e===i.PHASE_REQUESTED&&(this.timeoutTimer=setTimeout(this.cancelOnTimeout,this.timeout)),this.timeoutTimer){(e===i.PHASE_STARTED||e===i.PHASE_READY||e===i.PHASE_DONE||e===i.PHASE_CANCELLED)&&(clearTimeout(this.timeoutTimer),this.timeoutTimer=null)}}cancelOnError(e,t){return n(this,void 0,void 0,(function*(){if(e===i.START_TYPE){const e=t.getContent().method;if(!this.verificationMethods.has(e))return yield this.cancel((0,o.errorFromEvent)((0,o.newUnknownMethodError)())),!0}const n=e===i.REQUEST_TYPE&&this.phase!==i.PHASE_UNSENT,s=e===i.READY_TYPE&&this.phase!==i.PHASE_REQUESTED&&this.phase!==i.PHASE_STARTED;if(this.phase!==i.PHASE_UNSENT&&(n||s)){r.logger.warn(`Cancelling, unexpected ${e} verification event from ${t.getSender()}`);const i=`Unexpected ${e} event in phase ${this.phase}`;return yield this.cancel((0,o.errorFromEvent)((0,o.newUnexpectedMessageError)({reason:i}))),!0}return!1}))}adjustObserveOnly(e,t=!1){t||(this._observeOnly=!0),this.calculateEventTimeout(e)<3e3&&(this._observeOnly=!0)}addEvent(e,t,n=!1){if(n?this.eventsByUs.set(e,t):this.eventsByThem.set(e,t),e===i.REQUEST_TYPE){for(const[e,t]of this.eventsByThem.entries())t.getSender()!==this.otherUserId&&this.eventsByThem.delete(e);this.requestReceivedAt=Date.now()}}createVerifier(e,t=null,i=null){i||(i=this.targetDevice);const{userId:n,deviceId:o}=i,s=this.verificationMethods.get(e);if(s)return new s(this.channel,this.client,n,o,t,this);r.logger.warn("could not find verifier constructor for method",e)}wasSentByOwnUser(e){return(null==e?void 0:e.getSender())===this.client.getUserId()}wasSentByOwnDevice(e){if(!this.wasSentByOwnUser(e))return!1;const t=e.getContent();return!(!t||t.from_device!==this.client.getDeviceId())}onVerifierCancelled(){this._cancelled=!0;const e=this.applyPhaseTransitions();e.length&&this.setPhase(e[e.length-1].phase)}onVerifierFinished(){this.channel.send(a.EventType.KeyVerificationDone,{}),this.verifierHasFinished=!0;const e=this.applyPhaseTransitions();e.length&&this.setPhase(e[e.length-1].phase)}getEventFromOtherParty(e){return this.eventsByThem.get(e)}}i.VerificationRequest=u},{"../../../@types/event":306,"../../../logger":374,"../../../models/typed-event-emitter":395,"../Error":350,"../QRCode":352}],358:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},r=this&&this.__asyncValues||function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise((function(n,r){(function(e,t,i,n){Promise.resolve(n).then((function(t){e({value:t,done:i})}),t)})(n,r,(t=e[i](t)).done,t.value)}))}}};Object.defineProperty(i,"__esModule",{value:!0}),i.RoomWidgetClient=void 0;const o=e("matrix-widget-api"),s=e("./models/event"),a=e("./@types/event"),c=e("./logger"),d=e("./client"),l=e("./sync"),u=e("./sliding-sync-sdk"),h=e("./models/event"),f=e("./models/user"),p=e("./utils");class g extends d.MatrixClient{constructor(e,t,i,r){var s,u,f,p,g,v,m,y,b,S;super(r),this.widgetApi=e,this.capabilities=t,this.roomId=i,this.widgetApiReady=new Promise((e=>this.widgetApi.once("ready",e))),this.syncState=null,this.onEvent=e=>n(this,void 0,void 0,(function*(){if(e.preventDefault(),e.detail.data.room_id===this.roomId){const t=new h.MatrixEvent(e.detail.data);yield this.syncApi.injectRoomEvents(this.room,[],[t]),this.emit(d.ClientEvent.Event,t),this.setSyncState(l.SyncState.Syncing),c.logger.info(`Received event ${t.getId()} ${t.getType()} ${t.getStateKey()}`)}else{const{event_id:t,room_id:i}=e.detail.data;c.logger.info(`Received event ${t} for a different room ${i}; discarding`)}yield this.ack(e)})),this.onToDevice=e=>n(this,void 0,void 0,(function*(){e.preventDefault();const t=new h.MatrixEvent({type:e.detail.data.type,sender:e.detail.data.sender,content:e.detail.data.content});e.detail.data.encrypted&&t.makeEncrypted(a.EventType.RoomMessageEncrypted,{},"",""),this.emit(d.ClientEvent.ToDeviceEvent,t),this.setSyncState(l.SyncState.Syncing),yield this.ack(e)})),((null===(s=t.sendEvent)||void 0===s?void 0:s.length)||(null===(u=t.receiveEvent)||void 0===u?void 0:u.length)||!0===t.sendMessage||Array.isArray(t.sendMessage)&&t.sendMessage.length||!0===t.receiveMessage||Array.isArray(t.receiveMessage)&&t.receiveMessage.length||(null===(f=t.sendState)||void 0===f?void 0:f.length)||(null===(p=t.receiveState)||void 0===p?void 0:p.length))&&e.requestCapabilityForRoomTimeline(i),null===(g=t.sendEvent)||void 0===g||g.forEach((t=>e.requestCapabilityToSendEvent(t))),null===(v=t.receiveEvent)||void 0===v||v.forEach((t=>e.requestCapabilityToReceiveEvent(t))),!0===t.sendMessage?e.requestCapabilityToSendMessage():Array.isArray(t.sendMessage)&&t.sendMessage.forEach((t=>e.requestCapabilityToSendMessage(t))),!0===t.receiveMessage?e.requestCapabilityToReceiveMessage():Array.isArray(t.receiveMessage)&&t.receiveMessage.forEach((t=>e.requestCapabilityToReceiveMessage(t))),null===(m=t.sendState)||void 0===m||m.forEach((({eventType:t,stateKey:i})=>e.requestCapabilityToSendState(t,i))),null===(y=t.receiveState)||void 0===y||y.forEach((({eventType:t,stateKey:i})=>e.requestCapabilityToReceiveState(t,i))),null===(b=t.sendToDevice)||void 0===b||b.forEach((t=>e.requestCapabilityToSendToDevice(t))),null===(S=t.receiveToDevice)||void 0===S||S.forEach((t=>e.requestCapabilityToReceiveToDevice(t))),t.turnServers&&e.requestCapability(o.MatrixCapabilities.MSC3846TurnServers),e.on(`action:${o.WidgetApiToWidgetAction.SendEvent}`,this.onEvent),e.on(`action:${o.WidgetApiToWidgetAction.SendToDevice}`,this.onToDevice),e.start()}startClient(e={}){var t,i;return n(this,void 0,void 0,(function*(){this.lifecycle=new AbortController;const r=this.getUserId();r&&this.store.storeUser(new f.User(r)),e.slidingSync?this.syncApi=new u.SlidingSyncSdk(e.slidingSync,this,e,this.buildSyncApiOptions()):this.syncApi=new l.SyncApi(this,e,this.buildSyncApiOptions()),this.room=this.syncApi.createRoom(this.roomId),this.store.storeRoom(this.room),yield this.widgetApiReady,yield Promise.all(null!==(i=null===(t=this.capabilities.receiveState)||void 0===t?void 0:t.map((({eventType:e,stateKey:t})=>n(this,void 0,void 0,(function*(){const i=(yield this.widgetApi.readStateEvents(e,void 0,t,[this.roomId])).map((e=>new h.MatrixEvent(e)));yield this.syncApi.injectRoomEvents(this.room,[],i),i.forEach((e=>{this.emit(d.ClientEvent.Event,e),c.logger.info(`Backfilled event ${e.getId()} ${e.getType()} ${e.getStateKey()}`)}))})))))&&void 0!==i?i:[]),this.setSyncState(l.SyncState.Syncing),c.logger.info("Finished backfilling events"),this.capabilities.turnServers&&this.watchTurnServers()}))}stopClient(){this.widgetApi.off(`action:${o.WidgetApiToWidgetAction.SendEvent}`,this.onEvent),this.widgetApi.off(`action:${o.WidgetApiToWidgetAction.SendToDevice}`,this.onToDevice),super.stopClient(),this.lifecycle.abort()}joinRoom(e){return n(this,void 0,void 0,(function*(){if(e===this.roomId)return this.room;throw new Error(`Unknown room: ${e}`)}))}encryptAndSendEvent(e,t){return n(this,void 0,void 0,(function*(){let i;try{i=yield this.widgetApi.sendRoomEvent(t.getType(),t.getContent(),e.roomId)}catch(i){throw this.updatePendingEventStatus(e,t,s.EventStatus.NOT_SENT),i}return e.updatePendingEvent(t,s.EventStatus.SENT,i.event_id),{event_id:i.event_id}}))}sendStateEvent(e,t,i,r=""){return n(this,void 0,void 0,(function*(){return yield this.widgetApi.sendStateEvent(t,r,i,e)}))}sendToDevice(e,t){return n(this,void 0,void 0,(function*(){return yield this.widgetApi.sendToDevice(e,!1,(0,p.recursiveMapToObject)(t)),{}}))}queueToDevice({eventType:e,batch:t}){return n(this,void 0,void 0,(function*(){const i=new p.MapWithDefault((()=>new Map));for(const{userId:e,deviceId:n,payload:r}of t)i.getOrCreate(e).set(n,r);yield this.widgetApi.sendToDevice(e,!1,(0,p.recursiveMapToObject)(i))}))}encryptAndSendToDevices(e,t){return n(this,void 0,void 0,(function*(){const i=new p.MapWithDefault((()=>new Map));for(const{userId:n,deviceInfo:{deviceId:r}}of e)i.getOrCreate(n).set(r,t);yield this.widgetApi.sendToDevice(t.type,!0,(0,p.recursiveMapToObject)(i))}))}checkTurnServers(){return n(this,void 0,void 0,(function*(){return this.turnServers.length>0}))}getSyncState(){return this.syncState}setSyncState(e){const t=this.syncState;this.syncState=e,this.emit(d.ClientEvent.Sync,e,t)}ack(e){return n(this,void 0,void 0,(function*(){yield this.widgetApi.transport.reply(e.detail,{})}))}watchTurnServers(){var e,t,i,o;return n(this,void 0,void 0,(function*(){const n=this.widgetApi.getTurnServers(),s=()=>{n.return(void 0)};this.lifecycle.signal.addEventListener("abort",s);try{try{for(var a,l=!0,u=r(n);a=yield u.next(),!(e=a.done);){o=a.value,l=!1;try{const e=o;this.turnServers=[{urls:e.uris,username:e.username,credential:e.password}],this.emit(d.ClientEvent.TurnServers,this.turnServers),c.logger.log(`Received TURN server: ${e.uris}`)}finally{l=!0}}}catch(e){t={error:e}}finally{try{l||e||!(i=u.return)||(yield i.call(u))}finally{if(t)throw t.error}}}catch(e){c.logger.warn("Error watching TURN servers",e)}finally{this.lifecycle.signal.removeEventListener("abort",s)}}))}}i.RoomWidgetClient=g},{"./@types/event":306,"./client":321,"./logger":374,"./models/event":383,"./models/user":396,"./sliding-sync-sdk":406,"./sync":414,"./utils":416,"matrix-widget-api":178}],359:[function(e,t,i){"use strict";var n,r;Object.defineProperty(i,"__esModule",{value:!0}),i.KeySignatureUploadError=i.InvalidCryptoStoreError=i.InvalidCryptoStoreState=i.InvalidStoreError=i.InvalidStoreState=void 0,function(e){e[e.ToggledLazyLoading=0]="ToggledLazyLoading"}(n=i.InvalidStoreState||(i.InvalidStoreState={}));class o extends Error{constructor(e,t){super(`Store is invalid because ${e}, please stop the client, delete all data and start the client again`),this.reason=e,this.value=t,this.name="InvalidStoreError"}}i.InvalidStoreError=o,o.TOGGLED_LAZY_LOADING=n.ToggledLazyLoading,function(e){e.TooNew="TOO_NEW"}(r=i.InvalidCryptoStoreState||(i.InvalidCryptoStoreState={}));class s extends Error{constructor(e){super(`Crypto store is invalid because ${e}, please stop the client, delete all data and start the client again`),this.reason=e,this.name="InvalidCryptoStoreError"}}i.InvalidCryptoStoreError=s,s.TOO_NEW=r.TooNew;class a extends Error{constructor(e,t){super(e),this.value=t}}i.KeySignatureUploadError=a},{}],360:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.eventMapperFor=void 0;const n=e("./models/event"),r=e("./@types/event");i.eventMapperFor=function(e,t){let i=Boolean(t.preventReEmit);const o=!1!==t.decrypt;return function s(a){t.toDevice&&delete a.room_id;const c=e.getRoom(a.room_id);let d;c&&void 0===a.state_key&&(d=c.findEventById(a.event_id)),!d||d.status?d=new n.MatrixEvent(a):(d.setUnsigned(Object.assign(Object.assign({},d.getUnsigned()),a.unsigned)),i=!0);const l=d.getServerAggregatedRelation(r.RelationType.Replace);if(null==l?void 0:l.content){const e=s(l);d.makeReplaced(e)}const u=null==c?void 0:c.findThreadForEvent(d);return u&&d.setThread(u),d.isEncrypted()&&(i||e.reEmitter.reEmit(d,[n.MatrixEventEvent.Decrypted]),o&&e.decryptEventIfNeeded(d)),i||(e.reEmitter.reEmit(d,[n.MatrixEventEvent.Replaced,n.MatrixEventEvent.VisibilityChange]),null==c||c.reEmitter.reEmit(d,[n.MatrixEventEvent.BeforeRedaction])),d}}},{"./@types/event":306,"./models/event":383}],361:[function(e,t,i){"use strict";function n(e){return null!=e}Object.defineProperty(i,"__esModule",{value:!0}),i.isOptionalAString=i.isProvided=void 0,i.isProvided=n,i.isOptionalAString=function(e){return n(e)&&"string"==typeof e}},{}],362:[function(e,t,i){"use strict";var n,r,o=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.buildFeatureSupportMap=i.Feature=i.ServerSupport=void 0,function(e){e[e.Stable=0]="Stable",e[e.Unstable=1]="Unstable",e[e.Unsupported=2]="Unsupported"}(n=i.ServerSupport||(i.ServerSupport={})),function(e){e.Thread="Thread",e.ThreadUnreadNotifications="ThreadUnreadNotifications",e.LoginTokenRequest="LoginTokenRequest",e.RelationBasedRedactions="RelationBasedRedactions",e.AccountDataDeletion="AccountDataDeletion"}(r=i.Feature||(i.Feature={}));const s={[r.Thread]:{unstablePrefixes:["org.matrix.msc3440"],matrixVersion:"v1.3"},[r.ThreadUnreadNotifications]:{unstablePrefixes:["org.matrix.msc3771","org.matrix.msc3773"],matrixVersion:"v1.4"},[r.LoginTokenRequest]:{unstablePrefixes:["org.matrix.msc3882"]},[r.RelationBasedRedactions]:{unstablePrefixes:["org.matrix.msc3912"]},[r.AccountDataDeletion]:{unstablePrefixes:["org.matrix.msc3391"]}};i.buildFeatureSupportMap=function(e){var t,i,r,a;return o(this,void 0,void 0,(function*(){const o=new Map;for(const[c,d]of Object.entries(s)){const s=null!==(i=null===(t=e.versions)||void 0===t?void 0:t.includes(d.matrixVersion||""))&&void 0!==i&&i,l=null!==(a=null===(r=d.unstablePrefixes)||void 0===r?void 0:r.every((t=>{var i;return!0===(null===(i=e.unstable_features)||void 0===i?void 0:i[t])})))&&void 0!==a&&a;s?o.set(c,n.Stable):l?o.set(c,n.Unstable):o.set(c,n.Unsupported)}return o}))}},{}],363:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.FilterComponent=void 0;const n=e("./models/thread");i.FilterComponent=class{constructor(e,t){this.filterJson=e,this.userId=t}check(e){var t,i;const r=(null===(t=e.getUnsigned())||void 0===t?void 0:t["m.relations"])||{},o=Object.keys(r),s=[];return this.userId&&(null===(i=null==r?void 0:r[n.THREAD_RELATION_TYPE.name])||void 0===i?void 0:i.current_user_participated)&&s.push(this.userId),this.checkFields(e.getRoomId(),e.getSender(),e.getType(),!!e.getContent()&&void 0!==e.getContent().url,o,s)}toJSON(){return{types:this.filterJson.types||null,not_types:this.filterJson.not_types||[],rooms:this.filterJson.rooms||null,not_rooms:this.filterJson.not_rooms||[],senders:this.filterJson.senders||null,not_senders:this.filterJson.not_senders||[],contains_url:this.filterJson.contains_url||null,[n.FILTER_RELATED_BY_SENDERS.name]:this.filterJson[n.FILTER_RELATED_BY_SENDERS.name]||[],[n.FILTER_RELATED_BY_REL_TYPES.name]:this.filterJson[n.FILTER_RELATED_BY_REL_TYPES.name]||[]}}checkFields(e,t,i,r,o,s){const a={rooms:function(t){return e===t},senders:function(e){return t===e},types:function(e){return function(e,t){if(t.endsWith("*")){const i=t.slice(0,-1);return e.slice(0,i.length)===i}return e===t}(i,e)}};for(const e in a){const t=a[e],i="not_"+e,n=this.filterJson[i];if(null==n?void 0:n.some(t))return!1;const r=this.filterJson[e];if(r&&!r.some(t))return!1}const c=this.filterJson.contains_url;if(void 0!==c&&c!==r)return!1;const d=this.filterJson[n.FILTER_RELATED_BY_REL_TYPES.name];if(void 0!==d&&!this.arrayMatchesFilter(d,o))return!1;const l=this.filterJson[n.FILTER_RELATED_BY_SENDERS.name];return!(void 0!==l&&!this.arrayMatchesFilter(l,s))}arrayMatchesFilter(e,t){return t.length>0&&e.every((e=>t.includes(e)))}filter(e){return e.filter(this.check,this)}limit(){return void 0!==this.filterJson.limit?this.filterJson.limit:10}}},{"./models/thread":394}],364:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Filter=void 0;const n=e("./@types/sync"),r=e("./filter-component");function o(e,t,i){const n=t.split(".");let r=e;for(let e=0;e{"M_UNKNOWN_TOKEN"!=e.errcode||(null==r?void 0:r.inhibitLogoutEmit)?"M_CONSENT_NOT_GIVEN"==e.errcode&&this.eventEmitter.emit(l.HttpApiEvent.NoConsent,e.message,e.data.consent_uri):this.eventEmitter.emit(l.HttpApiEvent.SessionLoggedOut,e)})),o}request(e,t,i,n,r){const o=this.getUrl(t,i,null==r?void 0:r.prefix,null==r?void 0:r.baseUrl);return this.requestOtherUrl(e,o,n,r)}requestOtherUrl(e,t,i,n={}){var r,o,a,c;return s(this,void 0,void 0,(function*(){const s=Object.assign({},n.headers||{}),l=null===(r=n.json)||void 0===r||r,h=l&&(null===(o=null==i?void 0:i.constructor)||void 0===o?void 0:o.name)===Object.name;l&&(h&&!s["Content-Type"]&&(s["Content-Type"]="application/json"),s.Accept||(s.Accept="application/json"));const f=null!==(a=n.localTimeoutMs)&&void 0!==a?a:this.opts.localTimeoutMs,p=null!==(c=n.keepAlive)&&void 0!==c&&c,g=[this.abortController.signal];let v;void 0!==f&&g.push((0,u.timeoutSignal)(f)),n.abortSignal&&g.push(n.abortSignal),v=h?JSON.stringify(i):i;const{signal:m,cleanup:y}=(0,u.anySignal)(g);let b;try{b=yield this.fetch(t,{signal:m,method:e,body:v,headers:s,mode:"cors",redirect:"follow",referrer:"",referrerPolicy:"no-referrer",cache:"no-cache",credentials:"omit",keepalive:p})}catch(e){if("AbortError"===e.name)throw e;throw new d.ConnectionError("fetch failed",e)}finally{y()}if(!b.ok)throw(0,u.parseErrorResponse)(b,yield b.text());return this.opts.onlyData?l?b.json():b.text():b}))}getUrl(e,t,i,n){const r=new URL((null!=n?n:this.opts.baseUrl)+(null!=i?i:this.opts.prefix)+e);return t&&a.encodeParams(t,r.searchParams),r}}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../utils":416,"./errors":365,"./interface":368,"./method":369,"./utils":371}],367:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(i,"__esModule",{value:!0}),i.MatrixHttpApi=void 0;const a=e("./fetch"),c=e("./prefix"),d=o(e("../utils")),l=o(e("../realtime-callbacks")),u=e("./method"),h=e("./errors"),f=e("./utils");s(e("./interface"),i),s(e("./prefix"),i),s(e("./errors"),i),s(e("./method"),i),s(e("./utils"),i);class p extends a.FetchHttpApi{constructor(){super(...arguments),this.uploads=[]}uploadContent(e,i={}){var n,r,o,s,a;const p=null===(n=i.includeFilename)||void 0===n||n,g=null!==(r=i.abortController)&&void 0!==r?r:new AbortController,v=null!==(s=null!==(o=i.type)&&void 0!==o?o:e.type)&&void 0!==s?s:"application/octet-stream",m=null!==(a=i.name)&&void 0!==a?a:e.name,y={loaded:0,total:0,abortController:g},b=d.defer();if(t.XMLHttpRequest){const n=new t.XMLHttpRequest,r=function(){n.abort(),b.reject(new Error("Timeout"))};let o=l.setTimeout(r,3e4);n.onreadystatechange=function(){if(n.readyState===t.XMLHttpRequest.DONE){l.clearTimeout(o);try{if(0===n.status)throw new DOMException(n.statusText,"AbortError");if(!n.responseText)throw new Error("No response body.");n.status>=400?b.reject((0,f.parseErrorResponse)(n,n.responseText)):b.resolve(JSON.parse(n.responseText))}catch(e){if("AbortError"===e.name)return void b.reject(e);b.reject(new h.ConnectionError("request failed",e))}}},n.upload.onprogress=e=>{var t;l.clearTimeout(o),y.loaded=e.loaded,y.total=e.total,o=l.setTimeout(r,3e4),null===(t=i.progressHandler)||void 0===t||t.call(i,{loaded:e.loaded,total:e.total})};const s=this.getUrl("/upload",void 0,c.MediaPrefix.R0);p&&m&&s.searchParams.set("filename",encodeURIComponent(m)),!this.opts.useAuthorizationHeader&&this.opts.accessToken&&s.searchParams.set("access_token",encodeURIComponent(this.opts.accessToken)),n.open(u.Method.Post,s.href),this.opts.useAuthorizationHeader&&this.opts.accessToken&&n.setRequestHeader("Authorization","Bearer "+this.opts.accessToken),n.setRequestHeader("Content-Type",v),n.send(e),g.signal.addEventListener("abort",(()=>{n.abort()}))}else{const t={};p&&m&&(t.filename=m);const i={"Content-Type":v};this.authedRequest(u.Method.Post,"/upload",t,e,{prefix:c.MediaPrefix.R0,headers:i,abortSignal:g.signal}).then((e=>this.opts.onlyData?e:e.json())).then(b.resolve,b.reject)}return y.promise=b.promise.finally((()=>{d.removeElement(this.uploads,(e=>e===y))})),g.signal.addEventListener("abort",(()=>{d.removeElement(this.uploads,(e=>e===y)),b.reject(new DOMException("Aborted","AbortError"))})),this.uploads.push(y),y.promise}cancelUpload(e){const t=this.uploads.find((t=>t.promise===e));return!!t&&(t.abortController.abort(),!0)}getCurrentUploads(){return this.uploads}getContentUri(){return{base:this.opts.baseUrl,path:c.MediaPrefix.R0+"/upload",params:{access_token:this.opts.accessToken}}}}i.MatrixHttpApi=p}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../realtime-callbacks":399,"../utils":416,"./errors":365,"./fetch":366,"./interface":368,"./method":369,"./prefix":370,"./utils":371}],368:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.HttpApiEvent=void 0,function(e){e.SessionLoggedOut="Session.logged_out",e.NoConsent="no_consent"}(i.HttpApiEvent||(i.HttpApiEvent={}))},{}],369:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Method=void 0,function(e){e.Get="GET",e.Put="PUT",e.Post="POST",e.Delete="DELETE"}(i.Method||(i.Method={}))},{}],370:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MediaPrefix=i.IdentityPrefix=i.ClientPrefix=void 0,function(e){e.R0="/_matrix/client/r0",e.V1="/_matrix/client/v1",e.V3="/_matrix/client/v3",e.Unstable="/_matrix/client/unstable"}(i.ClientPrefix||(i.ClientPrefix={})),function(e){e.V2="/_matrix/identity/v2"}(i.IdentityPrefix||(i.IdentityPrefix={})),function(e){e.R0="/_matrix/media/r0"}(i.MediaPrefix||(i.MediaPrefix={}))},{}],371:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.retryNetworkOperation=i.parseErrorResponse=i.anySignal=i.timeoutSignal=void 0;const r=e("content-type"),o=e("../logger"),s=e("../utils"),a=e("./errors");function c(e){return"getResponseHeader"in e}i.timeoutSignal=function(e){const t=new AbortController;return setTimeout((()=>{t.abort()}),e),t.signal},i.anySignal=function(e){const t=new AbortController;function i(){for(const t of e)t.removeEventListener("abort",n)}function n(){t.abort(),i()}for(const t of e){if(t.aborted){n();break}t.addEventListener("abort",n)}return{signal:t.signal,cleanup:i}},i.parseErrorResponse=function(e,t){let i;try{i=function(e){let t;t=c(e)?e.getResponseHeader("Content-Type"):e.headers.get("Content-Type");if(!t)return null;try{return(0,r.parse)(t)}catch(e){throw new Error(`Error parsing Content-Type '${t}': ${e}`)}}(e)}catch(e){return e}return"application/json"===(null==i?void 0:i.type)&&t?new a.MatrixError(JSON.parse(t),e.status,c(e)?e.responseURL:e.url):"text/plain"===(null==i?void 0:i.type)?new a.HTTPError(`Server returned ${e.status} error: ${t}`,e.status):new a.HTTPError(`Server returned ${e.status} error`,e.status)},i.retryNetworkOperation=function(e,t){return n(this,void 0,void 0,(function*(){let i=0,n=null;for(;i0){const e=1e3*Math.pow(2,i);o.logger.log(`network operation failed ${i} times, retrying in ${e}ms...`),yield(0,s.sleep)(e)}return yield t()}catch(e){if(!(e instanceof a.ConnectionError))throw e;i+=1,n=e}throw n}))}},{"../logger":374,"../utils":416,"./errors":365,"content-type":72}],372:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.exists=void 0,i.exists=function(e,t){return new Promise(((i,n)=>{let r=!0;const o=e.open(t);o.onupgradeneeded=()=>{r=!1},o.onblocked=()=>n(o.error),o.onsuccess=()=>{o.result.close(),r||e.deleteDatabase(t),i(r)},o.onerror=()=>n(o.error)}))}},{}],373:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.InteractiveAuth=i.AuthType=void 0;const r=e("./logger"),o=e("./utils"),s="m.login.email.identity",a="m.login.msisdn";var c;!function(e){e.Password="m.login.password",e.Recaptcha="m.login.recaptcha",e.Terms="m.login.terms",e.Email="m.login.email.identity",e.Msisdn="m.login.msisdn",e.Sso="m.login.sso",e.SsoUnstable="org.matrix.login.sso",e.Dummy="m.login.dummy",e.RegistrationToken="m.login.registration_token",e.UnstableRegistrationToken="org.matrix.msc3231.login.registration_token"}(c=i.AuthType||(i.AuthType={}));class d extends Error{constructor(e,t,i){super(e),this.required_stages=t,this.flows=i,this.name="NoAuthFlowFoundError"}}i.InteractiveAuth=class{constructor(e){this.requestingEmailToken=!1,this.attemptAuthDeferred=null,this.chosenFlow=null,this.currentStage=null,this.emailAttempt=1,this.submitPromise=null,this.requestEmailToken=()=>n(this,void 0,void 0,(function*(){if(this.requestingEmailToken)r.logger.warn("Could not request email token: Already requesting");else{r.logger.trace("Requesting email token. Attempt: "+this.emailAttempt),this.requestingEmailToken=!0;try{const e=yield this.requestEmailTokenCallback(this.inputs.emailAddress,this.clientSecret,this.emailAttempt++,this.data.session);this.emailSid=e.sid,r.logger.trace("Email token request succeeded")}finally{this.requestingEmailToken=!1}}})),this.matrixClient=e.matrixClient,this.data=e.authData||{},this.requestCallback=e.doRequest,this.busyChangedCallback=e.busyChanged,this.stateUpdatedCallback=e.stateUpdated||e.startAuthStage,this.requestEmailTokenCallback=e.requestEmailToken,this.inputs=e.inputs||{},e.sessionId&&(this.data.session=e.sessionId),this.clientSecret=e.clientSecret||this.matrixClient.generateClientSecret(),this.emailSid=e.emailSid}attemptAuth(){var e,t;this.attemptAuthDeferred=(0,o.defer)();const i=this.attemptAuthDeferred.promise;if(null===(e=this.data)||void 0===e?void 0:e.flows)this.startNextAuthStage();else{null===(t=this.busyChangedCallback)||void 0===t||t.call(this,!0);const e=this.data.session?{session:this.data.session}:null;this.doRequest(e).finally((()=>{var e;null===(e=this.busyChangedCallback)||void 0===e||e.call(this,!1)}))}return i}poll(){return n(this,void 0,void 0,(function*(){if(!this.data.session)return;if(!this.attemptAuthDeferred)return;if(this.submitPromise)return;let e={};if(this.currentStage==s&&this.emailSid){const t={sid:this.emailSid,client_secret:this.clientSecret};if(yield this.matrixClient.doesServerRequireIdServerParam()){const e=new URL(this.matrixClient.getIdentityServerUrl());t.id_server=e.host}e={type:s,threepid_creds:t,threepidCreds:t}}this.submitAuthDict(e,!0)}))}getSessionId(){var e;return null===(e=this.data)||void 0===e?void 0:e.session}getClientSecret(){return this.clientSecret}getStageParams(e){var t;return null===(t=this.data.params)||void 0===t?void 0:t[e]}getChosenFlow(){return this.chosenFlow}submitAuthDict(e,t=!1){var i,r;return n(this,void 0,void 0,(function*(){if(!this.attemptAuthDeferred)throw new Error("submitAuthDict() called before attemptAuth()");for(t||null===(i=this.busyChangedCallback)||void 0===i||i.call(this,!0);this.submitPromise;)try{yield this.submitPromise}catch(e){}let n;this.data.session?(n={session:this.data.session},Object.assign(n,e)):n=e;try{this.submitPromise=this.doRequest(n,t),yield this.submitPromise}finally{this.submitPromise=null,t||null===(r=this.busyChangedCallback)||void 0===r||r.call(this,!1)}}))}getEmailSid(){return this.emailSid}setEmailSid(e){this.emailSid=e}doRequest(e,t=!1){var i,o,s,a;return n(this,void 0,void 0,(function*(){try{const i=yield this.requestCallback(e,t);this.attemptAuthDeferred.resolve(i),this.attemptAuthDeferred=null}catch(e){const n=null!==(o=null===(i=e.data)||void 0===i?void 0:i.flows)&&void 0!==o?o:null,d=this.data.flows||Boolean(n);401===e.httpStatus&&e.data&&d||(t?r.logger.log("Background poll request failed doing UI auth: ignoring",e):null===(s=this.attemptAuthDeferred)||void 0===s||s.reject(e)),e.data||(e.data={}),e.data.flows||e.data.completed||e.data.session||(e.data.flows=this.data.flows,e.data.completed=this.data.completed,e.data.session=this.data.session),this.data=e.data;try{this.startNextAuthStage()}catch(e){return this.attemptAuthDeferred.reject(e),void(this.attemptAuthDeferred=null)}if(!this.emailSid&&(null===(a=this.chosenFlow)||void 0===a?void 0:a.stages.includes(c.Email)))try{yield this.requestEmailToken()}catch(e){this.attemptAuthDeferred.reject(e),this.attemptAuthDeferred=null}}}))}startNextAuthStage(){var e,t,i,n;const r=this.chooseStage();if(!r)throw new Error("No incomplete flows from the server");this.currentStage=r,r!==c.Dummy?(null===(e=this.data)||void 0===e?void 0:e.errcode)||(null===(t=this.data)||void 0===t?void 0:t.error)?this.stateUpdatedCallback(r,{errcode:(null===(i=this.data)||void 0===i?void 0:i.errcode)||"",error:(null===(n=this.data)||void 0===n?void 0:n.error)||""}):this.stateUpdatedCallback(r,r===s?{emailSid:this.emailSid}:{}):this.submitAuthDict({type:"m.login.dummy"})}chooseStage(){null===this.chosenFlow&&(this.chosenFlow=this.chooseFlow()),r.logger.log("Active flow => %s",JSON.stringify(this.chosenFlow));const e=this.firstUncompletedStage(this.chosenFlow);return r.logger.log("Next stage: %s",e),e}chooseFlow(){const e=this.data.flows||[],t=Boolean(this.inputs.emailAddress)||Boolean(this.emailSid),i=Boolean(this.inputs.phoneCountry)&&Boolean(this.inputs.phoneNumber);for(const n of e){let e=!1,r=!1;for(const t of n.stages)t===s?e=!0:t==a&&(r=!0);if(e==t&&r==i)return n}const n=[];throw t&&n.push(s),i&&n.push(a),new d("No appropriate authentication flow found",n,e)}firstUncompletedStage(e){const t=this.data.completed||[];return e.stages.find((e=>!t.includes(e)))}}},{"./logger":374,"./utils":416}],374:[function(e,t,i){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(i,"__esModule",{value:!0}),i.logger=void 0;const r=n(e("loglevel")),o="matrix";function s(e){e.withPrefix=function(e){return function(e){const t=r.default.getLogger(`${o}-${e}`);t.prefix!==e&&(s(t),t.prefix=e,t.setLevel(r.default.levels.DEBUG,!1));return t}((this.prefix||"")+e)}}r.default.methodFactory=function(e,t,i){return function(...t){this.prefix&&t.unshift(this.prefix);return"error"===e||"warn"===e||"trace"===e||"info"===e?console[e](...t):console.log(...t)}},i.logger=r.default.getLogger(o),i.logger.setLevel(r.default.levels.DEBUG,!1),s(i.logger)},{loglevel:151}],375:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)},s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(i,"__esModule",{value:!0}),i.createRoomWidgetClient=i.createClient=i.setCryptoStoreFactory=i.GroupCallType=i.GroupCallState=i.GroupCallIntent=i.GroupCallEvent=i.createNewMatrixCall=i.SecretStorage=i.ContentHelpers=void 0;const a=e("./crypto/store/memory-crypto-store"),c=e("./store/memory"),d=e("./scheduler"),l=e("./client"),u=e("./embedded");o(e("./client"),i),o(e("./embedded"),i),o(e("./http-api"),i),o(e("./autodiscovery"),i),o(e("./sync-accumulator"),i),o(e("./errors"),i),o(e("./models/beacon"),i),o(e("./models/event"),i),o(e("./models/room"),i),o(e("./models/event-timeline"),i),o(e("./models/event-timeline-set"),i),o(e("./models/poll"),i),o(e("./models/room-member"),i),o(e("./models/room-state"),i),o(e("./models/user"),i),o(e("./scheduler"),i),o(e("./filter"),i),o(e("./timeline-window"),i),o(e("./interactive-auth"),i),o(e("./service-types"),i),o(e("./store/memory"),i),o(e("./store/indexeddb"),i),o(e("./crypto/store/memory-crypto-store"),i),o(e("./crypto/store/indexeddb-crypto-store"),i),o(e("./content-repo"),i),o(e("./@types/event"),i),o(e("./@types/PushRules"),i),o(e("./@types/partials"),i),o(e("./@types/requests"),i),o(e("./@types/search"),i),o(e("./models/room-summary"),i),i.ContentHelpers=s(e("./content-helpers")),i.SecretStorage=s(e("./secret-storage"));var h=e("./webrtc/call");Object.defineProperty(i,"createNewMatrixCall",{enumerable:!0,get:function(){return h.createNewMatrixCall}});var f=e("./webrtc/groupCall");Object.defineProperty(i,"GroupCallEvent",{enumerable:!0,get:function(){return f.GroupCallEvent}}),Object.defineProperty(i,"GroupCallIntent",{enumerable:!0,get:function(){return f.GroupCallIntent}}),Object.defineProperty(i,"GroupCallState",{enumerable:!0,get:function(){return f.GroupCallState}}),Object.defineProperty(i,"GroupCallType",{enumerable:!0,get:function(){return f.GroupCallType}});let p=()=>new a.MemoryCryptoStore;function g(e){var i,n,r;return e.store=null!==(i=e.store)&&void 0!==i?i:new c.MemoryStore({localStorage:t.localStorage}),e.scheduler=null!==(n=e.scheduler)&&void 0!==n?n:new d.MatrixScheduler,e.cryptoStore=null!==(r=e.cryptoStore)&&void 0!==r?r:p(),e}i.setCryptoStoreFactory=function(e){p=e},i.createClient=function(e){return new l.MatrixClient(g(e))},i.createRoomWidgetClient=function(e,t,i,n){return new u.RoomWidgetClient(e,t,i,g(n))}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./@types/PushRules":304,"./@types/event":306,"./@types/partials":309,"./@types/requests":312,"./@types/search":313,"./autodiscovery":319,"./client":321,"./content-helpers":322,"./content-repo":323,"./crypto/store/indexeddb-crypto-store":346,"./crypto/store/memory-crypto-store":348,"./embedded":358,"./errors":359,"./filter":364,"./http-api":367,"./interactive-auth":373,"./models/beacon":378,"./models/event":383,"./models/event-timeline":382,"./models/event-timeline-set":381,"./models/poll":385,"./models/room":392,"./models/room-member":389,"./models/room-state":390,"./models/room-summary":391,"./models/user":396,"./scheduler":403,"./secret-storage":404,"./service-types":405,"./store/indexeddb":410,"./store/memory":411,"./sync-accumulator":413,"./timeline-window":415,"./webrtc/call":418,"./webrtc/groupCall":422}],376:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.MSC3089Branch=void 0;const r=e("../@types/event"),o=e("./event-timeline");i.MSC3089Branch=class{constructor(e,t,i){this.client=e,this.indexEvent=t,this.directory=i}get id(){const e=this.indexEvent.getStateKey();if(!e)throw new Error("State key not found for branch");return e}get isActive(){return!0===this.indexEvent.getContent().active}get version(){var e;return null!==(e=this.indexEvent.getContent().version)&&void 0!==e?e:1}get roomId(){return this.indexEvent.getRoomId()}delete(){return n(this,void 0,void 0,(function*(){yield this.client.sendStateEvent(this.roomId,r.UNSTABLE_MSC3089_BRANCH.name,{},this.id),yield this.client.redactEvent(this.roomId,this.id);const e=(yield this.getVersionHistory())[1];e&&(yield e.delete())}))}getName(){return this.indexEvent.getContent().name||"Unnamed File"}setName(e){return n(this,void 0,void 0,(function*(){yield this.client.sendStateEvent(this.roomId,r.UNSTABLE_MSC3089_BRANCH.name,Object.assign(Object.assign({},this.indexEvent.getContent()),{name:e}),this.id)}))}isLocked(){return this.indexEvent.getContent().locked||!1}setLocked(e){return n(this,void 0,void 0,(function*(){yield this.client.sendStateEvent(this.roomId,r.UNSTABLE_MSC3089_BRANCH.name,Object.assign(Object.assign({},this.indexEvent.getContent()),{locked:e}),this.id)}))}getFileInfo(){return n(this,void 0,void 0,(function*(){const e=(yield this.getFileEvent()).getOriginalContent().file,t=this.client.mxcUrlToHttp(e.url);if(!t)throw new Error(`No HTTP URL available for ${e.url}`);return{info:e,httpUrl:t}}))}getFileEvent(){return n(this,void 0,void 0,(function*(){const e=this.client.getRoom(this.roomId);if(!e)throw new Error("Unknown room");let t=e.getUnfilteredTimelineSet().findEventById(this.id);for(;!t&&e.getLiveTimeline().getState(o.EventTimeline.BACKWARDS).paginationToken;)yield this.client.scrollback(e,100),t=e.getUnfilteredTimelineSet().findEventById(this.id);if(!t)throw new Error("Failed to find event");return yield this.client.decryptEventIfNeeded(t,{emit:!0,isRetry:!0}),t}))}createNewVersion(e,t,i,o){return n(this,void 0,void 0,(function*(){const n=yield this.directory.createFile(e,t,i,Object.assign(Object.assign({},null!=o?o:{}),{"m.new_content":!0,"m.relates_to":{rel_type:r.RelationType.Replace,event_id:this.id}}));return yield this.client.sendStateEvent(this.roomId,r.UNSTABLE_MSC3089_BRANCH.name,{active:!0,name:e,version:this.version+1},n.event_id),yield this.client.sendStateEvent(this.roomId,r.UNSTABLE_MSC3089_BRANCH.name,Object.assign(Object.assign({},this.indexEvent.getContent()),{active:!1}),this.id),n}))}getVersionHistory(){return n(this,void 0,void 0,(function*(){const e=[];e.push(this);const t=this.client.getRoom(this.roomId);if(!t)throw new Error("Invalid or unknown room");const i=[...t.getLiveTimeline().getEvents()].reverse();let n,r=yield this.getFileEvent();do{if(n=i.find((e=>e.replacingEventId()===r.getId())),n){const t=this.directory.getFile(n.getId());if(!t)break;e.push(t),r=n}}while(n);return e}))}}},{"../@types/event":306,"./event-timeline":382}],377:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(i,"__esModule",{value:!0}),i.MSC3089TreeSpace=i.TreePermissions=i.DEFAULT_TREE_POWER_LEVELS_TEMPLATE=void 0;const o=r(e("p-retry")),s=e("../@types/event"),a=e("../logger"),c=e("../utils"),d=e("./MSC3089Branch"),l=e("../crypto/algorithms/megolm");var u;i.DEFAULT_TREE_POWER_LEVELS_TEMPLATE={invite:100,kick:100,ban:100,redact:50,state_default:50,events_default:50,users_default:0,events:{[s.EventType.RoomPowerLevels]:100,[s.EventType.RoomHistoryVisibility]:100,[s.EventType.RoomTombstone]:100,[s.EventType.RoomEncryption]:100,[s.EventType.RoomName]:50,[s.EventType.RoomMessage]:50,[s.EventType.RoomMessageEncrypted]:50,[s.EventType.Sticker]:50},users:{}},function(e){e.Viewer="viewer",e.Editor="editor",e.Owner="owner"}(u=i.TreePermissions||(i.TreePermissions={}));i.MSC3089TreeSpace=class{constructor(e,t){if(this.client=e,this.roomId=t,this.room=this.client.getRoom(this.roomId),!this.room)throw new Error("Unknown room")}get id(){return this.roomId}get isTopLevel(){const e=this.room.currentState.getStateEvents(s.EventType.SpaceParent);return!(null==e?void 0:e.length)||e.every((e=>{var t;return!(null===(t=e.getContent())||void 0===t?void 0:t.via)}))}setName(e){return n(this,void 0,void 0,(function*(){yield this.client.sendStateEvent(this.roomId,s.EventType.RoomName,{name:e},"")}))}invite(e,t=!0,i=!0){return n(this,void 0,void 0,(function*(){const n=[this.retryInvite(e)];return t&&n.push(...this.getDirectories().map((n=>n.invite(e,t,i)))),Promise.all(n).then((()=>{i&&(0,l.isRoomSharedHistory)(this.room)&&this.client.sendSharedHistoryKeys(this.roomId,[e])}))}))}retryInvite(e){return(0,c.simpleRetryOperation)((()=>n(this,void 0,void 0,(function*(){yield this.client.invite(this.roomId,e).catch((e=>{if("M_FORBIDDEN"===(null==e?void 0:e.errcode))throw new o.default.AbortError(e);throw e}))}))))}setPermissions(e,t){var i;return n(this,void 0,void 0,(function*(){const n=this.room.currentState.getStateEvents(s.EventType.RoomPowerLevels,"");if(Array.isArray(n))throw new Error("Unexpected return type for power levels");const r=(null==n?void 0:n.getContent())||{},o=r.users_default||0,a=r.events_default||50,c=(null===(i=r.events)||void 0===i?void 0:i[s.EventType.RoomPowerLevels])||100,d=r.users||{};switch(t){case u.Viewer:d[e]=o;break;case u.Editor:d[e]=a;break;case u.Owner:d[e]=c;break;default:throw new Error("Invalid role: "+t)}r.users=d,yield this.client.sendStateEvent(this.roomId,s.EventType.RoomPowerLevels,r,"")}))}getPermissions(e){var t,i;const n=this.room.currentState.getStateEvents(s.EventType.RoomPowerLevels,"");if(Array.isArray(n))throw new Error("Unexpected return type for power levels");const r=(null==n?void 0:n.getContent())||{},o=r.users_default||0,a=r.events_default||50,c=(null===(t=r.events)||void 0===t?void 0:t[s.EventType.RoomPowerLevels])||100,d=(null===(i=r.users)||void 0===i?void 0:i[e])||o;return d>=c?u.Owner:d>=a?u.Editor:u.Viewer}createDirectory(e){return n(this,void 0,void 0,(function*(){const t=yield this.client.unstableCreateFileTree(e);return yield this.client.sendStateEvent(this.roomId,s.EventType.SpaceChild,{via:[this.client.getDomain()]},t.roomId),yield this.client.sendStateEvent(t.roomId,s.EventType.SpaceParent,{via:[this.client.getDomain()]},this.roomId),t}))}getDirectories(){const e=[],t=this.room.currentState.getStateEvents(s.EventType.SpaceChild);for(const i of t)try{const t=i.getStateKey();if(t){const i=this.client.unstableGetFileTreeSpace(t);i&&e.push(i)}}catch(e){a.logger.warn("Unable to create tree space instance for listing. Are we joined?",e)}return e}getDirectory(e){return this.getDirectories().find((t=>t.roomId===e))}delete(){return n(this,void 0,void 0,(function*(){const e=this.getDirectories();for(const t of e)yield t.delete();const t=["invite","knock","join"],i=this.room.currentState.getStateEvents(s.EventType.RoomMember);for(const e of i){if(e.getStateKey()!==this.client.getUserId()&&t.includes(e.getContent().membership)){const t=e.getStateKey();if(!t)throw new Error("State key not found for branch");yield this.client.kick(this.roomId,t,"Room deleted")}}yield this.client.leave(this.roomId)}))}getOrderedChildren(e){const t=e.map((e=>({roomId:e.getStateKey(),order:e.getContent().order}))).filter((e=>e.roomId));return t.sort(((e,t)=>{var i,n,r,o;if(e.order&&!t.order)return-1;if(!e.order&&t.order)return 1;if(e.order||t.order)return(0,c.lexicographicCompare)(e.order,t.order);{const a=this.client.getRoom(e.roomId),d=this.client.getRoom(t.roomId);if(!a||!d)return(0,c.lexicographicCompare)(e.roomId,t.roomId);const l=null!==(n=null===(i=a.currentState.getStateEvents(s.EventType.RoomCreate,""))||void 0===i?void 0:i.getTs())&&void 0!==n?n:0,u=null!==(o=null===(r=d.currentState.getStateEvents(s.EventType.RoomCreate,""))||void 0===r?void 0:r.getTs())&&void 0!==o?o:0;return l===u?(0,c.lexicographicCompare)(e.roomId,t.roomId):l-u}})),t}getParentRoom(){const e=this.room.currentState.getStateEvents(s.EventType.SpaceParent)[0];if(!e)throw new Error("Expected to have a parent in a non-top level space");const t=e.getStateKey();if(!t)throw new Error("No state key found for parent");const i=this.client.getRoom(t);if(!i)throw new Error("Unable to locate room for parent");return i}getOrder(){if(this.isTopLevel)return-1;const e=this.getParentRoom().currentState.getStateEvents(s.EventType.SpaceChild);return this.getOrderedChildren(e).findIndex((e=>e.roomId===this.roomId))}setOrder(e){var t,i;return n(this,void 0,void 0,(function*(){if(this.isTopLevel)throw new Error("Cannot set order of top level spaces currently");const n=this.getParentRoom(),r=n.currentState.getStateEvents(s.EventType.SpaceChild),o=this.getOrderedChildren(r);e=Math.max(Math.min(e,o.length-1),0);const a=this.getOrder()e.isActive))}listAllFiles(){var e;return(null!==(e=this.room.currentState.getStateEvents(s.UNSTABLE_MSC3089_BRANCH.name))&&void 0!==e?e:[]).map((e=>new d.MSC3089Branch(this.client,e,this)))}}},{"../@types/event":306,"../crypto/algorithms/megolm":334,"../logger":374,"../utils":416,"./MSC3089Branch":376,"p-retry":225}],378:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.Beacon=i.getBeaconInfoIdentifier=i.isTimestampInDuration=i.BeaconEvent=void 0;const n=e("../content-helpers"),r=e("../utils"),o=e("./typed-event-emitter");var s;!function(e){e.New="Beacon.new",e.Update="Beacon.update",e.LivenessChange="Beacon.LivenessChange",e.Destroy="Beacon.Destroy",e.LocationUpdate="Beacon.LocationUpdate"}(s=i.BeaconEvent||(i.BeaconEvent={}));i.isTimestampInDuration=(e,t,i)=>i>=e&&e+t>=i;i.getBeaconInfoIdentifier=e=>`${e.getRoomId()}_${e.getStateKey()}`;class a extends o.TypedEventEmitter{constructor(e){super(),this.rootEvent=e,this.clearLatestLocation=()=>{this._latestLocationEvent=void 0,this.emit(s.LocationUpdate,this.latestLocationState)},this.roomId=this.rootEvent.getRoomId(),this.setBeaconInfo(this.rootEvent)}get isLive(){return!!this._isLive}get identifier(){return(0,i.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&&(0,n.parseBeaconContent)(this._latestLocationEvent.getContent())}get latestLocationEvent(){return this._latestLocationEvent}update(e){if((0,i.getBeaconInfoIdentifier)(e)!==this.identifier)throw new Error("Invalid updating event");e.getTs()1&&(this.livenessWatchTimeout=setTimeout((()=>{this.monitorLiveness()}),e))}else this.beaconInfo.timestamp>Date.now()&&(this.livenessWatchTimeout=setTimeout((()=>{this.monitorLiveness()}),this.beaconInfo.timestamp-Date.now()))}addLocations(e){var t;if(!this.isLive)return;const o=null===(t=e.filter((e=>{const t=e.getContent(),r=(0,n.parseBeaconContent)(t);if(!r.uri||!r.timestamp)return!1;const{timestamp:o}=r;return this._beaconInfo.timestamp&&(0,i.isTimestampInDuration)(this._beaconInfo.timestamp,this._beaconInfo.timeout,o)&&(!this.latestLocationState||o>this.latestLocationState.timestamp)})).sort(r.sortEventsByLatestContentTimestamp))||void 0===t?void 0:t[0];o&&(this._latestLocationEvent=o,this.emit(s.LocationUpdate,this.latestLocationState))}setBeaconInfo(e){this._beaconInfo=(0,n.parseBeaconInfoContent)(e.getContent()),this.checkLiveness()}checkLiveness(){const e=this.isLive;if(!this.beaconInfo)return;const t=this.beaconInfo.timestamp>Date.now()?this.beaconInfo.timestamp-36e4:this.beaconInfo.timestamp;this._isLive=!!this._beaconInfo.live&&!!t&&(0,i.isTimestampInDuration)(t,this._beaconInfo.timeout,Date.now()),e!==this.isLive&&this.emit(s.LivenessChange,this.isLive,this)}}i.Beacon=a},{"../content-helpers":322,"../utils":416,"./typed-event-emitter":395}],379:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.EventContext=void 0;const n=e("./event-timeline");i.EventContext=class{constructor(e){this.ourEvent=e,this.ourEventIndex=0,this.paginateTokens={[n.Direction.Backward]:null,[n.Direction.Forward]:null},this.timeline=[e]}getEvent(){return this.timeline[this.ourEventIndex]}getTimeline(){return this.timeline}getOurEventIndex(){return this.ourEventIndex}getPaginateToken(e=!1){return this.paginateTokens[e?n.Direction.Backward:n.Direction.Forward]}setPaginateToken(e,t=!1){this.paginateTokens[t?n.Direction.Backward:n.Direction.Forward]=null!=e?e:null}addEvents(e,t=!1){t?(this.timeline=e.concat(this.timeline),this.ourEventIndex+=e.length):this.timeline=this.timeline.concat(e)}}},{"./event-timeline":382}],380:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.EventStatus=void 0,function(e){e.NOT_SENT="not_sent",e.ENCRYPTING="encrypting",e.SENDING="sending",e.QUEUED="queued",e.SENT="sent",e.CANCELLED="cancelled"}(i.EventStatus||(i.EventStatus={}))},{}],381:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.EventTimelineSet=i.DuplicateStrategy=void 0;const n=e("./event-timeline"),r=e("../logger"),o=e("./room"),s=e("./typed-event-emitter"),a=e("./relations-container");let c;var d;c=r.logger.log.bind(r.logger),function(e){e.Ignore="ignore",e.Replace="replace"}(d=i.DuplicateStrategy||(i.DuplicateStrategy={}));class l extends s.TypedEventEmitter{constructor(e,t={},i,r,o=null){var s,c,d;super(),this.room=e,this.thread=r,this.threadListType=o,this._eventIdToTimeline=new Map,this.timelineSupport=Boolean(t.timelineSupport),this.liveTimeline=new n.EventTimeline(this),this.displayPendingEvents=!1!==t.pendingEvents,this.timelines=[this.liveTimeline],this._eventIdToTimeline=new Map,this.filter=t.filter,this.relations=null!==(c=null===(s=this.room)||void 0===s?void 0:s.relations)&&void 0!==c?c:new a.RelationsContainer(null!==(d=null==e?void 0:e.client)&&void 0!==d?d:i)}getTimelines(){return this.timelines}getFilter(){return this.filter}setFilter(e){this.filter=e}getPendingEvents(){return this.room&&this.displayPendingEvents?this.room.getPendingEvents():[]}getLiveTimeline(){return this.liveTimeline}setLiveTimeline(e){this.liveTimeline=e}eventIdToTimeline(e){return this._eventIdToTimeline.get(e)}replaceEventId(e,t){const i=this._eventIdToTimeline.get(e);i&&(this._eventIdToTimeline.delete(e),this._eventIdToTimeline.set(t,i))}resetLiveTimeline(e,t){const i=!this.timelineSupport||!t,r=this.liveTimeline,s=i?r.forkLive(n.EventTimeline.FORWARDS):r.fork(n.EventTimeline.FORWARDS);i?(this.timelines=[s],this._eventIdToTimeline=new Map):this.timelines.push(s),t&&r.setPaginationToken(t,n.EventTimeline.FORWARDS),s.setPaginationToken(null!=e?e:null,n.EventTimeline.BACKWARDS),this.liveTimeline=s,this.emit(o.RoomEvent.TimelineReset,this.room,this,i)}getTimelineForEvent(e){if(null==e)return null;const t=this._eventIdToTimeline.get(e);return void 0===t?null:t}findEventById(e){const t=this.getTimelineForEvent(e);if(t)return t.getEvents().find((function(t){return t.getId()==e}))}addTimeline(){if(!this.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");const e=new n.EventTimeline(this);return this.timelines.push(e),e}addEventsToTimeline(e,t,i,o){if(!i)throw new Error("'timeline' not specified for EventTimelineSet.addEventsToTimeline");if(!t&&i==this.liveTimeline)throw new Error("EventTimelineSet.addEventsToTimeline cannot be used for adding events to the live timeline - use Room.addLiveEvents instead");if(this.filter&&!(e=this.filter.filterRoomTimeline(e)).length)return;const s=t?n.EventTimeline.BACKWARDS:n.EventTimeline.FORWARDS,a=t?n.EventTimeline.FORWARDS:n.EventTimeline.BACKWARDS;let d=!1,l=!1;for(const o of e){const e=o.getId(),u=this._eventIdToTimeline.get(e);if(!u){this.addEventToTimeline(o,i,{toStartOfTimeline:t}),l=!0,d=!0;continue}if(l=!1,u==i){c("Event "+e+" already in timeline "+i);continue}const h=i.getNeighbouringTimeline(s);if(h){c(u==h?"Event "+e+" in neighbouring timeline - switching to "+u:"Event "+e+" already in a different timeline "+u),i=u;continue}r.logger.info("Already have timeline for "+e+" - joining timeline "+i+" to "+u);const f=u===this.liveTimeline,p=i===this.liveTimeline,g=s===n.EventTimeline.BACKWARDS&&f,v=s===n.EventTimeline.FORWARDS&&p;g||v?(g&&r.logger.warn("Refusing to set a preceding existingTimeLine on our timeline as the existingTimeLine is live ("+u+")"),v&&r.logger.warn("Refusing to set our preceding timeline on a existingTimeLine as our timeline is live ("+i+")")):(i.setNeighbouringTimeline(u,s),u.setNeighbouringTimeline(i,a),i=u,d=!0)}if(l||!d){if(s===n.EventTimeline.FORWARDS&&i===this.liveTimeline)return r.logger.warn({lastEventWasNew:l,didUpdate:d}),void r.logger.warn(`Refusing to set forwards pagination token of live timeline ${i} to ${o}`);i.setPaginationToken(null!=o?o:null,s)}}addLiveEvent(e,t,i=!1,o){let s,a=t||d.Ignore;if("object"==typeof t?({duplicateStrategy:a=d.Ignore,fromCache:i=!1,roomState:o,timelineWasEmpty:s}=t):void 0!==t&&r.logger.warn("Overload deprecated: `EventTimelineSet.addLiveEvent(event, duplicateStrategy?, fromCache?, roomState?)` is deprecated in favor of the overload with `EventTimelineSet.addLiveEvent(event, IAddLiveEventOptions)`"),this.filter){if(!this.filter.filterRoomTimeline([e]).length)return}const l=this._eventIdToTimeline.get(e.getId());if(l)if(a===d.Replace){c("EventTimelineSet.addLiveEvent: replacing duplicate event "+e.getId());const t=l.getEvents();for(let i=0;i0)throw new Error("Cannot initialise state after events are added");null===(i=this.startState)||void 0===i||i.setStateEvents(e,{timelineWasEmpty:t}),null===(n=this.endState)||void 0===n||n.setStateEvents(e,{timelineWasEmpty:t})}forkLive(e){const t=this.getState(e),i=new a(this.eventTimelineSet);return i.startState=null==t?void 0:t.clone(),i.endState=t,this.endState=null==t?void 0:t.clone(),i}fork(e){const t=this.getState(e),i=new a(this.eventTimelineSet);return i.startState=null==t?void 0:t.clone(),i.endState=null==t?void 0:t.clone(),i}getRoomId(){return this.roomId}getFilter(){return this.eventTimelineSet.getFilter()}getTimelineSet(){return this.eventTimelineSet}getBaseIndex(){return this.baseIndex}getEvents(){return this.events}getState(e){if(e==a.BACKWARDS)return this.startState;if(e==a.FORWARDS)return this.endState;throw new Error("Invalid direction '"+e+"'")}getPaginationToken(e){return this.roomId?this.getState(e).paginationToken:e===s.Backward?this.startToken:this.endToken}setPaginationToken(e,t){this.roomId?this.getState(t).paginationToken=e:t===s.Backward?this.startToken=e:this.endToken=e}getNeighbouringTimeline(e){if(e==a.BACKWARDS)return this.prevTimeline;if(e==a.FORWARDS)return this.nextTimeline;throw new Error("Invalid direction '"+e+"'")}setNeighbouringTimeline(e,t){if(this.getNeighbouringTimeline(t))throw new Error("timeline already has a neighbouring timeline - cannot reset neighbour (direction: "+t+")");if(t==a.BACKWARDS)this.prevTimeline=e;else{if(t!=a.FORWARDS)throw new Error("Invalid direction '"+t+"'");this.nextTimeline=e}this.setPaginationToken(null,t)}addEvent(e,t,i){let r,s=!!t;"object"==typeof t?({toStartOfTimeline:s,roomState:i,timelineWasEmpty:r}=t):void 0!==t&&n.logger.warn("Overload deprecated: `EventTimeline.addEvent(event, toStartOfTimeline, roomState?)` is deprecated in favor of the overload with `EventTimeline.addEvent(event, IAddEventOptions)`"),i||(i=s?this.startState:this.endState);const c=this.getTimelineSet();let d;c.room&&(a.setEventMetadata(e,i,s),e.isState()&&c.room.getUnfilteredTimelineSet()===c&&(null==i||i.setStateEvents([e],{timelineWasEmpty:r}),e.sender&&(e.getType()!==o.EventType.RoomMember||s)||a.setEventMetadata(e,i,s))),d=s?0:this.events.length,this.events.splice(d,0,e),s&&this.baseIndex++}removeEvent(e){for(let t=this.events.length-1;t>=0;t--){const i=this.events[t];if(i.getId()==e)return this.events.splice(t,1),t{"string"==typeof e[t]&&(e[t]=(0,a.internaliseString)(e[t]))})),["membership","avatar_url","displayname"].forEach((t=>{var i;"string"==typeof(null===(i=e.content)||void 0===i?void 0:i[t])&&(e.content[t]=(0,a.internaliseString)(e.content[t]))})),["rel_type"].forEach((t=>{var i,n;"string"==typeof(null===(n=null===(i=e.content)||void 0===i?void 0:i["m.relates_to"])||void 0===n?void 0:n[t])&&(e.content["m.relates_to"][t]=(0,a.internaliseString)(e.content["m.relates_to"][t]))})),this.txnId=e.txn_id,this.localTimestamp=Date.now()-(null!==(t=this.getAge())&&void 0!==t?t:0),this.reEmitter=new d.TypedReEmitter(this)}get unstableExtensibleEvent(){return this._hasCachedExtEv||(this._cachedExtEv=r.ExtensibleEvents.parse(this.getEffectiveEvent())),this._cachedExtEv}invalidateExtensibleEvent(){this._hasCachedExtEv=!1}getEffectiveEvent(){const e=Object.assign({},this.getContent());if(this.getWireType()===s.EventType.RoomMessageEncrypted)for(const[t,i]of Object.entries(this.getWireContent()))["algorithm","ciphertext","device_id","sender_key","session_id"].includes(t)||void 0===e[t]&&(e[t]=i);return Object.assign({},this.event,this.clearEvent,{content:e})}getId(){return this.event.event_id}getSender(){return this.event.sender||this.event.user_id}getType(){return this.clearEvent?this.clearEvent.type:this.event.type}getWireType(){return this.event.type}getRoomId(){return this.event.room_id}getTs(){return this.event.origin_server_ts}getDate(){return this.event.origin_server_ts?new Date(this.event.origin_server_ts):null}getDetails(){let e=`id=${this.getId()} type=${this.getWireType()} sender=${this.getSender()}`;const t=this.getRoomId();t&&(e+=` room=${t}`);const i=this.getDate();return i&&(e+=` ts=${i.toISOString()}`),e}getOriginalContent(){return this._localRedactionEvent?{}:this.clearEvent?this.clearEvent.content||{}:this.event.content||{}}getContent(){return this._localRedactionEvent?{}:this._replacingEvent?this._replacingEvent.getContent()["m.new_content"]||{}:this.getOriginalContent()}getWireContent(){return this.event.content||{}}get threadRootId(){var e,t;const i=null===(e=this.getWireContent())||void 0===e?void 0:e["m.relates_to"];return(null==i?void 0:i.rel_type)===c.THREAD_RELATION_TYPE.name?i.event_id:(null===(t=this.getThread())||void 0===t?void 0:t.id)||this.threadId}get isThreadRoot(){var e;return!!this.getServerAggregatedRelation(c.THREAD_RELATION_TYPE.name)||(null===(e=this.getThread())||void 0===e?void 0:e.id)===this.getId()}get replyEventId(){var e,t;return null===(t=null===(e=this.getWireContent()["m.relates_to"])||void 0===e?void 0:e["m.in_reply_to"])||void 0===t?void 0:t.event_id}get relationEventId(){var e,t;return null===(t=null===(e=this.getWireContent())||void 0===e?void 0:e["m.relates_to"])||void 0===t?void 0:t.event_id}getPrevContent(){return this.getUnsigned().prev_content||this.event.prev_content||{}}getDirectionalContent(){return this.forwardLooking?this.getContent():this.getPrevContent()}getAge(){return this.getUnsigned().age||this.event.age}getLocalAge(){return Date.now()-this.localTimestamp}getStateKey(){return this.event.state_key}isState(){return void 0!==this.event.state_key}makeEncrypted(e,t,i,n){this.clearEvent={type:this.event.type,content:this.event.content},this.event.type=e,this.event.content=t,this.senderCurve25519Key=i,this.claimedEd25519Key=n}isBeingDecrypted(){return null!=this.decryptionPromise}getDecryptionPromise(){return this.decryptionPromise}isDecryptionFailure(){var e,t;return"m.bad.encrypted"===(null===(t=null===(e=this.clearEvent)||void 0===e?void 0:e.content)||void 0===t?void 0:t.msgtype)}get isEncryptedDisabledForUnverifiedDevices(){return this.isDecryptionFailure()&&this.encryptedDisabledForUnverifiedDevices}shouldAttemptDecryption(){return!this.isRedacted()&&(!this.isBeingDecrypted()&&(!this.clearEvent&&!!this.isEncrypted()))}attemptDecryption(e,t={}){return n(this,void 0,void 0,(function*(){if(!this.isEncrypted())throw new Error("Attempt to decrypt event which isn't encrypted");const i=this.clearEvent&&!this.isDecryptionFailure(),n=t.forceRedecryptIfUntrusted&&this.isKeySourceUntrusted();if(i&&!n)throw new Error("Attempt to decrypt event which has already been decrypted");return this.decryptionPromise?(o.logger.log(`Event ${this.getId()} already being decrypted; queueing a retry`),this.retryDecryption=!0,this.decryptionPromise):(this.decryptionPromise=this.decryptionLoop(e,t),this.decryptionPromise)}))}cancelAndResendKeyRequest(e,t){const i=this.getWireContent();return e.requestRoomKey({algorithm:i.algorithm,room_id:this.getRoomId(),session_id:i.session_id,sender_key:i.sender_key},this.getKeyRequestRecipients(t),!0)}getKeyRequestRecipients(e){return[{userId:e,deviceId:"*"}]}decryptionLoop(e,t={}){return n(this,void 0,void 0,(function*(){for(yield Promise.resolve();;){let i,n;this.retryDecryption=!1;try{e?(i=yield e.decryptEvent(this),!0===t.isRetry&&o.logger.info(`Decrypted event on retry (${this.getDetails()})`)):i=this.badEncryptedMessage("Encryption not enabled")}catch(e){const t=e instanceof u.DecryptionError?e.detailedString:String(e);if(n=e,this.retryDecryption){o.logger.log(`Error decrypting event (${this.getDetails()}), but retrying: ${t}`);continue}o.logger.warn(`Error decrypting event (${this.getDetails()}): ${t}`),i=this.badEncryptedMessage(String(e))}return this.decryptionPromise=null,this.retryDecryption=!1,this.setClearData(i),this.setPushActions(null),void(!1!==t.emit&&this.emit(g.Decrypted,this,n))}}))}badEncryptedMessage(e){return{clearEvent:{type:s.EventType.RoomMessage,content:{msgtype:"m.bad.encrypted",body:"** Unable to decrypt: "+e+" **"}},encryptedDisabledForUnverifiedDevices:e===`DecryptionError: ${h.WITHHELD_MESSAGES["m.unverified"]}`}}setClearData(e){var t,i;this.clearEvent=e.clearEvent,this.senderCurve25519Key=null!==(t=e.senderCurve25519Key)&&void 0!==t?t:null,this.claimedEd25519Key=null!==(i=e.claimedEd25519Key)&&void 0!==i?i:null,this.forwardingCurve25519KeyChain=e.forwardingCurve25519KeyChain||[],this.untrusted=e.untrusted||!1,this.encryptedDisabledForUnverifiedDevices=e.encryptedDisabledForUnverifiedDevices||!1,this.invalidateExtensibleEvent()}getClearContent(){return this.clearEvent?this.clearEvent.content:null}isEncrypted(){return!this.isState()&&this.event.type===s.EventType.RoomMessageEncrypted}getSenderKey(){return this.senderCurve25519Key}getKeysClaimed(){return this.claimedEd25519Key?{ed25519:this.claimedEd25519Key}:{}}getClaimedEd25519Key(){return this.claimedEd25519Key}getForwardingCurve25519KeyChain(){return this.forwardingCurve25519KeyChain}isKeySourceUntrusted(){return!!this.untrusted}getUnsigned(){return this.event.unsigned||{}}setUnsigned(e){this.event.unsigned=e}unmarkLocallyRedacted(){const e=this._localRedactionEvent;return this._localRedactionEvent=null,this.event.unsigned&&(this.event.unsigned.redacted_because=void 0),!!e}markLocallyRedacted(e){this._localRedactionEvent||(this.emit(g.BeforeRedaction,this,e),this._localRedactionEvent=e,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event)}applyVisibilityEvent(e){var t,i;const n=null===(t=null==e?void 0:e.visible)||void 0===t||t,r=null!==(i=null==e?void 0:e.reason)&&void 0!==i?i:null;let o=!1;this.visibility.visible!==n?o=!0:this.visibility.visible||this.visibility.reason===r||(o=!0),o&&(this.visibility=n?p:Object.freeze({visible:!1,reason:r}),this.emit(g.VisibilityChange,this,n))}messageVisibility(){return this.visibility}makeRedacted(e){if(!e.event)throw new Error("invalid redactionEvent in makeRedacted");this._localRedactionEvent=null,this.emit(g.BeforeRedaction,this,e),this._replacingEvent=null,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event;for(const e in this.event)this.event.hasOwnProperty(e)&&!m.has(e)&&delete this.event[e];this.isEncrypted()&&(this.clearEvent=void 0);const t=this.getType()in y?y[this.getType()]:{},i=this.getContent();for(const e in i)i.hasOwnProperty(e)&&!t[e]&&delete i[e];this.invalidateExtensibleEvent()}isRedacted(){return Boolean(this.getUnsigned().redacted_because)}isRedaction(){return this.getType()===s.EventType.RoomRedaction}asVisibilityChange(){if(!s.EVENT_VISIBILITY_CHANGE_TYPE.matches(this.getType()))return null;const e=this.getRelation();if(!e||"m.reference"!=e.rel_type)return null;const t=e.event_id;if(!t)return null;const i=this.getWireContent(),n=!!i.visible,r=i.reason;return r&&"string"!=typeof r?null:{visible:n,reason:r,eventId:t}}isVisibilityEvent(){return s.EVENT_VISIBILITY_CHANGE_TYPE.matches(this.getType())}getRedactionEvent(){var e,t,i,n;return this.isRedacted()?(null===(e=this.clearEvent)||void 0===e?void 0:e.unsigned)?null!==(i=null===(t=this.clearEvent)||void 0===t?void 0:t.unsigned.redacted_because)&&void 0!==i?i:null:(null===(n=this.event.unsigned)||void 0===n?void 0:n.redacted_because)?this.event.unsigned.redacted_because:{}:null}getPushActions(){return this.pushActions}setPushActions(e){this.pushActions=e}handleRemoteEcho(e){const t=this.getUnsigned(),i=this.getId();this.event=e,t.redacted_because&&(this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=t.redacted_because),this.setStatus(null),this.getId()!==i&&this.emit(g.LocalEventIdReplaced,this),this.localTimestamp=Date.now()-this.getAge()}isSending(){return!!this.status}setStatus(e){this.status=e,this.emit(g.Status,this,e)}replaceLocalEventId(e){this.event.event_id=e,this.emit(g.LocalEventIdReplaced,this)}isRelation(e){var t;const i=null===(t=this.getWireContent())||void 0===t?void 0:t["m.relates_to"];return(!this.isState()||(null==i?void 0:i.rel_type)!==s.RelationType.Replace)&&!(!(null==i?void 0:i.rel_type)||!i.event_id||e&&i.rel_type!==e)}getRelation(){var e;return this.isRelation()&&null!==(e=this.getWireContent()["m.relates_to"])&&void 0!==e?e:null}makeReplaced(e){this.isRedacted()&&e||this.isState()||this._replacingEvent!==e&&(this._replacingEvent=null!=e?e:null,this.emit(g.Replaced,this),this.invalidateExtensibleEvent())}getAssociatedStatus(){return this._replacingEvent?this._replacingEvent.status:this._localRedactionEvent?this._localRedactionEvent.status:this.status}getServerAggregatedRelation(e){var t;return null===(t=this.getUnsigned()["m.relations"])||void 0===t?void 0:t[e]}replacingEventId(){const e=this.getServerAggregatedRelation(s.RelationType.Replace);return e?e.event_id:this._replacingEvent?this._replacingEvent.getId():void 0}replacingEvent(){return this._replacingEvent}replacingEventDate(){var e;const t=this.getServerAggregatedRelation(s.RelationType.Replace);if(t){const e=t.origin_server_ts;if(Number.isFinite(e))return new Date(e)}else if(this._replacingEvent)return null!==(e=this._replacingEvent.getDate())&&void 0!==e?e:void 0}localRedactionEvent(){return this._localRedactionEvent}getAssociatedId(){const e=this.getRelation();return this.replyEventId?this.replyEventId:e?e.event_id:this.isRedaction()?this.event.redacts:void 0}hasAssocation(){return!!this.getAssociatedId()}hasAssociation(){return!!this.getAssociatedId()}updateAssociatedId(e){const t=this.getRelation();t?t.event_id=e:this.isRedaction()&&(this.event.redacts=e)}flagCancelled(e=!0){this._isCancelled=e}isCancelled(){return this._isCancelled}toSnapshot(){const e=new v(JSON.parse(JSON.stringify(this.event)));for(const[t,i]of Object.entries(this))"event"!==t&&(e[t]=i);return e}isEquivalentTo(e){if(!e)return!1;if(e===this)return!0;const t=(0,a.deepSortedObjectEntries)(this.event),i=(0,a.deepSortedObjectEntries)(e.event);return JSON.stringify(t)===JSON.stringify(i)}toJSON(){const e=this.getEffectiveEvent();return this.isEncrypted()?{decrypted:e,encrypted:this.event}:e}setVerificationRequest(e){this.verificationRequest=e}setTxnId(e){this.txnId=e}getTxnId(){return this.txnId}setThread(e){this.thread&&this.reEmitter.stopReEmitting(this.thread,[c.ThreadEvent.Update]),this.thread=e,this.setThreadId(null==e?void 0:e.id),e&&this.reEmitter.reEmit(e,[c.ThreadEvent.Update])}getThread(){return this.thread}setThreadId(e){this.threadId=e}}i.MatrixEvent=v;const m=new Set(["event_id","type","room_id","user_id","sender","state_key","prev_state","content","unsigned","origin_server_ts"]),y={[s.EventType.RoomMember]:{membership:1},[s.EventType.RoomCreate]:{creator:1},[s.EventType.RoomJoinRules]:{join_rule:1},[s.EventType.RoomPowerLevels]:{ban:1,events:1,events_default:1,kick:1,redact:1,state_default:1,users:1,users_default:1}}},{"../@types/event":306,"../ReEmitter":317,"../crypto/OlmDevice":327,"../crypto/algorithms":333,"../logger":374,"../utils":416,"./event-status":380,"./thread":394,"./typed-event-emitter":395,"matrix-events-sdk":167}],384:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.IgnoredInvites=i.PolicyScope=i.IGNORE_INVITES_ACCOUNT_EVENT_KEY=i.POLICIES_ACCOUNT_EVENT_TYPE=void 0;const r=e("matrix-events-sdk"),o=e("./event-timeline"),s=e("../@types/partials"),a=e("../utils");var c,d;i.POLICIES_ACCOUNT_EVENT_TYPE=new r.UnstableValue("m.policies","org.matrix.msc3847.policies"),i.IGNORE_INVITES_ACCOUNT_EVENT_KEY=new r.UnstableValue("m.ignore.invites","org.matrix.msc3847.ignore.invites"),function(e){e.Ban="m.ban"}(c||(c={})),function(e){e.User="m.policy.user",e.Room="m.policy.room",e.Server="m.policy.server"}(d=i.PolicyScope||(i.PolicyScope={}));i.IgnoredInvites=class{constructor(e){this.client=e}addRule(e,t,i){return n(this,void 0,void 0,(function*(){const n=yield this.getOrCreateTargetRoom();return(yield this.client.sendStateEvent(n.roomId,e,{entity:t,reason:i,recommendation:c.Ban})).event_id}))}removeRule(e){return n(this,void 0,void 0,(function*(){yield this.client.redactEvent(e.getRoomId(),e.getId())}))}addSource(e){return n(this,void 0,void 0,(function*(){yield this.client.joinRoom(e);const t=(yield this.getOrCreateSourceRooms()).map((e=>e.roomId));return!t.includes(e)&&(t.push(e),yield this.withIgnoreInvitesPolicies((e=>{e.sources=t})),!0)}))}getRuleForInvite({sender:e,roomId:t}){return n(this,void 0,void 0,(function*(){const i=yield this.getOrCreateSourceRooms(),n=e.split(":")[1],r=t.split(":")[1];for(const s of i){const i=s.getUnfilteredTimelineSet().getLiveTimeline().getState(o.EventTimeline.FORWARDS);for(const{scope:o,entities:s}of[{scope:d.Room,entities:[t]},{scope:d.User,entities:[e]},{scope:d.Server,entities:[n,r]}]){const e=i.getStateEvents(o);for(const t of e){const e=t.getContent();if((null==e?void 0:e.recommendation)!=c.Ban)continue;const i=null==e?void 0:e.entity;if(!i)continue;let n;try{n=new RegExp((0,a.globToRegexp)(i,!1))}catch(e){continue}for(const e of s)if(e&&n.test(e))return t}}}return null}))}getOrCreateTargetRoom(){return n(this,void 0,void 0,(function*(){let e=this.getIgnoreInvitesPolicies().target;if("string"!=typeof e&&(e=null),e){const t=this.client.getRoom(e);if(t)return t;e=null}return e=(yield this.client.createRoom({name:"Individual Policy Room",preset:s.Preset.PrivateChat})).room_id,yield this.withIgnoreInvitesPolicies((t=>{t.target=e})),this.client.getRoom(e)}))}getOrCreateSourceRooms(){return n(this,void 0,void 0,(function*(){let e=this.getIgnoreInvitesPolicies().sources,t=!1;Array.isArray(e)||(t=!0,e=[]);let i=e.filter((e=>"string"==typeof e)).map((e=>this.client.getRoom(e))).filter((e=>!!e));if(i.length!=e.length&&(t=!0),0==i.length){t=!0,i=[yield this.getOrCreateTargetRoom()]}return t&&(yield this.withIgnoreInvitesPolicies((t=>{t.sources=e}))),i}))}getIgnoreInvitesPolicies(){return this.getPoliciesAndIgnoreInvitesPolicies().ignoreInvitesPolicies}withIgnoreInvitesPolicies(e){return n(this,void 0,void 0,(function*(){const{policies:t,ignoreInvitesPolicies:n}=this.getPoliciesAndIgnoreInvitesPolicies();e(n),t[i.IGNORE_INVITES_ACCOUNT_EVENT_KEY.name]=n,yield this.client.setAccountData(i.POLICIES_ACCOUNT_EVENT_TYPE.name,t)}))}getPoliciesAndIgnoreInvitesPolicies(){var e;let t={};for(const n of[i.POLICIES_ACCOUNT_EVENT_TYPE.name,i.POLICIES_ACCOUNT_EVENT_TYPE.altName]){if(!n)continue;const i=null===(e=this.client.getAccountData(n))||void 0===e?void 0:e.getContent();if(i){t=i;break}}let n={},r=!1;for(const e of[i.IGNORE_INVITES_ACCOUNT_EVENT_KEY.name,i.IGNORE_INVITES_ACCOUNT_EVENT_KEY.altName]){if(!e)continue;const i=t[e];if(i&&"object"==typeof i){n=i,r=!0;break}}return r||(t[i.IGNORE_INVITES_ACCOUNT_EVENT_KEY.name]=n),{policies:t,ignoreInvitesPolicies:n}}}},{"../@types/partials":309,"../utils":416,"./event-timeline":382,"matrix-events-sdk":167}],385:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.Poll=i.PollEvent=void 0;const r=e("../@types/polls"),o=e("./relations"),s=e("./typed-event-emitter");var a;!function(e){e.New="Poll.new",e.End="Poll.end",e.Update="Poll.update",e.Responses="Poll.Responses",e.Destroy="Poll.Destroy",e.UndecryptableRelations="Poll.UndecryptableRelations"}(a=i.PollEvent||(i.PollEvent={}));const c=(e,t)=>({responseEvents:e.filter((e=>{if(!e.isDecryptionFailure())return r.M_POLL_RESPONSE.matches(e.getType())&&e.getTs()<=t}))});class d extends s.TypedEventEmitter{constructor(e,t,i){if(super(),this.rootEvent=e,this.matrixClient=t,this.room=i,this._isFetchingResponses=!1,this.responses=null,this.undecryptableRelationEventIds=new Set,this.countUndecryptableEvents=e=>{const t=e.filter((e=>e.isDecryptionFailure())).map((e=>e.getId())),i=this.undecryptableRelationsCount;this.undecryptableRelationEventIds=new Set([...this.undecryptableRelationEventIds,...t]),this.undecryptableRelationsCount!==i&&this.emit(a.UndecryptableRelations,this.undecryptableRelationsCount)},!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 e;return null===(e=this.endEvent)||void 0===e?void 0:e.getId()}get isEnded(){return!!this.endEvent}get isFetchingResponses(){return this._isFetchingResponses}get undecryptableRelationsCount(){return this.undecryptableRelationEventIds.size}getResponses(){return n(this,void 0,void 0,(function*(){return this.responses||this.isFetchingResponses||(yield this.fetchResponses()),this.responses}))}onNewRelation(e){var t;if(r.M_POLL_END.matches(e.getType())&&this.validateEndEvent(e)&&(this.endEvent=e,this.refilterResponsesOnEnd(),this.emit(a.End)),!this.responses)return;const i=(null===(t=this.endEvent)||void 0===t?void 0:t.getTs())||Number.MAX_SAFE_INTEGER,{responseEvents:n}=c([e],i);this.countUndecryptableEvents([e]),n.length&&(n.forEach((e=>{this.responses.addEvent(e)})),this.emit(a.Responses,this.responses))}fetchResponses(){var e,t;return n(this,void 0,void 0,(function*(){this._isFetchingResponses=!0;const i=yield this.matrixClient.relations(this.roomId,this.rootEvent.getId(),"m.reference",void 0,{from:this.relationsNextBatch||void 0});yield Promise.all(i.events.map((e=>this.matrixClient.decryptEventIfNeeded(e))));const n=this.responses||new o.Relations("m.reference",r.M_POLL_RESPONSE.name,this.matrixClient,[r.M_POLL_RESPONSE.altName]),s=i.events.find((e=>r.M_POLL_END.matches(e.getType())));this.validateEndEvent(s)&&(this.endEvent=s,this.refilterResponsesOnEnd(),this.emit(a.End));const d=(null===(e=this.endEvent)||void 0===e?void 0:e.getTs())||Number.MAX_SAFE_INTEGER,{responseEvents:l}=c(i.events,d);l.forEach((e=>{n.addEvent(e)})),this.relationsNextBatch=null!==(t=i.nextBatch)&&void 0!==t?t:void 0,this.responses=n,this.countUndecryptableEvents(i.events),this.relationsNextBatch?this.fetchResponses():this._isFetchingResponses=!1,this.emit(a.Responses,this.responses)}))}refilterResponsesOnEnd(){var e;if(!this.responses)return;const t=(null===(e=this.endEvent)||void 0===e?void 0:e.getTs())||Number.MAX_SAFE_INTEGER;this.responses.getRelations().forEach((e=>{var i;e.getTs()>t&&(null===(i=this.responses)||void 0===i||i.removeEvent(e))})),this.emit(a.Responses,this.responses)}validateEndEvent(e){if(!e)return!1;if(this.endEvent&&this.endEvent.getTs()new Map)),this.receiptCacheByEventId=new Map}getReadReceiptForUserId(e,t=!1,i=s.ReceiptType.Read){var n,r;const[o,a]=null!==(r=null===(n=this.receipts.get(i))||void 0===n?void 0:n.get(e))&&void 0!==r?r:[null,null];return t?o:null!=a?a:o}getEventReadUpTo(e,t=!1){var i,n,r,o,a,c,d;const l=this.getUnfilteredTimelineSet(),u=this.getReadReceiptForUserId(e,t,s.ReceiptType.Read),h=this.getReadReceiptForUserId(e,t,s.ReceiptType.ReadPrivate);let f;return(null==u?void 0:u.eventId)&&(null==h?void 0:h.eventId)&&(f=l.compareEventOrdering(null==u?void 0:u.eventId,null==h?void 0:h.eventId)),!f&&(null===(i=null==u?void 0:u.data)||void 0===i?void 0:i.ts)&&(null===(n=null==h?void 0:h.data)||void 0===n?void 0:n.ts)&&(f=(null===(r=null==u?void 0:u.data)||void 0===r?void 0:r.ts)-(null===(o=null==h?void 0:h.data)||void 0===o?void 0:o.ts)),f?null!==(d=f<0?null==h?void 0:h.eventId:null==u?void 0:u.eventId)&&void 0!==d?d:null:null!==(c=null!==(a=null==h?void 0:h.eventId)&&void 0!==a?a:null==u?void 0:u.eventId)&&void 0!==c?c:null}addReceiptToStructure(e,t,i,n,r){var o,s,a;const c=this.receipts.getOrCreate(t);let d=c.get(i);d||(d=[null,null],c.set(i,d));let l=d[0];if(r&&(l=null!==(o=d[1])&&void 0!==o?o:d[0]),l){const t=this.getUnfilteredTimelineSet().compareEventOrdering(l.eventId,e);if(null!==t&&t>=0)return}const u={eventId:e,data:n},h=r?d[0]:u,f=r?u:d[1];let p=null;h&&f&&(p=this.getUnfilteredTimelineSet().compareEventOrdering(h.eventId,f.eventId));const g=null===p||p<0,v=null!==(s=d[1])&&void 0!==s?s:d[0];r&&g?d[1]=u:r||(d[0]=u,g||(d[1]=null));if(v!==(null!==(a=d[1])&&void 0!==a?a:d[0])){if(v&&this.receiptCacheByEventId.get(v.eventId)){const e=v.eventId;this.receiptCacheByEventId.set(e,this.receiptCacheByEventId.get(e).filter((e=>e.type!==t||e.userId!==i))),this.receiptCacheByEventId.get(e).length<1&&this.receiptCacheByEventId.delete(e)}this.receiptCacheByEventId.get(e)||this.receiptCacheByEventId.set(e,[]),this.receiptCacheByEventId.get(e).push({userId:i,type:t,data:n})}}getReceiptsForEvent(e){return this.receiptCacheByEventId.get(e.getId())||[]}fixupNotifications(e){const t=this.getReadReceiptForUserId(e,!1),i=this.timeline[this.timeline.length-1];i&&(null==t?void 0:t.eventId)===i.getId()&&e===i.getSender()&&(this.setUnread(h.NotificationCountType.Total,0),this.setUnread(h.NotificationCountType.Highlight,0))}addLocalEchoReceipt(e,t,i){this.addReceipt(f(e,t,i),!0)}getUsersReadUpTo(e){return this.getReceiptsForEvent(e).filter((function(e){return c.isSupportedReceiptType(e.type)})).map((function(e){return e.userId}))}hasUserReadEvent(e,t){var i,n;const r=this.getEventReadUpTo(e,!1);if(r===t)return!0;if((null===(i=this.timeline)||void 0===i?void 0:i.length)&&this.timeline[this.timeline.length-1].getSender()&&this.timeline[this.timeline.length-1].getSender()===e)return!0;for(let e=(null===(n=this.timeline)||void 0===n?void 0:n.length)-1;e>=0;--e){const i=this.timeline[e];if(i.getId()===t)return!1;if(i.getId()===r)return!0}return!1}}i.ReadReceipt=p},{"../@types/event":306,"../@types/read_receipts":311,"../utils":416,"./event":383,"./room":392,"./typed-event-emitter":395}],387:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.RelationsContainer=void 0;const n=e("./relations"),r=e("./event");i.RelationsContainer=class{constructor(e,t){this.client=e,this.room=t,this.relations=new Map}getChildEventsForEvent(e,t,i){var n,r;return null===(r=null===(n=this.relations.get(e))||void 0===n?void 0:n.get(t))||void 0===r?void 0:r.get(i)}getAllChildEventsForEvent(e){var t;const i=null!==(t=this.relations.get(e))&&void 0!==t?t:new Map,n=[];for(const e of i.values())for(const t of e.values())n.push(...t.getRelations());return n}aggregateParentEvent(e){const t=this.relations.get(e.getId());if(t)for(const i of t.values())for(const t of i.values())t.setTargetEvent(e)}aggregateChildEvent(e,t){var i,o,s;if(e.isRedacted()||e.status===r.EventStatus.CANCELLED)return;const a=e.getRelation();if(!a)return;const c=()=>{e.isDecryptionFailure()?e.once(r.MatrixEventEvent.Decrypted,c):this.aggregateChildEvent(e,t)};if(e.isBeingDecrypted()||e.shouldAttemptDecryption())return void e.once(r.MatrixEventEvent.Decrypted,c);const{event_id:d,rel_type:l}=a,u=e.getType();let h=this.relations.get(d);h||(h=new Map,this.relations.set(d,h));let f=h.get(l);f||(f=new Map,h.set(l,f));let p=f.get(u);if(!p){p=new n.Relations(l,u,this.client),f.set(u,p);const e=null!==(i=this.room)&&void 0!==i?i:null==t?void 0:t.room,r=null!==(s=null!==(o=null==t?void 0:t.findEventById(d))&&void 0!==o?o:null==e?void 0:e.findEventById(d))&&void 0!==s?s:null==e?void 0:e.getPendingEvent(d);r&&p.setTargetEvent(r)}p.addEvent(e)}}},{"./event":383,"./relations":388}],388:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.Relations=i.RelationsEvent=void 0;const r=e("./event"),o=e("../logger"),s=e("../@types/event"),a=e("./typed-event-emitter"),c=e("./room");var d;!function(e){e.Add="Relations.add",e.Remove="Relations.remove",e.Redaction="Relations.redaction"}(d=i.RelationsEvent||(i.RelationsEvent={}));class l extends a.TypedEventEmitter{constructor(e,t,i,o){super(),this.relationType=e,this.eventType=t,this.altEventTypes=o,this.relationEventIds=new Set,this.relations=new Set,this.annotationsByKey={},this.annotationsBySender={},this.sortedAnnotationsByKey=[],this.targetEvent=null,this.creationEmitted=!1,this.onEventStatus=(e,t)=>{e.isSending()?t===r.EventStatus.CANCELLED&&(e.removeListener(r.MatrixEventEvent.Status,this.onEventStatus),this.removeEvent(e)):e.removeListener(r.MatrixEventEvent.Status,this.onEventStatus)},this.onBeforeRedaction=e=>n(this,void 0,void 0,(function*(){if(this.relations.has(e)){if(this.relations.delete(e),this.relationType===s.RelationType.Annotation)this.removeAnnotationFromAggregation(e);else if(this.relationType===s.RelationType.Replace&&this.targetEvent&&!this.targetEvent.isState()){const e=yield this.getLastReplacement();this.targetEvent.makeReplaced(e)}e.removeListener(r.MatrixEventEvent.BeforeRedaction,this.onBeforeRedaction),this.emit(d.Redaction,e)}})),this.client=i instanceof c.Room?i.client:i}addEvent(e){return n(this,void 0,void 0,(function*(){if(this.relationEventIds.has(e.getId()))return;const t=e.getRelation();if(!t)return void o.logger.error("Event must have relation info");const i=t.rel_type,n=e.getType();if(this.relationType===i&&((e,t,i=[])=>[t,...i].includes(e))(n,this.eventType,this.altEventTypes)){if(e.isSending()&&e.on(r.MatrixEventEvent.Status,this.onEventStatus),this.relations.add(e),this.relationEventIds.add(e.getId()),this.relationType===s.RelationType.Annotation)this.addAnnotationToAggregation(e);else if(this.relationType===s.RelationType.Replace&&this.targetEvent&&!this.targetEvent.isState()){const e=yield this.getLastReplacement();this.targetEvent.makeReplaced(e)}e.on(r.MatrixEventEvent.BeforeRedaction,this.onBeforeRedaction),this.emit(d.Add,e),this.maybeEmitCreated()}else o.logger.error("Event relation info doesn't match this container")}))}removeEvent(e){return n(this,void 0,void 0,(function*(){if(this.relations.has(e)){if(this.relations.delete(e),this.relationType===s.RelationType.Annotation)this.removeAnnotationFromAggregation(e);else if(this.relationType===s.RelationType.Replace&&this.targetEvent&&!this.targetEvent.isState()){const e=yield this.getLastReplacement();this.targetEvent.makeReplaced(e)}this.emit(d.Remove,e)}}))}getRelations(){return[...this.relations]}addAnnotationToAggregation(e){var t;const{key:i}=null!==(t=e.getRelation())&&void 0!==t?t:{};if(!i)return;let n=this.annotationsByKey[i];n||(n=this.annotationsByKey[i]=new Set,this.sortedAnnotationsByKey.push([i,n])),n.add(e),this.sortedAnnotationsByKey.sort(((e,t)=>{const i=e[1];return t[1].size-i.size}));const r=e.getSender();let o=this.annotationsBySender[r];o||(o=this.annotationsBySender[r]=new Set),o.add(e)}removeAnnotationFromAggregation(e){var t;const{key:i}=null!==(t=e.getRelation())&&void 0!==t?t:{};if(!i)return;const n=this.annotationsByKey[i];n&&(n.delete(e),this.sortedAnnotationsByKey.sort(((e,t)=>{const i=e[1];return t[1].size-i.size})));const r=e.getSender(),o=this.annotationsBySender[r];o&&o.delete(e)}getSortedAnnotationsByKey(){return this.relationType!==s.RelationType.Annotation?null:this.sortedAnnotationsByKey}getAnnotationsBySender(){return this.relationType!==s.RelationType.Annotation?null:this.annotationsBySender}getLastReplacement(){return n(this,void 0,void 0,(function*(){if(this.relationType!==s.RelationType.Replace)return null;if(!this.targetEvent)return null;const e=this.targetEvent.getServerAggregatedRelation(s.RelationType.Replace),t=null==e?void 0:e.origin_server_ts,i=this.getRelations().reduce(((e,i)=>i.getSender()!==this.targetEvent.getSender()||t&&t>i.getTs()||e&&e.getTs()>i.getTs()?e:i),null);return(null==i?void 0:i.shouldAttemptDecryption())&&this.client.isCryptoEnabled()?yield i.attemptDecryption(this.client.crypto):(null==i?void 0:i.isBeingDecrypted())&&(yield i.getDecryptionPromise()),i}))}setTargetEvent(e){return n(this,void 0,void 0,(function*(){if(!this.targetEvent){if(this.targetEvent=e,this.relationType===s.RelationType.Replace&&!this.targetEvent.isState()){const e=yield this.getLastReplacement();e&&this.targetEvent.makeReplaced(e)}this.maybeEmitCreated()}}))}maybeEmitCreated(){this.creationEmitted||this.targetEvent&&this.relations.size&&(this.creationEmitted=!0,this.targetEvent.emit(r.MatrixEventEvent.RelationsCreated,this.relationType,this.eventType))}}i.Relations=l},{"../@types/event":306,"../logger":374,"./event":383,"./room":392,"./typed-event-emitter":395}],389:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t};Object.defineProperty(i,"__esModule",{value:!0}),i.RoomMember=i.RoomMemberEvent=void 0;const s=e("../content-repo"),a=o(e("../utils")),c=e("../logger"),d=e("./typed-event-emitter"),l=e("../@types/event");var u;!function(e){e.Membership="RoomMember.membership",e.Name="RoomMember.name",e.PowerLevel="RoomMember.powerLevel",e.Typing="RoomMember.typing"}(u=i.RoomMemberEvent||(i.RoomMemberEvent={}));class h extends d.TypedEventEmitter{constructor(e,t){super(),this.roomId=e,this.userId=t,this._isOutOfBand=!1,this.modified=-1,this.requestedProfileInfo=!1,this.typing=!1,this.powerLevel=0,this.powerLevelNorm=0,this.disambiguate=!1,this.events={},this.name=t,this.rawDisplayName=t,this.updateModifiedTime()}markOutOfBand(){this._isOutOfBand=!0}isOutOfBand(){return this._isOutOfBand}setMembershipEvent(e,t){var i,n;const r=null!==(i=e.getDirectionalContent().displayname)&&void 0!==i?i:"";if(e.getType()!==l.EventType.RoomMember)return;this._isOutOfBand=!1,this.events.member=e;const o=this.membership;this.membership=e.getDirectionalContent().membership,void 0===this.membership&&c.logger.trace(`membership event with membership undefined (forwardLooking: ${e.forwardLooking})!`,e.getContent(),"prevcontent is ",e.getPrevContent()),this.disambiguate=function(e,t,i){if(!t||t===e)return!1;if(!a.removeHiddenChars(t))return!1;if(!i)return!1;if(f.test(t))return!0;if(p.test(t))return!0;const n=i.getUserIdsWithDisplayName(t);return!!n.some((t=>t!==e))}(this.userId,r,t);const s=this.name;this.name=function(e,t,i){return t&&t!==e?i?a.removeDirectionOverrideChars(t)+" ("+e+")":a.removeHiddenChars(t)?a.removeDirectionOverrideChars(t):e:e}(this.userId,r,this.disambiguate),this.rawDisplayName=a.removeDirectionOverrideChars(null!==(n=e.getDirectionalContent().displayname)&&void 0!==n?n:""),this.rawDisplayName&&a.removeHiddenChars(this.rawDisplayName)||(this.rawDisplayName=this.userId),o!==this.membership&&(this.updateModifiedTime(),this.emit(u.Membership,e,this,o)),s!==this.name&&(this.updateModifiedTime(),this.emit(u.Name,e,this,s))}setPowerLevelEvent(e){if(e.getType()!==l.EventType.RoomPowerLevels||""!==e.getStateKey())return;const t=e.getDirectionalContent();let i=t.users_default||0;const n=t.users||{};Object.values(n).forEach((e=>{i=Math.max(i,e)}));const r=this.powerLevel,o=this.powerLevelNorm;void 0!==n[this.userId]&&Number.isInteger(n[this.userId])?this.powerLevel=n[this.userId]:void 0!==t.users_default?this.powerLevel=t.users_default:this.powerLevel=0,this.powerLevelNorm=0,i>0&&(this.powerLevelNorm=100*this.powerLevel/i),r===this.powerLevel&&o===this.powerLevelNorm||(this.updateModifiedTime(),this.emit(u.PowerLevel,e,this))}setTypingEvent(e){if("m.typing"!==e.getType())return;const t=this.typing;this.typing=!1;const i=e.getContent().user_ids;Array.isArray(i)&&(-1!==i.indexOf(this.userId)&&(this.typing=!0),t!==this.typing&&(this.updateModifiedTime(),this.emit(u.Typing,e,this)))}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}isKicked(){return"leave"===this.membership&&void 0!==this.events.member&&this.events.member.getSender()!==this.events.member.getStateKey()}getDMInviter(){if(this.events.member){const e=this.events.member;let t=e.getContent(),i=e.getSender();if("join"===t.membership&&(t=e.getPrevContent(),i=e.getUnsigned().prev_sender),"invite"===t.membership&&t.is_direct)return i}}getAvatarUrl(e,t,i,n,r=!0,o){const a=this.getMxcAvatarUrl();if(!a&&!r)return null;const c=(0,s.getHttpUriForMxc)(e,a,t,i,n,o);return c||null}getMxcAvatarUrl(){return this.events.member?this.events.member.getDirectionalContent().avatar_url:this.user?this.user.avatarUrl:void 0}}i.RoomMember=h;const f=/@.+:.+/,p=/[\u200E\u200F\u202A-\u202F]/},{"../@types/event":306,"../content-repo":323,"../logger":374,"../utils":416,"./typed-event-emitter":395}],390:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.RoomState=i.RoomStateEvent=void 0;const a=e("./room-member"),c=e("../logger"),d=o(e("../utils")),l=e("../@types/event"),u=e("./event"),h=e("../@types/partials"),f=e("./typed-event-emitter"),p=e("./beacon"),g=e("../ReEmitter"),v=e("../@types/beacon");var m,y;!function(e){e[e.NotStarted=0]="NotStarted",e[e.InProgress=1]="InProgress",e[e.Finished=2]="Finished"}(m||(m={})),function(e){e.Events="RoomState.events",e.Members="RoomState.members",e.NewMember="RoomState.newMember",e.Update="RoomState.update",e.BeaconLiveness="RoomState.BeaconLiveness",e.Marker="RoomState.Marker"}(y=i.RoomStateEvent||(i.RoomStateEvent={}));class b extends f.TypedEventEmitter{constructor(e,t={status:m.NotStarted}){super(),this.roomId=e,this.oobMemberFlags=t,this.reEmitter=new g.TypedReEmitter(this),this.sentinels={},this.displayNameToUserIds=new Map,this.userIdsToDisplayNames={},this.tokenToInvite={},this.joinedMemberCount=null,this.summaryJoinedMemberCount=null,this.invitedMemberCount=null,this.summaryInvitedMemberCount=null,this.modified=-1,this.members={},this.events=new Map,this.paginationToken=null,this.beacons=new Map,this._liveBeaconIds=[],this.updateModifiedTime()}getJoinedMemberCount(){return null!==this.summaryJoinedMemberCount?this.summaryJoinedMemberCount:(null===this.joinedMemberCount&&(this.joinedMemberCount=this.getMembers().reduce(((e,t)=>"join"===t.membership?e+1:e),0)),this.joinedMemberCount)}setJoinedMemberCount(e){this.summaryJoinedMemberCount=e}getInvitedMemberCount(){return null!==this.summaryInvitedMemberCount?this.summaryInvitedMemberCount:(null===this.invitedMemberCount&&(this.invitedMemberCount=this.getMembers().reduce(((e,t)=>"invite"===t.membership?e+1:e),0)),this.invitedMemberCount)}setInvitedMemberCount(e){this.summaryInvitedMemberCount=e}getMembers(){return Object.values(this.members)}getMembersExcept(e){return this.getMembers().filter((t=>!e.includes(t.userId)))}getMember(e){return this.members[e]||null}getSentinelMember(e){if(!e)return null;let t=this.sentinels[e];if(void 0===t){t=new a.RoomMember(this.roomId,e);const i=this.members[e];(null==i?void 0:i.events.member)&&t.setMembershipEvent(i.events.member,this),this.sentinels[e]=t}return t}getStateEvents(e,t){if(!this.events.has(e))return void 0===t?[]:null;if(void 0===t)return Array.from(this.events.get(e).values());const i=this.events.get(e).get(t);return i||null}get hasLiveBeacons(){var e;return!!(null===(e=this.liveBeaconIds)||void 0===e?void 0:e.length)}get liveBeaconIds(){return this._liveBeaconIds}clone(){const e=new b(this.roomId,this.oobMemberFlags),t=this.oobMemberFlags.status;return this.oobMemberFlags.status=m.NotStarted,Array.from(this.events.values()).forEach((t=>{e.setStateEvents(Array.from(t.values()))})),this.oobMemberFlags.status=t,null!==this.summaryInvitedMemberCount&&e.setInvitedMemberCount(this.getInvitedMemberCount()),null!==this.summaryJoinedMemberCount&&e.setJoinedMemberCount(this.getJoinedMemberCount()),this.oobMemberFlags.status==m.Finished&&this.getMembers().forEach((t=>{var i;t.isOutOfBand()&&(null===(i=e.getMember(t.userId))||void 0===i||i.markOutOfBand())})),e}setUnknownStateEvents(e){const t=e.filter((e=>!this.events.has(e.getType())||!this.events.get(e.getType()).has(e.getStateKey())));this.setStateEvents(t)}setStateEvents(e,t){this.updateModifiedTime(),e.forEach((e=>{var t;if(e.getRoomId()!==this.roomId||!e.isState())return;v.M_BEACON_INFO.matches(e.getType())&&this.setBeacon(e);const i=this.getStateEventMatching(e);this.setStateEvent(e),e.getType()===l.EventType.RoomMember&&(this.updateDisplayNameCache(e.getStateKey(),null!==(t=e.getContent().displayname)&&void 0!==t?t:""),this.updateThirdPartyTokenCache(e)),this.emit(y.Events,e,this,i)})),this.onBeaconLivenessChange(),e.forEach((e=>{if(e.getRoomId()===this.roomId&&e.isState())if(e.getType()===l.EventType.RoomMember){const t=e.getStateKey();"leave"!==e.getContent().membership&&"ban"!==e.getContent().membership||(e.getContent().avatar_url=e.getContent().avatar_url||e.getPrevContent().avatar_url,e.getContent().displayname=e.getContent().displayname||e.getPrevContent().displayname);const i=this.getOrCreateMember(t,e);i.setMembershipEvent(e,this),this.updateMember(i),this.emit(y.Members,e,this,i)}else if(e.getType()===l.EventType.RoomPowerLevels){if(""!==e.getStateKey())return;Object.values(this.members).forEach((t=>{const i=t.getLastModifiedTime();t.setPowerLevelEvent(e),i!==t.getLastModifiedTime()&&this.emit(y.Members,e,this,t)})),this.sentinels={}}else l.UNSTABLE_MSC2716_MARKER.matches(e.getType())&&this.emit(y.Marker,e,t)})),this.emit(y.Update,this)}processBeaconEvents(e,t){var i;return s(this,void 0,void 0,(function*(){if(!e.length||!this.beacons.size)return;const n=[...this.beacons.values()].reduce(((e,t)=>(e[t.beaconInfoId]=t,e)),{}),r=(e,t)=>{if(!v.M_BEACON.matches(t.getType()))return;const i=n[e];i&&i.addLocations([t])};for(const o of e){const e=null===(i=o.getRelation())||void 0===i?void 0:i.event_id;if(!e||!n[e])return;if(!v.M_BEACON.matches(o.getType())&&!o.isEncrypted())return;try{yield t.decryptEventIfNeeded(o),r(e,o)}catch(t){o.isDecryptionFailure()&&o.once(u.MatrixEventEvent.Decrypted,(()=>s(this,void 0,void 0,(function*(){r(e,o)}))))}}}))}getOrCreateMember(e,t){let i=this.members[e];return i||(i=new a.RoomMember(this.roomId,e),this.members[e]=i,this.emit(y.NewMember,t,this,i)),i}setStateEvent(e){this.events.has(e.getType())||this.events.set(e.getType(),new Map),this.events.get(e.getType()).set(e.getStateKey(),e)}setBeacon(e){var t;const i=(0,p.getBeaconInfoIdentifier)(e);if(this.beacons.has(i)){const n=this.beacons.get(i);return e.isRedacted()?void(n.beaconInfoId===(null===(t=e.getRedactionEvent())||void 0===t?void 0:t.redacts)&&(n.destroy(),this.beacons.delete(i))):n.update(e)}if(e.isRedacted())return;const n=new p.Beacon(e);this.reEmitter.reEmit(n,[p.BeaconEvent.New,p.BeaconEvent.Update,p.BeaconEvent.Destroy,p.BeaconEvent.LivenessChange]),this.emit(p.BeaconEvent.New,e,n),n.on(p.BeaconEvent.LivenessChange,this.onBeaconLivenessChange.bind(this)),n.on(p.BeaconEvent.Destroy,this.onBeaconLivenessChange.bind(this)),this.beacons.set(n.identifier,n)}onBeaconLivenessChange(){this._liveBeaconIds=Array.from(this.beacons.values()).filter((e=>e.isLive)).map((e=>e.identifier)),this.emit(y.BeaconLiveness,this,this.hasLiveBeacons)}getStateEventMatching(e){var t,i;return null!==(i=null===(t=this.events.get(e.getType()))||void 0===t?void 0:t.get(e.getStateKey()))&&void 0!==i?i:null}updateMember(e){const t=this.getStateEvents(l.EventType.RoomPowerLevels,"");t&&e.setPowerLevelEvent(t),delete this.sentinels[e.userId],this.members[e.userId]=e,this.joinedMemberCount=null,this.invitedMemberCount=null}needsOutOfBandMembers(){return this.oobMemberFlags.status===m.NotStarted}outOfBandMembersReady(){return this.oobMemberFlags.status===m.Finished}markOutOfBandMembersStarted(){this.oobMemberFlags.status===m.NotStarted&&(this.oobMemberFlags.status=m.InProgress)}markOutOfBandMembersFailed(){this.oobMemberFlags.status===m.InProgress&&(this.oobMemberFlags.status=m.NotStarted)}clearOutOfBandMembers(){let e=0;Object.keys(this.members).forEach((t=>{this.members[t].isOutOfBand()&&(++e,delete this.members[t])})),c.logger.log(`LL: RoomState removed ${e} members...`),this.oobMemberFlags.status=m.NotStarted}setOutOfBandMembers(e){c.logger.log(`LL: RoomState about to set ${e.length} OOB members ...`),this.oobMemberFlags.status===m.InProgress&&(c.logger.log("LL: RoomState put in finished state ..."),this.oobMemberFlags.status=m.Finished,e.forEach((e=>this.setOutOfBandMember(e))),this.emit(y.Update,this))}setOutOfBandMember(e){if(e.getType()!==l.EventType.RoomMember)return;const t=e.getStateKey(),i=this.getMember(t);if(i&&!i.isOutOfBand())return;const n=this.getOrCreateMember(t,e);n.setMembershipEvent(e,this),n.markOutOfBand(),this.updateDisplayNameCache(n.userId,n.name),this.setStateEvent(e),this.updateMember(n),this.emit(y.Members,e,this,n)}setTypingEvent(e){Object.values(this.members).forEach((function(t){t.setTypingEvent(e)}))}getInviteForThreePidToken(e){return this.tokenToInvite[e]||null}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}getUserIdsWithDisplayName(e){var t;return null!==(t=this.displayNameToUserIds.get(d.removeHiddenChars(e)))&&void 0!==t?t:[]}maySendRedactionForEvent(e,t){const i=this.getMember(t);if(!i||"leave"===i.membership)return!1;if(e.status||e.isRedacted())return!1;const n=this.maySendEvent(l.EventType.RoomRedaction,t);return e.getSender()===t?n:this.hasSufficientPowerLevelFor("redact",i.powerLevel)}hasSufficientPowerLevelFor(e,t){const i=this.getStateEvents(l.EventType.RoomPowerLevels,"");let n={};i&&(n=i.getContent());let r=50;return d.isNumber(n[e])&&(r=n[e]),t>=r}maySendMessage(e){return this.maySendEventOfType(l.EventType.RoomMessage,e,!1)}maySendEvent(e,t){return this.maySendEventOfType(e,t,!1)}mayClientSendStateEvent(e,t){return!(t.isGuest()||!t.credentials.userId)&&this.maySendStateEvent(e,t.credentials.userId)}maySendStateEvent(e,t){return this.maySendEventOfType(e,t,!0)}maySendEventOfType(e,t,i){const n=this.getStateEvents(l.EventType.RoomPowerLevels,"");let r,o={},s=0,a=0,c=0;if(n){r=n.getContent(),o=r.events||{},s=Number.isSafeInteger(r.state_default)?r.state_default:50;const e=r.users&&r.users[t];Number.isSafeInteger(e)?c=e:Number.isSafeInteger(r.users_default)&&(c=r.users_default),Number.isSafeInteger(r.events_default)&&(a=r.events_default)}let d=i?s:a;return Number.isSafeInteger(o[e])&&(d=o[e]),c>=d}mayTriggerNotifOfType(e,t){const i=this.getMember(t);if(!i)return!1;const n=this.getStateEvents(l.EventType.RoomPowerLevels,"");let r=50;return n&&n.getContent()&&n.getContent().notifications&&d.isNumber(n.getContent().notifications[e])&&(r=n.getContent().notifications[e]),i.powerLevel>=r}getJoinRule(){var e;const t=this.getStateEvents(l.EventType.RoomJoinRules,"");return(null!==(e=null==t?void 0:t.getContent())&&void 0!==e?e:{}).join_rule||h.JoinRule.Invite}getHistoryVisibility(){var e;const t=this.getStateEvents(l.EventType.RoomHistoryVisibility,"");return(null!==(e=null==t?void 0:t.getContent())&&void 0!==e?e:{}).history_visibility||h.HistoryVisibility.Shared}getGuestAccess(){var e;const t=this.getStateEvents(l.EventType.RoomGuestAccess,"");return(null!==(e=null==t?void 0:t.getContent())&&void 0!==e?e:{}).guest_access||h.GuestAccess.Forbidden}findPredecessor(e=!1){if(e){const e=this.getStateEvents(l.EventType.RoomPredecessor,"");if(e){const t=e.getContent(),i=t.predecessor_room_id;let n=t.last_known_event_id;"string"!=typeof n&&(n=void 0);let r=t.via_servers;if(Array.isArray(r)||(r=void 0),"string"==typeof i)return{roomId:i,eventId:n,viaServers:r}}}const t=this.getStateEvents(l.EventType.RoomCreate,"");if(t){const e=t.getContent().predecessor;if(e){const t=e.room_id;if("string"==typeof t){let i=e.event_id;return"string"==typeof i&&""!==i||(i=void 0),{roomId:t,eventId:i}}}}return null}updateThirdPartyTokenCache(e){if(!e.getContent().third_party_invite)return;const t=(e.getContent().third_party_invite.signed||{}).token;if(!t)return;this.getStateEvents(l.EventType.RoomThirdPartyInvite,t)&&(this.tokenToInvite[t]=e)}updateDisplayNameCache(e,t){var i;const n=this.userIdsToDisplayNames[e];if(delete this.userIdsToDisplayNames[e],n){const t=d.removeHiddenChars(n),i=this.displayNameToUserIds.get(t);if(i){const n=i.filter((t=>t!==e));this.displayNameToUserIds.set(t,n)}}this.userIdsToDisplayNames[e]=t;const r=t&&d.removeHiddenChars(t);if(r){const t=null!==(i=this.displayNameToUserIds.get(r))&&void 0!==i?i:[];t.push(e),this.displayNameToUserIds.set(r,t)}}}i.RoomState=b},{"../@types/beacon":305,"../@types/event":306,"../@types/partials":309,"../ReEmitter":317,"../logger":374,"../utils":416,"./beacon":378,"./event":383,"./room-member":389,"./typed-event-emitter":395}],391:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.RoomSummary=void 0;i.RoomSummary=class{constructor(e,t){this.roomId=e}}},{}],392:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.RoomNameType=i.Room=i.RoomEvent=i.NotificationCountType=i.KNOWN_SAFE_ROOM_VERSION=void 0;const a=e("matrix-events-sdk"),c=e("./event-timeline-set"),d=e("./event-timeline"),l=e("../content-repo"),u=o(e("../utils")),h=e("../utils"),f=e("./event"),p=e("./event-status"),g=e("./room-member"),v=e("./room-summary"),m=e("../logger"),y=e("../ReEmitter"),b=e("../@types/event"),S=e("../client"),_=e("../filter"),E=e("./room-state"),w=e("./beacon"),T=e("./thread"),I=e("../@types/read_receipts"),R=e("./relations-container"),M=e("./read-receipt"),k=e("./poll");i.KNOWN_SAFE_ROOM_VERSION="9";const C=["1","2","3","4","5","6","7","8","9"];var O,A;!function(e){e.Highlight="highlight",e.Total="total"}(O=i.NotificationCountType||(i.NotificationCountType={})),function(e){e.MyMembership="Room.myMembership",e.Tags="Room.tags",e.AccountData="Room.accountData",e.Receipt="Room.receipt",e.Name="Room.name",e.Redaction="Room.redaction",e.RedactionCancelled="Room.redactionCancelled",e.LocalEchoUpdated="Room.localEchoUpdated",e.Timeline="Room.timeline",e.TimelineReset="Room.timelineReset",e.TimelineRefresh="Room.TimelineRefresh",e.OldStateUpdated="Room.OldStateUpdated",e.CurrentStateUpdated="Room.CurrentStateUpdated",e.HistoryImportedWithinTimeline="Room.historyImportedWithinTimeline",e.UnreadNotifications="Room.UnreadNotifications"}(A=i.RoomEvent||(i.RoomEvent={}));class P extends M.ReadReceipt{constructor(e,t,i,n={}){super(),this.roomId=e,this.client=t,this.myUserId=i,this.opts=n,this.txnToEvent=new Map,this.notificationCounts={},this.threadNotifications=new Map,this.cachedThreadReadReceipts=new Map,this.oldestThreadedReceiptTs=1/0,this.unthreadedReceipts=new Map,this.polls=new Map,this.threadsTimelineSets=[],this.filteredTimelineSets={},this.timelineNeedsRefresh=!1,this.summaryHeroes=null,this.getTypeWarning=!1,this.getVersionWarning=!1,this.tags={},this.accountData=new Map,this.summary=null,this.relations=new R.RelationsContainer(this.client,this),this.threads=new Map,this.visibilityEvents=new Map,this.threadTimelineSetsPromise=null,this.threadsReady=!1,this.updateThreadRootEvents=(e,t,i)=>{var n,r;e.length&&(this.updateThreadRootEvent(null===(n=this.threadsTimelineSets)||void 0===n?void 0:n[0],e,t,i),e.hasCurrentUserParticipated&&this.updateThreadRootEvent(null===(r=this.threadsTimelineSets)||void 0===r?void 0:r[1],e,t,i))},this.updateThreadRootEvent=(e,t,i,n)=>{e&&t.rootEvent&&(n&&e.removeEvent(t.id),T.Thread.hasServerSideSupport?e.addLiveEvent(t.rootEvent,{duplicateStrategy:c.DuplicateStrategy.Replace,fromCache:!1,roomState:this.currentState}):e.addEventToTimeline(t.rootEvent,e.getLiveTimeline(),{toStartOfTimeline:i}))},this.applyRedaction=e=>{if(e.isRedaction()){const t=e.event.redacts,i=t?this.findEventById(t):void 0;if(i){if(i.makeRedacted(e),i.isState()){const e=this.currentState.getStateEvents(i.getType(),i.getStateKey());(null==e?void 0:e.getId())===i.getId()&&this.currentState.setStateEvents([i])}this.emit(A.Redaction,e,this),this.visibilityEvents.delete(t),i.isVisibilityEvent()&&this.redactVisibilityChangeEvent(e)}}},this.setMaxListeners(100),this.reEmitter=new y.TypedReEmitter(this),n.pendingEventOrdering=n.pendingEventOrdering||S.PendingEventOrdering.Chronological,this.name=e,this.normalizedName=e,this.timelineSets=[new c.EventTimelineSet(this,n)],this.reEmitter.reEmit(this.getUnfilteredTimelineSet(),[A.Timeline,A.TimelineReset]),this.fixUpLegacyTimelineFields(),this.opts.pendingEventOrdering===S.PendingEventOrdering.Detached&&(this.pendingEventList=[],this.client.store.getPendingEvents(this.roomId).then((e=>{const i=this.client.getEventMapper({toDevice:!1,decrypt:!1});e.forEach((e=>s(this,void 0,void 0,(function*(){const n=i(e);yield t.decryptEventIfNeeded(n),n.setStatus(p.EventStatus.NOT_SENT),this.addPendingEvent(n,n.getTxnId())}))))}))),this.opts.lazyLoadMembers?this.membersPromise=void 0:this.membersPromise=Promise.resolve(!1)}createThreadsTimelineSets(){var e;return s(this,void 0,void 0,(function*(){if(this.threadTimelineSetsPromise)return this.threadTimelineSetsPromise;if(null===(e=this.client)||void 0===e?void 0:e.supportsThreads())try{this.threadTimelineSetsPromise=Promise.all([this.createThreadTimelineSet(),this.createThreadTimelineSet(T.ThreadFilterType.My)]);const e=yield this.threadTimelineSetsPromise;return this.threadsTimelineSets.push(...e),e}catch(e){return this.threadTimelineSetsPromise=null,null}return null}))}decryptCriticalEvents(){return s(this,void 0,void 0,(function*(){if(!this.client.isCryptoEnabled())return;const e=this.getEventReadUpTo(this.client.getUserId(),!0),t=this.getLiveTimeline().getEvents(),i=t.findIndex((t=>t.event.event_id===e)),n=t.slice(i).reverse().map((e=>this.client.decryptEventIfNeeded(e,{isRetry:!0})));yield Promise.allSettled(n)}))}decryptAllEvents(){return s(this,void 0,void 0,(function*(){if(!this.client.isCryptoEnabled())return;const e=this.getUnfilteredTimelineSet().getLiveTimeline().getEvents().slice(0).reverse().map((e=>this.client.decryptEventIfNeeded(e,{isRetry:!0})));yield Promise.allSettled(e)}))}getCreator(){var e;const t=this.currentState.getStateEvents(b.EventType.RoomCreate,"");return null!==(e=null==t?void 0:t.getContent().creator)&&void 0!==e?e:null}getVersion(){var e;const t=this.currentState.getStateEvents(b.EventType.RoomCreate,"");return t?null!==(e=t.getContent().room_version)&&void 0!==e?e:"1":(this.getVersionWarning||(m.logger.warn("[getVersion] Room "+this.roomId+" does not have an m.room.create event"),this.getVersionWarning=!0),"1")}shouldUpgradeToVersion(){return C.includes(this.getVersion())?null:i.KNOWN_SAFE_ROOM_VERSION}getRecommendedVersion(){return s(this,void 0,void 0,(function*(){let e=(yield this.client.getCapabilities())["m.room_versions"];if(!e){e={default:i.KNOWN_SAFE_ROOM_VERSION,available:{}};for(const t of C)e.available[t]=S.RoomVersionStability.Stable}let t=this.checkVersionAgainstCapability(e);if(t.urgent&&t.needsUpgrade){m.logger.warn("Refreshing room version capability because the server looks to be supporting a newer room version we don't know about.");if(e=(yield this.client.getCapabilities(!0))["m.room_versions"],!e)return m.logger.warn("No room version capability - assuming upgrade required."),t;t=this.checkVersionAgainstCapability(e)}return t}))}checkVersionAgainstCapability(e){const t=this.getVersion();m.logger.log(`[${this.roomId}] Current version: ${t}`),m.logger.log(`[${this.roomId}] Version capability: `,e);const i={version:t,needsUpgrade:!1,urgent:!1};if(t===e.default)return i;return Object.keys(e.available).filter((t=>"stable"===e.available[t])).includes(t)||(i.version=e.default,i.needsUpgrade=!0,i.urgent=!!this.getVersion().match(/^[0-9]+[0-9.]*$/g),i.urgent?m.logger.warn(`URGENT upgrade required on ${this.roomId}`):m.logger.warn(`Non-urgent upgrade required on ${this.roomId}`)),i}userMayUpgradeRoom(e){return this.currentState.maySendStateEvent(b.EventType.RoomTombstone,e)}getPendingEvents(){if(!this.pendingEventList)throw new Error("Cannot call getPendingEvents with pendingEventOrdering == "+this.opts.pendingEventOrdering);return this.pendingEventList}removePendingEvent(e){if(!this.pendingEventList)throw new Error("Cannot call removePendingEvent with pendingEventOrdering == "+this.opts.pendingEventOrdering);const t=u.removeElement(this.pendingEventList,(function(t){return t.getId()==e}),!1);return this.savePendingEvents(),t}hasPendingEvent(e){var t,i;return null!==(i=null===(t=this.pendingEventList)||void 0===t?void 0:t.some((t=>t.getId()===e)))&&void 0!==i&&i}getPendingEvent(e){var t,i;return null!==(i=null===(t=this.pendingEventList)||void 0===t?void 0:t.find((t=>t.getId()===e)))&&void 0!==i?i:null}getLiveTimeline(){return this.getUnfilteredTimelineSet().getLiveTimeline()}getLastActiveTimestamp(){const e=this.getLiveTimeline().getEvents();if(e.length){return e[e.length-1].getTs()}return Number.MIN_SAFE_INTEGER}getMyMembership(){var e;return null!==(e=this.selfMembership)&&void 0!==e?e:"leave"}getDMInviter(){var e;const t=this.getMember(this.myUserId);if(t)return t.getDMInviter();if("invite"===this.selfMembership){if(2===this.getInvitedAndJoinedMemberCount())return null===(e=this.summaryHeroes)||void 0===e?void 0:e[0]}}guessDMUserId(){const e=this.getMember(this.myUserId);if(e){const t=e.getDMInviter();if(t)return t}if(Array.isArray(this.summaryHeroes)&&this.summaryHeroes.length)return this.summaryHeroes[0];const t=this.currentState.getMembers().find((e=>e.userId!==this.myUserId));return t?t.userId:this.myUserId}getAvatarFallbackMember(){if(this.getInvitedAndJoinedMemberCount()>2)return;const e=Array.isArray(this.summaryHeroes)&&this.summaryHeroes.length;if(e){const e=this.summaryHeroes.map((e=>this.getMember(e))).find((e=>!!e));if(e)return e}const t=this.currentState.getMembers();if(t.length<=2){const e=t.find((e=>e.userId!==this.myUserId));if(e)return e}if(e){const e=this.summaryHeroes.map((e=>this.client.getUser(e))).find((e=>!!e));if(e){const t=new g.RoomMember(this.roomId,e.userId);return t.user=e,t}}}updateMyMembership(e){const t=this.selfMembership;this.selfMembership=e,t!==e&&("leave"===e&&this.cleanupAfterLeaving(),this.emit(A.MyMembership,this,e,t))}loadMembersFromServer(){return s(this,void 0,void 0,(function*(){const e=this.client.store.getSyncToken();return(yield this.client.members(this.roomId,void 0,"leave",null!=e?e:void 0)).chunk}))}loadMembers(){return s(this,void 0,void 0,(function*(){let e=!1,t=yield this.client.store.getOutOfBandMembers(this.roomId);(null===t||this.client.isCryptoEnabled()&&this.client.isRoomEncrypted(this.roomId))&&(e=!0,t=yield this.loadMembersFromServer(),m.logger.log(`LL: got ${t.length} members from server for room ${this.roomId}`));return{memberEvents:t.filter(h.noUnsafeEventProps).map(this.client.getEventMapper()),fromServer:e}}))}membersLoaded(){return!this.opts.lazyLoadMembers||this.currentState.outOfBandMembersReady()}loadMembersIfNeeded(){if(this.membersPromise)return this.membersPromise;this.currentState.markOutOfBandMembersStarted();const e=this.loadMembers().then((e=>(this.currentState.setOutOfBandMembers(e.memberEvents),e.fromServer))).catch((e=>{throw this.membersPromise=void 0,this.currentState.markOutOfBandMembersFailed(),e}));return e.then((e=>{if(e){const e=this.currentState.getMembers().filter((e=>e.isOutOfBand())).map((e=>{var t;return null===(t=e.events.member)||void 0===t?void 0:t.event}));m.logger.log(`LL: telling store to write ${e.length} members for room ${this.roomId}`);return this.client.store.setOutOfBandMembers(this.roomId,e).catch((e=>{m.logger.log("LL: storing OOB room members failed, oh well",e)}))}})).catch((e=>{m.logger.error(e)})),this.membersPromise=e,this.membersPromise}clearLoadedMembersIfNeeded(){return s(this,void 0,void 0,(function*(){this.opts.lazyLoadMembers&&this.membersPromise&&(yield this.loadMembersIfNeeded(),yield this.client.store.clearOutOfBandMembers(this.roomId),this.currentState.clearOutOfBandMembers(),this.membersPromise=void 0)}))}cleanupAfterLeaving(){this.clearLoadedMembersIfNeeded().catch((e=>{m.logger.error(`error after clearing loaded members from room ${this.roomId} after leaving`),m.logger.log(e)}))}refreshLiveTimeline(){return s(this,void 0,void 0,(function*(){const e=this.getLiveTimeline(),t=e.getPaginationToken(d.EventTimeline.FORWARDS),i=e.getPaginationToken(d.EventTimeline.BACKWARDS),n=e.getEvents(),r=n[n.length-1];m.logger.log(`[refreshLiveTimeline for ${this.roomId}] at mostRecentEventInTimeline=${r&&r.getId()} liveTimelineBefore=${e.toString()} forwardPaginationToken=${t} backwardPaginationToken=${i}`);const o=this.getUnfilteredTimelineSet();let s;r?(this.resetLiveTimeline(null,null),this.emit(A.TimelineRefresh,this,o),s=yield this.client.getEventTimeline(o,r.getId())):s=yield this.client.getLatestTimeline(o);const a=o.getLiveTimeline();!a||null===a.getPaginationToken(d.Direction.Forward)&&null===a.getPaginationToken(d.Direction.Backward)&&0===a.getEvents().length?(m.logger.log(`[refreshLiveTimeline for ${this.roomId}] using our new live timeline`),s.setPaginationToken(t,d.EventTimeline.FORWARDS),o.setLiveTimeline(s),this.fixUpLegacyTimelineFields()):m.logger.log(`[refreshLiveTimeline for ${this.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.`),this.setTimelineNeedsRefresh(!1),this.emit(A.TimelineRefresh,this,o)}))}resetLiveTimeline(e,t){for(const i of this.timelineSets)i.resetLiveTimeline(null!=e?e:void 0,null!=t?t:void 0);for(const i of this.threads.values())i.resetLiveTimeline(e,t);this.fixUpLegacyTimelineFields()}fixUpLegacyTimelineFields(){const e=this.oldState,t=this.currentState;this.timeline=this.getLiveTimeline().getEvents(),this.oldState=this.getLiveTimeline().getState(d.EventTimeline.BACKWARDS),this.currentState=this.getLiveTimeline().getState(d.EventTimeline.FORWARDS),e!==this.oldState&&this.emit(A.OldStateUpdated,this,e,this.oldState),t!==this.currentState&&(this.emit(A.CurrentStateUpdated,this,t,this.currentState),this.reEmitter.stopReEmitting(t,[E.RoomStateEvent.Events,E.RoomStateEvent.Members,E.RoomStateEvent.NewMember,E.RoomStateEvent.Update,E.RoomStateEvent.Marker,w.BeaconEvent.New,w.BeaconEvent.Update,w.BeaconEvent.Destroy,w.BeaconEvent.LivenessChange]),this.reEmitter.reEmit(this.currentState,[E.RoomStateEvent.Events,E.RoomStateEvent.Members,E.RoomStateEvent.NewMember,E.RoomStateEvent.Update,E.RoomStateEvent.Marker,w.BeaconEvent.New,w.BeaconEvent.Update,w.BeaconEvent.Destroy,w.BeaconEvent.LivenessChange]))}hasUnverifiedDevices(){return s(this,void 0,void 0,(function*(){if(!this.client.isRoomEncrypted(this.roomId))return!1;const e=yield this.getEncryptionTargetMembers();for(const t of e){if(this.client.getStoredDevicesForUser(t.userId).some((e=>e.isUnverified())))return!0}return!1}))}getTimelineSets(){return this.timelineSets}getUnfilteredTimelineSet(){return this.timelineSets[0]}getTimelineForEvent(e){const t=this.findEventById(e),i=this.findThreadForEvent(t);return i?i.timelineSet.getTimelineForEvent(e):this.getUnfilteredTimelineSet().getTimelineForEvent(e)}addTimeline(){return this.getUnfilteredTimelineSet().addTimeline()}setTimelineNeedsRefresh(e){this.timelineNeedsRefresh=e}getTimelineNeedsRefresh(){return this.timelineNeedsRefresh}findEventById(e){let t=this.getUnfilteredTimelineSet().findEventById(e);if(!t){const i=this.getThreads();for(let n=0;n0||(null!==(t=i.total)&&void 0!==t?t:0)>0)return!0;return!1}setThreadUnreadNotificationCount(e,t,i){var n,r;const o=Object.assign({highlight:null===(n=this.threadNotifications.get(e))||void 0===n?void 0:n.highlight,total:null===(r=this.threadNotifications.get(e))||void 0===r?void 0:r.total},{[t]:i});this.threadNotifications.set(e,o),this.emit(A.UnreadNotifications,o,e)}get threadsAggregateNotificationType(){var e,t;let i=null;for(const n of this.threadNotifications.values()){if((null!==(e=n.highlight)&&void 0!==e?e:0)>0)return O.Highlight;(null!==(t=n.total)&&void 0!==t?t:0)>0&&!i&&(i=O.Total)}return i}resetThreadUnreadNotificationCount(e){if(e)for(const[t]of this.threadNotifications)e.includes(t)||this.threadNotifications.delete(t);else this.threadNotifications.clear();this.emit(A.UnreadNotifications)}setUnreadNotificationCount(e,t){this.notificationCounts[e]=t,this.emit(A.UnreadNotifications,this.notificationCounts)}setUnread(e,t){return this.setUnreadNotificationCount(e,t)}setSummary(e){const t=e["m.heroes"],i=e["m.joined_member_count"],n=e["m.invited_member_count"];Number.isInteger(i)&&this.currentState.setJoinedMemberCount(i),Number.isInteger(n)&&this.currentState.setInvitedMemberCount(n),Array.isArray(t)&&(this.summaryHeroes=t.filter((e=>e!==this.myUserId)))}setBlacklistUnverifiedDevices(e){this.blacklistUnverifiedDevices=e}getBlacklistUnverifiedDevices(){return void 0===this.blacklistUnverifiedDevices?null:this.blacklistUnverifiedDevices}getAvatarUrl(e,t,i,n,r=!0){const o=this.currentState.getStateEvents(b.EventType.RoomAvatar,"");if(!o&&!r)return null;const s=o?o.getContent().url:null;return s?(0,l.getHttpUriForMxc)(e,s,t,i,n):null}getMxcAvatarUrl(){var e,t;return(null===(t=null===(e=this.currentState.getStateEvents(b.EventType.RoomAvatar,""))||void 0===e?void 0:e.getContent())||void 0===t?void 0:t.url)||null}getCanonicalAlias(){const e=this.currentState.getStateEvents(b.EventType.RoomCanonicalAlias,"");return e&&e.getContent().alias||null}getAltAliases(){const e=this.currentState.getStateEvents(b.EventType.RoomCanonicalAlias,"");return e&&e.getContent().alt_aliases||[]}addEventsToTimeline(e,t,i,n){i.getTimelineSet().addEventsToTimeline(e,t,i,n)}getThread(e){var t;return null!==(t=this.threads.get(e))&&void 0!==t?t:null}getThreads(){return Array.from(this.threads.values())}getMember(e){return this.currentState.getMember(e)}getMembers(){return this.currentState.getMembers()}getJoinedMembers(){return this.getMembersWithMembership("join")}getJoinedMemberCount(){return this.currentState.getJoinedMemberCount()}getInvitedMemberCount(){return this.currentState.getInvitedMemberCount()}getInvitedAndJoinedMemberCount(){return this.getInvitedMemberCount()+this.getJoinedMemberCount()}getMembersWithMembership(e){return this.currentState.getMembers().filter((function(t){return t.membership===e}))}getEncryptionTargetMembers(){return s(this,void 0,void 0,(function*(){yield this.loadMembersIfNeeded();let e=this.getMembersWithMembership("join");return this.shouldEncryptForInvitedMembers()&&(e=e.concat(this.getMembersWithMembership("invite"))),e}))}shouldEncryptForInvitedMembers(){var e;const t=this.currentState.getStateEvents(b.EventType.RoomHistoryVisibility,"");return"joined"!==(null===(e=null==t?void 0:t.getContent())||void 0===e?void 0:e.history_visibility)}getDefaultRoomName(e){return this.calculateRoomName(e,!0)}hasMembershipState(e,t){const i=this.getMember(e);return!!i&&i.membership===t}getOrCreateFilteredTimelineSet(e,{prepopulateTimeline:t=!0,useSyncEvents:i=!0,pendingEvents:n=!0}={}){if(this.filteredTimelineSets[e.filterId])return this.filteredTimelineSets[e.filterId];const r=Object.assign({filter:e,pendingEvents:n},this.opts),o=new c.EventTimelineSet(this,r);this.reEmitter.reEmit(o,[A.Timeline,A.TimelineReset]),i&&(this.filteredTimelineSets[e.filterId]=o,this.timelineSets.push(o));const s=this.getLiveTimeline();if(t){s.getEvents().forEach((function(e){o.addLiveEvent(e)}));let e=s;for(;e.getNeighbouringTimeline(d.EventTimeline.BACKWARDS);)e=e.getNeighbouringTimeline(d.EventTimeline.BACKWARDS);o.getLiveTimeline().setPaginationToken(e.getPaginationToken(d.EventTimeline.BACKWARDS),d.EventTimeline.BACKWARDS)}else if(i){const e=s.getPaginationToken(d.Direction.Forward);o.getLiveTimeline().setPaginationToken(e,d.Direction.Backward)}return o}getThreadListFilter(e=T.ThreadFilterType.All){return s(this,void 0,void 0,(function*(){const t=this.client.getUserId(),i=new _.Filter(t),n={room:{timeline:{[T.FILTER_RELATED_BY_REL_TYPES.name]:[T.THREAD_RELATION_TYPE.name]}}};e===T.ThreadFilterType.My&&(n.room.timeline[T.FILTER_RELATED_BY_SENDERS.name]=[t]),i.setDefinition(n);const r=yield this.client.getOrCreateFilter(`THREAD_PANEL_${this.roomId}_${e}`,i);return i.filterId=r,i}))}createThreadTimelineSet(e){return s(this,void 0,void 0,(function*(){let t;if(T.Thread.hasServerSideListSupport)t=new c.EventTimelineSet(this,Object.assign(Object.assign({},this.opts),{pendingEvents:!1}),void 0,void 0,null!=e?e:T.ThreadFilterType.All),this.reEmitter.reEmit(t,[A.Timeline,A.TimelineReset]);else if(T.Thread.hasServerSideSupport){const i=yield this.getThreadListFilter(e);t=this.getOrCreateFilteredTimelineSet(i,{prepopulateTimeline:!1,useSyncEvents:!1,pendingEvents:!1})}else t=new c.EventTimelineSet(this,{pendingEvents:!1}),Array.from(this.threads).forEach((([,i])=>{if(0===i.length)return;const n=i.timeline.some((e=>e.getSender()===this.client.getUserId()));(e!==T.ThreadFilterType.My||n)&&t.getLiveTimeline().addEvent(i.rootEvent,{toStartOfTimeline:!1})}));return t}))}processThreadRoots(e,t){for(const i of e)d.EventTimeline.setEventMetadata(i,this.currentState,t),this.getThread(i.getId())||this.createThread(i.getId(),i,[],t)}fetchRoomThreads(){var e,t;return s(this,void 0,void 0,(function*(){if(!this.threadsReady&&this.client.supportsThreads()){if(T.Thread.hasServerSideListSupport)yield Promise.all([this.fetchRoomThreadList(T.ThreadFilterType.All),this.fetchRoomThreadList(T.ThreadFilterType.My)]);else{const i=yield this.getThreadListFilter(),{chunk:n}=yield this.client.createMessagesRequest(this.roomId,"",Number.MAX_SAFE_INTEGER,d.Direction.Backward,i);if(!n.length)return;const r=n.map(this.client.getEventMapper()).sort(((e,t)=>{const i=e.getServerAggregatedRelation(T.THREAD_RELATION_TYPE.name),n=t.getServerAggregatedRelation(T.THREAD_RELATION_TYPE.name);return i.latest_event.origin_server_ts-n.latest_event.origin_server_ts}));let o;const s=this.getLiveTimeline().getState(d.EventTimeline.FORWARDS);for(const i of r){const n={duplicateStrategy:c.DuplicateStrategy.Ignore,fromCache:!1,roomState:s};null===(e=this.threadsTimelineSets[0])||void 0===e||e.addLiveEvent(i,n);const r=i.getServerAggregatedRelation(T.THREAD_RELATION_TYPE.name);(null==r?void 0:r.current_user_participated)&&(null===(t=this.threadsTimelineSets[1])||void 0===t||t.addLiveEvent(i,n),o=i)}this.processThreadRoots(r,!0),this.client.decryptEventIfNeeded(r[r.length-1]),o&&this.client.decryptEventIfNeeded(o)}this.on(T.ThreadEvent.NewReply,this.onThreadNewReply),this.on(T.ThreadEvent.Delete,this.onThreadDelete),this.threadsReady=!0}}))}processPollEvents(e){return s(this,void 0,void 0,(function*(){const t=e=>{if(a.M_POLL_START.matches(e.getType()))try{const t=new k.Poll(e,this.client,this);this.polls.set(e.getId(),t),this.emit(k.PollEvent.New,t)}catch(e){}},i=e=>{const t=e.relationEventId;if(t&&this.polls.has(t)){const i=this.polls.get(t);null==i||i.onNewRelation(e)}},n=e=>{t(e),i(e)};for(const t of e)try{yield this.client.decryptEventIfNeeded(t),n(t)}catch(e){}}))}fetchRoomThreadList(e){return s(this,void 0,void 0,(function*(){const t=e===T.ThreadFilterType.My?this.threadsTimelineSets[1]:this.threadsTimelineSets[0],{chunk:i,end:n}=yield this.client.createThreadListMessagesRequest(this.roomId,null,void 0,d.Direction.Backward,t.threadListType,t.getFilter());if(t.getLiveTimeline().setPaginationToken(null!=n?n:null,d.Direction.Backward),!i.length)return;const r=i.map(this.client.getEventMapper());this.processThreadRoots(r,!0);const o=this.getLiveTimeline().getState(d.EventTimeline.FORWARDS);for(const e of r)t.addLiveEvent(e,{duplicateStrategy:c.DuplicateStrategy.Replace,fromCache:!1,roomState:o})}))}onThreadNewReply(e){this.updateThreadRootEvents(e,!1,!0)}onThreadDelete(e){var t;this.threads.delete(e.id);const i=this.getTimelineForEvent(e.id),n=null===(t=null==i?void 0:i.getEvents())||void 0===t?void 0:t.find((t=>t.getId()===e.id));n?e.clearEventMetadata(n):m.logger.debug("onThreadDelete: Could not find root event in room timeline");for(const t of this.threadsTimelineSets)t.removeEvent(e.id)}removeFilteredTimelineSet(e){const t=this.filteredTimelineSets[e.filterId];delete this.filteredTimelineSets[e.filterId];const i=this.timelineSets.indexOf(t);i>-1&&this.timelineSets.splice(i,1)}eventShouldLiveIn(e,t,i){var n,r;if(!(null===(n=this.client)||void 0===n?void 0:n.supportsThreads()))return{shouldLiveInRoom:!0,shouldLiveInThread:!1};if(e.isThreadRoot||(null==i?void 0:i.has(e.getId())))return{shouldLiveInRoom:!0,shouldLiveInThread:!0,threadId:e.getId()};if(e.isRelation(T.THREAD_RELATION_TYPE.name))return{shouldLiveInRoom:!1,shouldLiveInThread:!0,threadId:e.threadRootId};const o=e.getAssociatedId();let s;return o&&(s=null!==(r=this.findEventById(o))&&void 0!==r?r:null==t?void 0:t.find((e=>e.getId()===o))),s&&(e.isRelation()||e.isRedaction())?this.eventShouldLiveIn(s,t,i):(null==i?void 0:i.has(e.relationEventId))?{shouldLiveInRoom:!0,shouldLiveInThread:!0,threadId:e.relationEventId}:{shouldLiveInRoom:!0,shouldLiveInThread:!1}}findThreadForEvent(e){if(!e)return null;const{threadId:t}=this.eventShouldLiveIn(e);return t?this.getThread(t):null}addThreadedEvents(e,t,i=!1){var n;let r=this.getThread(e);if(!r){const o=null!==(n=this.findEventById(e))&&void 0!==n?n:t.find((t=>t.getId()===e));r=this.createThread(e,o,t,i)}r.addEvents(t,i)}processThreadedEvents(e,t){var i;e.forEach(this.applyRedaction);const n={};for(const t of e){const{threadId:e,shouldLiveInThread:r}=this.eventShouldLiveIn(t);r&&!n[e]&&(n[e]=[]),null===(i=n[e])||void 0===i||i.push(t)}Object.entries(n).map((([e,i])=>this.addThreadedEvents(e,i,t)))}createThread(e,t,i=[],n){var r,o,s;if(this.threads.has(e))return this.threads.get(e);if(t){const e=this.relations.getAllChildEventsForEvent(t.getId());(null==e?void 0:e.length)&&(i=i.concat(e.filter((e=>!e.isRelation(b.RelationType.Replace)))))}const a=new T.Thread(e,t,{room:this,client:this.client,pendingEventOrdering:this.opts.pendingEventOrdering,receipts:null!==(r=this.cachedThreadReadReceipts.get(e))&&void 0!==r?r:[]});this.cachedThreadReadReceipts.delete(e),this.threads.set(a.id,a),a.addEvents(i,!1),this.reEmitter.reEmit(a,[T.ThreadEvent.Delete,T.ThreadEvent.Update,T.ThreadEvent.NewReply,A.Timeline,A.TimelineReset]);const c=(null===(o=this.lastThread)||void 0===o?void 0:o.rootEvent)&&(null==t?void 0:t.localTimestamp)&&(null===(s=this.lastThread.rootEvent)||void 0===s?void 0:s.localTimestamp)<(null==t?void 0:t.localTimestamp);return this.lastThread&&!c||(this.lastThread=a),this.threadsReady&&this.updateThreadRootEvents(a,n,!1),this.emit(T.ThreadEvent.New,a,n),a}processLiveEvent(e){this.applyRedaction(e),e.isVisibilityEvent()&&this.applyNewVisibilityEvent(e),this.applyPendingVisibilityEvents(e);if(!e.getUnsigned().transaction_id&&e.getSender()===this.myUserId)for(const[t,i]of this.txnToEvent)if(i.getId()===e.getId()){m.logger.debug("processLiveEvent: found sent event without txn ID: ",t,e.getId());const i=e.getUnsigned();i.transaction_id=t,e.setUnsigned(i);break}}addLiveEvent(e,t){const{duplicateStrategy:i,timelineWasEmpty:n,fromCache:r}=t;for(const t of this.timelineSets)t.addLiveEvent(e,{duplicateStrategy:i,fromCache:r,timelineWasEmpty:n});e.sender&&e.getType()!==b.EventType.RoomRedaction&&this.addReceipt((0,M.synthesizeReceipt)(e.sender.userId,e,I.ReceiptType.Read),!0)}addPendingEvent(e,t){if(e.status!==p.EventStatus.SENDING&&e.status!==p.EventStatus.NOT_SENT)throw new Error("addPendingEvent called on an event with status "+e.status);if(this.txnToEvent.get(t))throw new Error("addPendingEvent called on an event with known txnId "+t);if(d.EventTimeline.setEventMetadata(e,this.getLiveTimeline().getState(d.EventTimeline.FORWARDS),!1),this.txnToEvent.set(t,e),this.pendingEventList){if(this.pendingEventList.some((e=>e.status===p.EventStatus.NOT_SENT))&&(m.logger.warn("Setting event as NOT_SENT due to messages in the same state"),e.setStatus(p.EventStatus.NOT_SENT)),this.pendingEventList.push(e),this.savePendingEvents(),e.isRelation()&&this.aggregateNonLiveRelation(e),e.isRedaction()){const t=e.event.redacts;let i=this.pendingEventList.find((e=>e.getId()===t));!i&&t&&(i=this.findEventById(t)),i&&(i.markLocallyRedacted(e),this.emit(A.Redaction,e,this))}}else for(const t of this.timelineSets)t.getFilter()?t.getFilter().filterRoomTimeline([e]).length&&t.addEventToTimeline(e,t.getLiveTimeline(),{toStartOfTimeline:!1}):t.addEventToTimeline(e,t.getLiveTimeline(),{toStartOfTimeline:!1});this.emit(A.LocalEchoUpdated,e,this)}savePendingEvents(){if(this.pendingEventList){const e=this.pendingEventList.map((e=>Object.assign(Object.assign({},e.event),{txn_id:e.getTxnId()}))).filter((e=>{const t=e.type===b.EventType.RoomMessageEncrypted,i=this.client.isRoomEncrypted(this.roomId);return t||!i}));this.client.store.setPendingEvents(this.roomId,e)}}aggregateNonLiveRelation(e){this.relations.aggregateChildEvent(e)}getEventForTxnId(e){return this.txnToEvent.get(e)}handleRemoteEcho(e,t){const i=t.getId(),n=e.getId(),r=t.status;m.logger.debug(`Got remote echo for event ${i} -> ${n} old status ${r}`),this.txnToEvent.delete(e.getUnsigned().transaction_id),this.pendingEventList&&this.removePendingEvent(i),t.handleRemoteEcho(e.event);const{shouldLiveInRoom:o,threadId:s}=this.eventShouldLiveIn(e),a=s?this.getThread(s):null;if(null==a||a.setEventMetadata(t),null==a||a.timelineSet.handleRemoteEcho(t,i,n),o)for(const e of this.timelineSets)e.handleRemoteEcho(t,i,n);this.emit(A.LocalEchoUpdated,t,this,i,r)}updatePendingEvent(e,t,i){if(m.logger.log(`setting pendingEvent status to ${t} in ${e.getRoomId()} event ID ${e.getId()} -> ${i}`),t==p.EventStatus.SENT&&!i)throw new Error("updatePendingEvent called with status=SENT, but no new event id");if(t==p.EventStatus.SENT){if(this.getTimelineForEvent(i)){const t=this.findEventById(i);if(!(null==t?void 0:t.getUnsigned().transaction_id)&&t){const i=t.getUnsigned();i.transaction_id=e.getTxnId(),t.setUnsigned(i),this.removeEvent(t.getId()),this.handleRemoteEcho(t,e)}return}}const n=e.status,r=e.getId();if(!n)throw new Error("updatePendingEventStatus called on an event which is not a local echo.");const o=D[n];if(!(null==o?void 0:o.includes(t)))throw new Error(`Invalid EventStatus transition ${n}->${t}`);if(e.setStatus(t),t==p.EventStatus.SENT){e.replaceLocalEventId(i);const{shouldLiveInRoom:t,threadId:n}=this.eventShouldLiveIn(e),o=n?this.getThread(n):void 0;if(null==o||o.setEventMetadata(e),null==o||o.timelineSet.replaceEventId(r,i),t)for(const e of this.timelineSets)e.replaceEventId(r,i)}else if(t==p.EventStatus.CANCELLED){if(this.pendingEventList){const e=this.getPendingEvent(r);this.removePendingEvent(r),(null==e?void 0:e.isRedaction())&&this.revertRedactionLocalEcho(e)}this.removeEvent(r)}this.savePendingEvents(),this.emit(A.LocalEchoUpdated,e,this,r,n)}revertRedactionLocalEcho(e){const t=e.event.redacts;if(!t)return;const i=this.getUnfilteredTimelineSet().findEventById(t);i&&(i.unmarkLocallyRedacted(),this.emit(A.RedactionCancelled,e,this),i.isRelation()&&this.aggregateNonLiveRelation(i))}addLiveEvents(e,t,i=!1){var n;let r=t,o=!1;if("object"==typeof t?({duplicateStrategy:r,fromCache:i=!1,timelineWasEmpty:o}=t):void 0!==t&&m.logger.warn("Overload deprecated: `Room.addLiveEvents(events, duplicateStrategy?, fromCache?)` is deprecated in favor of the overload with `Room.addLiveEvents(events, IAddLiveEventOptions)`"),r&&-1===["replace","ignore"].indexOf(r))throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'");for(let e=0;e{this.addThreadedEvents(e,t,!1)}))}partitionThreadedEvents(e){if(this.client.supportsThreads()){const t=this.findThreadRoots(e);return e.reduce(((i,n)=>{const{shouldLiveInRoom:r,shouldLiveInThread:o,threadId:s}=this.eventShouldLiveIn(n,e,t);return r&&i[0].push(n),o&&(n.setThreadId(null!=s?s:""),i[1].push(n)),i}),[[],[]])}return[e,[]]}findThreadRoots(e){var t;const i=new Set;for(const n of e)n.isRelation(T.THREAD_RELATION_TYPE.name)&&i.add(null!==(t=n.relationEventId)&&void 0!==t?t:"");return i}addReceipt(e,t=!1){const i=e.getContent();Object.keys(i).forEach((e=>{Object.keys(i[e]).forEach((n=>{Object.keys(i[e][n]).forEach((r=>{var o,s,a,c;const d=i[e][n][r],l=!d.thread_id||d.thread_id===I.MAIN_ROOM_TIMELINE,u=l?this:this.threads.get(null!==(o=d.thread_id)&&void 0!==o?o:"");if(u){if(u.addReceiptToStructure(e,n,r,d,t),this.client.isInitialSyncComplete()&&r===this.client.getUserId()){const t=u.timeline[u.timeline.length-1];t&&e===t.getId()&&r===t.getSender()&&(u.setUnread(O.Total,0),u.setUnread(O.Highlight,0))}}else this.cachedThreadReadReceipts.set(d.thread_id,[...null!==(s=this.cachedThreadReadReceipts.get(d.thread_id))&&void 0!==s?s:[],{eventId:e,receiptType:n,userId:r,receipt:d,synthetic:t}]);r===this.client.getUserId()&&!l&&d.ts(null!==(c=null===(a=this.unthreadedReceipts.get(r))||void 0===a?void 0:a.ts)&&void 0!==c?c:0)&&this.unthreadedReceipts.set(r,d)}))}))})),this.emit(A.Receipt,e,this)}addEphemeralEvents(e){for(const t of e)t.getType()===b.EventType.Typing?this.currentState.setTypingEvent(t):t.getType()===b.EventType.Receipt&&this.addReceipt(t)}removeEvents(e){for(const t of e)this.removeEvent(t)}removeEvent(e){let t=!1;for(const i of this.timelineSets){const n=i.removeEvent(e);n&&(n.isRedaction()&&this.revertRedactionLocalEcho(n),t=!0)}return t}recalculate(){const e=this.currentState.getStateEvents(b.EventType.RoomMember,this.myUserId);if(e){const t=e.getContent().membership;if(this.updateMyMembership(t),"invite"===t){(e.getUnsigned().invite_room_state||[]).forEach((e=>{this.currentState.getStateEvents(e.type,e.state_key)||this.currentState.setStateEvents([new f.MatrixEvent({type:e.type,state_key:e.state_key,content:e.content,event_id:"$fake"+Date.now(),room_id:this.roomId,user_id:this.myUserId})])}))}}const t=this.name;this.name=this.calculateRoomName(this.myUserId),this.normalizedName=(0,h.normalize)(this.name),this.summary=new v.RoomSummary(this.roomId,{title:this.name}),t!==this.name&&this.emit(A.Name,this)}addTags(e){this.tags=e.getContent().tags||{},this.emit(A.Tags,e,this)}addAccountData(e){for(const t of e){"m.tag"===t.getType()&&this.addTags(t);const e=t.getType(),i=this.accountData.get(e);this.accountData.set(e,t),this.emit(A.AccountData,t,this,i)}}getAccountData(e){return this.accountData.get(e)}maySendMessage(){return"join"===this.getMyMembership()&&(this.client.isRoomEncrypted(this.roomId)?this.currentState.maySendEvent(b.EventType.RoomMessageEncrypted,this.myUserId):this.currentState.maySendEvent(b.EventType.RoomMessage,this.myUserId))}canInvite(e){let t="join"===this.getMyMembership();const i=this.currentState.getStateEvents(b.EventType.RoomPowerLevels,""),n=i&&i.getContent(),r=this.getMember(e);return n&&r&&n.invite>r.powerLevel&&(t=!1),t}getJoinRule(){return this.currentState.getJoinRule()}getHistoryVisibility(){return this.currentState.getHistoryVisibility()}getGuestAccess(){return this.currentState.getGuestAccess()}getType(){const e=this.currentState.getStateEvents(b.EventType.RoomCreate,"");if(e)return e.getContent()[b.RoomCreateTypeField];this.getTypeWarning||(m.logger.warn("[getType] Room "+this.roomId+" does not have an m.room.create event"),this.getTypeWarning=!0)}isSpaceRoom(){return this.getType()===b.RoomType.Space}isCallRoom(){return this.getType()===b.RoomType.UnstableCall}isElementVideoRoom(){return this.getType()===b.RoomType.ElementVideo}findPredecessor(e=!1){const t=this.getLiveTimeline().getState(d.EventTimeline.FORWARDS);return t?t.findPredecessor(e):null}roomNameGenerator(e){if(this.client.roomNameGenerator){const t=this.client.roomNameGenerator(this.roomId,e);if(null!==t)return t}switch(e.type){case x.Actual:return e.name;case x.Generated:return"Inviting"===e.subtype?`Inviting ${L(e.names,e.count)}`:L(e.names,e.count);case x.EmptyRoom:return e.oldName?`Empty room (was ${e.oldName})`:"Empty room"}}calculateRoomName(e,t=!1){if(!t){const e=this.currentState.getStateEvents(b.EventType.RoomName,"");if(null==e?void 0:e.getContent().name)return this.roomNameGenerator({type:x.Actual,name:e.getContent().name})}const i=this.getCanonicalAlias();if(i)return this.roomNameGenerator({type:x.Actual,name:i});let n=this.currentState.getJoinedMemberCount()+this.currentState.getInvitedMemberCount()-1,r=[];const o=this.currentState.getStateEvents(b.UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name,"");Array.isArray(null==o?void 0:o.getContent().service_members)&&(r=o.getContent().service_members);let s=[];if(this.summaryHeroes)this.summaryHeroes.forEach((e=>{if(r.includes(e))return void n--;const t=this.getMember(e);s.push(t?t.name:e)}));else{let t=this.currentState.getMembers().filter((t=>t.userId!==e&&("invite"===t.membership||"join"===t.membership)));t=t.filter((({userId:e})=>!r.includes(e)||(n--,!1))),t.sort(((e,t)=>u.compare(e.userId,t.userId))),t=t.slice(0,5),s=t.map((e=>e.name))}if(n)return this.roomNameGenerator({type:x.Generated,names:s,count:n});if("join"==this.getMyMembership()){const e=this.currentState.getStateEvents(b.EventType.RoomThirdPartyInvite);if(null==e?void 0:e.length){const t=e.map((e=>e.getContent().display_name));return this.roomNameGenerator({type:x.Generated,subtype:"Inviting",names:t,count:t.length+1})}}let a,c=s;return c.length||(c=this.currentState.getMembers().filter((t=>t.userId!==e&&"invite"!==t.membership&&"join"!==t.membership)).map((e=>e.name))),c.length&&(a=this.roomNameGenerator({type:x.Generated,names:c,count:c.length+1})),this.roomNameGenerator({type:x.EmptyRoom,oldName:a})}applyNewVisibilityEvent(e){const t=e.asVisibilityChange();if(!t)return;const i=e.getSender();if(!i)return;if(!(b.EVENT_VISIBILITY_CHANGE_TYPE.name&&this.currentState.maySendStateEvent(b.EVENT_VISIBILITY_CHANGE_TYPE.name,i)||b.EVENT_VISIBILITY_CHANGE_TYPE.altName&&this.currentState.maySendStateEvent(b.EVENT_VISIBILITY_CHANGE_TYPE.altName,i)))return;const n=this.visibilityEvents.get(t.eventId);if(n){let t=n.length-1;const i=Math.max(0,n.length-30);for(;t>=i;--t){if(n[t].getTs()t.getId()===e.getId()));if(-1!==r&&(n.splice(r,1),r===n.length)){const e=this.findEventById(i);if(!e)return;if(0===r)this.visibilityEvents.delete(i),e.applyVisibilityEvent();else{const t=n[n.length-1].asVisibilityChange();if(!t)throw new Error("at this stage, visibility changes should be well-formed");e.applyVisibilityEvent(t)}}}applyPendingVisibilityEvents(e){const t=this.visibilityEvents.get(e.getId());if(!t||0==t.length)return;const i=t[t.length-1],n=i.asVisibilityChange();n&&(n.visible,i.getTs()this.getThreadUnreadNotificationCount(e.id,O.Total)>0));for(const i of t)i.fixupNotifications(e)}}i.Room=P;const D={[p.EventStatus.ENCRYPTING]:[p.EventStatus.SENDING,p.EventStatus.NOT_SENT,p.EventStatus.CANCELLED],[p.EventStatus.SENDING]:[p.EventStatus.ENCRYPTING,p.EventStatus.QUEUED,p.EventStatus.NOT_SENT,p.EventStatus.SENT],[p.EventStatus.QUEUED]:[p.EventStatus.SENDING,p.EventStatus.NOT_SENT,p.EventStatus.CANCELLED],[p.EventStatus.SENT]:[],[p.EventStatus.NOT_SENT]:[p.EventStatus.SENDING,p.EventStatus.QUEUED,p.EventStatus.CANCELLED],[p.EventStatus.CANCELLED]:[]};var x;function L(e,t){const i=t-1;if(e.length){if(1===e.length&&i<=1)return e[0];if(2===e.length&&i<=2)return`${e[0]} and ${e[1]}`;return i>1?`${e[0]} and ${i} others`:`${e[0]} and 1 other`}return"Empty room"}!function(e){e[e.EmptyRoom=0]="EmptyRoom",e[e.Generated=1]="Generated",e[e.Actual=2]="Actual"}(x=i.RoomNameType||(i.RoomNameType={}))},{"../@types/event":306,"../@types/read_receipts":311,"../ReEmitter":317,"../client":321,"../content-repo":323,"../filter":364,"../logger":374,"../utils":416,"./beacon":378,"./event":383,"./event-status":380,"./event-timeline":382,"./event-timeline-set":381,"./poll":385,"./read-receipt":386,"./relations-container":387,"./room-member":389,"./room-state":390,"./room-summary":391,"./thread":394,"matrix-events-sdk":167}],393:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.SearchResult=void 0;const n=e("./event-context");class r{static fromJson(e,t){const i=e.context||{};let o=(i.events_before||[]).map(t),s=(i.events_after||[]).map(t);const a=new n.EventContext(t(e.result)),c=a.ourEvent.threadRootId;return o=o.filter((e=>e.threadRootId===c)),s=s.filter((e=>e.threadRootId===c)),a.setPaginateToken(i.start,!0),a.addEvents(o,!0),a.addEvents(s,!1),a.setPaginateToken(i.end,!1),new r(e.rank,a)}constructor(e,t){this.rank=e,this.context=t}}i.SearchResult=r},{"./event-context":379}],394:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.threadFilterTypeToFilter=i.ThreadFilterType=i.THREAD_RELATION_TYPE=i.FILTER_RELATED_BY_REL_TYPES=i.FILTER_RELATED_BY_SENDERS=i.Thread=i.determineFeatureSupport=i.FeatureSupport=i.ThreadEvent=void 0;const r=e("../client"),o=e("../ReEmitter"),s=e("../@types/event"),a=e("./event"),c=e("./event-timeline"),d=e("./event-timeline-set"),l=e("./room"),u=e("../NamespacedValue"),h=e("../logger"),f=e("./read-receipt"),p=e("../@types/read_receipts");var g,v,m;!function(e){e.New="Thread.new",e.Update="Thread.update",e.NewReply="Thread.newReply",e.ViewThread="Thread.viewThread",e.Delete="Thread.delete"}(g=i.ThreadEvent||(i.ThreadEvent={})),function(e){e[e.None=0]="None",e[e.Experimental=1]="Experimental",e[e.Stable=2]="Stable"}(v=i.FeatureSupport||(i.FeatureSupport={})),i.determineFeatureSupport=function(e,t){return e?v.Stable:t?v.Experimental:v.None};class y extends f.ReadReceipt{constructor(e,t,s){var c;if(super(),this.id=e,this.rootEvent=t,this.timeline=[],this._currentUserParticipated=!1,this.replyCount=0,this.pendingReplyCount=0,this.initialEventsFetched=!y.hasServerSideSupport,this.replayEvents=[],this.onBeforeRedaction=(e,t)=>{(null==e?void 0:e.isRelation(i.THREAD_RELATION_TYPE.name))&&this.room.eventShouldLiveIn(e).threadId===this.id&&e.getId()!==this.id&&!t.status&&(this.replyCount--,this.updatePendingReplyCount(),this.emit(g.Update,this))},this.onRedaction=e=>n(this,void 0,void 0,(function*(){if(e.threadRootId===this.id)if(this.replyCount<=0){for(const e of this.timeline)this.clearEventMetadata(e);this.lastEvent=this.rootEvent,this._currentUserParticipated=!1,this.emit(g.Delete,this)}else yield this.updateThreadMetadata()})),this.onTimelineEvent=(e,t,i)=>{i||t.addLocalEchoReceipt(e.getSender(),e,p.ReceiptType.Read),this.onEcho(e,null!=i&&i)},this.onLocalEcho=e=>{this.onEcho(e,!1)},this.onEcho=(e,t)=>n(this,void 0,void 0,(function*(){e.threadRootId===this.id&&this.lastEvent!==e&&(yield this.updateThreadMetadata(),e.isRelation(i.THREAD_RELATION_TYPE.name)&&(t||this.emit(g.NewReply,this,e)))})),!(null==s?void 0:s.room))throw new Error("element-web#22141: A thread requires a room in order to function");this.room=s.room,this.client=s.client,this.pendingEventOrdering=null!==(c=s.pendingEventOrdering)&&void 0!==c?c:r.PendingEventOrdering.Chronological,this.timelineSet=new d.EventTimelineSet(this.room,{timelineSupport:!0,pendingEvents:!0},this.client,this),this.reEmitter=new o.TypedReEmitter(this),this.reEmitter.reEmit(this.timelineSet,[l.RoomEvent.Timeline,l.RoomEvent.TimelineReset]),this.room.on(a.MatrixEventEvent.BeforeRedaction,this.onBeforeRedaction),this.room.on(l.RoomEvent.Redaction,this.onRedaction),this.room.on(l.RoomEvent.LocalEchoUpdated,this.onLocalEcho),this.timelineSet.on(l.RoomEvent.Timeline,this.onTimelineEvent),this.processReceipts(s.receipts),this.updateThreadMetadata(),this.setEventMetadata(this.rootEvent)}fetchRootEvent(){return n(this,void 0,void 0,(function*(){this.rootEvent=this.room.findEventById(this.id);try{const e=yield this.client.fetchRoomEvent(this.roomId,this.id),t=this.client.getEventMapper();this.rootEvent=t(e)}catch(e){h.logger.error("Failed to fetch thread root to construct thread with",e)}yield this.processEvent(this.rootEvent)}))}static setServerSideSupport(e){y.hasServerSideSupport=e,e!==v.Stable&&(i.FILTER_RELATED_BY_SENDERS.setPreferUnstable(!0),i.FILTER_RELATED_BY_REL_TYPES.setPreferUnstable(!0),i.THREAD_RELATION_TYPE.setPreferUnstable(!0))}static setServerSideListSupport(e){y.hasServerSideListSupport=e}static setServerSideFwdPaginationSupport(e){y.hasServerSideFwdPaginationSupport=e}get roomState(){return this.room.getLiveTimeline().getState(c.EventTimeline.FORWARDS)}addEventToTimeline(e,t){this.findEventById(e.getId())||(this.timelineSet.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:t,fromCache:!1,roomState:this.roomState}),this.timeline=this.events)}addEvents(e,t){e.forEach((e=>this.addEvent(e,t,!1))),this.updateThreadMetadata()}addEvent(e,t,r=!0){var o,a,c;return n(this,void 0,void 0,(function*(){this.setEventMetadata(e);const n=this.lastReply(),d=!n||e.localTimestamp>=n.localTimestamp;if(y.hasServerSideSupport){if(!t&&this.initialEventsFetched&&d)this.addEventToTimeline(e,!1),this.fetchEditsWhereNeeded(e);else if(e.isRelation(s.RelationType.Annotation)||e.isRelation(s.RelationType.Replace))return this.initialEventsFetched?this.addEventToTimeline(e,t):null===(o=this.replayEvents)||void 0===o||o.push(e),null===(a=this.timelineSet.relations)||void 0===a||a.aggregateParentEvent(e),void(null===(c=this.timelineSet.relations)||void 0===c||c.aggregateChildEvent(e,this.timelineSet))}else this.addEventToTimeline(e,t),this.client.decryptEventIfNeeded(e,{});y.hasServerSideSupport&&this.rootEvent||!e.isRelation(i.THREAD_RELATION_TYPE.name)||this.replyCount++,r&&(this.emit(g.NewReply,this,e),this.updateThreadMetadata())}))}processEvent(e){return n(this,void 0,void 0,(function*(){e&&(this.setEventMetadata(e),yield this.fetchEditsWhereNeeded(e)),this.timeline=this.events}))}processReceipts(e=[]){for(const{eventId:t,receiptType:i,userId:n,receipt:r,synthetic:o}of e)this.addReceiptToStructure(t,i,n,r,o)}getRootEventBundledRelationship(e=this.rootEvent){return null==e?void 0:e.getServerAggregatedRelation(i.THREAD_RELATION_TYPE.name)}processRootEvent(){return n(this,void 0,void 0,(function*(){const e=this.getRootEventBundledRelationship();if(y.hasServerSideSupport&&e){this.replyCount=e.count,this._currentUserParticipated=!!e.current_user_participated;const t=this.client.getEventMapper();this.lastEvent=t(Object.assign(Object.assign({},e.latest_event),{room_id:this.roomId})),this.updatePendingReplyCount(),yield this.processEvent(this.lastEvent)}}))}updatePendingReplyCount(){const e=(this.pendingEventOrdering===r.PendingEventOrdering.Detached?this.room.getPendingEvents():this.events).filter((e=>{var t;return e.threadRootId===this.id&&e.isRelation(i.THREAD_RELATION_TYPE.name)&&null!==e.status&&e.getId()!==(null===(t=this.lastEvent)||void 0===t?void 0:t.getId())}));this.lastPendingEvent=e.length?e[e.length-1]:void 0,this.pendingReplyCount=e.length}resetLiveTimeline(e,t){return n(this,void 0,void 0,(function*(){const i=this.liveTimeline;this.timelineSet.resetLiveTimeline(null!=e?e:void 0,null!=t?t:void 0);const n=this.liveTimeline;let r,o;if(e){r=(yield this.client.createMessagesRequest(this.roomId,e,1,c.Direction.Forward)).end}if(t){o=(yield this.client.createMessagesRequest(this.roomId,t,1,c.Direction.Backward)).start}t&&i.getPaginationToken(c.Direction.Forward)===t&&i.setPaginationToken(null!=o?o:null,c.Direction.Forward),e&&n.getPaginationToken(c.Direction.Backward)===e&&n.setPaginationToken(null!=r?r:null,c.Direction.Backward)}))}updateThreadMetadata(){return n(this,void 0,void 0,(function*(){if(this.updatePendingReplyCount(),y.hasServerSideSupport&&(this.initialEventsFetched||(yield this.processRootEvent()),yield this.fetchRootEvent()),yield this.processRootEvent(),!this.initialEventsFetched){this.initialEventsFetched=!0;try{0===this.replyCount&&this.rootEvent?(this.timelineSet.addEventsToTimeline([this.rootEvent],!0,this.liveTimeline,null),this.liveTimeline.setPaginationToken(null,c.Direction.Backward)):yield this.client.paginateEventTimeline(this.liveTimeline,{backwards:!0,limit:Math.max(1,this.length)});for(const e of this.replayEvents)this.addEvent(e,!1);this.replayEvents=null,this.emit(l.RoomEvent.TimelineReset,this.room,this.timelineSet,!0)}catch(e){h.logger.error("Failed to load start of newly created thread: ",e),this.initialEventsFetched=!1}}this.emit(g.Update,this)}))}fetchEditsWhereNeeded(...e){return n(this,void 0,void 0,(function*(){return Promise.all(e.filter((e=>e.isEncrypted())).map((e=>{if(!e.isRelation())return this.client.relations(this.roomId,e.getId(),s.RelationType.Replace,e.getType(),{limit:1}).then((t=>{t.events.length&&e.makeReplaced(t.events[0])})).catch((e=>{h.logger.error("Failed to load edits for encrypted thread event",e)}))})))}))}setEventMetadata(e){e&&(c.EventTimeline.setEventMetadata(e,this.roomState,!1),e.setThread(this))}clearEventMetadata(e){var t,n,r;e&&(e.setThread(void 0),null===(r=null===(n=null===(t=e.event)||void 0===t?void 0:t.unsigned)||void 0===n?void 0:n["m.relations"])||void 0===r||delete r[i.THREAD_RELATION_TYPE.name])}findEventById(e){return this.timelineSet.findEventById(e)}lastReply(e=(()=>!0)){for(let t=this.timeline.length-1;t>=0;t--){const i=this.timeline[t];if(e(i))return i}return null}get roomId(){return this.room.roomId}get length(){return this.replyCount+this.pendingReplyCount}get replyToEvent(){var e,t;return null!==(t=null!==(e=this.lastPendingEvent)&&void 0!==e?e:this.lastEvent)&&void 0!==t?t:this.lastReply()}get events(){return this.liveTimeline.getEvents()}has(e){return this.timelineSet.findEventById(e)instanceof a.MatrixEvent}get hasCurrentUserParticipated(){return this._currentUserParticipated}get liveTimeline(){return this.timelineSet.getLiveTimeline()}getUnfilteredTimelineSet(){return this.timelineSet}addReceipt(e,t){throw new Error("Unsupported function on the thread model")}getEventReadUpTo(e,t){var i,n;const r=e===this.client.getUserId(),o=this.timeline[this.timeline.length-1];if(r&&o){const e=o.getTs()=0;--e){const i=this.timeline[e];if(i.getId()===s)return s;if(i.getTs()t.rule_id===e.rule_id));let n;if(e.rule_id===o.RuleId.IsUserMention){if(!t)continue;n=JSON.parse(JSON.stringify(e)),n.conditions[0].value=t}else n=e;if(i)i.default=n.default,i.conditions=n.conditions,i.actions=n.actions;else{const e=n.rule_id;r.logger.warn(`Adding default global override for ${e}`),s.push(n)}}const a=null!==(i=n.global.underride)&&void 0!==i?i:[];for(const e of d){const t=a.find((t=>t.rule_id===e.rule_id));if(t)t.default=e.default,t.conditions=e.conditions,t.actions=e.actions;else{const t=e.rule_id;r.logger.warn(`Adding default global underride for ${t}`),a.push(e)}}return n}updateCachedPushRuleKeys(e){e||(e={}),e.global||(e.global={}),e.global.override||(e.global.override=[]),e.global.room||(e.global.room=[]),e.global.sender||(e.global.sender=[]),e.global.underride||(e.global.underride=[]);const t=new Set(this.parsedKeys.keys());for(const i of[e.global.override,e.global.room,e.global.sender,e.global.underride])for(const e of i)if(e.conditions)for(const i of e.conditions)i.kind===o.ConditionKind.EventMatch&&(t.delete(i.key),this.parsedKeys.set(i.key,l.partsForDottedKey(i.key)));t.forEach((e=>this.parsedKeys.delete(e)))}matchingRuleFromKindSet(e,t){for(const i of a){const n=t[i];if(n)for(const t of n){if(!t.enabled)continue;const n=this.templateRuleToRaw(i,t);if(n&&this.ruleMatchesEvent(n,e))return Object.assign(Object.assign({},t),{kind:i})}}return null}templateRuleToRaw(e,t){const i={rule_id:t.rule_id,actions:t.actions,conditions:[]};switch(e){case o.PushRuleKind.Underride:case o.PushRuleKind.Override:i.conditions=t.conditions;break;case o.PushRuleKind.RoomSpecific:if(!t.rule_id)return null;i.conditions.push({kind:o.ConditionKind.EventMatch,key:"room_id",value:t.rule_id});break;case o.PushRuleKind.SenderSpecific:if(!t.rule_id)return null;i.conditions.push({kind:o.ConditionKind.EventMatch,key:"user_id",value:t.rule_id});break;case o.PushRuleKind.ContentSpecific:if(!t.pattern)return null;i.conditions.push({kind:o.ConditionKind.EventMatch,key:"content.body",pattern:t.pattern})}return i}eventFulfillsCondition(e,t){switch(e.kind){case o.ConditionKind.EventMatch:return this.eventFulfillsEventMatchCondition(e,t);case o.ConditionKind.EventPropertyIs:return this.eventFulfillsEventPropertyIsCondition(e,t);case o.ConditionKind.EventPropertyContains:return this.eventFulfillsEventPropertyContains(e,t);case o.ConditionKind.ContainsDisplayName:return this.eventFulfillsDisplayNameCondition(e,t);case o.ConditionKind.RoomMemberCount:return this.eventFulfillsRoomMemberCountCondition(e,t);case o.ConditionKind.SenderNotificationPermission:return this.eventFulfillsSenderNotifPermCondition(e,t);case o.ConditionKind.CallStarted:case o.ConditionKind.CallStartedPrefix:return this.eventFulfillsCallStartedCondition(e,t)}return!1}eventFulfillsSenderNotifPermCondition(e,t){const i=e.key;if(!i)return!1;const n=this.client.getRoom(t.getRoomId());return!!(null==n?void 0:n.currentState)&&n.currentState.mayTriggerNotifOfType(i,t.getSender())}eventFulfillsRoomMemberCountCondition(e,t){if(!e.is)return!1;const i=this.client.getRoom(t.getRoomId());if(!i||!i.currentState||!i.currentState.members)return!1;const n=i.currentState.getJoinedMemberCount(),r=e.is.match(/^([=<>]*)(\d*)$/);if(!r)return!1;const o=r[1],s=parseInt(r[2]);if(isNaN(s))return!1;switch(o){case"":case"==":return n==s;case"<":return n":return n>s;case"<=":return n<=s;case">=":return n>=s;default:return!1}}eventFulfillsDisplayNameCondition(e,t){var i;let r=t.getContent();if(t.isEncrypted()&&t.getClearContent()&&(r=t.getClearContent()),!r||!r.body||"string"!=typeof r.body)return!1;const o=this.client.getRoom(t.getRoomId()),s=null===(i=null==o?void 0:o.currentState)||void 0===i?void 0:i.getMember(this.client.credentials.userId);if(!s)return!1;const a=s.name,c=new RegExp("(^|\\W)"+(0,n.escapeRegExp)(a)+"(\\W|$)","i");return r.body.search(c)>-1}eventFulfillsEventMatchCondition(e,t){if(!e.key)return!1;const i=this.valueForDottedKey(e.key,t);if("string"!=typeof i)return!1;if(e.value)return e.value===i;if("string"!=typeof e.pattern)return!1;const n="content.body"===e.key?this.createCachedRegex("(^|\\W)",e.pattern,"(\\W|$)"):this.createCachedRegex("^",e.pattern,"$");return!!i.match(n)}eventFulfillsEventPropertyIsCondition(e,t){return!(!e.key||void 0===e.value)&&e.value===this.valueForDottedKey(e.key,t)}eventFulfillsEventPropertyContains(e,t){if(!e.key||void 0===e.value)return!1;const i=this.valueForDottedKey(e.key,t);return!!Array.isArray(i)&&i.includes(e.value)}eventFulfillsCallStartedCondition(e,t){return["m.ring","m.prompt"].includes(t.getContent()["m.intent"])&&!("m.terminated"in t.getContent())&&(t.getPrevContent()["m.terminated"]!==t.getContent()["m.terminated"]||(0,n.deepCompare)(t.getPrevContent(),{}))}createCachedRegex(e,t,i){return l.cachedGlobToRegex[t]||(l.cachedGlobToRegex[t]=new RegExp(e+(0,n.globToRegexp)(t)+i,"i")),l.cachedGlobToRegex[t]}static partsForDottedKey(e){const t=[];let i="",n=!1;for(const r of e)n?(i+="\\"===r||"."===r?r:"\\"+r,n=!1):"."==r?(t.push(i),i=""):"\\"==r?n=!0:i+=r;return n&&(i+="\\"),t.push(i),t}valueForDottedKey(e,t){let i,r=this.parsedKeys.get(e);void 0===r&&(r=l.partsForDottedKey(e),this.parsedKeys.set(e,r));const o=r[0];let s=0;for("content"===o?(i=t.getContent(),++s):"type"===o?(i=t.getType(),++s):i=t.event;s!this.eventFulfillsCondition(e,t))))}actionsForEvent(e){return this.pushActionsForEventAndRulesets(e,this.client.pushRules)}getPushRuleById(e){var t;const i=this.getPushRuleAndKindById(e);return null!==(t=null==i?void 0:i.rule)&&void 0!==t?t:null}getPushRuleAndKindById(e){var t;for(const i of["global"])if(void 0!==(null===(t=this.client.pushRules)||void 0===t?void 0:t[i]))for(const t of a)if(void 0!==this.client.pushRules[i][t])for(const n of this.client.pushRules[i][t])if(n.rule_id===e)return{rule:n,kind:t};return null}}i.PushProcessor=l,l.cachedGlobToRegex={}},{"./@types/PushRules":304,"./@types/event":306,"./logger":374,"./utils":416}],398:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.randomUppercaseString=i.randomLowercaseString=i.randomString=void 0;const n="abcdefghijklmnopqrstuvwxyz",r="ABCDEFGHIJKLMNOPQRSTUVWXYZ",o="0123456789";function s(e,t){let i="";for(let n=0;ne)break;const n=a.shift();c("runCallbacks: popping",n.key),i.push(n)}d();for(const e of i)try{e.func.apply(t,e.params)}catch(e){n.logger.error("Uncaught exception in callback function",e)}}i.setTimeout=function(e,t,...i){(t=t||0)<0&&(t=0);const n=Date.now()+t,r=s++;c("setTimeout: scheduling cb",r,"at",n,"(delay",t,")");const o={runAt:n,func:e,params:i,key:r},l=function(e,t){let i=0,n=e.length;for(;i>1;t(e[r])>0?n=r:i=r+1}return i}(a,(function(e){return e.runAt-n}));return a.splice(l,0,o),d(),r},i.clearTimeout=function(e){if(0===a.length)return;let t;for(t=0;t0)return e}return t>4?-1:1e3*Math.pow(2,t)}static QUEUE_MESSAGES(e){return e.getType()===c.EventType.RoomMessage||e.hasAssociation()?"message":null}constructor(e=u.RETRY_BACKOFF_RATELIMIT,t=u.QUEUE_MESSAGES){this.retryAlgorithm=e,this.queueAlgorithm=t,this.queues={},this.activeQueues=[],this.procFn=null,this.processQueue=e=>{const t=this.peekNextEvent(e);t?(h("Queue '%s' has %s pending events",e,this.queues[e].length),Promise.resolve().then((()=>this.procFn(t.event))).then((i=>{this.removeNextEvent(e),h("Queue '%s' sent event %s",e,t.event.getId()),t.defer.resolve(i),this.processQueue(e)}),(i=>{t.attempts+=1;const n=this.retryAlgorithm(t.event,t.attempts,i);h("retry(%s) err=%s event_id=%s waitTime=%s",t.attempts,i,t.event.getId(),n),-1===n?(h("Queue '%s' giving up on event %s",e,t.event.getId()),this.clearQueue(e,i)):setTimeout(this.processQueue,n,e)}))):this.disableQueue(e)}}getQueueForEvent(e){const t=this.queueAlgorithm(e);return t&&this.queues[t]?this.queues[t].map((function(e){return e.event})):null}removeEventFromQueue(e){const t=this.queueAlgorithm(e);if(!t||!this.queues[t])return!1;let i=!1;return s.removeElement(this.queues[t],(t=>t.event.getId()===e.getId()&&(i=!0,!0))),i}setProcessFunction(e){this.procFn=e,this.startProcessingQueues()}queueEvent(e){const t=this.queueAlgorithm(e);if(!t)return null;this.queues[t]||(this.queues[t]=[]);const i=s.defer();return this.queues[t].push({event:e,defer:i,attempts:0}),h("Queue algorithm dumped event %s into queue '%s'",e.getId(),t),this.startProcessingQueues(),i.promise}startProcessingQueues(){this.procFn&&Object.keys(this.queues).filter((e=>-1===this.activeQueues.indexOf(e)&&this.queues[e].length>0)).forEach((e=>{this.activeQueues.push(e),h("Spinning up queue: '%s'",e),this.processQueue(e)}))}disableQueue(e){const t=this.activeQueues.indexOf(e);t>=0&&this.activeQueues.splice(t,1),h("Stopping queue '%s' as it is now empty",e)}clearQueue(e,t){let i;for(h("clearing queue '%s'",e);i=this.removeNextEvent(e);)i.defer.reject(t);this.disableQueue(e)}peekNextEvent(e){const t=this.queues[e];if(Array.isArray(t))return t[0]}removeNextEvent(e){const t=this.queues[e];if(Array.isArray(t))return t.shift()}}function h(...e){l&&a.logger.log(...e)}i.MatrixScheduler=u},{"./@types/event":306,"./http-api":367,"./logger":374,"./utils":416}],404:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0})},{}],405:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.SERVICE_TYPES=void 0,function(e){e.IS="SERVICE_TYPE_IS",e.IM="SERVICE_TYPE_IM"}(i.SERVICE_TYPES||(i.SERVICE_TYPES={}))},{}],406:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.SlidingSyncSdk=void 0;const a=e("./models/room"),c=e("./logger"),d=o(e("./utils")),l=e("./models/event-timeline"),u=e("./client"),h=e("./sync"),f=e("./http-api"),p=e("./sliding-sync"),g=e("./@types/event"),v=e("./models/room-state"),m=e("./models/room-member");class y{constructor(e){this.crypto=e}name(){return"e2ee"}when(){return p.ExtensionState.PreProcess}onRequest(e){if(e)return{enabled:!0}}onResponse(e){return s(this,void 0,void 0,(function*(){if(e.device_lists&&(yield this.crypto.handleDeviceListChanges({oldSyncToken:"yep"},e.device_lists)),e.device_one_time_keys_count){const t=e.device_one_time_keys_count.signed_curve25519||0;this.crypto.updateOneTimeKeyCount(t)}if(e.device_unused_fallback_key_types||e["org.matrix.msc2732.device_unused_fallback_key_types"]){const t=e.device_unused_fallback_key_types||e["org.matrix.msc2732.device_unused_fallback_key_types"];this.crypto.setNeedsNewFallback(Array.isArray(t)&&!t.includes("signed_curve25519"))}this.crypto.onSyncCompleted({})}))}}class b{constructor(e,t){this.client=e,this.cryptoCallbacks=t,this.nextBatch=null}name(){return"to_device"}when(){return p.ExtensionState.PreProcess}onRequest(e){const t={since:null!==this.nextBatch?this.nextBatch:void 0};return e&&(t.limit=100,t.enabled=!0),t}onResponse(e){return s(this,void 0,void 0,(function*(){const t=[];let i=e.events||[];i.length>0&&this.cryptoCallbacks&&(i=yield this.cryptoCallbacks.preprocessToDeviceMessages(i)),i.map(this.client.getEventMapper()).map((e=>{if("m.key.verification.cancel"===e.getType()){const i=e.getContent().transaction_id;i&&t.push(i)}return e})).forEach((e=>{const i=e.getContent();if("m.room.message"!=e.getType()||"m.bad.encrypted"!=i.msgtype){if("m.key.verification.start"===e.getType()||"m.key.verification.request"===e.getType()){const n=i.transaction_id;t.includes(n)&&e.flagCancelled()}this.client.emit(u.ClientEvent.ToDeviceEvent,e)}else c.logger.log("Ignoring undecryptable to-device event from "+e.getSender())})),this.nextBatch=e.next_batch}))}}class S{constructor(e){this.client=e}name(){return"account_data"}when(){return p.ExtensionState.PostProcess}onRequest(e){if(e)return{enabled:!0}}onResponse(e){e.global&&e.global.length>0&&this.processGlobalAccountData(e.global);for(const t in e.rooms){const i=w(this.client,t,e.rooms[t]),n=this.client.getRoom(t);n?(n.addAccountData(i),i.forEach((e=>{this.client.emit(u.ClientEvent.Event,e)}))):c.logger.warn("got account data for room but room doesn't exist on client:",t)}}processGlobalAccountData(e){const t=w(this.client,void 0,e),i=t.reduce(((e,t)=>(e[t.getType()]=this.client.store.getAccountData(t.getType()),e)),{});this.client.store.storeAccountDataEvents(t),t.forEach((e=>{if(e.getType()===g.EventType.PushRules){const t=e.getContent();this.client.setPushRules(t)}const t=i[e.getType()];return this.client.emit(u.ClientEvent.AccountData,e,t),e}))}}class _{constructor(e){this.client=e}name(){return"typing"}when(){return p.ExtensionState.PostProcess}onRequest(e){if(e)return{enabled:!0}}onResponse(e){if(null==e?void 0:e.rooms)for(const t in e.rooms)T(this.client,t,[e.rooms[t]])}}class E{constructor(e){this.client=e}name(){return"receipts"}when(){return p.ExtensionState.PostProcess}onRequest(e){if(e)return{enabled:!0}}onResponse(e){if(null==e?void 0:e.rooms)for(const t in e.rooms)T(this.client,t,[e.rooms[t]])}}function w(e,t,i,n=!0){const r=e.getEventMapper({decrypt:n});return i.map((function(e){return e.room_id=t,r(e)}))}function T(e,t,i){const n=w(e,t,i),r=e.getRoom(t);r?(r.addEphemeralEvents(n),n.forEach((t=>{e.emit(u.ClientEvent.Event,t)}))):c.logger.warn("got ephemeral events for room but room doesn't exist on client:",t)}i.SlidingSyncSdk=class{constructor(e,t,i,n){this.slidingSync=e,this.client=t,this.syncState=null,this.lastPos=null,this.failCount=0,this.notifEvents=[],this.opts=(0,h.defaultClientOpts)(i),this.syncOpts=(0,h.defaultSyncApiOpts)(n),t.getNotifTimelineSet()&&t.reEmitter.reEmit(t.getNotifTimelineSet(),[a.RoomEvent.Timeline,a.RoomEvent.TimelineReset]),this.slidingSync.on(p.SlidingSyncEvent.Lifecycle,this.onLifecycle.bind(this)),this.slidingSync.on(p.SlidingSyncEvent.RoomData,this.onRoomData.bind(this));const r=[new b(this.client,this.syncOpts.cryptoCallbacks),new S(this.client),new _(this.client),new E(this.client)];this.syncOpts.crypto&&r.push(new y(this.syncOpts.crypto)),r.forEach((e=>{this.slidingSync.registerExtension(e)}))}onRoomData(e,t){let i=this.client.store.getRoom(e);if(!i){if(!t.initial)return void c.logger.debug("initial flag not set but no stored room exists for room ",e,t);i=(0,h._createAndReEmitRoom)(this.client,e,this.opts)}this.processRoomData(this.client,i,t)}onLifecycle(e,t,i){switch(i&&c.logger.debug("onLifecycle",e,i),e){case p.SlidingSyncState.Complete:if(this.purgeNotifications(),!t)break;this.lastPos||this.updateSyncState(h.SyncState.Prepared,{oldSyncToken:void 0,nextSyncToken:t.pos,catchingUp:!1,fromCache:!1}),this.updateSyncState(h.SyncState.Syncing,{oldSyncToken:this.lastPos,nextSyncToken:t.pos,catchingUp:!1,fromCache:!1}),this.lastPos=t.pos;break;case p.SlidingSyncState.RequestFinished:if(i){if(this.failCount+=1,this.updateSyncState(this.failCount>3?h.SyncState.Error:h.SyncState.Reconnecting,{error:new f.MatrixError(i)}),this.shouldAbortSync(new f.MatrixError(i)))return}else this.failCount=0}}syncLeftRooms(){return s(this,void 0,void 0,(function*(){return[]}))}peek(e){return s(this,void 0,void 0,(function*(){return null}))}stopPeeking(){}getSyncState(){return this.syncState}getSyncStateData(){var e;return null!==(e=this.syncStateData)&&void 0!==e?e:null}createRoom(e){const{timelineSupport:t}=this.client,i=new a.Room(e,this.client,this.client.getUserId(),{lazyLoadMembers:this.opts.lazyLoadMembers,pendingEventOrdering:this.opts.pendingEventOrdering,timelineSupport:t});return this.client.reEmitter.reEmit(i,[a.RoomEvent.Name,a.RoomEvent.Redaction,a.RoomEvent.RedactionCancelled,a.RoomEvent.Receipt,a.RoomEvent.Tags,a.RoomEvent.LocalEchoUpdated,a.RoomEvent.AccountData,a.RoomEvent.MyMembership,a.RoomEvent.Timeline,a.RoomEvent.TimelineReset]),this.registerStateListeners(i),i}registerStateListeners(e){this.client.reEmitter.reEmit(e.currentState,[v.RoomStateEvent.Events,v.RoomStateEvent.Members,v.RoomStateEvent.NewMember,v.RoomStateEvent.Update]),e.currentState.on(v.RoomStateEvent.NewMember,((e,t,i)=>{var n;i.user=null!==(n=this.client.getUser(i.userId))&&void 0!==n?n:void 0,this.client.reEmitter.reEmit(i,[m.RoomMemberEvent.Name,m.RoomMemberEvent.Typing,m.RoomMemberEvent.PowerLevel,m.RoomMemberEvent.Membership])}))}shouldAbortSync(e){return"M_UNKNOWN_TOKEN"===e.errcode&&(c.logger.warn("Token no longer valid - assuming logout"),this.stop(),this.updateSyncState(h.SyncState.Error,{error:e}),!0)}processRoomData(e,t,i){var n;return s(this,void 0,void 0,(function*(){i=function(e,t,i){if(!i.name)return i;for(const e of i.required_state)if(e.type===g.EventType.RoomName&&""===e.state_key)return e.content={name:i.name},i;return i.required_state.push({event_id:"$fake-sliding-sync-name-event-"+t,state_key:"",type:g.EventType.RoomName,content:{name:i.name},sender:e.getUserId(),origin_server_ts:(new Date).getTime()}),i}(e,t.roomId,i);const r=w(this.client,t.roomId,i.required_state);let o=w(this.client,t.roomId,i.timeline,!1);const c=[];if(i.initial){const e=new Set;t.getLiveTimeline().getEvents().forEach((t=>{e.add(t.getId())}));const n=[],r=[];let s=!1;for(let t=o.length-1;t>=0;t--){const i=o[t];e.has(i.getId())?s=!0:s?n.push(i):r.unshift(i)}o=r,n.length>0&&t.addEventsToTimeline(n,!0,t.getLiveTimeline(),i.prev_batch)}const h=this.client.isRoomEncrypted(t.roomId);if(null!=i.notification_count&&t.setUnreadNotificationCount(a.NotificationCountType.Total,i.notification_count),null!=i.highlight_count&&(!h||h&&t.getUnreadNotificationCount(a.NotificationCountType.Highlight)<=0)&&t.setUnreadNotificationCount(a.NotificationCountType.Highlight,i.highlight_count),Number.isInteger(i.invited_count)&&t.currentState.setInvitedMemberCount(i.invited_count),Number.isInteger(i.joined_count)&&t.currentState.setJoinedMemberCount(i.joined_count),i.invite_state){const e=w(this.client,t.roomId,i.invite_state);return this.injectRoomEvents(t,e),i.initial&&(t.recalculate(),this.client.store.storeRoom(t),this.client.emit(u.ClientEvent.Room,t)),e.forEach((e=>{this.client.emit(u.ClientEvent.Event,e)})),void t.updateMyMembership("invite")}i.initial&&t.getLiveTimeline().setPaginationToken(null!==(n=i.prev_batch)&&void 0!==n?n:null,l.EventTimeline.BACKWARDS),this.injectRoomEvents(t,r,o,i.num_live),t.addEphemeralEvents(c),t.updateMyMembership("join"),t.recalculate(),i.initial&&(e.store.storeRoom(t),e.emit(u.ClientEvent.Room,t)),this.addNotifications(o);const f=i=>s(this,void 0,void 0,(function*(){e.emit(u.ClientEvent.Event,i),i.isState()&&i.getType()==g.EventType.RoomEncryption&&this.syncOpts.cryptoCallbacks&&(yield this.syncOpts.cryptoCallbacks.onCryptoEvent(t,i))}));yield d.promiseMapSeries(r,f),yield d.promiseMapSeries(o,f),c.forEach((function(t){e.emit(u.ClientEvent.Event,t)})),t.decryptCriticalEvents()}))}injectRoomEvents(e,t,i,n){i=i||[],t=t||[],n=n||0;const r=e.getLiveTimeline(),o=0==r.getEvents().length;if(o){for(const e of t)this.client.getPushActionsForEvent(e);r.initialiseState(t)}o||(e.oldState.setStateEvents(t),e.currentState.setStateEvents(t));let s=[];n>0&&(s=i.slice(-1*n),i=i.slice(0,-1*s.length)),e.addLiveEvents(i,{fromCache:!0}),s.length>0&&e.addLiveEvents(s,{fromCache:!1}),e.recalculate(),this.resolveInvites(e)}resolveInvites(e){if(!e||!this.opts.resolveInvitesToProfiles)return;const t=this.client;e.getMembersWithMembership("invite").forEach((function(i){if(i.requestedProfileInfo)return;i.requestedProfileInfo=!0;const n=t.getUser(i.userId);let r;r=n?Promise.resolve({avatar_url:n.avatarUrl,displayname:n.displayName}):t.getProfileInfo(i.userId),r.then((function(t){const n=i.events.member;"invite"===n.getContent().membership&&(n.getContent().avatar_url=t.avatar_url,n.getContent().displayname=t.displayname,i.setMembershipEvent(n,e.currentState))}),(function(e){}))}))}retryImmediately(){return!0}sync(){return s(this,void 0,void 0,(function*(){for(c.logger.debug("Sliding sync init loop");!this.client.isGuest();)try{c.logger.debug("Getting push rules...");const e=yield this.client.getPushRules();c.logger.debug("Got push rules"),this.client.pushRules=e;break}catch(e){if(c.logger.error("Getting push rules failed",e),this.shouldAbortSync(e))return}yield this.slidingSync.start()}))}stop(){c.logger.debug("SyncApi.stop"),this.slidingSync.stop()}updateSyncState(e,t){const i=this.syncState;this.syncState=e,this.syncStateData=t,this.client.emit(u.ClientEvent.Sync,this.syncState,i,t)}addNotifications(e){if(this.client.getNotifTimelineSet())for(const t of e){const e=this.client.getPushActionsForEvent(t);e&&e.notify&&e.tweaks&&e.tweaks.highlight&&this.notifEvents.push(t)}}purgeNotifications(){this.notifEvents.sort((function(e,t){return e.getTs()-t.getTs()})),this.notifEvents.forEach((e=>{var t;null===(t=this.client.getNotifTimelineSet())||void 0===t||t.addLiveEvent(e)})),this.notifEvents=[]}}},{"./@types/event":306,"./client":321,"./http-api":367,"./logger":374,"./models/event-timeline":382,"./models/room":392,"./models/room-member":389,"./models/room-state":390,"./sliding-sync":407,"./sync":414,"./utils":416}],407:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.SlidingSync=i.SlidingSyncEvent=i.ExtensionState=i.SlidingSyncState=i.MSC3575_STATE_KEY_LAZY=i.MSC3575_STATE_KEY_ME=i.MSC3575_WILDCARD=void 0;const r=e("./logger"),o=e("./models/typed-event-emitter"),s=e("./utils");var a,c,d;i.MSC3575_WILDCARD="*",i.MSC3575_STATE_KEY_ME="$ME",i.MSC3575_STATE_KEY_LAZY="$LAZY",function(e){e.RequestFinished="FINISHED",e.Complete="COMPLETE"}(a=i.SlidingSyncState||(i.SlidingSyncState={}));class l{constructor(e){this.roomIndexToRoomId={},this.joinedCount=0,this.replaceList(e)}setModified(e){this.isModified=e}updateListRange(e){this.list.ranges=JSON.parse(JSON.stringify(e))}replaceList(e){e.filters=e.filters||{},e.ranges=e.ranges||[],this.list=JSON.parse(JSON.stringify(e)),this.isModified=!0,this.roomIndexToRoomId={},this.joinedCount=0}getList(e){let t={ranges:JSON.parse(JSON.stringify(this.list.ranges))};return(this.isModified||e)&&(t=JSON.parse(JSON.stringify(this.list))),t}isIndexInRange(e){for(const t of this.list.ranges)if(t[0]<=e&&e<=t[1])return!0;return!1}}!function(e){e.PreProcess="ExtState.PreProcess",e.PostProcess="ExtState.PostProcess"}(c=i.ExtensionState||(i.ExtensionState={})),function(e){e.RoomData="SlidingSync.RoomData",e.Lifecycle="SlidingSync.Lifecycle",e.List="SlidingSync.List"}(d=i.SlidingSyncEvent||(i.SlidingSyncEvent={}));class u extends o.TypedEventEmitter{constructor(e,t,i,n,r){super(),this.proxyBaseUrl=e,this.roomSubscriptionInfo=i,this.client=n,this.timeoutMS=r,this.listModifiedCount=0,this.terminated=!1,this.needsResend=!1,this.txnId=null,this.txnIdDefers=[],this.extensions={},this.desiredRoomSubscriptions=new Set,this.confirmedRoomSubscriptions=new Set,this.customSubscriptions=new Map,this.roomIdToCustomSubscription=new Map,this.lists=new Map,t.forEach(((e,t)=>{this.lists.set(t,new l(e))}))}addCustomSubscription(e,t){this.customSubscriptions.has(e)?r.logger.warn(`addCustomSubscription: ${e} already exists as a custom subscription, ignoring.`):this.customSubscriptions.set(e,t)}useCustomSubscription(e,t){this.roomIdToCustomSubscription.get(e)!==t&&(this.roomIdToCustomSubscription.set(e,t),this.confirmedRoomSubscriptions.delete(e))}getListData(e){const t=this.lists.get(e);return t?{joinedCount:t.joinedCount,roomIndexToRoomId:Object.assign({},t.roomIndexToRoomId)}:null}getListParams(e){const t=this.lists.get(e);return t?t.getList(!0):null}setListRanges(e,t){const i=this.lists.get(e);return i?(i.updateListRange(t),this.resend()):Promise.reject(new Error("no list with key "+e))}setList(e,t){const i=this.lists.get(e);return i?(i.replaceList(t),this.lists.set(e,i)):this.lists.set(e,new l(t)),this.listModifiedCount+=1,this.resend()}getRoomSubscriptions(){return new Set(Array.from(this.desiredRoomSubscriptions))}modifyRoomSubscriptions(e){return this.desiredRoomSubscriptions=e,this.resend()}modifyRoomSubscriptionInfo(e){return this.roomSubscriptionInfo=e,this.confirmedRoomSubscriptions=new Set,this.resend()}registerExtension(e){if(this.extensions[e.name()])throw new Error(`registerExtension: ${e.name()} already exists as an extension`);this.extensions[e.name()]=e}getExtensionRequest(e){const t={};return Object.keys(this.extensions).forEach((i=>{t[i]=this.extensions[i].onRequest(e)})),t}onPreExtensionsResponse(e){Object.keys(e).forEach((t=>{this.extensions[t].when()==c.PreProcess&&this.extensions[t].onResponse(e[t])}))}onPostExtensionsResponse(e){Object.keys(e).forEach((t=>{this.extensions[t].when()==c.PostProcess&&this.extensions[t].onResponse(e[t])}))}invokeRoomDataListeners(e,t){t.required_state||(t.required_state=[]),t.timeline||(t.timeline=[]),this.emit(d.RoomData,e,t)}invokeLifecycleListeners(e,t,i){this.emit(d.Lifecycle,e,t,i)}shiftRight(e,t,i){const n=this.lists.get(e);if(n)for(let e=t;e>i;e--)n.isIndexInRange(e)&&(n.roomIndexToRoomId[e]=n.roomIndexToRoomId[e-1])}shiftLeft(e,t,i){const n=this.lists.get(e);if(n)for(let e=i;en&&(n=Number(e));n<0||t>n||(this.shiftLeft(e,n,t),delete i.roomIndexToRoomId[n])}addEntry(e,t){const i=this.lists.get(e);if(!i)return;let n=-1;for(const e in i.roomIndexToRoomId)Number(e)>n&&(n=Number(e));n<0||t>n||this.shiftRight(e,n+1,t)}processListOps(e,t){let i=-1;const n=this.lists.get(t);n&&(e.ops.forEach((e=>{if(n)switch(e.op){case"DELETE":r.logger.debug("DELETE",t,e.index,";"),delete n.roomIndexToRoomId[e.index],-1!==i&&this.removeEntry(t,i),i=e.index;break;case"INSERT":r.logger.debug("INSERT",t,e.index,e.room_id,";"),n.roomIndexToRoomId[e.index]&&(i<0?this.addEntry(t,e.index):i>e.index?this.shiftRight(t,i,e.index):i0)return this.txnIdDefers[this.txnIdDefers.length-1].promise;this.needsResend=!0,this.txnId=this.client.makeTxnId();const t=(0,s.defer)();return this.txnIdDefers.push(Object.assign(Object.assign({},t),{txnId:this.txnId})),null===(e=this.abortController)||void 0===e||e.abort(),this.abortController=new AbortController,t.promise}resolveTransactionDefers(e){if(!e)return;let t=-1;for(let i=0;i{e.reject(e.txnId)})),this.txnIdDefers=[],this.lists.forEach((e=>{e.setModified(!0)})),this.confirmedRoomSubscriptions=new Set,this.needsResend=!0,null===(e=this.abortController)||void 0===e||e.abort(),this.abortController=new AbortController}start(){return n(this,void 0,void 0,(function*(){let e;for(this.abortController=new AbortController;!this.terminated;){this.needsResend=!1;let t,i=!1;try{const n=this.listModifiedCount,o={};this.lists.forEach(((e,t)=>{o[t]=e.getList(!1)}));const s={lists:o,pos:e,timeout:this.timeoutMS,clientTimeout:this.timeoutMS+1e4,extensions:this.getExtensionRequest(void 0===e)},c=h(this.desiredRoomSubscriptions,this.confirmedRoomSubscriptions),d=h(this.confirmedRoomSubscriptions,this.desiredRoomSubscriptions);if(d.size>0&&(s.unsubscribe_rooms=Array.from(d)),c.size>0){s.room_subscriptions={};for(const e of c){const t=this.roomIdToCustomSubscription.get(e);let i=this.roomSubscriptionInfo;t&&this.customSubscriptions.has(t)&&(i=this.customSubscriptions.get(t)),s.room_subscriptions[e]=i}}this.txnId&&(s.txn_id=this.txnId,this.txnId=null),this.pendingReq=this.client.slidingSync(s,this.proxyBaseUrl,this.abortController.signal),t=yield this.pendingReq,e=t.pos;for(const e of c)this.confirmedRoomSubscriptions.add(e);for(const e of d)this.confirmedRoomSubscriptions.delete(e);n!==this.listModifiedCount&&(r.logger.debug("list modified during await call, not updating list"),i=!0),this.lists.forEach((e=>{e.setModified(!1)})),t.lists=t.lists||{},t.rooms=t.rooms||{},t.extensions=t.extensions||{},Object.keys(t.lists).forEach((e=>{const i=this.lists.get(e);i&&t&&(i.joinedCount=t.lists[e].count)})),this.invokeLifecycleListeners(a.RequestFinished,t)}catch(t){if(t.httpStatus){if(this.invokeLifecycleListeners(a.RequestFinished,null,t),400===t.httpStatus){this.resetup(),e=void 0,yield(0,s.sleep)(50);continue}}else if(this.needsResend||"AbortError"===t.name)continue;r.logger.error(t),yield(0,s.sleep)(5e3)}if(!t)continue;this.onPreExtensionsResponse(t.extensions),Object.keys(t.rooms).forEach((e=>{this.invokeRoomDataListeners(e,t.rooms[e])}));const n=new Set;if(!i)for(const[e,i]of Object.entries(t.lists))i.ops=i.ops||[],i.ops.length>0&&n.add(e),this.processListOps(i,e);this.invokeLifecycleListeners(a.Complete,t),this.onPostExtensionsResponse(t.extensions),n.forEach((e=>{const t=this.lists.get(e);t&&this.emit(d.List,e,t.joinedCount,Object.assign({},t.roomIndexToRoomId))})),this.resolveTransactionDefers(t.txn_id)}}))}}i.SlidingSync=u;const h=(e,t)=>{const i=new Set(e);for(const e of t)i.delete(e);return i}},{"./logger":374,"./models/typed-event-emitter":395,"./utils":416}],408:[function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.LocalIndexedDBStoreBackend=void 0;const a=e("../sync-accumulator"),c=o(e("../utils")),d=o(e("../indexeddb-helpers")),l=e("../logger"),u=[e=>{e.createObjectStore("users",{keyPath:["userId"]}),e.createObjectStore("accountData",{keyPath:["type"]}),e.createObjectStore("sync",{keyPath:["clobber"]})},e=>{e.createObjectStore("oob_membership_events",{keyPath:["room_id","state_key"]}).createIndex("room","room_id")},e=>{e.createObjectStore("client_options",{keyPath:["clobber"]})},e=>{e.createObjectStore("to_device_queue",{autoIncrement:!0})}],h=u.length;function f(e,t,i){const n=e.openCursor(t);return new Promise(((e,t)=>{const r=[];n.onerror=()=>{t(new Error("Query failed: "+n.error))},n.onsuccess=()=>{const t=n.result;t?(r.push(i(t)),t.continue()):e(r)}}))}function p(e){return new Promise(((t,i)=>{e.oncomplete=function(e){t(e)},e.onerror=function(){i(e.error)}}))}function g(e){return new Promise(((t,i)=>{e.onsuccess=function(e){t(e)},e.onerror=function(){i(e.error)}}))}function v(e){return g(e).then((t=>e.result))}i.LocalIndexedDBStoreBackend=class{static exists(e,t){return t="matrix-js-sdk:"+(t||"default"),d.exists(e,t)}constructor(e,t="default"){this.indexedDB=e,this.disconnected=!0,this._isNewlyCreated=!1,this.pendingUserPresenceData=[],this.dbName="matrix-js-sdk:"+t,this.syncAccumulator=new a.SyncAccumulator}connect(e){if(!this.disconnected)return l.logger.log("LocalIndexedDBStoreBackend.connect: already connected or connecting"),Promise.resolve();this.disconnected=!1,l.logger.log("LocalIndexedDBStoreBackend.connect: connecting...");const t=this.indexedDB.open(this.dbName,h);return t.onupgradeneeded=e=>{const i=t.result,n=e.oldVersion;l.logger.log(`LocalIndexedDBStoreBackend.connect: upgrading from ${n}`),n<1&&(this._isNewlyCreated=!0),u.forEach(((e,t)=>{n<=t&&e(i)}))},t.onblocked=()=>{l.logger.log("can't yet open LocalIndexedDBStoreBackend because it is open elsewhere")},l.logger.log("LocalIndexedDBStoreBackend.connect: awaiting connection..."),g(t).then((()=>s(this,void 0,void 0,(function*(){l.logger.log("LocalIndexedDBStoreBackend.connect: connected"),this.db=t.result,this.db.onversionchange=()=>{var t;null===(t=this.db)||void 0===t||t.close(),this.disconnected=!0,this.db=void 0,null==e||e()},this.db.onclose=()=>{this.disconnected=!0,this.db=void 0,null==e||e()},yield this.init()}))))}isNewlyCreated(){return Promise.resolve(this._isNewlyCreated)}init(){return Promise.all([this.loadAccountData(),this.loadSyncData()]).then((([e,t])=>{l.logger.log("LocalIndexedDBStoreBackend: loaded initial data"),this.syncAccumulator.accumulate({next_batch:t.nextBatch,rooms:t.roomsData,account_data:{events:e}},!0)}))}getOutOfBandMembers(e){return new Promise(((t,i)=>{const n=this.db.transaction(["oob_membership_events"],"readonly").objectStore("oob_membership_events").index("room"),r=IDBKeyRange.only(e),o=n.openCursor(r),s=[];let a=!1;o.onsuccess=()=>{const e=o.result;if(!e)return s.length||a?t(s):t(null);const i=e.value;i.oob_written?a=!0:s.push(i),e.continue()},o.onerror=e=>{i(e)}})).then((t=>(l.logger.log(`LL: got ${null==t?void 0:t.length} membershipEvents from storage for room ${e} ...`),t)))}setOutOfBandMembers(e,t){return s(this,void 0,void 0,(function*(){l.logger.log(`LL: backend about to store ${t.length} members for ${e}`);const i=this.db.transaction(["oob_membership_events"],"readwrite"),n=i.objectStore("oob_membership_events");t.forEach((e=>{n.put(e)}));const r={room_id:e,oob_written:!0,state_key:0};n.put(r),yield p(i),l.logger.log(`LL: backend done storing for ${e}!`)}))}clearOutOfBandMembers(e){return s(this,void 0,void 0,(function*(){const t=this.db.transaction(["oob_membership_events"],"readonly").objectStore("oob_membership_events").index("room"),i=IDBKeyRange.only(e),n=v(t.openKeyCursor(i,"next")).then((e=>(null==e?void 0:e.primaryKey)[1])),r=v(t.openKeyCursor(i,"prev")).then((e=>(null==e?void 0:e.primaryKey)[1])),[o,s]=yield Promise.all([n,r]),a=this.db.transaction(["oob_membership_events"],"readwrite").objectStore("oob_membership_events"),c=IDBKeyRange.bound([e,o],[e,s]);var d;l.logger.log(`LL: Deleting all users + marker in storage for room ${e}, with key range:`,[e,o],[e,s]),yield(d=a.delete(c),new Promise(((e,t)=>{d.onsuccess=()=>e(d),d.onerror=e=>t(e)})))}))}clearDatabase(){return new Promise((e=>{l.logger.log(`Removing indexeddb instance: ${this.dbName}`);const t=this.indexedDB.deleteDatabase(this.dbName);t.onblocked=()=>{l.logger.log(`can't yet delete indexeddb ${this.dbName} because it is open elsewhere`)},t.onerror=()=>{l.logger.warn(`unable to delete js-sdk store indexeddb: ${t.error}`),e()},t.onsuccess=()=>{l.logger.log(`Removed indexeddb instance: ${this.dbName}`),e()}}))}getSavedSync(e=!0){const t=this.syncAccumulator.getJSON();return t.nextBatch?e?Promise.resolve(c.deepCopy(t)):Promise.resolve(t):Promise.resolve(null)}getNextBatchToken(){return Promise.resolve(this.syncAccumulator.getNextBatchToken())}setSyncData(e){return Promise.resolve().then((()=>{this.syncAccumulator.accumulate(e)}))}syncToDatabase(e){return s(this,void 0,void 0,(function*(){return this.syncToDatabasePromise?(l.logger.warn("Skipping syncToDatabase() as persist already in flight"),this.pendingUserPresenceData.push(...e),this.syncToDatabasePromise):(e.unshift(...this.pendingUserPresenceData),this.syncToDatabasePromise=this.doSyncToDatabase(e),this.syncToDatabasePromise)}))}doSyncToDatabase(e){return s(this,void 0,void 0,(function*(){try{const t=this.syncAccumulator.getJSON(!0);yield Promise.all([this.persistUserPresenceEvents(e),this.persistAccountData(t.accountData),this.persistSyncData(t.nextBatch,t.roomsData)])}finally{this.syncToDatabasePromise=void 0}}))}persistSyncData(e,t){return l.logger.log("Persisting sync data up to",e),c.promiseTry((()=>{const i=this.db.transaction(["sync"],"readwrite");return i.objectStore("sync").put({clobber:"-",nextBatch:e,roomsData:t}),p(i).then((()=>{l.logger.log("Persisted sync data up to",e)}))}))}persistAccountData(e){return c.promiseTry((()=>{const t=this.db.transaction(["accountData"],"readwrite"),i=t.objectStore("accountData");for(const t of e)i.put(t);return p(t).then()}))}persistUserPresenceEvents(e){return c.promiseTry((()=>{const t=this.db.transaction(["users"],"readwrite"),i=t.objectStore("users");for(const t of e)i.put({userId:t[0],event:t[1]});return p(t).then()}))}getUserPresenceEvents(){return c.promiseTry((()=>f(this.db.transaction(["users"],"readonly").objectStore("users"),void 0,(e=>[e.value.userId,e.value.event]))))}loadAccountData(){return l.logger.log("LocalIndexedDBStoreBackend: loading account data..."),c.promiseTry((()=>f(this.db.transaction(["accountData"],"readonly").objectStore("accountData"),void 0,(e=>e.value)).then((e=>(l.logger.log("LocalIndexedDBStoreBackend: loaded account data"),e)))))}loadSyncData(){return l.logger.log("LocalIndexedDBStoreBackend: loading sync data..."),c.promiseTry((()=>f(this.db.transaction(["sync"],"readonly").objectStore("sync"),void 0,(e=>e.value)).then((e=>(l.logger.log("LocalIndexedDBStoreBackend: loaded sync data"),e.length>1&&l.logger.warn("loadSyncData: More than 1 sync row found."),e.length>0?e[0]:{})))))}getClientOptions(){return Promise.resolve().then((()=>f(this.db.transaction(["client_options"],"readonly").objectStore("client_options"),void 0,(e=>{var t;return null===(t=e.value)||void 0===t?void 0:t.options})).then((e=>e[0]))))}storeClientOptions(e){return s(this,void 0,void 0,(function*(){const t=this.db.transaction(["client_options"],"readwrite");t.objectStore("client_options").put({clobber:"-",options:e}),yield p(t)}))}saveToDeviceBatches(e){return s(this,void 0,void 0,(function*(){const t=this.db.transaction(["to_device_queue"],"readwrite"),i=t.objectStore("to_device_queue");for(const t of e)i.add(t);yield p(t)}))}getOldestToDeviceBatch(){return s(this,void 0,void 0,(function*(){const e=this.db.transaction(["to_device_queue"],"readonly").objectStore("to_device_queue"),t=yield v(e.openCursor());if(!t)return null;const i=t.value;return{id:t.key,txnId:i.txnId,eventType:i.eventType,batch:i.batch}}))}removeToDeviceBatch(e){return s(this,void 0,void 0,(function*(){const t=this.db.transaction(["to_device_queue"],"readwrite");t.objectStore("to_device_queue").delete(e),yield p(t)}))}}},{"../indexeddb-helpers":372,"../logger":374,"../sync-accumulator":413,"../utils":416}],409:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.RemoteIndexedDBStoreBackend=void 0;const r=e("../logger"),o=e("../utils");i.RemoteIndexedDBStoreBackend=class{constructor(e,t){this.workerFactory=e,this.dbName=t,this.nextSeq=0,this.inFlight={},this.onWorkerMessage=e=>{var t;const i=e.data;if("closed"==i.command)null===(t=this.onClose)||void 0===t||t.call(this);else if("cmd_success"==i.command||"cmd_fail"==i.command){if(void 0===i.seq)return void r.logger.error("Got reply from worker with no seq");const e=this.inFlight[i.seq];if(void 0===e)return void r.logger.error("Got reply for unknown seq "+i.seq);if(delete this.inFlight[i.seq],"cmd_success"==i.command)e.resolve(i.result);else{const t=new Error(i.error.message);t.name=i.error.name,e.reject(t)}}else r.logger.warn("Unrecognised message from worker: ",i)}}connect(e){return this.onClose=e,this.ensureStarted().then((()=>this.doCmd("connect")))}clearDatabase(){return this.ensureStarted().then((()=>this.doCmd("clearDatabase")))}isNewlyCreated(){return this.doCmd("isNewlyCreated")}getSavedSync(){return this.doCmd("getSavedSync")}getNextBatchToken(){return this.doCmd("getNextBatchToken")}setSyncData(e){return this.doCmd("setSyncData",[e])}syncToDatabase(e){return this.doCmd("syncToDatabase",[e])}getOutOfBandMembers(e){return this.doCmd("getOutOfBandMembers",[e])}setOutOfBandMembers(e,t){return this.doCmd("setOutOfBandMembers",[e,t])}clearOutOfBandMembers(e){return this.doCmd("clearOutOfBandMembers",[e])}getClientOptions(){return this.doCmd("getClientOptions")}storeClientOptions(e){return this.doCmd("storeClientOptions",[e])}getUserPresenceEvents(){return this.doCmd("getUserPresenceEvents")}saveToDeviceBatches(e){return n(this,void 0,void 0,(function*(){return this.doCmd("saveToDeviceBatches",[e])}))}getOldestToDeviceBatch(){return n(this,void 0,void 0,(function*(){return this.doCmd("getOldestToDeviceBatch")}))}removeToDeviceBatch(e){return n(this,void 0,void 0,(function*(){return this.doCmd("removeToDeviceBatch",[e])}))}ensureStarted(){return this.startPromise||(this.worker=this.workerFactory(),this.worker.onmessage=this.onWorkerMessage,this.startPromise=this.doCmd("setupWorker",[this.dbName]).then((()=>{r.logger.log("IndexedDB worker is ready")}))),this.startPromise}doCmd(e,t){return Promise.resolve().then((()=>{var i;const n=this.nextSeq++,r=(0,o.defer)();return this.inFlight[n]=r,null===(i=this.worker)||void 0===i||i.postMessage({command:e,seq:n,args:t}),r.promise}))}}},{"../logger":374,"../utils":416}],410:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.IndexedDBStore=void 0;const r=e("./memory"),o=e("./indexeddb-local-backend"),s=e("./indexeddb-remote-backend"),a=e("../models/user"),c=e("../models/event"),d=e("../logger"),l=e("../models/typed-event-emitter");class u extends r.MemoryStore{static exists(e,t){return o.LocalIndexedDBStoreBackend.exists(e,t)}constructor(e){if(super(e),this.startedUp=!1,this.syncTs=0,this.userModifiedMap={},this.emitter=new l.TypedEventEmitter,this.on=this.emitter.on.bind(this.emitter),this.onClose=()=>{this.emitter.emit("closed")},this.getSavedSync=this.degradable((()=>this.backend.getSavedSync()),"getSavedSync"),this.isNewlyCreated=this.degradable((()=>this.backend.isNewlyCreated()),"isNewlyCreated"),this.getSavedSyncToken=this.degradable((()=>this.backend.getNextBatchToken()),"getSavedSyncToken"),this.deleteAllData=this.degradable((()=>(super.deleteAllData(),this.backend.clearDatabase().then((()=>{d.logger.log("Deleted indexeddb data.")}),(e=>{throw d.logger.error(`Failed to delete indexeddb data: ${e}`),e}))))),this.reallySave=this.degradable((()=>{this.syncTs=Date.now();const e=[];for(const t of this.getUsers())this.userModifiedMap[t.userId]!==t.getLastModifiedTime()&&t.events.presence&&(e.push([t.userId,t.events.presence.event]),this.userModifiedMap[t.userId]=t.getLastModifiedTime());return this.backend.syncToDatabase(e)})),this.setSyncData=this.degradable((e=>this.backend.setSyncData(e)),"setSyncData"),this.getOutOfBandMembers=this.degradable((e=>this.backend.getOutOfBandMembers(e)),"getOutOfBandMembers"),this.setOutOfBandMembers=this.degradable(((e,t)=>(super.setOutOfBandMembers(e,t),this.backend.setOutOfBandMembers(e,t))),"setOutOfBandMembers"),this.clearOutOfBandMembers=this.degradable((e=>(super.clearOutOfBandMembers(e),this.backend.clearOutOfBandMembers(e))),"clearOutOfBandMembers"),this.getClientOptions=this.degradable((()=>this.backend.getClientOptions()),"getClientOptions"),this.storeClientOptions=this.degradable((e=>(super.storeClientOptions(e),this.backend.storeClientOptions(e))),"storeClientOptions"),!e.indexedDB)throw new Error("Missing required option: indexedDB");e.workerFactory?this.backend=new s.RemoteIndexedDBStoreBackend(e.workerFactory,e.dbName):this.backend=new o.LocalIndexedDBStoreBackend(e.indexedDB,e.dbName)}startup(){return this.startedUp?(d.logger.log("IndexedDBStore.startup: already started"),Promise.resolve()):(d.logger.log("IndexedDBStore.startup: connecting to backend"),this.backend.connect(this.onClose).then((()=>(d.logger.log("IndexedDBStore.startup: loading presence events"),this.backend.getUserPresenceEvents()))).then((e=>{d.logger.log("IndexedDBStore.startup: processing presence events"),e.forEach((([e,t])=>{const i=new a.User(e);t&&i.setPresenceEvent(new c.MatrixEvent(t)),this.userModifiedMap[i.userId]=i.getLastModifiedTime(),this.storeUser(i)})),this.startedUp=!0})))}wantsSave(){return Date.now()-this.syncTs>3e5}save(e=!1){return e||this.wantsSave()?this.reallySave():Promise.resolve()}degradable(e,t){const i=t?super[t]:null;return(...t)=>n(this,void 0,void 0,(function*(){try{return yield e.call(this,...t)}catch(e){d.logger.error("IndexedDBStore failure, degrading to MemoryStore",e),this.emitter.emit("degraded",e);try{d.logger.log("IndexedDBStore trying to delete degraded data"),yield this.backend.clearDatabase(),d.logger.log("IndexedDBStore delete after degrading succeeded")}catch(e){d.logger.warn("IndexedDBStore delete after degrading failed",e)}if(i)return i.call(this,...t)}}))}getPendingEvents(e){const t=Object.create(null,{getPendingEvents:{get:()=>super.getPendingEvents}});return n(this,void 0,void 0,(function*(){if(!this.localStorage)return t.getPendingEvents.call(this,e);const i=this.localStorage.getItem(h(e));if(i)try{return JSON.parse(i)}catch(e){d.logger.error("Could not parse persisted pending events",e)}return[]}))}setPendingEvents(e,t){const i=Object.create(null,{setPendingEvents:{get:()=>super.setPendingEvents}});return n(this,void 0,void 0,(function*(){if(!this.localStorage)return i.setPendingEvents.call(this,e,t);t.length>0?this.localStorage.setItem(h(e),JSON.stringify(t)):this.localStorage.removeItem(h(e))}))}saveToDeviceBatches(e){return this.backend.saveToDeviceBatches(e)}getOldestToDeviceBatch(){return this.backend.getOldestToDeviceBatch()}removeToDeviceBatch(e){return this.backend.removeToDeviceBatch(e)}}function h(e){return`mx_pending_events_${e}`}i.IndexedDBStore=u},{"../logger":374,"../models/event":383,"../models/typed-event-emitter":395,"../models/user":396,"./indexeddb-local-backend":408,"./indexeddb-remote-backend":409,"./memory":411}],411:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.MemoryStore=void 0;const r=e("../models/user"),o=e("../models/room-state"),s=e("../utils");function a(e){return"string"==typeof e&&!!e&&"undefined"!==e&&"null"!==e||"number"==typeof e}i.MemoryStore=class{constructor(e={}){this.rooms={},this.users={},this.syncToken=null,this.filters=new s.MapWithDefault((()=>new Map)),this.accountData=new Map,this.oobMembers=new Map,this.pendingEvents={},this.pendingToDeviceBatches=[],this.nextToDeviceBatchId=0,this.onRoomMember=(e,t,i)=>{if("invite"===i.membership)return;const n=this.users[i.userId]||new r.User(i.userId);i.name&&(n.setDisplayName(i.name),i.events.member&&n.setRawDisplayName(i.events.member.getDirectionalContent().displayname)),i.events.member&&i.events.member.getContent().avatar_url&&n.setAvatarUrl(i.events.member.getContent().avatar_url),this.users[n.userId]=n},this.localStorage=e.localStorage}getSyncToken(){return this.syncToken}isNewlyCreated(){return Promise.resolve(!0)}setSyncToken(e){this.syncToken=e}storeRoom(e){this.rooms[e.roomId]=e,e.currentState.on(o.RoomStateEvent.Members,this.onRoomMember),e.currentState.getMembers().forEach((t=>{this.onRoomMember(null,e.currentState,t)}))}getRoom(e){return this.rooms[e]||null}getRooms(){return Object.values(this.rooms)}removeRoom(e){this.rooms[e]&&this.rooms[e].currentState.removeListener(o.RoomStateEvent.Members,this.onRoomMember),delete this.rooms[e]}getRoomSummaries(){return Object.values(this.rooms).map((function(e){return e.summary}))}storeUser(e){this.users[e.userId]=e}getUser(e){return this.users[e]||null}getUsers(){return Object.values(this.users)}scrollback(e,t){return[]}storeEvents(e,t,i,n){}storeFilter(e){(null==e?void 0:e.userId)&&(null==e?void 0:e.filterId)&&this.filters.getOrCreate(e.userId).set(e.filterId,e)}getFilter(e,t){var i;return(null===(i=this.filters.get(e))||void 0===i?void 0:i.get(t))||null}getFilterIdByName(e){if(!this.localStorage)return null;const t="mxjssdk_memory_filter_"+e;try{const e=this.localStorage.getItem(t);if(a(e))return e}catch(e){}return null}setFilterIdByName(e,t){if(!this.localStorage)return;const i="mxjssdk_memory_filter_"+e;try{a(t)?this.localStorage.setItem(i,t):this.localStorage.removeItem(i)}catch(e){}}storeAccountDataEvents(e){e.forEach((e=>{!Object.keys(e.getContent()).length?this.accountData.delete(e.getType()):this.accountData.set(e.getType(),e)}))}getAccountData(e){return this.accountData.get(e)}setSyncData(e){return Promise.resolve()}wantsSave(){return!1}save(e){}startup(){return Promise.resolve()}getSavedSync(){return Promise.resolve(null)}getSavedSyncToken(){return Promise.resolve(null)}deleteAllData(){return this.rooms={},this.users={},this.syncToken=null,this.filters=new s.MapWithDefault((()=>new Map)),this.accountData=new Map,Promise.resolve()}getOutOfBandMembers(e){return Promise.resolve(this.oobMembers.get(e)||null)}setOutOfBandMembers(e,t){return this.oobMembers.set(e,t),Promise.resolve()}clearOutOfBandMembers(e){return this.oobMembers.delete(e),Promise.resolve()}getClientOptions(){return Promise.resolve(this.clientOptions)}storeClientOptions(e){return this.clientOptions=Object.assign({},e),Promise.resolve()}getPendingEvents(e){var t;return n(this,void 0,void 0,(function*(){return null!==(t=this.pendingEvents[e])&&void 0!==t?t:[]}))}setPendingEvents(e,t){return n(this,void 0,void 0,(function*(){this.pendingEvents[e]=t}))}saveToDeviceBatches(e){for(const t of e)this.pendingToDeviceBatches.push({id:this.nextToDeviceBatchId++,eventType:t.eventType,txnId:t.txnId,batch:t.batch});return Promise.resolve()}getOldestToDeviceBatch(){return n(this,void 0,void 0,(function*(){return 0===this.pendingToDeviceBatches.length?null:this.pendingToDeviceBatches[0]}))}removeToDeviceBatch(e){return this.pendingToDeviceBatches=this.pendingToDeviceBatches.filter((t=>t.id!==e)),Promise.resolve()}}},{"../models/room-state":390,"../models/user":396,"../utils":416}],412:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.StubStore=void 0;i.StubStore=class{constructor(){this.accountData=new Map,this.fromToken=null}isNewlyCreated(){return Promise.resolve(!0)}getSyncToken(){return this.fromToken}setSyncToken(e){this.fromToken=e}storeRoom(e){}getRoom(e){return null}getRooms(){return[]}removeRoom(e){}getRoomSummaries(){return[]}storeUser(e){}getUser(e){return null}getUsers(){return[]}scrollback(e,t){return[]}storeEvents(e,t,i,n){}storeFilter(e){}getFilter(e,t){return null}getFilterIdByName(e){return null}setFilterIdByName(e,t){}storeAccountDataEvents(e){}getAccountData(e){}setSyncData(e){return Promise.resolve()}wantsSave(){return!1}save(){}startup(){return Promise.resolve()}getSavedSync(){return Promise.resolve(null)}getSavedSyncToken(){return Promise.resolve(null)}deleteAllData(){return Promise.resolve()}getOutOfBandMembers(){return Promise.resolve(null)}setOutOfBandMembers(e,t){return Promise.resolve()}clearOutOfBandMembers(){return Promise.resolve()}getClientOptions(){return Promise.resolve(void 0)}storeClientOptions(e){return Promise.resolve()}getPendingEvents(e){return n(this,void 0,void 0,(function*(){return[]}))}setPendingEvents(e,t){return Promise.resolve()}saveToDeviceBatches(e){return n(this,void 0,void 0,(function*(){return Promise.resolve()}))}getOldestToDeviceBatch(){return Promise.resolve(null)}removeToDeviceBatch(e){return n(this,void 0,void 0,(function*(){return Promise.resolve()}))}}},{}],413:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.SyncAccumulator=i.Category=void 0;const n=e("./logger"),r=e("./utils"),o=e("./@types/event"),s=e("./@types/read_receipts"),a=e("./@types/sync");var c;!function(e){e.Invite="invite",e.Leave="leave",e.Join="join"}(c=i.Category||(i.Category={}));function d(e,t){null!==t.state_key&&void 0!==t.state_key&&t.type&&(e[t.type]||(e[t.type]=Object.create(null)),e[t.type][t.state_key]=t)}i.SyncAccumulator=class{constructor(e={}){this.opts=e,this.accountData={},this.inviteRooms={},this.joinRooms={},this.nextBatch=null,this.opts.maxTimelineEntries=this.opts.maxTimelineEntries||50}accumulate(e,t=!1){this.accumulateRooms(e,t),this.accumulateAccountData(e),this.nextBatch=e.next_batch}accumulateAccountData(e){e.account_data&&e.account_data.events&&e.account_data.events.forEach((e=>{this.accountData[e.type]=e}))}accumulateRooms(e,t=!1){e.rooms&&(e.rooms.invite&&Object.keys(e.rooms.invite).forEach((i=>{this.accumulateRoom(i,c.Invite,e.rooms.invite[i],t)})),e.rooms.join&&Object.keys(e.rooms.join).forEach((i=>{this.accumulateRoom(i,c.Join,e.rooms.join[i],t)})),e.rooms.leave&&Object.keys(e.rooms.leave).forEach((i=>{this.accumulateRoom(i,c.Leave,e.rooms.leave[i],t)})))}accumulateRoom(e,t,i,r=!1){switch(t){case c.Invite:this.accumulateInviteState(e,i);break;case c.Join:this.inviteRooms[e]&&delete this.inviteRooms[e],this.accumulateJoinState(e,i,r);break;case c.Leave:this.inviteRooms[e]?delete this.inviteRooms[e]:delete this.joinRooms[e];break;default:n.logger.error("Unknown cateogory: ",t)}}accumulateInviteState(e,t){if(!t.invite_state||!t.invite_state.events)return;if(!this.inviteRooms[e])return void(this.inviteRooms[e]={invite_state:t.invite_state});const i=this.inviteRooms[e];t.invite_state.events.forEach((e=>{let t=!1;for(let n=0;n{v._accountData[e.type]=e})),t.unread_notifications&&(v._unreadNotifications=t.unread_notifications),v._unreadThreadNotifications=null!==(c=null!==(n=t[a.UNREAD_THREAD_NOTIFICATIONS.stable])&&void 0!==n?n:t[a.UNREAD_THREAD_NOTIFICATIONS.unstable])&&void 0!==c?c:void 0,t.summary){const e="m.heroes",i="m.invited_member_count",n="m.joined_member_count",r=v._summary,o=t.summary;r[e]=o[e]||r[e],r[n]=o[n]||r[n],r[i]=o[i]||r[i]}if(null===(u=null===(l=t.ephemeral)||void 0===l?void 0:l.events)||void 0===u||u.forEach((e=>{e.type===o.EventType.Receipt&&e.content&&Object.keys(e.content).forEach((t=>{Object.entries(e.content[t]).forEach((([i,n])=>{var o;if((0,r.isSupportedReceiptType)(i))for(const r of Object.keys(n)){const n=e.content[t][i][r],a={data:e.content[t][i][r],type:i,eventId:t};n.thread_id&&n.thread_id!==s.MAIN_ROOM_TIMELINE?v._threadReadReceipts=Object.assign(Object.assign({},v._threadReadReceipts),{[n.thread_id]:Object.assign(Object.assign({},null!==(o=v._threadReadReceipts[n.thread_id])&&void 0!==o?o:{}),{[r]:a})}):v._readReceipts[r]=a}}))}))})),t.timeline&&t.timeline.limited&&(v._timeline=[]),null===(f=null===(h=t.state)||void 0===h?void 0:h.events)||void 0===f||f.forEach((e=>{d(v._currentState,e)})),null===(g=null===(p=t.timeline)||void 0===p?void 0:p.events)||void 0===g||g.forEach(((e,n)=>{var r;let o;if(d(v._currentState,e),i)o=e;else{o=Object.assign({},e),void 0!==o.unsigned&&(o.unsigned=Object.assign({},o.unsigned));const t=e.unsigned?e.unsigned.age:e.age;void 0!==t&&(o._localTs=Date.now()-t)}v._timeline.push({event:o,token:0===n&&null!==(r=t.timeline.prev_batch)&&void 0!==r?r:null})})),v._timeline.length>this.opts.maxTimelineEntries){for(let e=v._timeline.length-this.opts.maxTimelineEntries;e{t.invite[e]=this.inviteRooms[e]})),Object.keys(this.joinRooms).forEach((i=>{const n=this.joinRooms[i],s={ephemeral:{events:[]},account_data:{events:[]},state:{events:[]},timeline:{events:[],prev_batch:null},unread_notifications:n._unreadNotifications,unread_thread_notifications:n._unreadThreadNotifications,summary:n._summary};Object.keys(n._accountData).forEach((e=>{s.account_data.events.push(n._accountData[e])}));const a={type:o.EventType.Receipt,room_id:i,content:{}},c=new r.MapWithDefault((()=>new r.MapWithDefault((()=>new Map))));for(const[e,t]of Object.entries(n._readReceipts))c.getOrCreate(t.eventId).getOrCreate(t.type).set(e,t.data);for(const e of Object.values(n._threadReadReceipts))for(const[t,i]of Object.entries(e))c.getOrCreate(i.eventId).getOrCreate(i.type).set(t,i.data);a.content=(0,r.recursiveMapToObject)(c),c.size>0&&s.ephemeral.events.push(a),n._timeline.forEach((t=>{if(!s.timeline.prev_batch){if(!t.token)return;s.timeline.prev_batch=t.token}let i;var n;!e&&("_localTs"in(n=t.event)&&void 0!==n._localTs)?(i=Object.assign({},t.event),void 0!==i.unsigned&&(i.unsigned=Object.assign({},i.unsigned)),delete i._localTs,i.unsigned=i.unsigned||{},i.unsigned.age=Date.now()-t.event._localTs):i=t.event,s.timeline.events.push(i)}));const l=Object.create(null);for(let e=s.timeline.events.length-1;e>=0;e--){const t=s.timeline.events[e];if(null===t.state_key||void 0===t.state_key)continue;const i=(0,r.deepCopy)(t);i.unsigned&&(i.unsigned.prev_content&&(i.content=i.unsigned.prev_content),i.unsigned.prev_sender&&(i.sender=i.unsigned.prev_sender)),d(l,i)}Object.keys(n._currentState).forEach((e=>{Object.keys(n._currentState[e]).forEach((t=>{let i=n._currentState[e][t];l[e]&&l[e][t]&&(i=l[e][t]),s.state.events.push(i)}))})),t.join[i]=s}));const i=[];return Object.keys(this.accountData).forEach((e=>{i.push(this.accountData[e])})),{nextBatch:this.nextBatch,roomsData:t,accountData:i}}getNextBatchToken(){return this.nextBatch}}},{"./@types/event":306,"./@types/read_receipts":311,"./@types/sync":314,"./logger":374,"./utils":416}],414:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i._createAndReEmitRoom=i.SyncApi=i.defaultSyncApiOpts=i.defaultClientOpts=i.SyncState=void 0;const a=e("./models/user"),c=e("./models/room"),d=o(e("./utils")),l=e("./utils"),u=e("./filter"),h=e("./models/event-timeline"),f=e("./logger"),p=e("./errors"),g=e("./client"),v=e("./http-api"),m=e("./@types/event"),y=e("./models/room-state"),b=e("./models/room-member"),S=e("./models/beacon"),_=e("./@types/sync"),E=e("./feature"),w=!0;var T;!function(e){e.Error="ERROR",e.Prepared="PREPARED",e.Stopped="STOPPED",e.Syncing="SYNCING",e.Catchup="CATCHUP",e.Reconnecting="RECONNECTING"}(T=i.SyncState||(i.SyncState={}));const I=["org.matrix.msc2716v3"];function R(e,t){return`FILTER_SYNC_${e}`+(t?"_"+t:"")}function M(...e){w&&f.logger.log(...e)}var k;function C(e){return Object.assign({initialSyncLimit:8,resolveInvitesToProfiles:!1,pollTimeout:3e4,pendingEventOrdering:g.PendingEventOrdering.Chronological,threadSupport:!1},e)}function O(e){return Object.assign({canResetEntireTimeline:e=>!1},e)}!function(e){e.Offline="offline",e.Online="online",e.Unavailable="unavailable"}(k||(k={})),i.defaultClientOpts=C,i.defaultSyncApiOpts=O;function A(e,t){const i=new a.User(t);return e.reEmitter.reEmit(i,[a.UserEvent.AvatarUrl,a.UserEvent.DisplayName,a.UserEvent.Presence,a.UserEvent.CurrentlyActive,a.UserEvent.LastPresenceTs]),i}function P(e,t,i){const{timelineSupport:n}=e,r=new c.Room(t,e,e.getUserId(),{lazyLoadMembers:i.lazyLoadMembers,pendingEventOrdering:i.pendingEventOrdering,timelineSupport:n});return e.reEmitter.reEmit(r,[c.RoomEvent.Name,c.RoomEvent.Redaction,c.RoomEvent.RedactionCancelled,c.RoomEvent.Receipt,c.RoomEvent.Tags,c.RoomEvent.LocalEchoUpdated,c.RoomEvent.AccountData,c.RoomEvent.MyMembership,c.RoomEvent.Timeline,c.RoomEvent.TimelineReset,y.RoomStateEvent.Events,y.RoomStateEvent.Members,y.RoomStateEvent.NewMember,y.RoomStateEvent.Update,S.BeaconEvent.New,S.BeaconEvent.Update,S.BeaconEvent.Destroy,S.BeaconEvent.LivenessChange]),r.on(y.RoomStateEvent.NewMember,((t,i,n)=>{var r;n.user=null!==(r=e.getUser(n.userId))&&void 0!==r?r:void 0,e.reEmitter.reEmit(n,[b.RoomMemberEvent.Name,b.RoomMemberEvent.Typing,b.RoomMemberEvent.PowerLevel,b.RoomMemberEvent.Membership])})),r}i.SyncApi=class{constructor(e,t,i){this.client=e,this._peekRoom=null,this.syncState=null,this.catchingUp=!1,this.running=!1,this.notifEvents=[],this.failedSyncCount=0,this.storeIsInvalid=!1,this.getPushRules=()=>s(this,void 0,void 0,(function*(){try{M("Getting push rules...");const e=yield this.client.getPushRules();M("Got push rules"),this.client.pushRules=e}catch(e){if(f.logger.error("Getting push rules failed",e),this.shouldAbortSync(e))return;return M("Waiting for saved sync before retrying push rules..."),yield this.recoverFromSyncStartupError(this.savedSyncPromise,e),this.getPushRules()}})),this.buildDefaultFilter=()=>{const e=new u.Filter(this.client.credentials.userId);return this.client.canSupport.get(E.Feature.ThreadUnreadNotifications)!==E.ServerSupport.Unsupported&&e.setUnreadThreadNotifications(!0),e},this.checkLazyLoadStatus=()=>s(this,void 0,void 0,(function*(){var e;if(M("Checking lazy load status..."),this.opts.lazyLoadMembers&&this.client.isGuest()&&(this.opts.lazyLoadMembers=!1),this.opts.lazyLoadMembers){M("Checking server lazy load support...");(yield this.client.doesServerSupportLazyLoading())?(M("Enabling lazy load on sync filter..."),this.opts.filter||(this.opts.filter=this.buildDefaultFilter()),this.opts.filter.setLazyLoadMembers(!0)):(M("LL: lazy loading requested but not supported by server, so disabling"),this.opts.lazyLoadMembers=!1)}M("Checking whether lazy loading has changed in store...");if(yield this.wasLazyLoadingToggled(this.opts.lazyLoadMembers)){this.storeIsInvalid=!0;const e=new p.InvalidStoreError(p.InvalidStoreState.ToggledLazyLoading,!!this.opts.lazyLoadMembers);return this.updateSyncState(T.Error,{error:e}),void f.logger.warn("InvalidStoreError: store is not usable: stopping sync.")}this.opts.lazyLoadMembers&&(null===(e=this.syncOpts.crypto)||void 0===e||e.enableLazyLoading());try{M("Storing client options..."),yield this.client.storeClientOptions(),M("Stored client options")}catch(e){throw f.logger.error("Storing client options failed",e),e}})),this.getFilter=()=>s(this,void 0,void 0,(function*(){let e,t;M("Getting filter..."),e=this.opts.filter?this.opts.filter:this.buildDefaultFilter();try{t=yield this.client.getOrCreateFilter(R(this.client.credentials.userId),e)}catch(e){return f.logger.error("Getting filter failed",e),this.shouldAbortSync(e)?{}:(M("Waiting for saved sync before retrying filter..."),yield this.recoverFromSyncStartupError(this.savedSyncPromise,e),this.getFilter())}return{filter:e,filterId:t}})),this.onOnline=()=>{M("Browser thinks we are back online"),this.startKeepAlives(0)},this.opts=C(t),this.syncOpts=O(i),e.getNotifTimelineSet()&&e.reEmitter.reEmit(e.getNotifTimelineSet(),[c.RoomEvent.Timeline,c.RoomEvent.TimelineReset])}createRoom(e){const t=P(this.client,e,this.opts);return t.on(y.RoomStateEvent.Marker,((e,i)=>{this.onMarkerStateEvent(t,e,i)})),t}onMarkerStateEvent(e,t,{timelineWasEmpty:i}={}){if(i)return void f.logger.debug(`MarkerState: Ignoring markerEventId=${t.getId()} in roomId=${e.roomId} because the timeline was empty before the marker arrived which means there is nothing to refresh.`);I.includes(e.getVersion())||t.getSender()===e.getCreator()?(f.logger.debug(`MarkerState: Timeline needs to be refreshed because a new markerEventId=${t.getId()} was sent in roomId=${e.roomId}`),e.setTimelineNeedsRefresh(!0),e.emit(c.RoomEvent.HistoryImportedWithinTimeline,t,e)):f.logger.debug(`MarkerState: Ignoring markerEventId=${t.getId()} in roomId=${e.roomId} because MSC2716 is not supported in the room version or for any room version, the marker wasn't sent by the room creator.`)}syncLeftRooms(){var e;return s(this,void 0,void 0,(function*(){const t=this.client,i=new u.Filter(this.client.credentials.userId);i.setTimelineLimit(1),i.setIncludeLeaveRooms(!0);const n=this.opts.pollTimeout+8e4,r={timeout:0,filter:yield t.getOrCreateFilter(R(t.credentials.userId,"LEFT_ROOMS"),i)},o=yield t.http.authedRequest(v.Method.Get,"/sync",r,void 0,{localTimeoutMs:n});let a=[];(null===(e=o.rooms)||void 0===e?void 0:e.leave)&&(a=this.mapSyncResponseToRoomArray(o.rooms.leave));return(yield Promise.all(a.map((e=>s(this,void 0,void 0,(function*(){const i=e.room;if(!e.isBrandNewRoom)return;e.timeline=e.timeline||{prev_batch:null,events:[]};const n=this.mapSyncEventsFormat(e.timeline,i),r=this.mapSyncEventsFormat(e.state,i);return i.getLiveTimeline().setPaginationToken(e.timeline.prev_batch,h.EventTimeline.BACKWARDS),yield this.injectRoomEvents(i,r,n),i.recalculate(),t.store.storeRoom(i),t.emit(g.ClientEvent.Room,i),this.processEventsForNotifs(i,n),i})))))).filter(Boolean)}))}peek(e){var t;if((null===(t=this._peekRoom)||void 0===t?void 0:t.roomId)===e)return Promise.resolve(this._peekRoom);const i=this.client;return this._peekRoom=this.createRoom(e),this.client.roomInitialSync(e,20).then((e=>{e.messages=e.messages||{chunk:[]},e.messages.chunk=e.messages.chunk||[],e.state=e.state||[];const t=d.deepCopy(e.state).map(i.getEventMapper()),n=e.state.map(i.getEventMapper()),r=e.messages.chunk.map(i.getEventMapper());return Array.isArray(e.presence)&&e.presence.map(i.getEventMapper()).forEach((function(e){let t=i.store.getUser(e.getContent().user_id);t?t.setPresenceEvent(e):(t=A(i,e.getContent().user_id),t.setPresenceEvent(e),i.store.storeUser(t)),i.emit(g.ClientEvent.Event,e)})),e.messages.start&&(this._peekRoom.oldState.paginationToken=e.messages.start),this._peekRoom.oldState.setStateEvents(t),this._peekRoom.currentState.setStateEvents(n),this.resolveInvites(this._peekRoom),this._peekRoom.recalculate(),this._peekRoom.addEventsToTimeline(r.reverse(),!0,this._peekRoom.getLiveTimeline(),e.messages.start),i.store.storeRoom(this._peekRoom),i.emit(g.ClientEvent.Room,this._peekRoom),this.peekPoll(this._peekRoom),this._peekRoom}))}stopPeeking(){this._peekRoom=null}peekPoll(e,t){var i;this._peekRoom===e?this.client.http.authedRequest(v.Method.Get,"/events",{room_id:e.roomId,timeout:String(3e4),from:t},void 0,{localTimeoutMs:5e4,abortSignal:null===(i=this.abortController)||void 0===i?void 0:i.signal}).then((t=>{if(this._peekRoom!==e)return void M("Stopped peeking in room %s",e.roomId);t.chunk.filter((function(e){return"m.presence"===e.type})).map(this.client.getEventMapper()).forEach((e=>{let t=this.client.store.getUser(e.getContent().user_id);t?t.setPresenceEvent(e):(t=A(this.client,e.getContent().user_id),t.setPresenceEvent(e),this.client.store.storeUser(t)),this.client.emit(g.ClientEvent.Event,e)}));const i=t.chunk.filter((function(t){return t.room_id===e.roomId&&t.event_id})).map(this.client.getEventMapper());e.addLiveEvents(i),this.peekPoll(e,t.end)}),(i=>{f.logger.error("[%s] Peek poll failed: %s",e.roomId,i),setTimeout((()=>{this.peekPoll(e,t)}),3e4)})):M("Stopped peeking in room %s",e.roomId)}getSyncState(){return this.syncState}getSyncStateData(){var e;return null!==(e=this.syncStateData)&&void 0!==e?e:null}recoverFromSyncStartupError(e,t){return s(this,void 0,void 0,(function*(){yield e;const i=this.startKeepAlives();this.updateSyncState(T.Error,{error:t}),yield i}))}wasLazyLoadingToggled(e=!1){return s(this,void 0,void 0,(function*(){let t=!1;if(!(yield this.client.store.isNewlyCreated())){const i=yield this.client.store.getClientOptions();return i&&(t=!!i.lazyLoadMembers),t!==e}return!1}))}shouldAbortSync(e){return"M_UNKNOWN_TOKEN"===e.errcode&&(f.logger.warn("Token no longer valid - assuming logout"),this.stop(),this.updateSyncState(T.Error,{error:e}),!0)}sync(){var e,i;return s(this,void 0,void 0,(function*(){if(this.running=!0,this.abortController=new AbortController,null===(i=null===(e=t.window)||void 0===e?void 0:e.addEventListener)||void 0===i||i.call(e,"online",this.onOnline,!1),this.client.isGuest())return this.doSync({});M("Getting saved sync token...");const n=this.client.store.getSavedSyncToken().then((e=>(M("Got saved sync token"),e)));this.savedSyncPromise=this.client.store.getSavedSync().then((e=>{if(M(`Got reply from saved sync, exists? ${!!e}`),e)return this.syncFromCache(e)})).catch((e=>{f.logger.error("Getting saved sync failed",e)})),yield this.getPushRules(),yield this.checkLazyLoadStatus();const{filterId:r,filter:o}=yield this.getFilter();if(o){if(this.client.resetNotifTimelineSet(),!this.currentSyncRequest){let e=r;const t=yield n;if(t)M("Sending first sync request...");else{M("Sending initial sync request...");const t=this.buildDefaultFilter();t.setDefinition(o.getDefinition()),t.setTimelineLimit(this.opts.initialSyncLimit),e=JSON.stringify(t.getDefinition())}this.currentSyncRequest=this.doSyncRequest({filter:e},t)}return M("Waiting for saved sync before starting sync processing..."),yield this.savedSyncPromise,this.doSync({filter:r})}}))}stop(){var e,i,n;M("SyncApi.stop"),null===(i=null===(e=t.window)||void 0===e?void 0:e.removeEventListener)||void 0===i||i.call(e,"online",this.onOnline,!1),this.running=!1,null===(n=this.abortController)||void 0===n||n.abort(),this.keepAliveTimer&&(clearTimeout(this.keepAliveTimer),this.keepAliveTimer=void 0)}retryImmediately(){return!!this.connectionReturnedDefer&&(this.startKeepAlives(0),!0)}syncFromCache(e){return s(this,void 0,void 0,(function*(){M("sync(): not doing HTTP hit, instead returning stored /sync data");const t=e.nextBatch;this.client.store.setSyncToken(t);const i={nextSyncToken:t,catchingUp:!1,fromCache:!0},n={next_batch:t,rooms:e.roomsData,account_data:{events:e.accountData}};try{yield this.processSyncResponse(i,n)}catch(e){f.logger.error("Error processing cached sync",e)}this.storeIsInvalid||this.updateSyncState(T.Prepared,i)}))}doSync(e){return s(this,void 0,void 0,(function*(){for(;this.running;){const t=this.client.store.getSyncToken();let i;try{this.currentSyncRequest||(this.currentSyncRequest=this.doSyncRequest(e,t)),i=yield this.currentSyncRequest}catch(e){if(yield this.onSyncError(e))return;continue}finally{this.currentSyncRequest=void 0}this.client.store.setSyncToken(i.next_batch),this.failedSyncCount=0,yield this.client.store.setSyncData(i);const n={oldSyncToken:null!=t?t:void 0,nextSyncToken:i.next_batch,catchingUp:this.catchingUp};this.syncOpts.crypto&&(yield this.syncOpts.crypto.onSyncWillProcess(n));try{yield this.processSyncResponse(n,i)}catch(e){f.logger.error("Caught /sync error",e),this.client.emit(g.ClientEvent.SyncUnexpectedError,e)}n.catchingUp=this.catchingUp,e.hasSyncedBefore||(this.updateSyncState(T.Prepared,n),e.hasSyncedBefore=!0),this.syncOpts.cryptoCallbacks&&(yield this.syncOpts.cryptoCallbacks.onSyncCompleted(n)),this.updateSyncState(T.Syncing,n),this.client.store.wantsSave()&&(this.syncOpts.crypto&&(yield this.syncOpts.crypto.saveDeviceList(0)),this.client.store.save())}this.running||(M("Sync no longer running: exiting."),this.connectionReturnedDefer&&(this.connectionReturnedDefer.reject(),this.connectionReturnedDefer=void 0),this.updateSyncState(T.Stopped))}))}doSyncRequest(e,t){var i;const n=this.getSyncParams(e,t);return this.client.http.authedRequest(v.Method.Get,"/sync",n,void 0,{localTimeoutMs:n.timeout+8e4,abortSignal:null===(i=this.abortController)||void 0===i?void 0:i.signal})}getSyncParams(e,t){let i=this.opts.pollTimeout;(this.getSyncState()!==T.Syncing||this.catchingUp)&&(this.catchingUp=!0,i=0);let n=e.filter;this.client.isGuest()&&!n&&(n=this.getGuestFilter());const r={filter:n,timeout:i};return this.opts.disablePresence&&(r.set_presence=k.Offline),t?r.since=t:r._cacheBuster=Date.now(),[T.Reconnecting,T.Error].includes(this.getSyncState())&&(r.timeout=0),r}onSyncError(e){return s(this,void 0,void 0,(function*(){if(!this.running)return M("Sync no longer running: exiting"),this.connectionReturnedDefer&&(this.connectionReturnedDefer.reject(),this.connectionReturnedDefer=void 0),this.updateSyncState(T.Stopped),!0;if(f.logger.error("/sync error %s",e),this.shouldAbortSync(e))return!0;this.failedSyncCount++,f.logger.log("Number of consecutive failed sync requests:",this.failedSyncCount),M("Starting keep-alive");const t=this.startKeepAlives();this.currentSyncRequest=void 0,this.updateSyncState(this.failedSyncCount>=3?T.Error:T.Reconnecting,{error:e});return(yield t)&&this.getSyncState()===T.Error&&this.updateSyncState(T.Catchup,{catchingUp:!0}),!1}))}processSyncResponse(e,t){var i,n,r,o;return s(this,void 0,void 0,(function*(){const a=this.client;if(Array.isArray(null===(i=t.presence)||void 0===i?void 0:i.events)&&t.presence.events.filter(l.noUnsafeEventProps).map(a.getEventMapper()).forEach((function(e){let t=a.store.getUser(e.getSender());t?t.setPresenceEvent(e):(t=A(a,e.getSender()),t.setPresenceEvent(e),a.store.storeUser(t)),a.emit(g.ClientEvent.Event,e)})),Array.isArray(null===(n=t.account_data)||void 0===n?void 0:n.events)){const e=t.account_data.events.filter(l.noUnsafeEventProps).map(a.getEventMapper()),i=e.reduce(((e,t)=>(e[t.getType()]=a.store.getAccountData(t.getType()),e)),{});a.store.storeAccountDataEvents(e),e.forEach((function(e){if(e.getType()===m.EventType.PushRules){const t=e.getContent();a.setPushRules(t)}const t=i[e.getType()];return a.emit(g.ClientEvent.AccountData,e,t),e}))}if(t.to_device&&Array.isArray(t.to_device.events)&&t.to_device.events.length>0){let e=t.to_device.events.filter(l.noUnsafeEventProps);this.syncOpts.cryptoCallbacks&&(e=yield this.syncOpts.cryptoCallbacks.preprocessToDeviceMessages(e));const i=[];e.map(a.getEventMapper({toDevice:!0})).map((e=>{if("m.key.verification.cancel"===e.getType()){const t=e.getContent().transaction_id;t&&i.push(t)}return e})).forEach((function(e){const t=e.getContent();if("m.room.message"!=e.getType()||"m.bad.encrypted"!=t.msgtype){if("m.key.verification.start"===e.getType()||"m.key.verification.request"===e.getType()){const n=t.transaction_id;i.includes(n)&&e.flagCancelled()}a.emit(g.ClientEvent.ToDeviceEvent,e)}else f.logger.log("Ignoring undecryptable to-device event from "+e.getSender())}))}else this.catchingUp=!1;let u=[],p=[],v=[];if(t.rooms&&(t.rooms.invite&&(u=this.mapSyncResponseToRoomArray(t.rooms.invite)),t.rooms.join&&(p=this.mapSyncResponseToRoomArray(t.rooms.join)),t.rooms.leave&&(v=this.mapSyncResponseToRoomArray(t.rooms.leave))),this.notifEvents=[],yield d.promiseMapSeries(u,(e=>s(this,void 0,void 0,(function*(){var t;const i=e.room,n=this.mapSyncEventsFormat(e.invite_state,i);yield this.injectRoomEvents(i,n);const r=null===(t=i.currentState.getStateEvents(m.EventType.RoomMember,a.getUserId()))||void 0===t?void 0:t.getSender(),o=a.crypto;if(o){const e=yield o.cryptoStore.takeParkedSharedHistory(i.roomId);for(const t of e)t.senderId===r&&(yield o.olmDevice.addInboundGroupSession(i.roomId,t.senderKey,t.forwardingCurve25519KeyChain,t.sessionId,t.sessionKey,t.keysClaimed,!0,{sharedHistory:!0,untrusted:!0}))}e.isBrandNewRoom?(i.recalculate(),a.store.storeRoom(i),a.emit(g.ClientEvent.Room,i)):i.recalculate(),n.forEach((function(e){a.emit(g.ClientEvent.Event,e)}))})))),yield d.promiseMapSeries(p,(t=>s(this,void 0,void 0,(function*(){var i,n,r,o,s,d;const l=t.room,u=this.mapSyncEventsFormat(t.state,l),p=this.mapSyncEventsFormat(t.timeline,l,!1),v=this.mapSyncEventsFormat(t.ephemeral),y=this.mapSyncEventsFormat(t.account_data),b=a.isRoomEncrypted(l.roomId);t.unread_notifications&&(b&&0!==t.unread_notifications.notification_count||l.setUnreadNotificationCount(c.NotificationCountType.Total,null!==(i=t.unread_notifications.notification_count)&&void 0!==i?i:0),(!b||l.getUnreadNotificationCount(c.NotificationCountType.Highlight)<=0)&&l.setUnreadNotificationCount(c.NotificationCountType.Highlight,null!==(n=t.unread_notifications.highlight_count)&&void 0!==n?n:0));const S=null!==(r=t[_.UNREAD_THREAD_NOTIFICATIONS.name])&&void 0!==r?r:t[_.UNREAD_THREAD_NOTIFICATIONS.altName];if(S){l.resetThreadUnreadNotificationCount(Object.keys(S));for(const[e,t]of Object.entries(S)){b&&0!==t.notification_count||l.setThreadUnreadNotificationCount(e,c.NotificationCountType.Total,null!==(o=t.notification_count)&&void 0!==o?o:0);const i=l.getThreadUnreadNotificationCount(e,c.NotificationCountType.Highlight)<=0;(!b||b&&i)&&l.setThreadUnreadNotificationCount(e,c.NotificationCountType.Highlight,null!==(s=t.highlight_count)&&void 0!==s?s:0)}}else l.resetThreadUnreadNotificationCount();if(t.timeline=t.timeline||{},t.isBrandNewRoom)null!==t.timeline.prev_batch&&l.getLiveTimeline().setPaginationToken(t.timeline.prev_batch,h.EventTimeline.BACKWARDS);else if(t.timeline.limited){let i=!0;for(let e=p.length-1;e>=0;e--){const t=p[e].getId();if(l.getTimelineForEvent(t)){M(`Already have event ${t} in limited sync - not resetting`),i=!1,p.splice(0,e);break}}i&&(l.resetLiveTimeline(t.timeline.prev_batch,this.syncOpts.canResetEntireTimeline(l.roomId)?null:null!==(d=e.oldSyncToken)&&void 0!==d?d:null),a.resetNotifTimelineSet())}if(this.syncOpts.cryptoCallbacks)for(const e of u.concat(p))e.isState()&&e.getType()===m.EventType.RoomEncryption&&""===e.getStateKey()&&(yield this.syncOpts.cryptoCallbacks.onCryptoEvent(l,e));try{yield this.injectRoomEvents(l,u,p,e.fromCache)}catch(e){f.logger.error(`Failed to process events on room ${l.roomId}:`,e)}t.summary&&l.setSummary(t.summary),l.addEphemeralEvents(v),l.addAccountData(y),l.recalculate(),t.isBrandNewRoom&&(a.store.storeRoom(l),a.emit(g.ClientEvent.Room,l)),this.processEventsForNotifs(l,p);const E=e=>a.emit(g.ClientEvent.Event,e);u.forEach(E),p.forEach(E),v.forEach(E),y.forEach(E),l.decryptCriticalEvents()})))),yield d.promiseMapSeries(v,(e=>s(this,void 0,void 0,(function*(){const t=e.room,i=this.mapSyncEventsFormat(e.state,t),n=this.mapSyncEventsFormat(e.timeline,t),r=this.mapSyncEventsFormat(e.account_data);yield this.injectRoomEvents(t,i,n),t.addAccountData(r),t.recalculate(),e.isBrandNewRoom&&(a.store.storeRoom(t),a.emit(g.ClientEvent.Room,t)),this.processEventsForNotifs(t,n),i.forEach((function(e){a.emit(g.ClientEvent.Event,e)})),n.forEach((function(e){a.emit(g.ClientEvent.Event,e)})),r.forEach((function(e){a.emit(g.ClientEvent.Event,e)}))})))),e.oldSyncToken&&this.notifEvents.length&&(this.notifEvents.sort((function(e,t){return e.getTs()-t.getTs()})),this.notifEvents.forEach((function(e){var t;null===(t=a.getNotifTimelineSet())||void 0===t||t.addLiveEvent(e)}))),t.device_lists&&this.syncOpts.crypto&&(yield this.syncOpts.crypto.handleDeviceListChanges(e,t.device_lists)),t.device_one_time_keys_count){const e=new Map(Object.entries(t.device_one_time_keys_count));null===(r=this.syncOpts.cryptoCallbacks)||void 0===r||r.preprocessOneTimeKeyCounts(e)}if(t.device_unused_fallback_key_types||t["org.matrix.msc2732.device_unused_fallback_key_types"]){const e=t.device_unused_fallback_key_types||t["org.matrix.msc2732.device_unused_fallback_key_types"];null===(o=this.syncOpts.cryptoCallbacks)||void 0===o||o.preprocessUnusedFallbackKeys(new Set(e||null))}}))}startKeepAlives(e){return void 0===e&&(e=2e3+Math.floor(5e3*Math.random())),null!==this.keepAliveTimer&&clearTimeout(this.keepAliveTimer),e>0?this.keepAliveTimer=setTimeout(this.pokeKeepAlive.bind(this),e):this.pokeKeepAlive(),this.connectionReturnedDefer||(this.connectionReturnedDefer=d.defer()),this.connectionReturnedDefer.promise}pokeKeepAlive(e=!1){var t;const i=()=>{clearTimeout(this.keepAliveTimer),this.connectionReturnedDefer&&(this.connectionReturnedDefer.resolve(e),this.connectionReturnedDefer=void 0)};this.client.http.request(v.Method.Get,"/_matrix/client/versions",void 0,void 0,{prefix:"",localTimeoutMs:15e3,abortSignal:null===(t=this.abortController)||void 0===t?void 0:t.signal}).then((()=>{i()}),(t=>{400==t.httpStatus||404==t.httpStatus?this.keepAliveTimer=setTimeout(i,2e3):(e=!0,this.keepAliveTimer=setTimeout(this.pokeKeepAlive.bind(this,e),5e3+Math.floor(5e3*Math.random())),this.updateSyncState(T.Error,{error:t}))}))}mapSyncResponseToRoomArray(e){const t=this.client;return Object.keys(e).filter((e=>!(0,l.unsafeProp)(e))).map((i=>{const n=e[i];let r=t.store.getRoom(i),o=!1;return r||(r=this.createRoom(i),o=!0),n.room=r,n.isBrandNewRoom=o,n}))}mapSyncEventsFormat(e,t,i=!0){if(!e||!Array.isArray(e.events))return[];const n=this.client.getEventMapper({decrypt:i});return e.events.filter(l.noUnsafeEventProps).map((function(e){return t&&(e.room_id=t.roomId),n(e)}))}resolveInvites(e){if(!e||!this.opts.resolveInvitesToProfiles)return;const t=this.client;e.getMembersWithMembership("invite").forEach((function(i){if(i.requestedProfileInfo)return;i.requestedProfileInfo=!0;const n=t.getUser(i.userId);let r;r=n?Promise.resolve({avatar_url:n.avatarUrl,displayname:n.displayName}):t.getProfileInfo(i.userId),r.then((function(t){const n=i.events.member;"invite"===(null==n?void 0:n.getContent().membership)&&(n.getContent().avatar_url=t.avatar_url,n.getContent().displayname=t.displayname,i.setMembershipEvent(n,e.currentState))}),(function(e){}))}))}injectRoomEvents(e,t,i,n=!1){return s(this,void 0,void 0,(function*(){const r=e.getLiveTimeline(),o=0==r.getEvents().length;if(o){for(const e of t)this.client.getPushActionsForEvent(e);r.initialiseState(t,{timelineWasEmpty:o})}this.resolveInvites(e),e.recalculate(),o||(e.oldState.setStateEvents(t||[]),e.currentState.setStateEvents(t||[])),e.addLiveEvents(i||[],{fromCache:n,timelineWasEmpty:o}),this.client.processBeaconEvents(e,i)}))}processEventsForNotifs(e,t){var i;if(this.client.getNotifTimelineSet())for(const e of t){const t=this.client.getPushActionsForEvent(e);(null==t?void 0:t.notify)&&(null===(i=t.tweaks)||void 0===i?void 0:i.highlight)&&this.notifEvents.push(e)}}getGuestFilter(){return"{}"}updateSyncState(e,t){const i=this.syncState;this.syncState=e,this.syncStateData=t,this.client.emit(g.ClientEvent.Sync,this.syncState,i,t)}},i._createAndReEmitRoom=P}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./@types/event":306,"./@types/sync":314,"./client":321,"./errors":359,"./feature":362,"./filter":364,"./http-api":367,"./logger":374,"./models/beacon":378,"./models/event-timeline":382,"./models/room":392,"./models/room-member":389,"./models/room-state":390,"./models/user":396,"./utils":416}],415:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.TimelineIndex=i.TimelineWindow=void 0;const r=e("./models/event-timeline"),o=(e("./logger"),function(){});i.TimelineWindow=class{constructor(e,t,i={}){this.client=e,this.timelineSet=t,this.eventCount=0,this.windowLimit=i.windowLimit||1e3}load(e,t=20){const i=i=>{if(!i)throw new Error("No timeline given to initFields");let n;const r=i.getEvents();if(e){if(n=r.findIndex((t=>t.getId()===e)),n<0)throw new Error("getEventTimeline result didn't include requested event")}else n=r.length;const o=Math.min(r.length,n+Math.ceil(t/2)),a=Math.max(0,o-t);this.start=new s(i,a-i.getBaseIndex()),this.end=new s(i,o-i.getBaseIndex()),this.eventCount=o-a};return this.timelineSet.getTimelineForEvent(e)?(i(this.timelineSet.getTimelineForEvent(e)),Promise.resolve()):e?this.client.getEventTimeline(this.timelineSet,e).then(i):(i(this.timelineSet.getLiveTimeline()),Promise.resolve())}getTimelineIndex(e){var t,i;if(e==r.EventTimeline.BACKWARDS)return null!==(t=this.start)&&void 0!==t?t:null;if(e==r.EventTimeline.FORWARDS)return null!==(i=this.end)&&void 0!==i?i:null;throw new Error("Invalid direction '"+e+"'")}extend(e,t){const i=this.getTimelineIndex(e);if(!i)return o("TimelineWindow: no timeline yet"),!1;const n=e==r.EventTimeline.BACKWARDS?i.retreat(t):i.advance(t);if(n){this.eventCount+=n,o("TimelineWindow: increased cap by "+n+" (now "+this.eventCount+")");const t=this.eventCount-this.windowLimit;return t>0&&this.unpaginate(t,e!=r.EventTimeline.BACKWARDS),!0}return!1}canPaginate(e){const t=this.getTimelineIndex(e);if(!t)return o("TimelineWindow: no timeline yet"),!1;if(e==r.EventTimeline.BACKWARDS){if(t.index>t.minIndex())return!0}else if(t.index(o("TimelineWindow: request completed with result "+i),i?this.paginate(e,t,!0,s-1):this.paginate(e,t,!1,0))));return n.pendingPaginate=a,a}))}unpaginate(e,t){const i=t?this.start:this.end;if(!i)throw new Error(`Attempting to unpaginate startOfTimeline=${t} but don't have this direction`);if(e>this.eventCount||e<0)throw new Error(`Attemting to unpaginate ${e} events, but only have ${this.eventCount} in the timeline`);for(;e>0;){const n=t?i.advance(e):i.retreat(e);if(n<=0)throw new Error("Unable to unpaginate any further, but still have "+this.eventCount+" events");e-=n,this.eventCount-=n,o("TimelineWindow.unpaginate: dropped "+n+" (now "+this.eventCount+")")}}getEvents(){var e,t;if(!this.start)return[];const i=[];let n=this.start.timeline;for(;;){const o=n.getEvents();let s=0,a=o.length;n===this.start.timeline&&(s=this.start.index+n.getBaseIndex()),n===(null===(e=this.end)||void 0===e?void 0:e.timeline)&&(a=this.end.index+n.getBaseIndex());for(let e=s;e0)return this.index+=t,t;const i=this.timeline.getNeighbouringTimeline(e<0?r.EventTimeline.BACKWARDS:r.EventTimeline.FORWARDS);return i?(this.timeline=i,this.index=e<0?this.maxIndex():this.minIndex(),o("paginate: switched to new neighbour"),this.advance(e)):0}retreat(e){return-1*this.advance(-1*e)}}i.TimelineIndex=s},{"./logger":374,"./models/event-timeline":382}],416:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))},r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(i,"__esModule",{value:!0}),i.MapWithDefault=i.noUnsafeEventProps=i.safeSet=i.unsafeProp=i.recursiveMapToObject=i.mapsEqual=i.isSupportedReceiptType=i.sortEventsByLatestContentTimestamp=i.recursivelyAssign=i.compare=i.lexicographicCompare=i.prevString=i.nextString=i.averageBetweenStrings=i.stringToBase=i.baseToString=i.alphabetPad=i.DEFAULT_ALPHABET=i.simpleRetryOperation=i.chunkPromises=i.promiseTry=i.promiseMapSeries=i.defer=i.isNullOrUndefined=i.immediate=i.sleep=i.ensureNoTrailingSlash=i.globToRegexp=i.escapeRegExp=i.normalize=i.removeDirectionOverrideChars=i.removeHiddenChars=i.isNumber=i.deepSortedObjectEntries=i.deepCompare=i.deepCopy=i.checkObjectHasKeys=i.isFunction=i.removeElement=i.encodeUri=i.decodeParams=i.replaceParam=i.encodeParams=i.internaliseString=void 0;const o=r(e("unhomoglyph")),s=r(e("p-retry")),a=e("./@types/location"),c=e("./@types/read_receipts"),d=new Map;function l(e){return"string"==typeof e?(0,o.default)(e.normalize("NFD").replace(u,"")):""}i.internaliseString=function(e){return e instanceof String&&(e=e.toString()),d.has(e)||d.set(e,e),d.get(e)},i.encodeParams=function(e,t){const i=null!=t?t:new URLSearchParams;for(const[t,n]of Object.entries(e))null!=n&&(Array.isArray(n)?n.forEach((e=>{i.append(t,String(e))})):i.append(t,String(n)));return i},i.replaceParam=function(e,t,i){const n=Object.assign(Object.assign({},i),{[t]:i[e]});return delete n[e],n},i.decodeParams=function(e){const t={},i=new URLSearchParams(e);for(const e of i.keys()){const n=i.getAll(e);t[e]=1===n.length?n[0]:n}return t},i.encodeUri=function(e,t){for(const i in t){if(!t.hasOwnProperty(i))continue;const n=t[i];null!=n&&(e=e.replace(i,encodeURIComponent(n)))}return e},i.removeElement=function(e,t,i){let n;if(i){for(n=e.length-1;n>=0;n--)if(t(e[n],n,e))return e.splice(n,1),!0}else for(n=0;nv(e[0],t[0]))),i},i.isNumber=function(e){return"number"==typeof e&&isFinite(e)},i.removeHiddenChars=l,i.removeDirectionOverrideChars=function(e){return"string"==typeof e?e.replace(/[\u202d-\u202e]/g,""):""},i.normalize=function(e){return l(e.toLowerCase()).replace(/[\\'!"#$%&()*+,\-./:;<=>?@[\]^_`{|}~\u2000-\u206f\u2e00-\u2e7f]/g,"").toLowerCase()};const u=/[\u2000-\u200F\u202A-\u202F\u0300-\u036F\uFEFF\u061C\u2800\u2062-\u2063\s]/g;function h(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function f(e,t,n=i.DEFAULT_ALPHABET){return e.padEnd(t,n[0])}function p(e,t=i.DEFAULT_ALPHABET){var n;const r=BigInt(t.length);if(e<=r)return null!==(n=t[Number(e)-1])&&void 0!==n?n:"";let o=e/r,s=Number(e%r)-1;return s<0&&(o-=BigInt(Math.abs(s)),s=Number(r)-1),p(o,t)+t[s]}function g(e,t=i.DEFAULT_ALPHABET){const n=BigInt(t.length);let r=BigInt(0);for(let i=e.length-1,o=BigInt(0);i>=0;i--,o++){const s=e.charCodeAt(i)-t.charCodeAt(0);r+=BigInt(1+s)*n**o}return r}function v(e,t){return et?1:0}i.escapeRegExp=h,i.globToRegexp=function(e,t=!1){const i=[[/\\\*/g,".*"],[/\?/g,"."]];return t||i.push([/\\\[(!|)(.*)\\]/g,(e,t,i)=>["[",t?"^":"",i.replace(/\\-/,"-"),"]"].join("")]),i.reduce(((e,t)=>t?e.replace(t[0],t[1]):e),h(e))},i.ensureNoTrailingSlash=function(e){return(null==e?void 0:e.endsWith("/"))?e.slice(0,-1):e},i.sleep=function(e,t){return new Promise((i=>{setTimeout(i,e,t)}))},i.immediate=function(){return new Promise(t)},i.isNullOrUndefined=function(e){return null==e},i.defer=function(){let e,t;const i=new Promise(((i,n)=>{e=i,t=n}));return{resolve:e,reject:t,promise:i}},i.promiseMapSeries=function(e,t){return n(this,void 0,void 0,(function*(){for(const i of e)yield t(yield i)}))},i.promiseTry=function(e){return Promise.resolve(e())},i.chunkPromises=function(e,t){return n(this,void 0,void 0,(function*(){const i=[];for(let n=0;ne()))));return i}))},i.simpleRetryOperation=function(e){return(0,s.default)((t=>e(t)),{forever:!0,factor:2,minTimeout:3e3,maxTimeout:15e3})},i.DEFAULT_ALPHABET=(()=>{let e="";for(let t=32;t<=126;t++)e+=String.fromCharCode(t);return e})(),i.alphabetPad=f,i.baseToString=p,i.stringToBase=g,i.averageBetweenStrings=function(e,t,n=i.DEFAULT_ALPHABET){const r=Math.max(e.length,t.length),o=g(f(e,r,n),n),s=g(f(t,r,n),n),a=(o+s)/BigInt(2);return a===o||a==s?p(a,n)+n[0]:p(a,n)},i.nextString=function(e,t=i.DEFAULT_ALPHABET){return p(g(e,t)+BigInt(1),t)},i.prevString=function(e,t=i.DEFAULT_ALPHABET){return p(g(e,t)-BigInt(1),t)},i.lexicographicCompare=v;const m=new Intl.Collator;function y(e){var t;return null!==(t=a.M_TIMESTAMP.findIn(e.getContent()))&&void 0!==t?t:-1}function b(e){return e instanceof Map?S(e):Array.isArray(e)?e.map((e=>b(e))):e}function S(e){const t=new Map;for(const[i,n]of e)t.set(i,b(n));return Object.fromEntries(t.entries())}function _(e){return"__proto__"===e||"prototype"===e||"constructor"===e}i.compare=function(e,t){return m.compare(e,t)},i.recursivelyAssign=function e(t,i,n=!1){for(const[r,o]of Object.entries(i))t[r]instanceof Object&&o?e(t[r],o):null==o&&n||(t[r]=o);return t},i.sortEventsByLatestContentTimestamp=function(e,t){return y(t)-y(e)},i.isSupportedReceiptType=function(e){return[c.ReceiptType.Read,c.ReceiptType.ReadPrivate].includes(e)},i.mapsEqual=function(e,t,i=((e,t)=>e===t)){if(e.size!==t.size)return!1;for(const[n,r]of e){const e=t.get(n);if(void 0===e||!i(r,e))return!1}return!0},i.recursiveMapToObject=S,i.unsafeProp=_,i.safeSet=function(e,t,i){if(_(t))throw new Error("Trying to modify prototype or constructor");e[t]=i},i.noUnsafeEventProps=function(e){return!(_(e.room_id)||_(e.sender)||_(e.user_id)||_(e.event_id))};class E extends Map{constructor(e){super(),this.createDefault=e}getOrCreate(e){return this.has(e)||this.set(e,this.createDefault()),this.get(e)}}i.MapWithDefault=E}).call(this)}).call(this,e("timers").setImmediate)},{"./@types/location":308,"./@types/read_receipts":311,"p-retry":225,timers:280,unhomoglyph:282}],417:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.releaseContext=i.acquireContext=void 0;let n=null,r=0;i.acquireContext=()=>(null===n&&(n=new AudioContext),r++,n);i.releaseContext=()=>{r--,0===r&&(null==n||n.close(),n=null)}},{}],418:[function(e,t,i){(function(t){(function(){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)"default"!==i&&Object.prototype.hasOwnProperty.call(e,i)&&n(t,e,i);return r(t,e),t},s=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.createNewMatrixCall=i.supportsMatrixCall=i.setTracksEnabled=i.MatrixCall=i.genCallID=i.CallError=i.CallErrorCode=i.CallEvent=i.CallParty=i.CallDirection=i.CallType=i.CallState=void 0;const a=e("uuid"),c=e("sdp-transform"),d=e("../logger"),l=o(e("../utils")),u=e("../@types/event"),h=e("../randomstring"),f=e("./callEventTypes"),p=e("./callFeed"),g=e("../models/typed-event-emitter"),v=e("../crypto/deviceinfo"),m=e("./groupCall"),y=e("../http-api");var b,S,_,E,w,T,I,R;!function(e){e.AUDIO="audio",e.VIDEO="video"}(b||(b={})),function(e){e.OPUS="opus"}(S||(S={})),function(e){e.Fledgling="fledgling",e.InviteSent="invite_sent",e.WaitLocalMedia="wait_local_media",e.CreateOffer="create_offer",e.CreateAnswer="create_answer",e.Connecting="connecting",e.Connected="connected",e.Ringing="ringing",e.Ended="ended"}(_=i.CallState||(i.CallState={})),function(e){e.Voice="voice",e.Video="video"}(E=i.CallType||(i.CallType={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(w=i.CallDirection||(i.CallDirection={})),function(e){e.Local="local",e.Remote="remote"}(T=i.CallParty||(i.CallParty={})),function(e){e.Hangup="hangup",e.State="state",e.Error="error",e.Replaced="replaced",e.LocalHoldUnhold="local_hold_unhold",e.RemoteHoldUnhold="remote_hold_unhold",e.HoldUnhold="hold_unhold",e.FeedsChanged="feeds_changed",e.AssertedIdentityChanged="asserted_identity_changed",e.LengthChanged="length_changed",e.DataChannel="datachannel",e.SendVoipEvent="send_voip_event"}(I=i.CallEvent||(i.CallEvent={})),function(e){e.UserHangup="user_hangup",e.LocalOfferFailed="local_offer_failed",e.NoUserMedia="no_user_media",e.UnknownDevices="unknown_devices",e.SendInvite="send_invite",e.CreateAnswer="create_answer",e.CreateOffer="create_offer",e.SendAnswer="send_answer",e.SetRemoteDescription="set_remote_description",e.SetLocalDescription="set_local_description",e.AnsweredElsewhere="answered_elsewhere",e.IceFailed="ice_failed",e.InviteTimeout="invite_timeout",e.Replaced="replaced",e.SignallingFailed="signalling_timeout",e.UserBusy="user_busy",e.Transferred="transferred",e.NewSession="new_session"}(R=i.CallErrorCode||(i.CallErrorCode={}));class M extends Error{constructor(e,t,i){super(t+": "+i),this.code=e}}function k(){return Date.now().toString()+(0,h.randomString)(16)}function C(e){return[{mediaType:"audio",codec:"opus",enableDtx:!0,maxAverageBitrate:e?12e3:void 0}]}function O(e,t){return e+":"+t}i.CallError=M,i.genCallID=k;class A extends g.TypedEventEmitter{constructor(e){var t;if(super(),this.toDeviceSeq=0,this.isPtt=!1,this._state=_.Fledgling,this.candidateSendQueue=[],this.candidateSendTries=0,this.candidatesEnded=!1,this.feeds=[],this.transceivers=new Map,this.inviteOrAnswerSent=!1,this.waitForLocalAVStream=!1,this.removeTrackListeners=new Map,this.remoteOnHold=!1,this.makingOffer=!1,this.ignoreOffer=!1,this.remoteCandidateBuffer=new Map,this.gotLocalIceCandidate=e=>{if(e.candidate){if(this.candidatesEnded)return void d.logger.warn(`Call ${this.callId} gotLocalIceCandidate() got candidate after candidates have ended - ignoring!`);if(d.logger.debug(`Call ${this.callId} got local ICE ${e.candidate.sdpMid} ${e.candidate.candidate}`),this.callHasEnded())return;""===e.candidate.candidate?this.queueCandidate(null):this.queueCandidate(e.candidate)}},this.onIceGatheringStateChange=e=>{var t;d.logger.debug(`Call ${this.callId} onIceGatheringStateChange() ice gathering state changed to ${this.peerConn.iceGatheringState}`),"complete"===(null===(t=this.peerConn)||void 0===t?void 0:t.iceGatheringState)&&this.queueCandidate(null)},this.getLocalOfferFailed=e=>{d.logger.error(`Call ${this.callId} getLocalOfferFailed() running`,e),this.emit(I.Error,new M(R.LocalOfferFailed,"Failed to get local offer!",e),this),this.terminate(T.Local,R.LocalOfferFailed,!1)},this.getUserMediaFailed=e=>{this.successor?this.successor.getUserMediaFailed(e):(d.logger.warn(`Call ${this.callId} getUserMediaFailed() failed to get user media - ending call`,e),this.emit(I.Error,new M(R.NoUserMedia,"Couldn't start capturing media! Is your microphone set up and does this app have permission?",e),this),this.terminate(T.Local,R.NoUserMedia,!1))},this.onIceConnectionStateChanged=()=>{var e,t,i,n,r,o;if(!this.callHasEnded()&&(d.logger.debug(`Call ${this.callId} onIceConnectionStateChanged() running (state=${null===(e=this.peerConn)||void 0===e?void 0:e.iceConnectionState})`),["connected","completed"].includes(null!==(i=null===(t=this.peerConn)||void 0===t?void 0:t.iceConnectionState)&&void 0!==i?i:"")?(clearTimeout(this.iceDisconnectedTimeout),this.iceDisconnectedTimeout=void 0,this.state=_.Connected,this.callLengthInterval||this.callStartTime||(this.callStartTime=Date.now(),this.callLengthInterval=setInterval((()=>{this.emit(I.LengthChanged,Math.round((Date.now()-this.callStartTime)/1e3),this)}),1e3))):"failed"==(null===(n=this.peerConn)||void 0===n?void 0:n.iceConnectionState)?(null===(r=this.peerConn)||void 0===r?void 0:r.restartIce)?(this.candidatesEnded=!1,this.peerConn.restartIce()):(d.logger.info(`Call ${this.callId} onIceConnectionStateChanged() hanging up call (ICE failed and no ICE restart method)`),this.hangup(R.IceFailed,!1)):"disconnected"==(null===(o=this.peerConn)||void 0===o?void 0:o.iceConnectionState)&&(this.iceDisconnectedTimeout=setTimeout((()=>{d.logger.info(`Call ${this.callId} onIceConnectionStateChanged() hanging up call (ICE disconnected for too long)`),this.hangup(R.IceFailed,!1)}),3e4),this.state=_.Connecting),this.isPtt&&["failed","disconnected"].includes(this.peerConn.iceConnectionState)))for(const e of this.getRemoteFeeds())e.setAudioVideoMuted(!0,!0)},this.onSignallingStateChanged=()=>{var e;d.logger.debug(`Call ${this.callId} onSignallingStateChanged() running (state=${null===(e=this.peerConn)||void 0===e?void 0:e.signalingState})`)},this.onTrack=e=>{if(0===e.streams.length)return void d.logger.warn(`Call ${this.callId} onTrack() called with streamless track streamless (kind=${e.track.kind})`);const t=e.streams[0];if(this.pushRemoteFeed(t),!this.removeTrackListeners.has(t)){const e=()=>{0===t.getTracks().length&&(d.logger.info(`Call ${this.callId} onTrack() removing track (streamId=${t.id})`),this.deleteFeedByStream(t),t.removeEventListener("removetrack",e),this.removeTrackListeners.delete(t))};t.addEventListener("removetrack",e),this.removeTrackListeners.set(t,e)}},this.onDataChannel=e=>{this.emit(I.DataChannel,e.channel,this)},this.onNegotiationNeeded=()=>s(this,void 0,void 0,(function*(){d.logger.info(`Call ${this.callId} onNegotiationNeeded() negotiation is needed!`),this.state===_.CreateOffer||0!==this.opponentVersion?this.queueGotLocalOffer():d.logger.info(`Call ${this.callId} onNegotiationNeeded() opponent does not support renegotiation: ignoring negotiationneeded event`)})),this.onHangupReceived=e=>{d.logger.debug(`Call ${this.callId} onHangupReceived() running`),this.partyIdMatches(e)||this.state===_.Ringing?this.terminate(T.Remote,e.reason||R.UserHangup,!0):d.logger.info(`Call ${this.callId} onHangupReceived() ignoring message from party ID ${e.party_id}: our partner is ${this.opponentPartyId}`)},this.onRejectReceived=e=>{d.logger.debug(`Call ${this.callId} onRejectReceived() running`);[_.InviteSent,_.Ringing].includes(this.state)||this.state===_.Fledgling&&this.direction===w.Inbound?this.terminate(T.Remote,e.reason||R.UserHangup,!0):d.logger.debug(`Call ${this.callId} onRejectReceived() called in wrong state (state=${this.state})`)},this.onAnsweredElsewhere=e=>{d.logger.debug(`Call ${this.callId} onAnsweredElsewhere() running`),this.terminate(T.Remote,R.AnsweredElsewhere,!0)},this.roomId=e.roomId,this.invitee=e.invitee,this.client=e.client,!this.client.deviceId)throw new Error("Client must have a device ID to start calls");this.forceTURN=null!==(t=e.forceTURN)&&void 0!==t&&t,this.ourPartyId=this.client.deviceId,this.opponentDeviceId=e.opponentDeviceId,this.opponentSessionId=e.opponentSessionId,this.groupCallId=e.groupCallId,this.turnServers=e.turnServers||[],0===this.turnServers.length&&this.client.isFallbackICEServerAllowed()&&this.turnServers.push({urls:["stun:turn.matrix.org"]});for(const e of this.turnServers)l.checkObjectHasKeys(e,["urls"]);this.callId=k(),this.isOnlyDataChannelAllowed=this.client.isVoipWithNoMediaAllowed}placeVoiceCall(){return s(this,void 0,void 0,(function*(){yield this.placeCall(!0,!1)}))}placeVideoCall(){return s(this,void 0,void 0,(function*(){yield this.placeCall(!0,!0)}))}createDataChannel(e,t){const i=this.peerConn.createDataChannel(e,t);return this.emit(I.DataChannel,i,this),i}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(e){const t=this._state;this._state=e,this.emit(I.State,e,t,this)}get type(){return this.hasUserMediaVideoSender||this.hasRemoteUserMediaVideoTrack?E.Video:E.Voice}get hasLocalUserMediaVideoTrack(){var e;return!!(null===(e=this.localUsermediaStream)||void 0===e?void 0:e.getVideoTracks().length)}get hasRemoteUserMediaVideoTrack(){return this.getRemoteFeeds().some((e=>{var t;return e.purpose===f.SDPStreamMetadataPurpose.Usermedia&&(null===(t=e.stream)||void 0===t?void 0:t.getVideoTracks().length)}))}get hasLocalUserMediaAudioTrack(){var e;return!!(null===(e=this.localUsermediaStream)||void 0===e?void 0:e.getAudioTracks().length)}get hasRemoteUserMediaAudioTrack(){return this.getRemoteFeeds().some((e=>{var t;return e.purpose===f.SDPStreamMetadataPurpose.Usermedia&&!!(null===(t=e.stream)||void 0===t?void 0:t.getAudioTracks().length)}))}get hasUserMediaAudioSender(){var e;return Boolean(null===(e=this.transceivers.get(O(f.SDPStreamMetadataPurpose.Usermedia,"audio")))||void 0===e?void 0:e.sender)}get hasUserMediaVideoSender(){var e;return Boolean(null===(e=this.transceivers.get(O(f.SDPStreamMetadataPurpose.Usermedia,"video")))||void 0===e?void 0:e.sender)}get localUsermediaFeed(){return this.getLocalFeeds().find((e=>e.purpose===f.SDPStreamMetadataPurpose.Usermedia))}get localScreensharingFeed(){return this.getLocalFeeds().find((e=>e.purpose===f.SDPStreamMetadataPurpose.Screenshare))}get localUsermediaStream(){var e;return null===(e=this.localUsermediaFeed)||void 0===e?void 0:e.stream}get localScreensharingStream(){var e;return null===(e=this.localScreensharingFeed)||void 0===e?void 0:e.stream}get remoteUsermediaFeed(){return this.getRemoteFeeds().find((e=>e.purpose===f.SDPStreamMetadataPurpose.Usermedia))}get remoteScreensharingFeed(){return this.getRemoteFeeds().find((e=>e.purpose===f.SDPStreamMetadataPurpose.Screenshare))}get remoteUsermediaStream(){var e;return null===(e=this.remoteUsermediaFeed)||void 0===e?void 0:e.stream}get remoteScreensharingStream(){var e;return null===(e=this.remoteScreensharingFeed)||void 0===e?void 0:e.stream}getFeedByStreamId(e){return this.getFeeds().find((t=>t.stream.id===e))}getFeeds(){return this.feeds}getLocalFeeds(){return this.feeds.filter((e=>e.isLocal()))}getRemoteFeeds(){return this.feeds.filter((e=>!e.isLocal()))}initOpponentCrypto(){var e,t;return s(this,void 0,void 0,(function*(){if(!this.opponentDeviceId)return;if(!this.client.getUseE2eForGroupCall())return;if(!this.client.isCryptoEnabled())return void(this.opponentDeviceInfo=new v.DeviceInfo(this.opponentDeviceId));if(!this.client.crypto)throw new Error("Crypto is not initialised.");const i=this.invitee||(null===(e=this.getOpponentMember())||void 0===e?void 0:e.userId);if(!i)throw new Error("Couldn't find opponent user ID to init crypto");const n=yield this.client.crypto.deviceList.downloadKeys([i],!1);if(this.opponentDeviceInfo=null===(t=n.get(i))||void 0===t?void 0:t.get(this.opponentDeviceId),void 0===this.opponentDeviceInfo)throw new m.GroupCallUnknownDeviceError(i)}))}getLocalSDPStreamMetadata(e=!1){const t={};for(const i of this.getLocalFeeds())e&&(i.sdpMetadataStreamId=i.stream.id),t[i.sdpMetadataStreamId]={purpose:i.purpose,audio_muted:i.isAudioMuted(),video_muted:i.isVideoMuted()};return t}noIncomingFeeds(){return!this.feeds.some((e=>!e.isLocal()))}pushRemoteFeed(e){if(!this.opponentSupportsSDPStreamMetadata())return void this.pushRemoteFeedWithoutMetadata(e);const t=this.getOpponentMember().userId,i=this.remoteSDPStreamMetadata[e.id].purpose,n=this.remoteSDPStreamMetadata[e.id].audio_muted,r=this.remoteSDPStreamMetadata[e.id].video_muted;i?this.getFeedByStreamId(e.id)?d.logger.warn(`Call ${this.callId} pushRemoteFeed() ignoring stream because we already have a feed for it (streamId=${e.id})`):(this.feeds.push(new p.CallFeed({client:this.client,call:this,roomId:this.roomId,userId:t,deviceId:this.getOpponentDeviceId(),stream:e,purpose:i,audioMuted:n,videoMuted:r})),this.emit(I.FeedsChanged,this.feeds,this),d.logger.info(`Call ${this.callId} pushRemoteFeed() pushed stream (streamId=${e.id}, active=${e.active}, purpose=${i})`)):d.logger.warn(`Call ${this.callId} pushRemoteFeed() ignoring stream because we didn't get any metadata about it (streamId=${e.id})`)}pushRemoteFeedWithoutMetadata(e){var t;const i=this.getOpponentMember().userId,n=f.SDPStreamMetadataPurpose.Usermedia,r=null===(t=this.feeds.find((e=>!e.isLocal())))||void 0===t?void 0:t.stream;r&&e.id!==r.id?d.logger.warn(`Call ${this.callId} pushRemoteFeedWithoutMetadata() ignoring new stream because we already have stream (streamId=${e.id})`):this.getFeedByStreamId(e.id)?d.logger.warn(`Call ${this.callId} pushRemoteFeedWithoutMetadata() ignoring stream because we already have a feed for it (streamId=${e.id})`):(this.feeds.push(new p.CallFeed({client:this.client,call:this,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:i,deviceId:this.getOpponentDeviceId(),stream:e,purpose:n})),this.emit(I.FeedsChanged,this.feeds,this),d.logger.info(`Call ${this.callId} pushRemoteFeedWithoutMetadata() pushed stream (streamId=${e.id}, active=${e.active})`))}pushNewLocalFeed(e,t,i=!0){const n=this.client.getUserId();P(e.getAudioTracks(),!0),P(e.getVideoTracks(),!0),this.getFeedByStreamId(e.id)?d.logger.warn(`Call ${this.callId} pushNewLocalFeed() ignoring stream because we already have a feed for it (streamId=${e.id})`):this.pushLocalFeed(new p.CallFeed({client:this.client,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:n,deviceId:this.getOpponentDeviceId(),stream:e,purpose:t}),i)}pushLocalFeed(e,t=!0){if(this.feeds.some((t=>e.stream.id===t.stream.id)))d.logger.info(`Call ${this.callId} pushLocalFeed() ignoring duplicate local stream (streamId=${e.stream.id})`);else{if(this.feeds.push(e),t)for(const t of e.stream.getTracks()){d.logger.info(`Call ${this.callId} pushLocalFeed() adding track to peer connection (id=${t.id}, kind=${t.kind}, streamId=${e.stream.id}, streamPurpose=${e.purpose}, enabled=${t.enabled})`);const i=O(e.purpose,t.kind);if(this.transceivers.has(i)){const e=this.transceivers.get(i);e.sender.replaceTrack(t),e.direction="inactive"===e.direction?"sendonly":"sendrecv"}else{const n=this.peerConn.addTrack(t,e.stream),r=this.peerConn.getTransceivers().find((e=>e.sender===n));r?this.transceivers.set(i,r):d.logger.warn(`Call ${this.callId} pushLocalFeed() didn't find a matching transceiver after adding track!`)}}d.logger.info(`Call ${this.callId} pushLocalFeed() pushed stream (id=${e.stream.id}, active=${e.stream.active}, purpose=${e.purpose})`),this.emit(I.FeedsChanged,this.feeds,this)}}removeLocalFeed(e){const t=O(e.purpose,"audio"),i=O(e.purpose,"video");for(const e of[t,i])if(this.transceivers.has(e)){const t=this.transceivers.get(e);t.sender&&this.peerConn.removeTrack(t.sender)}e.purpose===f.SDPStreamMetadataPurpose.Screenshare&&this.client.getMediaHandler().stopScreensharingStream(e.stream),this.deleteFeed(e)}deleteAllFeeds(){for(const e of this.feeds)e.isLocal()&&this.groupCallId||e.dispose();this.feeds=[],this.emit(I.FeedsChanged,this.feeds,this)}deleteFeedByStream(e){const t=this.getFeedByStreamId(e.id);t?this.deleteFeed(t):d.logger.warn(`Call ${this.callId} deleteFeedByStream() didn't find the feed to delete (streamId=${e.id})`)}deleteFeed(e){e.dispose(),this.feeds.splice(this.feeds.indexOf(e),1),this.emit(I.FeedsChanged,this.feeds,this)}getCurrentCallStats(){return s(this,void 0,void 0,(function*(){return this.callHasEnded()?this.callStatsAtEnd:this.collectCallStats()}))}collectCallStats(){return s(this,void 0,void 0,(function*(){if(!this.peerConn)return;const e=yield this.peerConn.getStats(),t=[];return e.forEach((e=>{t.push(e)})),t}))}initWithInvite(e){var t;return s(this,void 0,void 0,(function*(){const i=e.getContent();this.direction=w.Inbound;(yield this.client.checkTurnServers())||d.logger.warn(`Call ${this.callId} initWithInvite() failed to get TURN credentials! Proceeding with call anyway...`);const n=i[f.SDPStreamMetadataKey];n?this.updateRemoteSDPStreamMetadata(n):d.logger.debug(`Call ${this.callId} initWithInvite() did not get any SDPStreamMetadata! Can not send/receive multiple streams`),this.peerConn=this.createPeerConnection(),this.chooseOpponent(e),yield this.initOpponentCrypto();try{yield this.peerConn.setRemoteDescription(i.offer),yield this.addBufferedIceCandidates()}catch(e){return d.logger.debug(`Call ${this.callId} initWithInvite() failed to set remote description`,e),void this.terminate(T.Local,R.SetRemoteDescription,!1)}const r=null===(t=this.feeds.find((e=>!e.isLocal())))||void 0===t?void 0:t.stream;if(!(this.isOnlyDataChannelAllowed||r&&0!==r.getTracks().length))return d.logger.error(`Call ${this.callId} initWithInvite() no remote stream or no tracks after setting remote description!`),void this.terminate(T.Local,R.SetRemoteDescription,!1);if(this.state=_.Ringing,e.getLocalAge()){const t=setTimeout((()=>{var e;this.state==_.Ringing&&(d.logger.debug(`Call ${this.callId} initWithInvite() invite has expired. Hanging up.`),this.hangupParty=T.Remote,this.state=_.Ended,this.stopAllMedia(),"closed"!=this.peerConn.signalingState&&this.peerConn.close(),null===(e=this.stats)||void 0===e||e.removeStatsReportGatherer(this.callId),this.emit(I.Hangup,this))}),i.lifetime-e.getLocalAge()),n=e=>{e!==_.Ringing&&(clearTimeout(t),this.off(I.State,n))};this.on(I.State,n)}}))}initWithHangup(e){this.state=_.Ended}shouldAnswerWithMediaType(e,t,i){return e&&!t?(d.logger.warn(`Call ${this.callId} shouldAnswerWithMediaType() unable to answer with ${i} because the other side isn't sending it either.`),!1):l.isNullOrUndefined(e)||e===t||this.opponentSupportsSDPStreamMetadata()?null!=e?e:t:(d.logger.warn(`Call ${this.callId} shouldAnswerWithMediaType() unable to answer with ${i}=${e} because the other side doesn't support it. Answering with ${i}=${t}.`),t)}answer(e,t){var i;return s(this,void 0,void 0,(function*(){if(!this.inviteOrAnswerSent){if(!1===e&&!1===t)throw new Error("You CANNOT answer a call without media");if(this.localUsermediaStream||this.waitForLocalAVStream)this.waitForLocalAVStream&&(this.state=_.WaitLocalMedia);else{const n=this.state,r=this.shouldAnswerWithMediaType(e,this.hasRemoteUserMediaAudioTrack,"audio"),o=this.shouldAnswerWithMediaType(t,this.hasRemoteUserMediaVideoTrack,"video");this.state=_.WaitLocalMedia,this.waitForLocalAVStream=!0;try{const e=yield this.client.getMediaHandler().getUserMediaStream(r,o);this.waitForLocalAVStream=!1;const t=[new p.CallFeed({client:this.client,roomId:this.roomId,userId:this.client.getUserId(),deviceId:null!==(i=this.client.getDeviceId())&&void 0!==i?i:void 0,stream:e,purpose:f.SDPStreamMetadataPurpose.Usermedia,audioMuted:!1,videoMuted:!1})];this.localScreensharingFeed&&t.push(this.localScreensharingFeed),this.answerWithCallFeeds(t)}catch(e){if(!o)return void this.getUserMediaFailed(e);d.logger.warn(`Call ${this.callId} answer() failed to getUserMedia(), trying to getUserMedia() without video`),this.state=n,this.waitForLocalAVStream=!1,yield this.answer(r,!1)}}}}))}answerWithCallFeeds(e){this.inviteOrAnswerSent||this.queueGotCallFeedsForAnswer(e)}replacedBy(e){d.logger.debug(`Call ${this.callId} replacedBy() running (newCallId=${e.callId})`),this.state===_.WaitLocalMedia?(d.logger.debug(`Call ${this.callId} replacedBy() telling new call to wait for local media (newCallId=${e.callId})`),e.waitForLocalAVStream=!0):[_.CreateOffer,_.InviteSent].includes(this.state)&&(e.direction===w.Outbound?e.queueGotCallFeedsForAnswer([]):(d.logger.debug(`Call ${this.callId} replacedBy() handing local stream to new call(newCallId=${e.callId})`),e.queueGotCallFeedsForAnswer(this.getLocalFeeds().map((e=>e.clone()))))),this.successor=e,this.emit(I.Replaced,e,this),this.hangup(R.Replaced,!0)}hangup(e,t){if(this.callHasEnded())return;if(d.logger.debug(`Call ${this.callId} hangup() ending call (reason=${e})`),this.terminate(T.Local,e,!t),[_.Fledgling,_.WaitLocalMedia].includes(this.state))return;const i={};(this.opponentVersion&&0!==this.opponentVersion||e!==R.UserHangup)&&(i.reason=e),this.sendVoipEvent(u.EventType.CallHangup,i)}reject(){if(this.state!==_.Ringing)throw Error("Call must be in 'ringing' state to reject!");if(0===this.opponentVersion)return d.logger.info(`Call ${this.callId} reject() opponent version is less than 1: sending hangup instead of reject (opponentVersion=${this.opponentVersion})`),void this.hangup(R.UserHangup,!0);d.logger.debug("Rejecting call: "+this.callId),this.terminate(T.Local,R.UserHangup,!0),this.sendVoipEvent(u.EventType.CallReject,{})}upgradeCall(e,t){return s(this,void 0,void 0,(function*(){if((e||t)&&this.opponentSupportsSDPStreamMetadata())try{d.logger.debug(`Call ${this.callId} upgradeCall() upgrading call (audio=${e}, video=${t})`);const i=e||this.hasLocalUserMediaAudioTrack,n=t||this.hasLocalUserMediaVideoTrack,r=yield this.client.getMediaHandler().getUserMediaStream(i,n,!1);yield this.updateLocalUsermediaStream(r,e,t)}catch(e){d.logger.error(`Call ${this.callId} upgradeCall() failed to upgrade the call`,e),this.emit(I.Error,new M(R.NoUserMedia,"Failed to get camera access: ",e),this)}}))}opponentSupportsSDPStreamMetadata(){return Boolean(this.remoteSDPStreamMetadata)}isScreensharing(){return Boolean(this.localScreensharingStream)}setScreensharingEnabled(e,t){return s(this,void 0,void 0,(function*(){if(e&&this.isScreensharing())return d.logger.warn(`Call ${this.callId} setScreensharingEnabled() there is already a screensharing stream - there is nothing to do!`),!0;if(!e&&!this.isScreensharing())return d.logger.warn(`Call ${this.callId} setScreensharingEnabled() there already isn't a screensharing stream - there is nothing to do!`),!1;if(!this.opponentSupportsSDPStreamMetadata())return this.setScreensharingEnabledWithoutMetadataSupport(e,t);if(d.logger.debug(`Call ${this.callId} setScreensharingEnabled() running (enabled=${e})`),!e){const e=this.transceivers.get(O(f.SDPStreamMetadataPurpose.Screenshare,"audio")),t=this.transceivers.get(O(f.SDPStreamMetadataPurpose.Screenshare,"video"));for(const i of[e,t])i&&i.sender&&this.peerConn.removeTrack(i.sender);return this.client.getMediaHandler().stopScreensharingStream(this.localScreensharingStream),this.deleteFeedByStream(this.localScreensharingStream),!1}try{const e=yield this.client.getMediaHandler().getScreensharingStream(t);return!!e&&(this.pushNewLocalFeed(e,f.SDPStreamMetadataPurpose.Screenshare),!0)}catch(e){return d.logger.error(`Call ${this.callId} setScreensharingEnabled() failed to get screen-sharing stream:`,e),!1}}))}setScreensharingEnabledWithoutMetadataSupport(e,t){var i,n,r;return s(this,void 0,void 0,(function*(){if(d.logger.debug(`Call ${this.callId} setScreensharingEnabledWithoutMetadataSupport() running (enabled=${e})`),!e){const e=null===(n=this.localUsermediaStream)||void 0===n?void 0:n.getTracks().find((e=>"video"===e.kind)),t=null===(r=this.transceivers.get(O(f.SDPStreamMetadataPurpose.Usermedia,"video")))||void 0===r?void 0:r.sender;return null==t||t.replaceTrack(null!=e?e:null),this.client.getMediaHandler().stopScreensharingStream(this.localScreensharingStream),this.deleteFeedByStream(this.localScreensharingStream),!1}try{const e=yield this.client.getMediaHandler().getScreensharingStream(t);if(!e)return!1;const n=e.getTracks().find((e=>"video"===e.kind)),r=null===(i=this.transceivers.get(O(f.SDPStreamMetadataPurpose.Usermedia,"video")))||void 0===i?void 0:i.sender;return null==r||r.replaceTrack(null!=n?n:null),this.pushNewLocalFeed(e,f.SDPStreamMetadataPurpose.Screenshare,!1),!0}catch(e){return d.logger.error(`Call ${this.callId} setScreensharingEnabledWithoutMetadataSupport() failed to get screen-sharing stream:`,e),!1}}))}updateLocalUsermediaStream(e,t=!1,i=!1){return s(this,void 0,void 0,(function*(){const n=this.localUsermediaFeed,r=t||!n.isAudioMuted()&&!this.remoteOnHold,o=i||!n.isVideoMuted()&&!this.remoteOnHold;d.logger.log(`Call ${this.callId} updateLocalUsermediaStream() running (streamId=${e.id}, audio=${r}, video=${o})`),P(e.getAudioTracks(),r),P(e.getVideoTracks(),o);for(const e of this.localUsermediaStream.getTracks())this.localUsermediaStream.removeTrack(e),e.stop();for(const t of e.getTracks())this.localUsermediaStream.addTrack(t);for(const t of e.getTracks()){const i=O(f.SDPStreamMetadataPurpose.Usermedia,t.kind),r=this.transceivers.get(i),o=null==r?void 0:r.sender;let s=!1;if(o)try{d.logger.info(`Call ${this.callId} updateLocalUsermediaStream() replacing track (id=${t.id}, kind=${t.kind}, streamId=${e.id}, streamPurpose=${n.purpose})`),yield o.replaceTrack(t),r.direction="inactive"===r.direction?"sendonly":"sendrecv",s=!0}catch(e){d.logger.warn(`Call ${this.callId} updateLocalUsermediaStream() replaceTrack failed: adding new transceiver instead`,e)}if(!s){d.logger.info(`Call ${this.callId} updateLocalUsermediaStream() adding track to peer connection (id=${t.id}, kind=${t.kind}, streamId=${e.id}, streamPurpose=${n.purpose})`);const r=this.peerConn.addTrack(t,this.localUsermediaStream),o=this.peerConn.getTransceivers().find((e=>e.sender===r));o?this.transceivers.set(i,o):d.logger.warn(`Call ${this.callId} updateLocalUsermediaStream() couldn't find matching transceiver for newly added track!`)}}}))}setLocalVideoMuted(e){var t,i;return s(this,void 0,void 0,(function*(){if(d.logger.log(`Call ${this.callId} setLocalVideoMuted() running ${e}`),e||void 0===this.stopVideoTrackTimer||(clearTimeout(this.stopVideoTrackTimer),this.stopVideoTrackTimer=void 0),!(yield this.client.getMediaHandler().hasVideoDevice()))return this.isLocalVideoMuted();if(!this.hasUserMediaVideoSender&&!e)return null===(t=this.localUsermediaFeed)||void 0===t||t.setAudioVideoMuted(null,e),yield this.upgradeCall(!1,!0),this.isLocalVideoMuted();if(!e&&0===this.localUsermediaStream.getVideoTracks().length){const e=yield this.client.getMediaHandler().getUserMediaStream(!0,!0);yield this.updateLocalUsermediaStream(e)}return null===(i=this.localUsermediaFeed)||void 0===i||i.setAudioVideoMuted(null,e),this.updateMuteStatus(),yield this.sendMetadataUpdate(),e&&(this.stopVideoTrackTimer=setTimeout((()=>{for(const e of this.localUsermediaStream.getVideoTracks())e.stop(),this.localUsermediaStream.removeTrack(e)}),120)),this.isLocalVideoMuted()}))}isLocalVideoMuted(){var e,t;return null!==(t=null===(e=this.localUsermediaFeed)||void 0===e?void 0:e.isVideoMuted())&&void 0!==t&&t}setMicrophoneMuted(e){var t;return s(this,void 0,void 0,(function*(){return d.logger.log(`Call ${this.callId} setMicrophoneMuted() running ${e}`),(yield this.client.getMediaHandler().hasAudioDevice())?e||this.hasUserMediaAudioSender&&this.hasLocalUserMediaAudioTrack?(null===(t=this.localUsermediaFeed)||void 0===t||t.setAudioVideoMuted(e,null),this.updateMuteStatus(),yield this.sendMetadataUpdate(),this.isMicrophoneMuted()):(yield this.upgradeCall(!0,!1),this.isMicrophoneMuted()):this.isMicrophoneMuted()}))}isMicrophoneMuted(){var e,t;return null!==(t=null===(e=this.localUsermediaFeed)||void 0===e?void 0:e.isAudioMuted())&&void 0!==t&&t}isRemoteOnHold(){return this.remoteOnHold}setRemoteOnHold(e){if(this.isRemoteOnHold()!==e){this.remoteOnHold=e;for(const t of this.peerConn.getTransceivers())t.direction=e?"sendonly":"sendrecv";this.updateMuteStatus(),this.sendMetadataUpdate(),this.emit(I.RemoteHoldUnhold,this.remoteOnHold,this)}}isLocalOnHold(){if(this.state!==_.Connected)return!1;let e=!0;for(const t of this.peerConn.getTransceivers()){["inactive","recvonly"].includes(t.currentDirection)||(e=!1)}return e}sendDtmfDigit(e){var t;for(const i of this.peerConn.getSenders())if("audio"===(null===(t=i.track)||void 0===t?void 0:t.kind)&&i.dtmf)return void i.dtmf.insertDTMF(e);throw new Error("Unable to find a track to send DTMF on")}updateMuteStatus(){const e=this.isMicrophoneMuted()||this.remoteOnHold,t=this.isLocalVideoMuted()||this.remoteOnHold;d.logger.log(`Call ${this.callId} updateMuteStatus stream ${this.localUsermediaStream.id} micShouldBeMuted ${e} vidShouldBeMuted ${t}`),P(this.localUsermediaStream.getAudioTracks(),!e),P(this.localUsermediaStream.getVideoTracks(),!t)}sendMetadataUpdate(){return s(this,void 0,void 0,(function*(){yield this.sendVoipEvent(u.EventType.CallSDPStreamMetadataChangedPrefix,{[f.SDPStreamMetadataKey]:this.getLocalSDPStreamMetadata()})}))}gotCallFeedsForInvite(e,t=!1){if(this.successor)this.successor.queueGotCallFeedsForAnswer(e);else if(this.callHasEnded())this.stopAllMedia();else{for(const t of e)this.pushLocalFeed(t);t&&this.peerConn.addTransceiver("video",{direction:"recvonly"}),this.state=_.CreateOffer,d.logger.debug(`Call ${this.callId} gotUserMediaForInvite() run`)}}sendAnswer(){return s(this,void 0,void 0,(function*(){const e={answer:{sdp:this.peerConn.localDescription.sdp,type:this.peerConn.localDescription.type},[f.SDPStreamMetadataKey]:this.getLocalSDPStreamMetadata(!0)};e.capabilities={"m.call.transferee":this.client.supportsCallTransfer,"m.call.dtmf":!1};const t=this.discardDuplicateCandidates();d.logger.info(`Call ${this.callId} sendAnswer() discarding ${t} candidates that will be sent in answer`);try{yield this.sendVoipEvent(u.EventType.CallAnswer,e),this.inviteOrAnswerSent=!0}catch(e){this.state=_.Ringing,e instanceof y.MatrixError&&e.event&&this.client.cancelPendingEvent(e.event);let t=R.SendAnswer,i="Failed to send answer";throw"UnknownDeviceError"==e.name&&(t=R.UnknownDevices,i="Unknown devices present in the room"),this.emit(I.Error,new M(t,i,e),this),e}this.sendCandidateQueue()}))}queueGotCallFeedsForAnswer(e){this.responsePromiseChain?this.responsePromiseChain=this.responsePromiseChain.then((()=>this.gotCallFeedsForAnswer(e))):this.responsePromiseChain=this.gotCallFeedsForAnswer(e)}mungeSdp(e,t){const i=(0,c.parse)(e.sdp);i.media.forEach((e=>{const i=new Map,n=new Map;for(const t of e.rtp)i.set(t.payload,t.codec),n.set(t.codec,t.payload);for(const r of t){if(r.mediaType!==e.type)continue;if(!n.has(r.codec)){d.logger.info(`Call ${this.callId} mungeSdp() ignoring SDP modifications for ${r.codec} as it's not present.`);continue}const t=[];void 0!==r.enableDtx&&t.push("usedtx="+(r.enableDtx?"1":"0")),void 0!==r.maxAverageBitrate&&t.push(`maxaveragebitrate=${r.maxAverageBitrate}`);let o=!1;for(const n of e.fmtp)i.get(n.payload)===r.codec&&(o=!0,n.config+=";"+t.join(";"));o||e.fmtp.push({payload:n.get(r.codec),config:t.join(";")})}})),e.sdp=(0,c.write)(i)}createOffer(){return s(this,void 0,void 0,(function*(){const e=yield this.peerConn.createOffer();return this.mungeSdp(e,C(this.isPtt)),e}))}createAnswer(){return s(this,void 0,void 0,(function*(){const e=yield this.peerConn.createAnswer();return this.mungeSdp(e,C(this.isPtt)),e}))}gotCallFeedsForAnswer(e){return s(this,void 0,void 0,(function*(){if(this.callHasEnded())return;this.waitForLocalAVStream=!1;for(const t of e)this.pushLocalFeed(t);let t;this.state=_.CreateAnswer;try{this.getRidOfRTXCodecs(),t=yield this.createAnswer()}catch(e){return d.logger.debug(`Call ${this.callId} gotCallFeedsForAnswer() failed to create answer: `,e),void this.terminate(T.Local,R.CreateAnswer,!0)}try{if(yield this.peerConn.setLocalDescription(t),this.callHasEnded())return;if(this.state=_.Connecting,yield new Promise((e=>{setTimeout(e,200)})),this.callHasEnded())return;this.sendAnswer()}catch(e){return d.logger.debug(`Call ${this.callId} gotCallFeedsForAnswer() error setting local description!`,e),void this.terminate(T.Local,R.SetLocalDescription,!0)}}))}onRemoteIceCandidatesReceived(e){return s(this,void 0,void 0,(function*(){if(this.callHasEnded())return;const t=e.getContent(),i=t.candidates;if(!i)return void d.logger.info(`Call ${this.callId} onRemoteIceCandidatesReceived() ignoring candidates event with no candidates!`);const n=0===t.version?null:t.party_id||null;if(void 0!==this.opponentPartyId)this.partyIdMatches(t)?yield this.addIceCandidates(i):d.logger.info(`Call ${this.callId} onRemoteIceCandidatesReceived() ignoring candidates from party ID ${t.party_id}: we have chosen party ID ${this.opponentPartyId}`);else if(n){d.logger.info(`Call ${this.callId} onRemoteIceCandidatesReceived() buffering ${i.length} candidates until we pick an opponent`);const e=this.remoteCandidateBuffer.get(n)||[];e.push(...i),this.remoteCandidateBuffer.set(n,e)}}))}onAnswerReceived(e){return s(this,void 0,void 0,(function*(){const t=e.getContent();if(d.logger.debug(`Call ${this.callId} onAnswerReceived() running (hangupParty=${t.party_id})`),this.callHasEnded())return void d.logger.debug(`Call ${this.callId} onAnswerReceived() ignoring answer because call has ended`);if(void 0!==this.opponentPartyId)return void d.logger.info(`Call ${this.callId} onAnswerReceived() ignoring answer from party ID ${t.party_id}: we already have an answer/reject from ${this.opponentPartyId}`);this.chooseOpponent(e),yield this.addBufferedIceCandidates(),this.state=_.Connecting;const i=t[f.SDPStreamMetadataKey];i?this.updateRemoteSDPStreamMetadata(i):d.logger.warn(`Call ${this.callId} onAnswerReceived() did not get any SDPStreamMetadata! Can not send/receive multiple streams`);try{yield this.peerConn.setRemoteDescription(t.answer)}catch(e){return d.logger.debug(`Call ${this.callId} onAnswerReceived() failed to set remote description`,e),void this.terminate(T.Local,R.SetRemoteDescription,!1)}if(null!==this.opponentPartyId)try{yield this.sendVoipEvent(u.EventType.CallSelectAnswer,{selected_party_id:this.opponentPartyId})}catch(e){d.logger.warn(`Call ${this.callId} onAnswerReceived() failed to send select_answer event`,e)}}))}onSelectAnswerReceived(e){return s(this,void 0,void 0,(function*(){if(this.direction!==w.Inbound)return void d.logger.warn(`Call ${this.callId} onSelectAnswerReceived() got select_answer for an outbound call: ignoring`);const t=e.getContent().selected_party_id;null!=t?t!==this.ourPartyId&&(d.logger.info(`Call ${this.callId} onSelectAnswerReceived() got select_answer for party ID ${t}: we are party ID ${this.ourPartyId}.`),yield this.terminate(T.Remote,R.AnsweredElsewhere,!0)):d.logger.warn(`Call ${this.callId} onSelectAnswerReceived() got nonsensical select_answer with null/undefined selected_party_id: ignoring`)}))}onNegotiateReceived(e){var t;return s(this,void 0,void 0,(function*(){const i=e.getContent(),n=i.description;if(!n||!n.sdp||!n.type)return void d.logger.info(`Call ${this.callId} onNegotiateReceived() ignoring invalid m.call.negotiate event`);const r=this.direction===w.Inbound,o="offer"===n.type&&(this.makingOffer||"stable"!==this.peerConn.signalingState);if(this.ignoreOffer=!r&&o,this.ignoreOffer)return void d.logger.info(`Call ${this.callId} onNegotiateReceived() ignoring colliding negotiate event because we're impolite`);const s=this.isLocalOnHold(),a=i[f.SDPStreamMetadataKey];a?this.updateRemoteSDPStreamMetadata(a):d.logger.warn(`Call ${this.callId} onNegotiateReceived() received negotiation event without SDPStreamMetadata!`);try{if(yield this.peerConn.setRemoteDescription(n),"offer"===n.type){let e;try{this.getRidOfRTXCodecs(),e=yield this.createAnswer()}catch(e){return d.logger.debug(`Call ${this.callId} onNegotiateReceived() failed to create answer: `,e),void this.terminate(T.Local,R.CreateAnswer,!0)}yield this.peerConn.setLocalDescription(e),this.sendVoipEvent(u.EventType.CallNegotiate,{description:null===(t=this.peerConn.localDescription)||void 0===t?void 0:t.toJSON(),[f.SDPStreamMetadataKey]:this.getLocalSDPStreamMetadata(!0)})}}catch(e){d.logger.warn(`Call ${this.callId} onNegotiateReceived() failed to complete negotiation`,e)}const c=this.isLocalOnHold();s!==c&&(this.emit(I.LocalHoldUnhold,c,this),this.emit(I.HoldUnhold,c))}))}updateRemoteSDPStreamMetadata(e){var t;this.remoteSDPStreamMetadata=l.recursivelyAssign(this.remoteSDPStreamMetadata||{},e,!0);for(const e of this.getRemoteFeeds()){const i=e.stream.id,n=this.remoteSDPStreamMetadata[i];e.setAudioVideoMuted(null==n?void 0:n.audio_muted,null==n?void 0:n.video_muted),e.purpose=null===(t=this.remoteSDPStreamMetadata[i])||void 0===t?void 0:t.purpose}}onSDPStreamMetadataChangedReceived(e){const t=e.getContent()[f.SDPStreamMetadataKey];this.updateRemoteSDPStreamMetadata(t)}onAssertedIdentityReceived(e){return s(this,void 0,void 0,(function*(){const t=e.getContent();t.asserted_identity&&(this.remoteAssertedIdentity={id:t.asserted_identity.id,displayName:t.asserted_identity.display_name},this.emit(I.AssertedIdentityChanged,this))}))}callHasEnded(){return this.state===_.Ended}queueGotLocalOffer(){this.responsePromiseChain?this.responsePromiseChain=this.responsePromiseChain.then((()=>this.wrappedGotLocalOffer())):this.responsePromiseChain=this.wrappedGotLocalOffer()}wrappedGotLocalOffer(){return s(this,void 0,void 0,(function*(){this.makingOffer=!0;try{yield this.gotLocalOffer()}catch(e){return void this.getLocalOfferFailed(e)}finally{this.makingOffer=!1}}))}gotLocalOffer(){var e,t;return s(this,void 0,void 0,(function*(){if(d.logger.debug(`Call ${this.callId} gotLocalOffer() running`),this.callHasEnded())return void d.logger.debug(`Call ${this.callId} gotLocalOffer() ignoring newly created offer because the call has ended"`);let i;try{this.getRidOfRTXCodecs(),i=yield this.createOffer()}catch(e){return d.logger.debug(`Call ${this.callId} gotLocalOffer() failed to create offer: `,e),void this.terminate(T.Local,R.CreateOffer,!0)}try{yield this.peerConn.setLocalDescription(i)}catch(e){return d.logger.debug(`Call ${this.callId} gotLocalOffer() error setting local description!`,e),void this.terminate(T.Local,R.SetLocalDescription,!0)}if("gathering"===this.peerConn.iceGatheringState&&(yield new Promise((e=>{setTimeout(e,200)}))),this.callHasEnded())return;const n=this.state===_.CreateOffer?u.EventType.CallInvite:u.EventType.CallNegotiate,r={lifetime:6e4};n===u.EventType.CallInvite&&this.invitee&&(r.invitee=this.invitee),this.state===_.CreateOffer?r.offer=null===(e=this.peerConn.localDescription)||void 0===e?void 0:e.toJSON():r.description=null===(t=this.peerConn.localDescription)||void 0===t?void 0:t.toJSON(),r.capabilities={"m.call.transferee":this.client.supportsCallTransfer,"m.call.dtmf":!1},r[f.SDPStreamMetadataKey]=this.getLocalSDPStreamMetadata(!0);const o=this.discardDuplicateCandidates();d.logger.info(`Call ${this.callId} gotLocalOffer() discarding ${o} candidates that will be sent in offer`);try{yield this.sendVoipEvent(n,r)}catch(e){d.logger.error(`Call ${this.callId} gotLocalOffer() failed to send invite`,e),e instanceof y.MatrixError&&e.event&&this.client.cancelPendingEvent(e.event);let t=R.SignallingFailed,i="Signalling failed";return this.state===_.CreateOffer&&(t=R.SendInvite,i="Failed to send invite"),"UnknownDeviceError"==e.name&&(t=R.UnknownDevices,i="Unknown devices present in the room"),this.emit(I.Error,new M(t,i,e),this),void this.terminate(T.Local,t,!1)}this.sendCandidateQueue(),this.state===_.CreateOffer&&(this.inviteOrAnswerSent=!0,this.state=_.InviteSent,this.inviteTimeout=setTimeout((()=>{this.inviteTimeout=void 0,this.state===_.InviteSent&&this.hangup(R.InviteTimeout,!1)}),6e4))}))}getRidOfRTXCodecs(){if(!RTCRtpReceiver.getCapabilities||!RTCRtpSender.getCapabilities)return;const e=RTCRtpReceiver.getCapabilities("video").codecs,t=[...RTCRtpSender.getCapabilities("video").codecs,...e];for(const e of t)if("video/rtx"===e.mimeType){const i=t.indexOf(e);t.splice(i,1)}const i=this.transceivers.get(O(f.SDPStreamMetadataPurpose.Screenshare,"video"));i&&i.setCodecPreferences(t)}sendVoipEvent(e,t){var i,n;return s(this,void 0,void 0,(function*(){const r=Object.assign({},t,{version:"1",call_id:this.callId,party_id:this.ourPartyId,conf_id:this.groupCallId});if(this.opponentDeviceId){const t=this.toDeviceSeq++,n=Object.assign(Object.assign({},r),{device_id:this.client.deviceId,sender_session_id:this.client.getSessionId(),dest_session_id:this.opponentSessionId,seq:t,[u.ToDeviceMessageId]:(0,a.v4)()});this.emit(I.SendVoipEvent,{type:"toDevice",eventType:e,userId:this.invitee||(null===(i=this.getOpponentMember())||void 0===i?void 0:i.userId),opponentDeviceId:this.opponentDeviceId,content:n},this);const o=this.invitee||this.getOpponentMember().userId;if(this.client.getUseE2eForGroupCall()){if(!this.opponentDeviceInfo)return void d.logger.warn(`Call ${this.callId} sendVoipEvent() failed: we do not have opponentDeviceInfo`);yield this.client.encryptAndSendToDevices([{userId:o,deviceInfo:this.opponentDeviceInfo}],{type:e,content:n})}else yield this.client.sendToDevice(e,new Map([[o,new Map([[this.opponentDeviceId,n]])]]))}else this.emit(I.SendVoipEvent,{type:"sendEvent",eventType:e,roomId:this.roomId,content:r,userId:this.invitee||(null===(n=this.getOpponentMember())||void 0===n?void 0:n.userId)},this),yield this.client.sendEvent(this.roomId,e,r)}))}queueCandidate(e){if(e?this.candidateSendQueue.push(e):this.candidatesEnded=!0,this.state===_.Ringing||!this.inviteOrAnswerSent)return;const t=this.direction===w.Inbound?500:2e3;0===this.candidateSendTries&&setTimeout((()=>{this.sendCandidateQueue()}),t)}discardDuplicateCandidates(){let e=0;const t=[];for(let i=0;ie.toJSON()))};this.candidatesEnded&&t.candidates.push({candidate:""}),d.logger.debug(`Call ${this.callId} sendCandidateQueue() attempting to send ${e.length} candidates`);try{yield this.sendVoipEvent(u.EventType.CallCandidates,t),this.candidateSendTries=0,this.sendCandidateQueue()}catch(t){if(t instanceof y.MatrixError&&t.event&&this.client.cancelPendingEvent(t.event),this.candidateSendQueue.push(...e),this.candidateSendTries>5){d.logger.debug(`Call ${this.callId} sendCandidateQueue() failed to send candidates on attempt ${this.candidateSendTries}. Giving up on this call.`,t);const e=R.SignallingFailed,i="Signalling failed";return this.emit(I.Error,new M(e,i,t),this),void this.hangup(e,!1)}const i=500*Math.pow(2,this.candidateSendTries);++this.candidateSendTries,d.logger.debug(`Call ${this.callId} sendCandidateQueue() failed to send candidates. Retrying in ${i}ms`,t),setTimeout((()=>{this.sendCandidateQueue()}),i)}}))}placeCall(e,t){var i;return s(this,void 0,void 0,(function*(){if(!e)throw new Error("You CANNOT start a call without audio");this.state=_.WaitLocalMedia;try{const n=yield this.client.getMediaHandler().getUserMediaStream(e,t);P(n.getAudioTracks(),!0),P(n.getVideoTracks(),!0);const r=new p.CallFeed({client:this.client,roomId:this.roomId,userId:this.client.getUserId(),deviceId:null!==(i=this.client.getDeviceId())&&void 0!==i?i:void 0,stream:n,purpose:f.SDPStreamMetadataPurpose.Usermedia,audioMuted:!1,videoMuted:!1});yield this.placeCallWithCallFeeds([r])}catch(e){return void this.getUserMediaFailed(e)}}))}placeCallWithCallFeeds(e,t=!1){return s(this,void 0,void 0,(function*(){this.checkForErrorListener(),this.direction=w.Outbound,yield this.initOpponentCrypto(),this.client.callEventHandler.calls.set(this.callId,this);(yield this.client.checkTurnServers())||d.logger.warn(`Call ${this.callId} placeCallWithCallFeeds() failed to get TURN credentials! Proceeding with call anyway...`),this.peerConn=this.createPeerConnection(),this.gotCallFeedsForInvite(e,t)}))}createPeerConnection(){var e;const t=new window.RTCPeerConnection({iceTransportPolicy:this.forceTURN?"relay":void 0,iceServers:this.turnServers,iceCandidatePoolSize:this.client.iceCandidatePoolSize,bundlePolicy:"max-bundle"});return t.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChanged),t.addEventListener("signalingstatechange",this.onSignallingStateChanged),t.addEventListener("icecandidate",this.gotLocalIceCandidate),t.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),t.addEventListener("track",this.onTrack),t.addEventListener("negotiationneeded",this.onNegotiationNeeded),t.addEventListener("datachannel",this.onDataChannel),null===(e=this.stats)||void 0===e||e.addStatsReportGatherer(this.callId,"unknown",t),t}partyIdMatches(e){return(0===e.version?null:e.party_id||null)===this.opponentPartyId}chooseOpponent(e){var t;const i=e.getContent();d.logger.debug(`Call ${this.callId} chooseOpponent() running (partyId=${i.party_id})`),this.opponentVersion=i.version,0===this.opponentVersion?this.opponentPartyId=null:this.opponentPartyId=i.party_id||null,this.opponentCaps=i.capabilities||{},this.opponentMember=null!==(t=this.client.getRoom(this.roomId).getMember(e.getSender()))&&void 0!==t?t:void 0}addBufferedIceCandidates(){return s(this,void 0,void 0,(function*(){const e=this.remoteCandidateBuffer.get(this.opponentPartyId);e&&(d.logger.info(`Call ${this.callId} addBufferedIceCandidates() adding ${e.length} buffered candidates for opponent ${this.opponentPartyId}`),yield this.addIceCandidates(e)),this.remoteCandidateBuffer.clear()}))}addIceCandidates(e){return s(this,void 0,void 0,(function*(){for(const t of e){null!==t.sdpMid&&void 0!==t.sdpMid||null!==t.sdpMLineIndex&&void 0!==t.sdpMLineIndex?d.logger.debug(`Call ${this.callId} addIceCandidates() got remote ICE candidate (sdpMid=${t.sdpMid}, candidate=${t.candidate})`):d.logger.debug(`Call ${this.callId} addIceCandidates() got remote ICE end-of-candidates`);try{yield this.peerConn.addIceCandidate(t)}catch(e){this.ignoreOffer||d.logger.info(`Call ${this.callId} addIceCandidates() failed to add remote ICE candidate`,e)}}}))}get hasPeerConnection(){return Boolean(this.peerConn)}initStats(e,t="unknown"){this.stats=e,this.stats.start()}}function P(e,t){for(const i of e)i.enabled=t}function D(){if("undefined"==typeof window||"undefined"==typeof document)return!1;try{if(!Boolean(window.RTCPeerConnection||window.RTCSessionDescription||window.RTCIceCandidate||navigator.mediaDevices))return"test"!==t.env.NODE_ENV&&d.logger.error("WebRTC is not supported in this browser / environment"),!1}catch(e){return d.logger.error("Exception thrown when trying to access WebRTC",e),!1}return!0}i.MatrixCall=A,i.setTracksEnabled=P,i.supportsMatrixCall=D,i.createNewMatrixCall=function(e,t,i){if(!D())return null;const n=!!i&&i.forceTURN,r={client:e,roomId:t,invitee:null==i?void 0:i.invitee,turnServers:e.getTurnServers(),forceTURN:e.forceTURN||n,opponentDeviceId:null==i?void 0:i.opponentDeviceId,opponentSessionId:null==i?void 0:i.opponentSessionId,groupCallId:null==i?void 0:i.groupCallId},o=new A(r);return e.reEmitter.reEmit(o,Object.values(I)),o}}).call(this)}).call(this,e("_process"))},{"../@types/event":306,"../crypto/deviceinfo":340,"../http-api":367,"../logger":374,"../models/typed-event-emitter":395,"../randomstring":398,"../utils":416,"./callEventTypes":420,"./callFeed":421,"./groupCall":422,_process:237,"sdp-transform":253,uuid:287}],419:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.CallEventHandler=i.CallEventHandlerEvent=void 0;const r=e("../logger"),o=e("./call"),s=e("../@types/event"),a=e("../client"),c=e("./groupCall"),d=e("../models/room");var l;!function(e){e.Incoming="Call.incoming"}(l=i.CallEventHandlerEvent||(i.CallEventHandlerEvent={}));i.CallEventHandler=class{constructor(e){this.nextSeqByCall=new Map,this.toDeviceEventBuffers=new Map,this.onSync=()=>{const e=this.callEventBuffer;this.callEventBuffer=[],this.eventBufferPromiseChain?this.eventBufferPromiseChain=this.eventBufferPromiseChain.then((()=>this.evaluateEventBuffer(e))):this.eventBufferPromiseChain=this.evaluateEventBuffer(e)},this.onRoomTimeline=e=>{this.callEventBuffer.push(e)},this.onToDeviceEvent=e=>{const t=e.getContent();if(!t.call_id)return void this.callEventBuffer.push(e);if(this.nextSeqByCall.has(t.call_id)||this.nextSeqByCall.set(t.call_id,0),void 0===t.seq)return void this.callEventBuffer.push(e);const i=this.nextSeqByCall.get(t.call_id)||0;if(t.seq!==i){this.toDeviceEventBuffers.has(t.call_id)||this.toDeviceEventBuffers.set(t.call_id,[]);const i=this.toDeviceEventBuffers.get(t.call_id),n=i.findIndex((e=>e.getContent().seq>t.seq));-1===n?i.push(e):i.splice(n,0,e)}else{const i=t.call_id;this.callEventBuffer.push(e),this.nextSeqByCall.set(i,t.seq+1);const n=this.toDeviceEventBuffers.get(i);let r=n&&n.shift();for(;r&&r.getContent().seq===this.nextSeqByCall.get(i);)this.callEventBuffer.push(r),this.nextSeqByCall.set(i,r.getContent().seq+1),r=n.shift()}},this.client=e,this.calls=new Map,this.callEventBuffer=[],this.candidateEventsByCall=new Map}start(){this.client.on(a.ClientEvent.Sync,this.onSync),this.client.on(d.RoomEvent.Timeline,this.onRoomTimeline),this.client.on(a.ClientEvent.ToDeviceEvent,this.onToDeviceEvent)}stop(){this.client.removeListener(a.ClientEvent.Sync,this.onSync),this.client.removeListener(d.RoomEvent.Timeline,this.onRoomTimeline),this.client.removeListener(a.ClientEvent.ToDeviceEvent,this.onToDeviceEvent)}evaluateEventBuffer(e){return n(this,void 0,void 0,(function*(){yield Promise.all(e.map((e=>this.client.decryptEventIfNeeded(e))));const t=e.filter((e=>{const t=e.getType();return t.startsWith("m.call.")||t.startsWith("org.matrix.call.")})),i=new Set;for(const e of t){const t=e.getType();t!==s.EventType.CallAnswer&&t!==s.EventType.CallHangup||i.add(e.getContent().call_id)}for(const e of t){const t=e.getType(),n=e.getContent().call_id;if(t!==s.EventType.CallInvite||!i.has(n))try{yield this.handleCallEvent(e)}catch(e){r.logger.error("CallEventHandler evaluateEventBuffer() caught exception handling call event",e)}}}))}handleCallEvent(e){var t,i,d,u,h,f;return n(this,void 0,void 0,(function*(){this.client.emit(a.ClientEvent.ReceivedVoipEvent,e);const n=e.getContent(),p=e.getRoomId()||(null===(i=null===(t=this.client.groupCallEventHandler.getGroupCallById(n.conf_id))||void 0===t?void 0:t.room)||void 0===i?void 0:i.roomId),g=n.conf_id,v=e.getType(),m=e.getSender();let y,b,S=n.call_id?this.calls.get(n.call_id):void 0;if(g){if(b=this.client.groupCallEventHandler.getGroupCallById(g),!b)return void r.logger.warn(`CallEventHandler handleCallEvent() could not find a group call - ignoring event (groupCallId=${g}, type=${v})`);if(y=n.device_id,!y)return r.logger.warn(`CallEventHandler handleCallEvent() could not find a device id - ignoring event (senderId=${m})`),void b.emit(c.GroupCallEvent.Error,new c.GroupCallUnknownDeviceError(m));if(n.dest_session_id!==this.client.getSessionId())return void r.logger.warn("CallEventHandler handleCallEvent() call event does not match current session id - ignoring")}const _=m===this.client.credentials.userId&&(void 0===y||y===this.client.getDeviceId());if(p)if(v!==s.EventType.CallInvite)if(v!==s.EventType.CallCandidates)if([s.EventType.CallHangup,s.EventType.CallReject].includes(v))S?S.state!==o.CallState.Ended&&(v===s.EventType.CallHangup?S.onHangupReceived(n):S.onRejectReceived(n),S.state===o.CallState.Ended&&this.calls.delete(n.call_id)):(S=null!==(f=(0,o.createNewMatrixCall)(this.client,p,{opponentDeviceId:y,opponentSessionId:n.sender_session_id}))&&void 0!==f?f:void 0,S&&(S.callId=n.call_id,S.initWithHangup(e),this.calls.set(n.call_id,S)));else if(S&&S.hasPeerConnection){if(e.getContent().party_id!==S.ourPartyId)switch(v){case s.EventType.CallAnswer:_?S.state===o.CallState.Ringing&&S.onAnsweredElsewhere(n):S.onAnswerReceived(e);break;case s.EventType.CallSelectAnswer:S.onSelectAnswerReceived(e);break;case s.EventType.CallNegotiate:S.onNegotiateReceived(e);break;case s.EventType.CallAssertedIdentity:case s.EventType.CallAssertedIdentityPrefix:S.onAssertedIdentityReceived(e);break;case s.EventType.CallSDPStreamMetadataChanged:case s.EventType.CallSDPStreamMetadataChangedPrefix:S.onSDPStreamMetadataChangedReceived(e)}}else r.logger.info(`CallEventHandler handleCallEvent() discarding possible call event as we don't have a call (type=${v})`);else{if(_)return;S?S.onRemoteIceCandidatesReceived(e):(this.candidateEventsByCall.has(n.call_id)||this.candidateEventsByCall.set(n.call_id,[]),this.candidateEventsByCall.get(n.call_id).push(e))}else{if(_)return;if(e.getLocalAge()>n.lifetime-3e3)return;if(S&&S.state===o.CallState.Ended)return;if(S&&r.logger.warn(`CallEventHandler handleCallEvent() already has a call but got an invite - clobbering (callId=${n.call_id})`),n.invitee&&n.invitee!==this.client.getUserId())return;const t=(null!==(d=this.client.getTurnServersExpiry())&&void 0!==d?d:0)-Date.now();if(r.logger.info("CallEventHandler handleCallEvent() current turn creds expire in "+t+" ms"),S=null!==(u=(0,o.createNewMatrixCall)(this.client,p,{forceTURN:this.client.forceTURN,opponentDeviceId:y,groupCallId:g,opponentSessionId:n.sender_session_id}))&&void 0!==u?u:void 0,!S)return void r.logger.log(`CallEventHandler handleCallEvent() this client does not support WebRTC (callId=${n.call_id})`);S.callId=n.call_id;const i=null==b?void 0:b.getGroupCallStats();i&&S.initStats(i);try{yield S.initWithInvite(e)}catch(e){e instanceof o.CallError&&(e.code===c.GroupCallErrorCode.UnknownDevice?null==b||b.emit(c.GroupCallEvent.Error,e):r.logger.error(e))}if(this.calls.set(S.callId,S),this.candidateEventsByCall.get(S.callId))for(const e of this.candidateEventsByCall.get(S.callId))S.onRemoteIceCandidatesReceived(e);let s;for(const e of this.calls.values()){const t=[o.CallState.WaitLocalMedia,o.CallState.CreateOffer,o.CallState.InviteSent].includes(e.state);if(S.roomId===e.roomId&&e.direction===o.CallDirection.Outbound&&(null===(h=S.getOpponentMember())||void 0===h?void 0:h.userId)===e.invitee&&t){s=e;break}}s?s.callId>S.callId?(r.logger.log(`CallEventHandler handleCallEvent() detected glare - answering incoming call and canceling outgoing call (incomingId=${S.callId}, outgoingId=${s.callId})`),s.replacedBy(S)):(r.logger.log(`CallEventHandler handleCallEvent() detected glare - hanging up incoming call (incomingId=${S.callId}, outgoingId=${s.callId})`),S.hangup(o.CallErrorCode.Replaced,!0)):this.client.emit(l.Incoming,S)}}))}}},{"../@types/event":306,"../client":321,"../logger":374,"../models/room":392,"./call":418,"./groupCall":422}],420:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.SDPStreamMetadataPurpose=i.SDPStreamMetadataKey=void 0,i.SDPStreamMetadataKey="org.matrix.msc3077.sdp_stream_metadata",function(e){e.Usermedia="m.usermedia",e.Screenshare="m.screenshare"}(i.SDPStreamMetadataPurpose||(i.SDPStreamMetadataPurpose={}))},{}],421:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.CallFeed=i.CallFeedEvent=i.SPEAKING_THRESHOLD=void 0;const n=e("./callEventTypes"),r=e("./audioContext"),o=e("../logger"),s=e("../models/typed-event-emitter"),a=e("./call");i.SPEAKING_THRESHOLD=-60;var c;!function(e){e.NewStream="new_stream",e.MuteStateChanged="mute_state_changed",e.LocalVolumeChanged="local_volume_changed",e.VolumeChanged="volume_changed",e.ConnectedChanged="connected_changed",e.Speaking="speaking",e.Disposed="disposed"}(c=i.CallFeedEvent||(i.CallFeedEvent={}));class d extends s.TypedEventEmitter{constructor(e){super(),this.localVolume=1,this.measuringVolumeActivity=!1,this.speakingThreshold=i.SPEAKING_THRESHOLD,this.speaking=!1,this._disposed=!1,this._connected=!1,this.onAddTrack=()=>{this.emit(c.NewStream,this.stream)},this.onCallState=e=>{e===a.CallState.Connected?this.connected=!0:e===a.CallState.Connecting&&(this.connected=!1)},this.volumeLooper=()=>{if(!this.analyser)return;if(!this.measuringVolumeActivity)return;this.analyser.getFloatFrequencyData(this.frequencyBinCount);let e=-1/0;for(const t of this.frequencyBinCount)t>e&&(e=t);this.speakingVolumeSamples.shift(),this.speakingVolumeSamples.push(e),this.emit(c.VolumeChanged,e);let t=!1;for(const e of this.speakingVolumeSamples)if(e>this.speakingThreshold){t=!0;break}this.speaking!==t&&(this.speaking=t,this.emit(c.Speaking,this.speaking)),this.volumeLooperTimeout=setTimeout(this.volumeLooper,200)},this.client=e.client,this.call=e.call,this.roomId=e.roomId,this.userId=e.userId,this.deviceId=e.deviceId,this.purpose=e.purpose,this.audioMuted=e.audioMuted,this.videoMuted=e.videoMuted,this.speakingVolumeSamples=new Array(8).fill(-1/0),this.sdpMetadataStreamId=e.stream.id,this.updateStream(null,e.stream),this.stream=e.stream,this.hasAudioTrack&&this.initVolumeMeasuring(),e.call&&(e.call.addListener(a.CallEvent.State,this.onCallState),this.onCallState(e.call.state))}get connected(){return this.isLocal()||this._connected}set connected(e){this._connected=e,this.emit(c.ConnectedChanged,this.connected)}get hasAudioTrack(){return this.stream.getAudioTracks().length>0}updateStream(e,t){t!==e&&(e&&(e.removeEventListener("addtrack",this.onAddTrack),this.measureVolumeActivity(!1)),this.stream=t,t.addEventListener("addtrack",this.onAddTrack),this.hasAudioTrack?this.initVolumeMeasuring():this.measureVolumeActivity(!1),this.emit(c.NewStream,this.stream))}initVolumeMeasuring(){if(!this.hasAudioTrack)return;this.audioContext||(this.audioContext=(0,r.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)}getMember(){var e;const t=this.client.getRoom(this.roomId);return null!==(e=null==t?void 0:t.getMember(this.userId))&&void 0!==e?e:null}isLocal(){return this.userId===this.client.getUserId()&&(void 0===this.deviceId||this.deviceId===this.client.getDeviceId())}isAudioMuted(){return 0===this.stream.getAudioTracks().length||this.audioMuted}isVideoMuted(){return 0===this.stream.getVideoTracks().length||this.videoMuted}isSpeaking(){return this.speaking}setNewStream(e){this.updateStream(this.stream,e)}setAudioVideoMuted(e,t){null!==e&&(this.audioMuted!==e&&this.speakingVolumeSamples.fill(-1/0),this.audioMuted=e),null!==t&&(this.videoMuted=t),this.emit(c.MuteStateChanged,this.audioMuted,this.videoMuted)}measureVolumeActivity(e){if(e){if(!this.analyser||!this.frequencyBinCount||!this.hasAudioTrack)return;this.measuringVolumeActivity=!0,this.volumeLooper()}else this.measuringVolumeActivity=!1,this.speakingVolumeSamples.fill(-1/0),this.emit(c.VolumeChanged,-1/0)}setSpeakingThreshold(e){this.speakingThreshold=e}clone(){const e=this.client.getMediaHandler(),t=this.stream.clone();return o.logger.log(`CallFeed clone() cloning stream (originalStreamId=${this.stream.id}, newStreamId${t.id})`),this.purpose===n.SDPStreamMetadataPurpose.Usermedia?e.userMediaStreams.push(t):e.screensharingStreams.push(t),new d({client:this.client,roomId:this.roomId,userId:this.userId,deviceId:this.deviceId,stream:t,purpose:this.purpose,audioMuted:this.audioMuted,videoMuted:this.videoMuted})}dispose(){var e,t;clearTimeout(this.volumeLooperTimeout),null===(e=this.stream)||void 0===e||e.removeEventListener("addtrack",this.onAddTrack),null===(t=this.call)||void 0===t||t.removeListener(a.CallEvent.State,this.onCallState),this.audioContext&&(this.audioContext=void 0,this.analyser=void 0,(0,r.releaseContext)()),this._disposed=!0,this.emit(c.Disposed)}get disposed(){return this._disposed}set disposed(e){this._disposed=e}getLocalVolume(){return this.localVolume}setLocalVolume(e){this.localVolume=e,this.emit(c.LocalVolumeChanged,e)}}i.CallFeed=d},{"../logger":374,"../models/typed-event-emitter":395,"./audioContext":417,"./call":418,"./callEventTypes":420}],422:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.GroupCall=i.GroupCallState=i.OtherUserSpeakingError=i.GroupCallUnknownDeviceError=i.GroupCallError=i.GroupCallErrorCode=i.GroupCallStatsReportEvent=i.GroupCallEvent=i.GroupCallTerminationReason=i.GroupCallType=i.GroupCallIntent=void 0;const r=e("../models/typed-event-emitter"),o=e("./callFeed"),s=e("./call"),a=e("../models/room-state"),c=e("../logger"),d=e("../ReEmitter"),l=e("./callEventTypes"),u=e("../@types/event"),h=e("./callEventHandler"),f=e("./groupCallEventHandler"),p=e("../utils"),g=e("./stats/groupCallStats"),v=e("./stats/statsReport");var m,y,b,S,_,E;!function(e){e.Ring="m.ring",e.Prompt="m.prompt",e.Room="m.room"}(i.GroupCallIntent||(i.GroupCallIntent={})),function(e){e.Video="m.video",e.Voice="m.voice"}(m=i.GroupCallType||(i.GroupCallType={})),function(e){e.CallEnded="call_ended"}(y=i.GroupCallTerminationReason||(i.GroupCallTerminationReason={})),function(e){e.GroupCallStateChanged="group_call_state_changed",e.ActiveSpeakerChanged="active_speaker_changed",e.CallsChanged="calls_changed",e.UserMediaFeedsChanged="user_media_feeds_changed",e.ScreenshareFeedsChanged="screenshare_feeds_changed",e.LocalScreenshareStateChanged="local_screenshare_state_changed",e.LocalMuteStateChanged="local_mute_state_changed",e.ParticipantsChanged="participants_changed",e.Error="group_call_error"}(b=i.GroupCallEvent||(i.GroupCallEvent={})),function(e){e.ConnectionStats="GroupCall.connection_stats",e.ByteSentStats="GroupCall.byte_sent_stats"}(S=i.GroupCallStatsReportEvent||(i.GroupCallStatsReportEvent={})),function(e){e.NoUserMedia="no_user_media",e.UnknownDevice="unknown_device",e.PlaceCallFailed="place_call_failed"}(_=i.GroupCallErrorCode||(i.GroupCallErrorCode={}));class w extends Error{constructor(e,t,i){super(i?t+": "+i:t),this.code=e}}i.GroupCallError=w;i.GroupCallUnknownDeviceError=class extends w{constructor(e){super(_.UnknownDevice,"No device found for "+e),this.userId=e}};class T extends Error{constructor(){super("Cannot unmute: another user is speaking")}}i.OtherUserSpeakingError=T,function(e){e.LocalCallFeedUninitialized="local_call_feed_uninitialized",e.InitializingLocalCallFeed="initializing_local_call_feed",e.LocalCallFeedInitialized="local_call_feed_initialized",e.Entered="entered",e.Ended="ended"}(E=i.GroupCallState||(i.GroupCallState={}));const I=36e5;function R(e){var t;return(null===(t=e.getOpponentMember())||void 0===t?void 0:t.userId)||e.invitee||null}class M extends r.TypedEventEmitter{constructor(e,t,i,n,r,l,h,f,p){var m,y;super(),this.client=e,this.room=t,this.type=i,this.isPtt=n,this.intent=r,this.dataChannelsEnabled=h,this.dataChannelOptions=f,this.activeSpeakerInterval=1e3,this.retryCallInterval=5e3,this.participantTimeout=15e3,this.pttMaxTransmitTime=2e4,this.userMediaFeeds=[],this.screenshareFeeds=[],this.calls=new Map,this.callHandlers=new Map,this.retryCallCounts=new Map,this.transmitTimer=null,this.participantsExpirationTimer=null,this.resendMemberStateTimer=null,this.initWithAudioMuted=!1,this.initWithVideoMuted=!1,this.onConnectionStats=e=>{this.emit(S.ConnectionStats,{report:e})},this.onByteSentStats=e=>{this.emit(S.ByteSentStats,{report:e})},this._state=E.LocalCallFeedUninitialized,this._participants=new Map,this._creationTs=null,this._enteredViaAnotherSession=!1,this.onIncomingCall=e=>{var t,i;if(e.roomId!==this.room.roomId)return;if(e.state!==s.CallState.Ringing)return void c.logger.warn(`GroupCall ${this.groupCallId} onIncomingCall() incoming call no longer in ringing state - ignoring`);if(!e.groupCallId||e.groupCallId!==this.groupCallId)return c.logger.log(`GroupCall ${this.groupCallId} onIncomingCall() ignored because it doesn't match the current group call`),void e.reject();const n=null===(t=e.getOpponentMember())||void 0===t?void 0:t.userId;if(void 0===n)return void c.logger.warn(`GroupCall ${this.groupCallId} onIncomingCall() incoming call with no member - ignoring`);const r=null!==(i=this.calls.get(n))&&void 0!==i?i:new Map,o=r.get(e.getOpponentDeviceId());if((null==o?void 0:o.callId)===e.callId)return;c.logger.log(`GroupCall ${this.groupCallId} onIncomingCall() incoming call (userId=${n}, callId=${e.callId})`),o&&o.hangup(s.CallErrorCode.Replaced,!1),this.initCall(e);const a=this.getLocalFeeds().map((e=>e.clone()));if(!this.callExpected(e))for(const e of a)(0,s.setTracksEnabled)(e.stream.getAudioTracks(),!1),(0,s.setTracksEnabled)(e.stream.getVideoTracks(),!1);e.answerWithCallFeeds(a),r.set(e.getOpponentDeviceId(),e),this.calls.set(n,r),this.emit(b.CallsChanged,this.calls)},this.onRetryCallLoop=()=>{var e;let t=!1;for(const[{userId:i},n]of this.participants){const r=this.calls.get(i);let o=this.retryCallCounts.get(i);for(const[s,a]of n){const n=null==r?void 0:r.get(s),c=null!==(e=null==o?void 0:o.get(s))&&void 0!==e?e:0;(null==n?void 0:n.getOpponentSessionId())!==a.sessionId&&this.wantsOutgoingCall(i,s)&&c<3&&(void 0===o&&(o=new Map,this.retryCallCounts.set(i,o)),o.set(s,c+1),t=!0)}}t&&this.placeOutgoingCalls()},this.onCallFeedsChanged=e=>{const t=R(e),i=e.getOpponentDeviceId();if(!t)throw new Error("Cannot change call feeds without user id");const n=this.getUserMediaFeed(t,i),r=e.remoteUsermediaFeed;r!==n&&(!n&&r?this.addUserMediaFeed(r):n&&r?this.replaceUserMediaFeed(n,r):n&&!r&&this.removeUserMediaFeed(n));const o=this.getScreenshareFeed(t,i),s=e.remoteScreensharingFeed;s!==o&&(!o&&s?this.addScreenshareFeed(s):o&&s?this.replaceScreenshareFeed(o,s):o&&!s&&this.removeScreenshareFeed(o))},this.onCallStateChanged=(e,t,i)=>{var n;if(t===s.CallState.Ended)return;const r=this.localCallFeed.isAudioMuted();e.localUsermediaStream&&e.isMicrophoneMuted()!==r&&e.setMicrophoneMuted(r);const o=this.localCallFeed.isVideoMuted();e.localUsermediaStream&&e.isLocalVideoMuted()!==o&&e.setLocalVideoMuted(o);const a=null===(n=e.getOpponentMember())||void 0===n?void 0:n.userId;if(t===s.CallState.Connected&&a){const t=this.retryCallCounts.get(a);null==t||t.delete(e.getOpponentDeviceId()),0===(null==t?void 0:t.size)&&this.retryCallCounts.delete(a)}},this.onCallHangup=e=>{var t,i;if(e.hangupReason===s.CallErrorCode.Replaced)return;const n=null!==(i=null===(t=e.getOpponentMember())||void 0===t?void 0:t.userId)&&void 0!==i?i:this.room.getMember(e.invitee).userId,r=this.calls.get(n);(null==r?void 0:r.get(e.getOpponentDeviceId()))===e&&(this.disposeCall(e,e.hangupReason),r.delete(e.getOpponentDeviceId()),0===r.size&&this.calls.delete(n),this.emit(b.CallsChanged,this.calls))},this.onCallReplaced=(e,t)=>{const i=e.getOpponentMember().userId;let n=this.calls.get(i);void 0===n&&(n=new Map,this.calls.set(i,n)),e.hangup(s.CallErrorCode.Replaced,!1),this.initCall(t),n.set(e.getOpponentDeviceId(),t),this.emit(b.CallsChanged,this.calls)},this.onActiveSpeakerLoop=()=>{let e,t;for(const i of this.userMediaFeeds){if(i.isLocal()&&this.userMediaFeeds.length>1)continue;const n=i.speakingVolumeSamples.reduce(((e,t)=>e+Math.max(t,o.SPEAKING_THRESHOLD)))/i.speakingVolumeSamples.length;(!e||n>e)&&(e=n,t=i)}t&&this.activeSpeaker!==t&&e&&e>o.SPEAKING_THRESHOLD&&(this.activeSpeaker=t,this.emit(b.ActiveSpeakerChanged,this.activeSpeaker))},this.onRoomState=()=>this.updateParticipants(),this.onParticipantsChanged=()=>{this.forEachCall((e=>{const t=this.callExpected(e);for(const i of e.getLocalFeeds())(0,s.setTracksEnabled)(i.stream.getAudioTracks(),!i.isAudioMuted()&&t),(0,s.setTracksEnabled)(i.stream.getVideoTracks(),!i.isVideoMuted()&&t)})),this.state===E.Entered&&this.placeOutgoingCalls()},this.onStateChanged=(e,t)=>{e!==E.Entered&&t!==E.Entered&&e!==E.Ended||(this.updateParticipants(),this.updateMemberState().catch((e=>c.logger.error(`GroupCall ${this.groupCallId} onStateChanged() failed to update member state devices"`,e))))},this.onLocalFeedsChanged=()=>{this.state===E.Entered&&this.updateMemberState().catch((e=>c.logger.error(`GroupCall ${this.groupCallId} onLocalFeedsChanged() failed to update member state feeds`,e)))},this.reEmitter=new d.ReEmitter(this),this.groupCallId=null!=l?l:(0,s.genCallID)(),this.creationTs=null!==(y=null===(m=t.currentState.getStateEvents(u.EventType.GroupCallPrefix,this.groupCallId))||void 0===m?void 0:m.getTs())&&void 0!==y?y:null,this.updateParticipants(),t.on(a.RoomStateEvent.Update,this.onRoomState),this.on(b.ParticipantsChanged,this.onParticipantsChanged),this.on(b.GroupCallStateChanged,this.onStateChanged),this.on(b.LocalScreenshareStateChanged,this.onLocalFeedsChanged),this.allowCallWithoutVideoAndAudio=!!p;const _=this.client.getUserId()||"unknown";this.stats=new g.GroupCallStats(this.groupCallId,_),this.stats.reports.on(v.StatsReport.CONNECTION_STATS,this.onConnectionStats),this.stats.reports.on(v.StatsReport.BYTE_SENT_STATS,this.onByteSentStats)}create(){return n(this,void 0,void 0,(function*(){this.creationTs=Date.now(),this.client.groupCallEventHandler.groupCalls.set(this.room.roomId,this),this.client.emit(f.GroupCallEventHandlerEvent.Outgoing,this);const e={"m.intent":this.intent,"m.type":this.type,"io.element.ptt":this.isPtt,dataChannelsEnabled:this.dataChannelsEnabled,dataChannelOptions:this.dataChannelsEnabled?this.dataChannelOptions:void 0};return yield this.client.sendStateEvent(this.room.roomId,u.EventType.GroupCallPrefix,e,this.groupCallId),this}))}get state(){return this._state}set state(e){const t=this._state;e!==t&&(this._state=e,this.emit(b.GroupCallStateChanged,e,t))}get participants(){return this._participants}set participants(e){const t=this._participants,i=(e,t)=>e.sessionId===t.sessionId&&e.screensharing===t.screensharing;(0,p.mapsEqual)(e,t,((e,t)=>(0,p.mapsEqual)(e,t,i)))||(this._participants=e,this.emit(b.ParticipantsChanged,e))}get creationTs(){return this._creationTs}set creationTs(e){this._creationTs=e}get enteredViaAnotherSession(){return this._enteredViaAnotherSession}set enteredViaAnotherSession(e){this._enteredViaAnotherSession=e,this.updateParticipants()}forEachCall(e){for(const t of this.calls.values())for(const i of t.values())e(i)}getLocalFeeds(){const e=[];return this.localCallFeed&&e.push(this.localCallFeed),this.localScreenshareFeed&&e.push(this.localScreenshareFeed),e}hasLocalParticipant(){var e,t;return null!==(t=null===(e=this.participants.get(this.room.getMember(this.client.getUserId())))||void 0===e?void 0:e.has(this.client.getDeviceId()))&&void 0!==t&&t}callExpected(e){var t;const i=R(e),n=null===i?null:this.room.getMember(i),r=e.getOpponentDeviceId();return null!==n&&void 0!==r&&void 0!==(null===(t=this.participants.get(n))||void 0===t?void 0:t.get(r))}initLocalCallFeed(){return n(this,void 0,void 0,(function*(){if(this.state!==E.LocalCallFeedUninitialized)throw new Error(`Cannot initialize local call feed in the "${this.state}" state.`);if(this.state=E.InitializingLocalCallFeed,this.initCallFeedPromise)return this.initCallFeedPromise;try{this.initCallFeedPromise=this.initLocalCallFeedInternal(),yield this.initCallFeedPromise}finally{this.initCallFeedPromise=void 0}}))}initLocalCallFeedInternal(){return n(this,void 0,void 0,(function*(){let e;c.logger.log(`GroupCall ${this.groupCallId} initLocalCallFeedInternal() running`);try{e=yield this.client.getMediaHandler().getUserMediaStream(!0,this.type===m.Video)}catch(t){if(!this.allowCallWithoutVideoAndAudio)throw this.state=E.LocalCallFeedUninitialized,t;e=new MediaStream}if(this._state!==E.InitializingLocalCallFeed)throw this.client.getMediaHandler().stopUserMediaStream(e),new Error("Group call disposed while gathering media stream");const t=new o.CallFeed({client:this.client,roomId:this.room.roomId,userId:this.client.getUserId(),deviceId:this.client.getDeviceId(),stream:e,purpose:l.SDPStreamMetadataPurpose.Usermedia,audioMuted:this.initWithAudioMuted||0===e.getAudioTracks().length||this.isPtt,videoMuted:this.initWithVideoMuted||0===e.getVideoTracks().length});(0,s.setTracksEnabled)(e.getAudioTracks(),!t.isAudioMuted()),(0,s.setTracksEnabled)(e.getVideoTracks(),!t.isVideoMuted()),this.localCallFeed=t,this.addUserMediaFeed(t),this.state=E.LocalCallFeedInitialized}))}updateLocalUsermediaStream(e){return n(this,void 0,void 0,(function*(){if(this.localCallFeed){const t=this.localCallFeed.stream;this.localCallFeed.setNewStream(e);const i=this.localCallFeed.isAudioMuted(),n=this.localCallFeed.isVideoMuted();c.logger.log(`GroupCall ${this.groupCallId} updateLocalUsermediaStream() (oldStreamId=${t.id}, newStreamId=${e.id}, micShouldBeMuted=${i}, vidShouldBeMuted=${n})`),(0,s.setTracksEnabled)(e.getAudioTracks(),!i),(0,s.setTracksEnabled)(e.getVideoTracks(),!n),this.client.getMediaHandler().stopUserMediaStream(t)}}))}enter(){return n(this,void 0,void 0,(function*(){if(this.state===E.LocalCallFeedUninitialized)yield this.initLocalCallFeed();else if(this.state!==E.LocalCallFeedInitialized)throw new Error(`Cannot enter call in the "${this.state}" state`);c.logger.log(`GroupCall ${this.groupCallId} enter() running`),this.state=E.Entered,this.client.on(h.CallEventHandlerEvent.Incoming,this.onIncomingCall);for(const e of this.client.callEventHandler.calls.values())this.onIncomingCall(e);this.retryCallLoopInterval=setInterval(this.onRetryCallLoop,this.retryCallInterval),this.activeSpeaker=void 0,this.onActiveSpeakerLoop(),this.activeSpeakerLoopInterval=setInterval(this.onActiveSpeakerLoop,this.activeSpeakerInterval)}))}dispose(){this.localCallFeed&&(this.removeUserMediaFeed(this.localCallFeed),this.localCallFeed=void 0),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(),null!==this.transmitTimer&&(clearTimeout(this.transmitTimer),this.transmitTimer=null),void 0!==this.retryCallLoopInterval&&(clearInterval(this.retryCallLoopInterval),this.retryCallLoopInterval=void 0),null!==this.participantsExpirationTimer&&(clearTimeout(this.participantsExpirationTimer),this.participantsExpirationTimer=null),this.state===E.Entered&&(this.forEachCall((e=>e.hangup(s.CallErrorCode.UserHangup,!1))),this.activeSpeaker=void 0,clearInterval(this.activeSpeakerLoopInterval),this.retryCallCounts.clear(),clearInterval(this.retryCallLoopInterval),this.client.removeListener(h.CallEventHandlerEvent.Incoming,this.onIncomingCall),this.stats.stop())}leave(){this.dispose(),this.state=E.LocalCallFeedUninitialized}terminate(e=!0){return n(this,void 0,void 0,(function*(){if(this.dispose(),this.room.off(a.RoomStateEvent.Update,this.onRoomState),this.client.groupCallEventHandler.groupCalls.delete(this.room.roomId),this.client.emit(f.GroupCallEventHandlerEvent.Ended,this),this.state=E.Ended,e){const e=this.room.currentState.getStateEvents(u.EventType.GroupCallPrefix,this.groupCallId);yield this.client.sendStateEvent(this.room.roomId,u.EventType.GroupCallPrefix,Object.assign(Object.assign({},e.getContent()),{"m.terminated":y.CallEnded}),this.groupCallId)}}))}isLocalVideoMuted(){return!this.localCallFeed||this.localCallFeed.isVideoMuted()}isMicrophoneMuted(){return!this.localCallFeed||this.localCallFeed.isAudioMuted()}setMicrophoneMuted(e){return n(this,void 0,void 0,(function*(){if(!e&&!(yield this.client.getMediaHandler().hasAudioDevice()))return!1;const t=!e&&this.isPtt;this.isPtt&&(!e&&this.isMicrophoneMuted()?this.transmitTimer=setTimeout((()=>{this.setMicrophoneMuted(!0)}),this.pttMaxTransmitTime):e&&!this.isMicrophoneMuted()&&(null!==this.transmitTimer&&clearTimeout(this.transmitTimer),this.transmitTimer=null)),this.forEachCall((t=>{var i;return null===(i=t.localUsermediaFeed)||void 0===i?void 0:i.setAudioVideoMuted(e,null)}));const i=()=>n(this,void 0,void 0,(function*(){const e=[];this.forEachCall((t=>e.push(t.sendMetadataUpdate()))),yield Promise.all(e).catch((e=>c.logger.info(`GroupCall ${this.groupCallId} setMicrophoneMuted() failed to send some metadata updates`,e)))}));if(t&&(yield i()),this.localCallFeed){c.logger.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() (streamId=${this.localCallFeed.stream.id}, muted=${e})`);try{if(!e){if(null===(yield this.client.getMediaHandler().getUserMediaStream(!0,!this.localCallFeed.isVideoMuted())))return c.logger.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() no device to receive local stream, muted=${e}`),!1}}catch(t){return c.logger.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() no device or permission to receive local stream, muted=${e}`),!1}this.localCallFeed.setAudioVideoMuted(e,null),(0,s.setTracksEnabled)(this.localCallFeed.stream.getAudioTracks(),!e)}else c.logger.log(`GroupCall ${this.groupCallId} setMicrophoneMuted() no stream muted (muted=${e})`),this.initWithAudioMuted=e;return this.forEachCall((t=>(0,s.setTracksEnabled)(t.localUsermediaFeed.stream.getAudioTracks(),!e&&this.callExpected(t)))),this.emit(b.LocalMuteStateChanged,e,this.isLocalVideoMuted()),t||(yield i()),!0}))}setLocalVideoMuted(e){return n(this,void 0,void 0,(function*(){if(!e&&!(yield this.client.getMediaHandler().hasVideoDevice()))return!1;if(this.localCallFeed){c.logger.log(`GroupCall ${this.groupCallId} setLocalVideoMuted() (stream=${this.localCallFeed.stream.id}, muted=${e})`);try{const t=yield this.client.getMediaHandler().getUserMediaStream(!0,!e);yield this.updateLocalUsermediaStream(t),this.localCallFeed.setAudioVideoMuted(null,e),(0,s.setTracksEnabled)(this.localCallFeed.stream.getVideoTracks(),!e)}catch(t){return c.logger.log(`GroupCall ${this.groupCallId} setLocalVideoMuted() no device or permission to receive local stream, muted=${e}`),!1}}else c.logger.log(`GroupCall ${this.groupCallId} setLocalVideoMuted() no stream muted (muted=${e})`),this.initWithVideoMuted=e;const t=[];return this.forEachCall((i=>t.push(i.setLocalVideoMuted(e)))),yield Promise.all(t),this.forEachCall((t=>(0,s.setTracksEnabled)(t.localUsermediaFeed.stream.getVideoTracks(),!e&&this.callExpected(t)))),this.emit(b.LocalMuteStateChanged,this.isMicrophoneMuted(),e),!0}))}setScreensharingEnabled(e,t={}){return n(this,void 0,void 0,(function*(){if(e===this.isScreensharing())return e;if(!e)return this.forEachCall((e=>{e.localScreensharingFeed&&e.removeLocalFeed(e.localScreensharingFeed)})),this.client.getMediaHandler().stopScreensharingStream(this.localScreenshareFeed.stream),this.removeScreenshareFeed(this.localScreenshareFeed),this.localScreenshareFeed=void 0,this.localDesktopCapturerSourceId=void 0,this.emit(b.LocalScreenshareStateChanged,!1,void 0,void 0),!1;try{c.logger.log(`GroupCall ${this.groupCallId} setScreensharingEnabled() is asking for screensharing permissions`);const e=yield this.client.getMediaHandler().getScreensharingStream(t);for(const t of e.getTracks()){const e=()=>{this.setScreensharingEnabled(!1),t.removeEventListener("ended",e)};t.addEventListener("ended",e)}return c.logger.log(`GroupCall ${this.groupCallId} setScreensharingEnabled() granted screensharing permissions. Setting screensharing enabled on all calls`),this.localDesktopCapturerSourceId=t.desktopCapturerSourceId,this.localScreenshareFeed=new o.CallFeed({client:this.client,roomId:this.room.roomId,userId:this.client.getUserId(),deviceId:this.client.getDeviceId(),stream:e,purpose:l.SDPStreamMetadataPurpose.Screenshare,audioMuted:!1,videoMuted:!1}),this.addScreenshareFeed(this.localScreenshareFeed),this.emit(b.LocalScreenshareStateChanged,!0,this.localScreenshareFeed,this.localDesktopCapturerSourceId),this.forEachCall((e=>e.pushLocalFeed(this.localScreenshareFeed.clone()))),!0}catch(e){if(t.throwOnFail)throw e;return c.logger.error(`GroupCall ${this.groupCallId} setScreensharingEnabled() enabling screensharing error`,e),this.emit(b.Error,new w(_.NoUserMedia,"Failed to get screen-sharing stream: ",e)),!1}}))}isScreensharing(){return!!this.localScreenshareFeed}wantsOutgoingCall(e,t){const i=this.client.getUserId(),n=this.client.getDeviceId();return e>=i&&(e!==i||t>n)}placeOutgoingCalls(){var e;let t=!1;for(const[{userId:i},n]of this.participants){const r=null!==(e=this.calls.get(i))&&void 0!==e?e:new Map;for(const[e,o]of n){const n=r.get(e);if((null==n?void 0:n.getOpponentSessionId())!==o.sessionId&&this.wantsOutgoingCall(i,e)){t=!0,void 0!==n&&(c.logger.debug(`GroupCall ${this.groupCallId} placeOutgoingCalls() replacing call (userId=${i}, deviceId=${e}, callId=${n.callId})`),n.hangup(s.CallErrorCode.NewSession,!1));const a=(0,s.createNewMatrixCall)(this.client,this.room.roomId,{invitee:i,opponentDeviceId:e,opponentSessionId:o.sessionId,groupCallId:this.groupCallId});null===a?(c.logger.error(`GroupCall ${this.groupCallId} placeOutgoingCalls() failed to create call (userId=${i}, device=${e})`),r.delete(e)):(this.initCall(a),r.set(e,a),c.logger.debug(`GroupCall ${this.groupCallId} placeOutgoingCalls() placing call (userId=${i}, deviceId=${e}, sessionId=${o.sessionId})`),a.placeCallWithCallFeeds(this.getLocalFeeds().map((e=>e.clone())),o.screensharing).then((()=>{this.dataChannelsEnabled&&a.createDataChannel("datachannel",this.dataChannelOptions)})).catch((t=>{c.logger.warn(`GroupCall ${this.groupCallId} placeOutgoingCalls() failed to place call (userId=${i})`,t),t instanceof s.CallError&&t.code===_.UnknownDevice?this.emit(b.Error,t):this.emit(b.Error,new w(_.PlaceCallFailed,`Failed to place call to ${i}`)),a.hangup(s.CallErrorCode.SignallingFailed,!1),r.get(e)===a&&r.delete(e)})))}}r.size>0?this.calls.set(i,r):this.calls.delete(i)}t&&this.emit(b.CallsChanged,this.calls)}getMemberStateEvents(e){return void 0===e?this.room.currentState.getStateEvents(u.EventType.GroupCallMemberPrefix):this.room.currentState.getStateEvents(u.EventType.GroupCallMemberPrefix,e)}initCall(e){const t=R(e);if(!t)throw new Error("Cannot init call without user id");const i=()=>this.onCallFeedsChanged(e),n=(t,i)=>this.onCallStateChanged(e,t,i),r=this.onCallHangup,o=t=>this.onCallReplaced(e,t);let a=this.callHandlers.get(t);void 0===a&&(a=new Map,this.callHandlers.set(t,a)),a.set(e.getOpponentDeviceId(),{onCallFeedsChanged:i,onCallStateChanged:n,onCallHangup:r,onCallReplaced:o}),e.on(s.CallEvent.FeedsChanged,i),e.on(s.CallEvent.State,n),e.on(s.CallEvent.Hangup,r),e.on(s.CallEvent.Replaced,o),e.isPtt=this.isPtt,this.reEmitter.reEmit(e,Object.values(s.CallEvent)),e.initStats(this.stats),i()}disposeCall(e,t){const i=R(e),n=e.getOpponentDeviceId();if(!i)throw new Error("Cannot dispose call without user id");const r=this.callHandlers.get(i),{onCallFeedsChanged:o,onCallStateChanged:a,onCallHangup:c,onCallReplaced:d}=r.get(n);if(e.removeListener(s.CallEvent.FeedsChanged,o),e.removeListener(s.CallEvent.State,a),e.removeListener(s.CallEvent.Hangup,c),e.removeListener(s.CallEvent.Replaced,d),r.delete(i),0===r.size&&this.callHandlers.delete(i),e.hangupReason===s.CallErrorCode.Replaced)return;const l=this.getUserMediaFeed(i,n);l&&this.removeUserMediaFeed(l);const u=this.getScreenshareFeed(i,n);u&&this.removeScreenshareFeed(u)}getUserMediaFeed(e,t){return this.userMediaFeeds.find((i=>i.userId===e&&i.deviceId===t))}addUserMediaFeed(e){this.userMediaFeeds.push(e),e.measureVolumeActivity(!0),this.emit(b.UserMediaFeedsChanged,this.userMediaFeeds)}replaceUserMediaFeed(e,t){const i=this.userMediaFeeds.findIndex((t=>t.userId===e.userId&&t.deviceId===e.deviceId));if(-1===i)throw new Error("Couldn't find user media feed to replace");this.userMediaFeeds.splice(i,1,t),e.dispose(),t.measureVolumeActivity(!0),this.emit(b.UserMediaFeedsChanged,this.userMediaFeeds)}removeUserMediaFeed(e){const t=this.userMediaFeeds.findIndex((t=>t.userId===e.userId&&t.deviceId===e.deviceId));if(-1===t)throw new Error("Couldn't find user media feed to remove");this.userMediaFeeds.splice(t,1),e.dispose(),this.emit(b.UserMediaFeedsChanged,this.userMediaFeeds),this.activeSpeaker===e&&(this.activeSpeaker=this.userMediaFeeds[0],this.emit(b.ActiveSpeakerChanged,this.activeSpeaker))}getScreenshareFeed(e,t){return this.screenshareFeeds.find((i=>i.userId===e&&i.deviceId===t))}addScreenshareFeed(e){this.screenshareFeeds.push(e),this.emit(b.ScreenshareFeedsChanged,this.screenshareFeeds)}replaceScreenshareFeed(e,t){const i=this.screenshareFeeds.findIndex((t=>t.userId===e.userId&&t.deviceId===e.deviceId));if(-1===i)throw new Error("Couldn't find screenshare feed to replace");this.screenshareFeeds.splice(i,1,t),e.dispose(),this.emit(b.ScreenshareFeedsChanged,this.screenshareFeeds)}removeScreenshareFeed(e){const t=this.screenshareFeeds.findIndex((t=>t.userId===e.userId&&t.deviceId===e.deviceId));if(-1===t)throw new Error("Couldn't find screenshare feed to remove");this.screenshareFeeds.splice(t,1),e.dispose(),this.emit(b.ScreenshareFeedsChanged,this.screenshareFeeds)}updateParticipants(){const e=this.room.getMember(this.client.getUserId());if(!e)return void c.logger.warn(`GroupCall ${this.groupCallId} updateParticipants() tried to update participants before local room member is available`);if(null!==this.participantsExpirationTimer&&(clearTimeout(this.participantsExpirationTimer),this.participantsExpirationTimer=null),this.state===E.Ended)return void(this.participants=new Map);const t=new Map,i=Date.now(),n=this.state===E.Entered||this.enteredViaAnotherSession;let r=1/0;for(const e of this.getMemberStateEvents()){const o=this.room.getMember(e.getStateKey()),s=e.getContent(),a=(Array.isArray(s["m.calls"])?s["m.calls"]:[]).find((e=>e["m.call_id"]===this.groupCallId));let c=(Array.isArray(null==a?void 0:a["m.devices"])?a["m.devices"]:[]).filter((e=>"string"==typeof e.device_id&&"string"==typeof e.session_id&&"number"==typeof e.expires_ts&&e.expires_ts>i&&Array.isArray(e.feeds)));if(n||(null==o?void 0:o.userId)!==this.client.getUserId()||(c=c.filter((e=>e.device_id!==this.client.getDeviceId()))),c.length>0&&"join"===(null==o?void 0:o.membership)){const e=new Map;t.set(o,e);for(const t of c)e.set(t.device_id,{sessionId:t.session_id,screensharing:t.feeds.some((e=>e.purpose===l.SDPStreamMetadataPurpose.Screenshare))}),t.expires_tse.purpose===l.SDPStreamMetadataPurpose.Screenshare))})}this.participants=t,r<1/0&&(this.participantsExpirationTimer=setTimeout((()=>this.updateParticipants()),r-i))}updateDevices(e,t=!1){var i;return n(this,void 0,void 0,(function*(){const n=Date.now(),r=this.client.getUserId(),o=this.getMemberStateEvents(r),s=null!==(i=null==o?void 0:o.getContent())&&void 0!==i?i:{},a=Array.isArray(s["m.calls"])?s["m.calls"]:[];let c=null;const d=[];for(const e of a)e["m.call_id"]===this.groupCallId?c=e:d.push(e);null===c&&(c={});const l=(Array.isArray(c["m.devices"])?c["m.devices"]:[]).filter((e=>"string"==typeof e.device_id&&"string"==typeof e.session_id&&"number"==typeof e.expires_ts&&e.expires_ts>n&&Array.isArray(e.feeds))),h=e(l);if(null===h)return;const f=[...d];h.length>0&&f.push(Object.assign(Object.assign({},c),{"m.call_id":this.groupCallId,"m.devices":h}));const p={"m.calls":f};yield this.client.sendStateEvent(this.room.roomId,u.EventType.GroupCallMemberPrefix,p,r,{keepAlive:t})}))}addDeviceToMemberState(){return n(this,void 0,void 0,(function*(){yield this.updateDevices((e=>[...e.filter((e=>e.device_id!==this.client.getDeviceId())),{device_id:this.client.getDeviceId(),session_id:this.client.getSessionId(),expires_ts:Date.now()+I,feeds:this.getLocalFeeds().map((e=>({purpose:e.purpose})))}]))}))}updateMemberState(){return n(this,void 0,void 0,(function*(){null!==this.resendMemberStateTimer&&(clearInterval(this.resendMemberStateTimer),this.resendMemberStateTimer=null),this.state===E.Entered?(yield this.addDeviceToMemberState(),this.resendMemberStateTimer=setInterval((()=>n(this,void 0,void 0,(function*(){c.logger.log(`GroupCall ${this.groupCallId} updateMemberState() resending call member state"`);try{yield this.addDeviceToMemberState()}catch(e){c.logger.error(`GroupCall ${this.groupCallId} updateMemberState() failed to resend call member state`,e)}}))),27e5)):yield this.updateDevices((e=>e.filter((e=>e.device_id!==this.client.getDeviceId()))),!0)}))}cleanMemberState(){return n(this,void 0,void 0,(function*(){const{devices:e}=yield this.client.getDevices(),t=new Map(e.map((e=>[e.device_id,e])));yield this.updateDevices((e=>{const i=e.filter((e=>{const i=t.get(e.device_id);return void 0!==(null==i?void 0:i.last_seen_ts)&&!(e.device_id===this.client.getDeviceId()&&this.state!==E.Entered&&!this.enteredViaAnotherSession)}));return i.length===e.length?null:i}))}))}getGroupCallStats(){return this.stats}}i.GroupCall=M},{"../@types/event":306,"../ReEmitter":317,"../logger":374,"../models/room-state":390,"../models/typed-event-emitter":395,"../utils":416,"./call":418,"./callEventHandler":419,"./callEventTypes":420,"./callFeed":421,"./groupCallEventHandler":423,"./stats/groupCallStats":427,"./stats/statsReport":432}],423:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.GroupCallEventHandler=i.GroupCallEventHandlerEvent=void 0;const r=e("../client"),o=e("./groupCall"),s=e("../models/room-state"),a=e("../logger"),c=e("../@types/event"),d=e("../sync");var l;!function(e){e.Incoming="GroupCall.incoming",e.Outgoing="GroupCall.outgoing",e.Ended="GroupCall.ended",e.Participants="GroupCall.participants"}(l=i.GroupCallEventHandlerEvent||(i.GroupCallEventHandlerEvent={}));i.GroupCallEventHandler=class{constructor(e){this.client=e,this.groupCalls=new Map,this.roomDeferreds=new Map,this.onRoomsChanged=e=>{this.createGroupCallForRoom(e)},this.onRoomStateChanged=(e,t)=>{if(e.getType()===c.EventType.GroupCallPrefix){const i=e.getStateKey(),n=e.getContent(),r=this.groupCalls.get(t.roomId);r||n["m.terminated"]||e.isRedacted()?r&&r.groupCallId===i?n["m.terminated"]||e.isRedacted()?r.terminate(!1):n["m.type"]!==r.type&&a.logger.warn(`GroupCallEventHandler onRoomStateChanged() currently does not support changing type (roomId=${t.roomId})`):r&&r.groupCallId!==i&&a.logger.warn(`GroupCallEventHandler onRoomStateChanged() currently does not support multiple calls (roomId=${t.roomId})`):this.createGroupCallFromRoomStateEvent(e)}}}start(){return n(this,void 0,void 0,(function*(){this.client.getSyncState()!==d.SyncState.Syncing&&(a.logger.debug("GroupCallEventHandler start() waiting for client to start syncing"),yield new Promise((e=>{const t=()=>{if(this.client.getSyncState()===d.SyncState.Syncing)return this.client.off(r.ClientEvent.Sync,t),e()};this.client.on(r.ClientEvent.Sync,t)})));const e=this.client.getRooms();for(const t of e)this.createGroupCallForRoom(t);this.client.on(r.ClientEvent.Room,this.onRoomsChanged),this.client.on(s.RoomStateEvent.Events,this.onRoomStateChanged)}))}stop(){this.client.removeListener(s.RoomStateEvent.Events,this.onRoomStateChanged)}getRoomDeferred(e){let t=this.roomDeferreds.get(e);if(void 0===t){let i;t={prom:new Promise((e=>{i=e}))},t.resolve=i,this.roomDeferreds.set(e,t)}return t}waitUntilRoomReadyForGroupCalls(e){return this.getRoomDeferred(e).prom}getGroupCallById(e){return[...this.groupCalls.values()].find((t=>t.groupCallId===e))}createGroupCallForRoom(e){const t=e.currentState.getStateEvents(c.EventType.GroupCallPrefix),i=t.sort(((e,t)=>t.getTs()-e.getTs()));for(const n of i){if(!n.getContent()["m.terminated"]&&!n.isRedacted()){a.logger.debug(`GroupCallEventHandler createGroupCallForRoom() choosing group call from possible calls (stateKey=${n.getStateKey()}, ts=${n.getTs()}, roomId=${e.roomId}, numOfPossibleCalls=${t.length})`),this.createGroupCallFromRoomStateEvent(n);break}}a.logger.info(`GroupCallEventHandler createGroupCallForRoom() processed room (roomId=${e.roomId})`),this.getRoomDeferred(e.roomId).resolve()}createGroupCallFromRoomStateEvent(e){const t=e.getRoomId(),i=e.getContent(),n=this.client.getRoom(t);if(!n)return void a.logger.warn(`GroupCallEventHandler createGroupCallFromRoomStateEvent() couldn't find room for call (roomId=${t})`);const r=e.getStateKey(),s=i["m.type"];if(!Object.values(o.GroupCallType).includes(s))return void a.logger.warn(`GroupCallEventHandler createGroupCallFromRoomStateEvent() received invalid call type (type=${s}, roomId=${t})`);const c=i["m.intent"];if(!Object.values(o.GroupCallIntent).includes(c))return void a.logger.warn(`Received invalid group call intent (type=${s}, roomId=${t})`);const d=Boolean(i["io.element.ptt"]);let u;if((null==i?void 0:i.dataChannelsEnabled)&&(null==i?void 0:i.dataChannelOptions)){const{ordered:e,maxPacketLifeTime:t,maxRetransmits:n,protocol:r}=i.dataChannelOptions;u={ordered:e,maxPacketLifeTime:t,maxRetransmits:n,protocol:r}}const h=new o.GroupCall(this.client,n,s,d,c,r,(null==i?void 0:i.dataChannelsEnabled)||this.client.isVoipWithNoMediaAllowed,u,this.client.isVoipWithNoMediaAllowed);return this.groupCalls.set(n.roomId,h),this.client.emit(l.Incoming,h),h}}},{"../@types/event":306,"../client":321,"../logger":374,"../models/room-state":390,"../sync":414,"./groupCall":422}],424:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.MediaHandler=i.MediaHandlerEvent=void 0;const r=e("../models/typed-event-emitter"),o=e("../webrtc/groupCall"),s=e("../logger");var a;!function(e){e.LocalStreamsChanged="local_streams_changed"}(a=i.MediaHandlerEvent||(i.MediaHandlerEvent={}));class c extends r.TypedEventEmitter{constructor(e){super(),this.client=e,this.userMediaStreams=[],this.screensharingStreams=[]}restoreMediaSettings(e,t){this.audioInput=e,this.videoInput=t}setAudioInput(e){return n(this,void 0,void 0,(function*(){s.logger.info(`MediaHandler setAudioInput() running (deviceId=${e})`),this.audioInput!==e&&(this.audioInput=e,yield this.updateLocalUsermediaStreams())}))}setAudioSettings(e){return n(this,void 0,void 0,(function*(){s.logger.info(`MediaHandler setAudioSettings() running (opts=${JSON.stringify(e)})`),this.audioSettings=Object.assign({},e),yield this.updateLocalUsermediaStreams()}))}setVideoInput(e){return n(this,void 0,void 0,(function*(){s.logger.info(`MediaHandler setVideoInput() running (deviceId=${e})`),this.videoInput!==e&&(this.videoInput=e,yield this.updateLocalUsermediaStreams())}))}setMediaInputs(e,t){return n(this,void 0,void 0,(function*(){s.logger.log(`MediaHandler setMediaInputs() running (audioInput: ${e} videoInput: ${t})`),this.audioInput=e,this.videoInput=t,yield this.updateLocalUsermediaStreams()}))}updateLocalUsermediaStreams(){return n(this,void 0,void 0,(function*(){if(0===this.userMediaStreams.length)return;const e=new Map;for(const t of this.client.callEventHandler.calls.values())e.set(t.callId,{audio:t.hasLocalUserMediaAudioTrack,video:t.hasLocalUserMediaVideoTrack});for(const e of this.userMediaStreams){s.logger.log(`MediaHandler updateLocalUsermediaStreams() stopping all tracks (streamId=${e.id})`);for(const t of e.getTracks())t.stop()}this.userMediaStreams=[],this.localUserMediaStream=void 0;for(const t of this.client.callEventHandler.calls.values()){if(t.callHasEnded()||!e.has(t.callId))continue;const{audio:i,video:n}=e.get(t.callId);s.logger.log(`MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (callId=${t.callId})`);const r=yield this.getUserMediaStream(i,n);t.callHasEnded()||(yield t.updateLocalUsermediaStream(r))}for(const e of this.client.groupCallEventHandler.groupCalls.values()){if(!e.localCallFeed)continue;s.logger.log(`MediaHandler updateLocalUsermediaStreams() calling getUserMediaStream() (groupCallId=${e.groupCallId})`);const t=yield this.getUserMediaStream(!0,e.type===o.GroupCallType.Video);e.state!==o.GroupCallState.Ended&&(yield e.updateLocalUsermediaStream(t))}this.emit(a.LocalStreamsChanged)}))}hasAudioDevice(){return n(this,void 0,void 0,(function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind)).length>0}catch(e){return s.logger.log("MediaHandler hasAudioDevice() calling navigator.mediaDevices.enumerateDevices with error",e),!1}}))}hasVideoDevice(){return n(this,void 0,void 0,(function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind)).length>0}catch(e){return s.logger.log("MediaHandler hasVideoDevice() calling navigator.mediaDevices.enumerateDevices with error",e),!1}}))}getUserMediaStream(e,t,i=!0){return n(this,void 0,void 0,(function*(){return this.getMediaStreamPromise?this.getMediaStreamPromise=this.getMediaStreamPromise.then((()=>this.getUserMediaStreamInternal(e,t,i))):this.getMediaStreamPromise=this.getUserMediaStreamInternal(e,t,i),this.getMediaStreamPromise}))}getUserMediaStreamInternal(e,t,i){var r,o,c,d,l;return n(this,void 0,void 0,(function*(){const n=e&&(yield this.hasAudioDevice()),u=t&&(yield this.hasVideoDevice());let h,f=!0;if(this.localUserMediaStream?(n!==this.localUserMediaStream.getAudioTracks().length>0&&(f=!1),u!==this.localUserMediaStream.getVideoTracks().length>0&&(f=!1),n&&(null===(o=null===(r=this.localUserMediaStream.getAudioTracks()[0])||void 0===r?void 0:r.getSettings())||void 0===o?void 0:o.deviceId)!==this.audioInput&&(f=!1),u&&(null===(d=null===(c=this.localUserMediaStream.getVideoTracks()[0])||void 0===c?void 0:c.getSettings())||void 0===d?void 0:d.deviceId)!==this.videoInput&&(f=!1)):f=!1,f){if(h=this.localUserMediaStream.clone(),s.logger.log(`MediaHandler getUserMediaStreamInternal() cloning (oldStreamId=${null===(l=this.localUserMediaStream)||void 0===l?void 0:l.id} newStreamId=${h.id} shouldRequestAudio=${n} shouldRequestVideo=${u})`),!n)for(const e of h.getAudioTracks())h.removeTrack(e);if(!u)for(const e of h.getVideoTracks())h.removeTrack(e)}else{const e=this.getUserMediaContraints(n,u);h=yield navigator.mediaDevices.getUserMedia(e),s.logger.log(`MediaHandler getUserMediaStreamInternal() calling getUserMediaStream (streamId=${h.id}, shouldRequestAudio=${n}, shouldRequestVideo=${u}, constraints=${JSON.stringify(e)})`);for(const e of h.getTracks()){const t=e.getSettings();"audio"===e.kind?this.audioInput=t.deviceId:"video"===e.kind&&(this.videoInput=t.deviceId)}i&&(this.localUserMediaStream=h)}return i&&this.userMediaStreams.push(h),this.emit(a.LocalStreamsChanged),h}))}stopUserMediaStream(e){s.logger.log(`MediaHandler stopUserMediaStream() stopping (streamId=${e.id})`);for(const t of e.getTracks())t.stop();const t=this.userMediaStreams.indexOf(e);-1!==t&&(s.logger.debug(`MediaHandler stopUserMediaStream() splicing usermedia stream out stream array (streamId=${e.id})`,e.id),this.userMediaStreams.splice(t,1)),this.emit(a.LocalStreamsChanged),this.localUserMediaStream===e&&(this.localUserMediaStream=void 0)}getScreensharingStream(e={},t=!0){return n(this,void 0,void 0,(function*(){let i;if(0===this.screensharingStreams.length){const t=this.getScreenshareContraints(e);e.desktopCapturerSourceId?(s.logger.debug(`MediaHandler getScreensharingStream() calling getUserMedia() (opts=${JSON.stringify(e)})`),i=yield navigator.mediaDevices.getUserMedia(t)):(s.logger.debug(`MediaHandler getScreensharingStream() calling getDisplayMedia() (opts=${JSON.stringify(e)})`),i=yield navigator.mediaDevices.getDisplayMedia(t))}else{const e=this.screensharingStreams[this.screensharingStreams.length-1];s.logger.log(`MediaHandler getScreensharingStream() cloning (streamId=${e.id})`),i=e.clone()}return t&&this.screensharingStreams.push(i),this.emit(a.LocalStreamsChanged),i}))}stopScreensharingStream(e){s.logger.debug(`MediaHandler stopScreensharingStream() stopping stream (streamId=${e.id})`);for(const t of e.getTracks())t.stop();const t=this.screensharingStreams.indexOf(e);-1!==t&&(s.logger.debug(`MediaHandler stopScreensharingStream() splicing stream out (streamId=${e.id})`),this.screensharingStreams.splice(t,1)),this.emit(a.LocalStreamsChanged)}stopAllStreams(){for(const e of this.userMediaStreams){s.logger.log(`MediaHandler stopAllStreams() stopping (streamId=${e.id})`);for(const t of e.getTracks())t.stop()}for(const e of this.screensharingStreams)for(const t of e.getTracks())t.stop();this.userMediaStreams=[],this.screensharingStreams=[],this.localUserMediaStream=void 0,this.emit(a.LocalStreamsChanged)}getUserMediaContraints(e,t){const i=!!navigator.webkitGetUserMedia;return{audio:!!e&&{deviceId:this.audioInput?{ideal:this.audioInput}:void 0,autoGainControl:this.audioSettings?{ideal:this.audioSettings.autoGainControl}:void 0,echoCancellation:this.audioSettings?{ideal:this.audioSettings.echoCancellation}:void 0,noiseSuppression:this.audioSettings?{ideal:this.audioSettings.noiseSuppression}:void 0},video:!!t&&{deviceId:this.videoInput?{ideal:this.videoInput}:void 0,width:i?{exact:640}:{ideal:640},height:i?{exact:360}:{ideal:360}}}}getScreenshareContraints(e){const{desktopCapturerSourceId:t,audio:i}=e;return t?{audio:null!=i&&i,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t}}}:{audio:null!=i&&i,video:!0}}}i.MediaHandler=c},{"../logger":374,"../models/typed-event-emitter":395,"../webrtc/groupCall":422}],425:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConnectionStats=void 0;i.ConnectionStats=class{constructor(){this.bandwidth={},this.bitrate={},this.packetLoss={},this.transport=[]}}},{}],426:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.ConnectionStatsReporter=void 0;i.ConnectionStatsReporter=class{static buildBandwidthReport(e){const t=e.availableIncomingBitrate,i=e.availableOutgoingBitrate;return{download:t?Math.round(t/1e3):0,upload:i?Math.round(i/1e3):0}}}},{}],427:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.GroupCallStats=void 0;const n=e("./statsReportGatherer"),r=e("./statsReportEmitter");i.GroupCallStats=class{constructor(e,t,i=1e4){this.groupCallId=e,this.userId=t,this.interval=i,this.gatherers=new Map,this.reports=new r.StatsReportEmitter}start(){void 0===this.timer&&(this.timer=setInterval((()=>{this.processStats()}),this.interval))}stop(){void 0!==this.timer&&(clearInterval(this.timer),this.gatherers.forEach((e=>e.stopProcessingStats())))}hasStatsReportGatherer(e){return this.gatherers.has(e)}addStatsReportGatherer(e,t,i){return!this.hasStatsReportGatherer(e)&&(this.gatherers.set(e,new n.StatsReportGatherer(e,t,i,this.reports)),!0)}removeStatsReportGatherer(e){return this.gatherers.delete(e)}getStatsReportGatherer(e){return this.hasStatsReportGatherer(e)?this.gatherers.get(e):void 0}processStats(){this.gatherers.forEach((e=>e.processStats(this.groupCallId,this.userId)))}}},{"./statsReportEmitter":434,"./statsReportGatherer":435}],428:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MediaSsrcHandler=void 0;const n=e("sdp-transform");i.MediaSsrcHandler=class{constructor(){this.ssrcToMid={local:new Map,remote:new Map}}findMidBySsrc(e,t){let i;return this.ssrcToMid[t].forEach(((t,n)=>{t.find((t=>t==e))&&(i=n)})),i}parse(e,t){const i=(0,n.parse)(e),r=new Map;i.media.forEach((e=>{var t;if(e.mid&&"video"===e.type||"audio"===e.type){const i=[];null===(t=e.ssrcs)||void 0===t||t.forEach((e=>{"cname"===e.attribute&&i.push(`${e.id}`)})),r.set(`${e.mid}`,i)}})),this.ssrcToMid[t]=r}getSsrcToMidMap(e){return this.ssrcToMid[e]}}},{"sdp-transform":253}],429:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MediaTrackHandler=void 0;i.MediaTrackHandler=class{constructor(e){this.pc=e}getLocalTracks(e){return this.pc.getTransceivers().filter((e=>"sendonly"===e.currentDirection||"sendrecv"===e.currentDirection)).filter((e=>null!==e.sender)).map((e=>e.sender)).map((e=>e.track)).filter((t=>null!==t&&t.kind===e))}getTackById(e){return this.pc.getTransceivers().map((t=>null!==(null==t?void 0:t.sender.track)&&t.sender.track.id===e?t.sender.track:null!==(null==t?void 0:t.receiver.track)&&t.receiver.track.id===e?t.receiver.track:void 0)).find((e=>void 0!==e))}getLocalTrackIdByMid(e){const t=this.pc.getTransceivers().find((t=>t.mid===e));if(void 0!==t&&t.sender&&t.sender.track)return t.sender.track.id}getRemoteTrackIdByMid(e){const t=this.pc.getTransceivers().find((t=>t.mid===e));if(void 0!==t&&t.receiver&&t.receiver.track)return t.receiver.track.id}getActiveSimulcastStreams(){return 3}}},{}],430:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MediaTrackStats=void 0;i.MediaTrackStats=class{constructor(e,t,i){this.trackId=e,this.type=t,this.kind=i,this.loss={packetsTotal:0,packetsLost:0,isDownloadStream:!1},this.bitrate={download:0,upload:0},this.resolution={width:-1,height:-1},this.framerate=0,this.codec=""}getType(){return this.type}setLoss(e){this.loss=e}getLoss(){return this.loss}setResolution(e){this.resolution=e}getResolution(){return this.resolution}setFramerate(e){this.framerate=e}getFramerate(){return this.framerate}setBitrate(e){this.bitrate=e}getBitrate(){return this.bitrate}setCodec(e){return this.codec=e,!0}getCodec(){return this.codec}resetBitrate(){this.bitrate={download:0,upload:0}}}},{}],431:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.MediaTrackStatsHandler=void 0;const n=e("./mediaTrackStats");i.MediaTrackStatsHandler=class{constructor(e,t){this.mediaSsrcHandler=e,this.mediaTrackHandler=t,this.track2stats=new Map}findTrack2Stats(e,t){let i;if(e.trackIdentifier)i=e.trackIdentifier;else if(e.mid)i="remote"===t?this.mediaTrackHandler.getRemoteTrackIdByMid(e.mid):this.mediaTrackHandler.getLocalTrackIdByMid(e.mid);else if(e.ssrc){if(!this.mediaSsrcHandler.findMidBySsrc(e.ssrc,t))return;i="remote"===t?this.mediaTrackHandler.getRemoteTrackIdByMid(e.mid):this.mediaTrackHandler.getLocalTrackIdByMid(e.mid)}if(!i)return;let r=this.track2stats.get(i);if(!r){const e=this.mediaTrackHandler.getTackById(i);if(void 0===e)return;{const o="audio"===e.kind?e.kind:"video";r=new n.MediaTrackStats(i,t,o),this.track2stats.set(i,r)}}return r}findLocalVideoTrackStats(e){if(0!==this.mediaTrackHandler.getLocalTracks("video").length)return this.findTrack2Stats(e,"local")}getTrack2stats(){return this.track2stats}}},{"./mediaTrackStats":430}],432:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.StatsReport=void 0,function(e){e.CONNECTION_STATS="StatsReport.connection_stats",e.BYTE_SENT_STATS="StatsReport.byte_sent_stats"}(i.StatsReport||(i.StatsReport={}))},{}],433:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.StatsReportBuilder=void 0;class n{static build(e){const t={},i={download:0,upload:0},r={download:0,upload:0};let o=0,s=0;const a={local:new Map,remote:new Map},c={local:new Map,remote:new Map},d={local:new Map,remote:new Map};let l=0,u=0,h=0,f=0;for(const[t,n]of e){const e=n.getLoss(),p=e.isDownloadStream?"download":"upload";i[p]+=e.packetsTotal,r[p]+=e.packetsLost,o+=n.getBitrate().download,s+=n.getBitrate().upload,"audio"===n.kind?(l+=n.getBitrate().download,u+=n.getBitrate().upload):(h+=n.getBitrate().download,f+=n.getBitrate().upload),a[n.getType()].set(t,n.getResolution()),c[n.getType()].set(t,n.getFramerate()),d[n.getType()].set(t,n.getCodec()),n.resetBitrate()}return t.bitrate={upload:s,download:o},t.bitrate.audio={upload:u,download:l},t.bitrate.video={upload:f,download:h},t.packetLoss={total:n.calculatePacketLoss(r.download+r.upload,i.download+i.upload),download:n.calculatePacketLoss(r.download,i.download),upload:n.calculatePacketLoss(r.upload,i.upload)},t.framerate=c,t.resolution=a,t.codec=d,t}static calculatePacketLoss(e,t){return!t||t<=0||!e||e<=0?0:Math.round(e/t*100)}}i.StatsReportBuilder=n},{}],434:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.StatsReportEmitter=void 0;const n=e("../../models/typed-event-emitter"),r=e("./statsReport");class o extends n.TypedEventEmitter{emitByteSendReport(e){this.emit(r.StatsReport.BYTE_SENT_STATS,e)}emitConnectionStatsReport(e){this.emit(r.StatsReport.CONNECTION_STATS,e)}}i.StatsReportEmitter=o},{"../../models/typed-event-emitter":395,"./statsReport":432}],435:[function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,a)}c((n=n.apply(e,t||[])).next())}))};Object.defineProperty(i,"__esModule",{value:!0}),i.StatsReportGatherer=void 0;const r=e("./connectionStats"),o=e("./connectionStatsReporter"),s=e("./transportStatsReporter"),a=e("./media/mediaSsrcHandler"),c=e("./media/mediaTrackHandler"),d=e("./media/mediaTrackStatsHandler"),l=e("./trackStatsReporter"),u=e("./statsReportBuilder"),h=e("./statsValueFormatter");i.StatsReportGatherer=class{constructor(e,t,i,n,o=!0){this.callId=e,this.remoteUserId=t,this.pc=i,this.emitter=n,this.isFocus=o,this.isActive=!0,this.connectionStats=new r.ConnectionStats,i.addEventListener("signalingstatechange",this.onSignalStateChange.bind(this)),this.trackStats=new d.MediaTrackStatsHandler(new a.MediaSsrcHandler,new c.MediaTrackHandler(i))}processStats(e,t){return n(this,void 0,void 0,(function*(){if(this.isActive){const i=this.pc.getStats();if("function"==typeof(null==i?void 0:i.then))return i.then((i=>{this.currentStatsReport="function"==typeof(null==i?void 0:i.result)?i.result():i;try{this.processStatsReport(e,t)}catch(e){return this.isActive=!1,!1}return this.previousStatsReport=this.currentStatsReport,!0})).catch((e=>(this.handleError(e),!1)));this.isActive=!1}return Promise.resolve(!1)}))}processStatsReport(e,t){var i;const n=new Map;null===(i=this.currentStatsReport)||void 0===i||i.forEach((e=>{const t=this.previousStatsReport?this.previousStatsReport.get(e.id):null;if("candidate-pair"===e.type&&e.nominated&&"succeeded"===e.state)this.connectionStats.bandwidth=o.ConnectionStatsReporter.buildBandwidthReport(e),this.connectionStats.transport=s.TransportStatsReporter.buildReport(this.currentStatsReport,e,this.connectionStats.transport,this.isFocus);else if("inbound-rtp"===e.type||"outbound-rtp"===e.type){const i=this.trackStats.findTrack2Stats(e,"inbound-rtp"===e.type?"remote":"local");if(!i)return;t&&l.TrackStatsReporter.buildPacketsLost(i,e,t),"inbound-rtp"===e.type?(l.TrackStatsReporter.buildFramerateResolution(i,e),t&&l.TrackStatsReporter.buildBitrateReceived(i,e,t)):t&&(n.set(i.trackId,h.StatsValueFormatter.getNonNegativeValue(e.bytesSent)),l.TrackStatsReporter.buildBitrateSend(i,e,t)),l.TrackStatsReporter.buildCodec(this.currentStatsReport,i,e)}else if("track"===e.type&&"video"===e.kind&&!e.remoteSource){const i=this.trackStats.findLocalVideoTrackStats(e);if(!i)return;l.TrackStatsReporter.buildFramerateResolution(i,e),l.TrackStatsReporter.calculateSimulcastFramerate(i,e,t,this.trackStats.mediaTrackHandler.getActiveSimulcastStreams())}})),this.emitter.emitByteSendReport(n),this.processAndEmitReport()}setActive(e){this.isActive=e}getActive(){return this.isActive}handleError(e){this.isActive=!1}processAndEmitReport(){const e=u.StatsReportBuilder.build(this.trackStats.getTrack2stats());this.connectionStats.bandwidth=e.bandwidth,this.connectionStats.bitrate=e.bitrate,this.connectionStats.packetLoss=e.packetLoss,this.emitter.emitConnectionStatsReport(Object.assign(Object.assign({},e),{transport:this.connectionStats.transport})),this.connectionStats.transport=[]}stopProcessingStats(){}onSignalStateChange(){"stable"===this.pc.signalingState&&(this.pc.currentRemoteDescription&&this.trackStats.mediaSsrcHandler.parse(this.pc.currentRemoteDescription.sdp,"remote"),this.pc.currentLocalDescription&&this.trackStats.mediaSsrcHandler.parse(this.pc.currentLocalDescription.sdp,"local"))}}},{"./connectionStats":425,"./connectionStatsReporter":426,"./media/mediaSsrcHandler":428,"./media/mediaTrackHandler":429,"./media/mediaTrackStatsHandler":431,"./statsReportBuilder":433,"./statsValueFormatter":436,"./trackStatsReporter":437,"./transportStatsReporter":438}],436:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.StatsValueFormatter=void 0;i.StatsValueFormatter=class{static getNonNegativeValue(e){let t=e;return"number"!=typeof t&&(t=Number(t)),isNaN(t)?0:Math.max(0,t)}}},{}],437:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TrackStatsReporter=void 0;const n=e("./statsValueFormatter");class r{static buildFramerateResolution(e,t){const i={height:t.frameHeight,width:t.frameWidth},n=t.framesPerSecond;i.height&&i.width&&e.setResolution(i),e.setFramerate(Math.round(n||0))}static calculateSimulcastFramerate(e,t,i,n){let r=e.getFramerate();if(!r){if(i){const e=t.timestamp-i.timestamp;if(e>0&&t.framesSent){r=(t.framesSent-i.framesSent)/e*1e3}}if(!r)return}r=n?Math.round(r/n):0,e.setFramerate(r)}static buildCodec(e,t,i){const n=null==e?void 0:e.get(i.codecId);if(n){const e=n.mimeType.split("/")[1];e&&t.setCodec(e)}}static buildBitrateReceived(e,t,i){e.setBitrate({download:r.calculateBitrate(t.bytesReceived,i.bytesReceived,t.timestamp,i.timestamp),upload:0})}static buildBitrateSend(e,t,i){e.setBitrate({download:0,upload:this.calculateBitrate(t.bytesSent,i.bytesSent,t.timestamp,i.timestamp)})}static buildPacketsLost(e,t,i){const r="outbound-rtp"===t.type?"packetsSent":"packetsReceived";let o=t[r];(!o||o<0)&&(o=0);const s=n.StatsValueFormatter.getNonNegativeValue(i[r]),a=Math.max(0,o-s),c=n.StatsValueFormatter.getNonNegativeValue(t.packetsLost),d=n.StatsValueFormatter.getNonNegativeValue(i.packetsLost),l=Math.max(0,c-d);e.setLoss({packetsTotal:a+l,packetsLost:l,isDownloadStream:"outbound-rtp"!==t.type})}static calculateBitrate(e,t,i,r){const o=n.StatsValueFormatter.getNonNegativeValue(e),s=n.StatsValueFormatter.getNonNegativeValue(t),a=Math.max(0,o-s),c=i-r;let d=0;return c>0&&(d=Math.round(8*a/c)),d}}i.TrackStatsReporter=r},{"./statsValueFormatter":436}],438:[function(e,t,i){"use strict";Object.defineProperty(i,"__esModule",{value:!0}),i.TransportStatsReporter=void 0;i.TransportStatsReporter=class{static buildReport(e,t,i,n){const r=null==e?void 0:e.get(t.localCandidateId),o=null==e?void 0:e.get(t.remoteCandidateId);if(o&&r){const e=`${void 0!==o.ip?o.ip:o.address}:${o.port}`,s=`${void 0!==r.ip?r.ip:r.address}:${r.port}`,a=o.protocol;i.some((t=>t.ip===e&&t.type===a&&t.localIp===s))||i.push({ip:e,type:a,localIp:s,isFocus:n,localCandidateType:r.candidateType,remoteCandidateType:o.candidateType,networkType:r.networkType,rtt:t.currentRoundTripTime?1e3*t.currentRoundTripTime:NaN})}return i}}},{}]},{},[320]); \ No newline at end of file diff --git a/includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.min.js.map b/includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.min.js.map deleted file mode 100644 index 2e96db6..0000000 --- a/includes/external/matrix/node_modules/matrix-js-sdk/dist/browser-matrix.min.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"names":["r","e","n","t","o","i","f","c","require","u","a","Error","code","p","exports","call","length","module","escaped","escapes","String","fromCharCode","toString","slice","toUpperCase","escapeString","value","lastIndex","replace","stringify","isFinite","Array","isArray","array","sep","result","stringifyArray","object","keys","Object","sort","key","stringifyObject","asn1","bignum","define","base","constants","decoders","encoders","inherits","Entity","name","body","this","prototype","_createNamed","Base","Generated","entity","_initNamed","_getDecoder","enc","hasOwnProperty","decode","data","options","_getEncoder","encode","reporter","Reporter","Buffer","DecoderBuffer","isBuffer","offset","error","EncoderBuffer","map","item","isEncoderBuffer","byteLength","isDecoderBuffer","constructor","save","restore","isEmpty","readUInt8","skip","raw","res","fail","bytes","_reporterState","join","out","alloc","forEach","write","copy","Node","assert","tags","methods","concat","parent","state","_baseState","children","tag","args","reverseArgs","choice","optional","any","obj","use","useDecoder","explicit","implicit","contains","_wrap","stateProps","clone","cstate","prop","method","push","apply","arguments","_init","filter","child","equal","_useArgs","arg","def","val","num","newKey","_decode","input","wrapResult","prevObj","present","prevKey","enterKey","_peekTag","isError","_decodeGeneric","_decodeChoice","enterObject","_decodeTag","start","track","path","_getUse","leaveObject","exitKey","leaveKey","_decodeList","test","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeBool","_decodeInt","_use","match","some","node","type","_createEncoderBuffer","_encode","_encodeValue","undefined","_skipDefault","content","primitive","_encodeChoice","_encodePrimitive","cls","_encodeComposite","JSON","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool","_isNumstr","str","_isPrintstr","errors","ReporterError","msg","rethrow","pathLen","index","prev","now","err","inherited","elem","message","stack","partial","captureStackTrace","reverse","tagClass","tagClassByName","tagByName","_reverse","der","DERDecoder","tree","DERNode","derDecodeTag","buf","oct","tagStr","derDecodeLen","len","j","buffer","decodedTag","_skipUntilEnd","decoder","possibleEnd","unused","readUInt16BE","numstr","printstr","values","relative","identifiers","ident","subident","first","second","tmp","year","mon","day","hour","min","sec","Date","UTC","pem","PEMDecoder","lines","split","label","re","end","base64","from","DEREncoder","two","encodedTag","encodeTag","header","lenOctets","writeUInt16BE","charCodeAt","id","splice","size","objid","time","date","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","numArray","toArray","sign","unshift","dataBuffer","defaultBuffer","PEMEncoder","global","possibleNames","g","globalThis","self","window","b64","lens","getLens","validLen","placeHoldersLen","toByteArray","arr","Arr","_byteLength","curByte","revLookup","fromByteArray","uint8","extraBytes","parts","maxChunkLength","len2","encodeChunk","lookup","Uint8Array","indexOf","output","ctor","superCtor","super_","TempCtor","BN","number","endian","isBN","negative","words","red","wordSize","parseHex4Bits","string","parseHexByte","lowerBound","parseBase","mul","Math","max","left","right","cmp","_initNumber","_initArray","_parseHex","_parseBase","ceil","w","off","strip","limbLen","limbPow","total","mod","word","imuln","_iaddn","pow","dest","_expand","_normSign","inspect","zeros","groupSizes","groupBases","smallMulTo","b","lo","carry","k","ncarry","rword","maxJ","padding","groupSize","groupBase","isZero","modn","idivn","toNumber","ret","toJSON","toBuffer","toArrayLike","ArrayType","reqLength","littleEndian","q","andln","iushrn","clz32","_countBits","_zeroBits","bitLength","hi","zeroBits","toTwos","width","abs","inotn","iaddn","fromTwos","testn","notn","ineg","isNeg","neg","iuor","ior","or","uor","iuand","iand","and","uand","iuxor","ixor","xor","uxor","bytesNeeded","bitsLeft","setn","bit","wbit","iadd","isub","add","sub","comb10MulTo","mid","a0","al0","ah0","a1","al1","ah1","a2","al2","ah2","a3","al3","ah3","a4","al4","ah4","a5","al5","ah5","a6","al6","ah6","a7","al7","ah7","a8","al8","ah8","a9","al9","ah9","b0","bl0","bh0","b1","bl1","bh1","b2","bl2","bh2","b3","bl3","bh3","b4","bl4","bh4","b5","bl5","bh5","b6","bl6","bh6","b7","bl7","bh7","b8","bl8","bh8","b9","bl9","bh9","w0","imul","w1","w2","w3","w4","w5","w6","w7","w8","w9","w10","w11","w12","w13","w14","w15","w16","w17","w18","jumboMulTo","FFTM","mulp","x","y","mulTo","hncarry","bigMulTo","makeRBT","N","l","revBin","rb","permute","rbt","rws","iws","rtws","itws","transform","s","rtwdf","cos","PI","itwdf","sin","rtwdf_","itwdf_","ie","ro","io","rx","guessLen13b","m","odd","conjugate","normalize13b","ws","round","convert13b","stub","ph","_","rwst","iwst","nrws","nrwst","niwst","rmws","mulf","muln","sqr","isqr","toBitArray","iushln","bits","carryMask","newCarry","ishln","hint","extended","h","mask","maskedWords","ishrn","shln","ushln","shrn","ushrn","imaskn","maskn","isubn","addn","subn","iabs","_ishlnsubmul","shift","_wordDiv","mode","bhi","diff","qj","div","divmod","positive","divn","umod","divRound","dm","half","r2","acc","egcd","A","B","C","D","isEven","yp","xp","im","isOdd","jm","gcd","_invmp","x1","x2","delta","cmpn","invm","bincn","ucmp","gtn","gt","gten","gte","ltn","lt","lten","lte","eqn","eq","Red","toRed","ctx","convertTo","_forceRed","fromRed","convertFrom","forceRed","redAdd","redIAdd","redSub","redISub","redShl","shl","redMul","_verify2","redIMul","redSqr","_verify1","redISqr","redSqrt","sqrt","redInvm","redNeg","redPow","primes","k256","p224","p192","p25519","MPrime","_tmp","K256","P224","P192","P25519","prime","_prime","Mont","imod","rinv","minv","ireduce","rlen","imulK","_strip","outLen","next","mod3","one","nOne","lpow","z","inv","wnd","current","currentLen","mont","Rand","rand","generate","_rand","getBytes","getByte","crypto","getRandomValues","msCrypto","randomBytes","asUInt32Array","readUInt32BE","scrubVec","v","cryptBlock","M","keySchedule","SUB_MIX","SBOX","nRounds","t0","t1","t2","t3","SUB_MIX0","SUB_MIX1","SUB_MIX2","SUB_MIX3","s0","s1","s2","s3","ksRow","RCON","G","d","INV_SBOX","INV_SUB_MIX","xi","sx","x4","x8","AES","_key","_reset","blockSize","keySize","keyWords","ksRows","invKeySchedule","ik","ksR","tt","_nRounds","_keySchedule","_invKeySchedule","encryptBlockRaw","encryptBlock","allocUnsafe","writeUInt32BE","decryptBlock","m1","scrub","aes","Transform","GHASH","incr32","StreamCipher","iv","decrypt","_cipher","ck","_ghash","_finID","ghash","toPad","update","ivBits","tail","writeUIntBE","calcIv","_prev","_cache","_secCache","_decrypt","_alen","_len","_mode","_authTag","_called","_update","chunk","rump","encrypt","_final","final","xorTest","getAuthTag","setAuthTag","setAAD","ciphers","deciphers","modes","createCipher","Cipher","createCipheriv","Cipheriv","createDecipher","Decipher","createDecipheriv","Decipheriv","listCiphers","getCiphers","AuthCipher","MODES","ebtk","Splitter","_last","_autopadding","cache","suite","password","config","toLowerCase","TypeError","thing","get","flush","last","padded","unpad","setAutoPadding","setTo","autoPadding","evp_bytestokey","PADDING","equals","padBuff","writeUInt8","ZEROES","fromArray","block","_multiply","lsbVi","Vi","Zi","abl","bl","pad","encryptStart","encryptByte","byteParam","shiftIn","getBlock","chunkNum","modeModules","ECB","CBC","CFB","CFB8","CFB1","OFB","CTR","GCM","cipher","aes128","aes192","aes256","DES","aesModes","desModes","keyLen","ivLen","CipherBase","des","instantiate","EDE","opts","modeName","_des","create","des3","getr","priv","modulus","prime1","prime2","crt","blinds","blinder","publicExponent","unblinder","blind","blinded","c1","c2","qinv","coefficient","exponent1","m2","exponent2","randombytes","move","src","_move","Symbol","for","modrn","allocate","_toArrayLikeLE","position","_toArrayLikeBE","isNegNum","sha224WithRSAEncryption","hash","sha256WithRSAEncryption","sha384WithRSAEncryption","sha512WithRSAEncryption","sha256","sha224","sha384","sha512","DSA","ripemd160WithRSA","md5WithRSAEncryption","createHash","stream","verify","algorithms","Sign","algorithm","Writable","_hashType","_hash","_tag","_signType","Verify","createSign","createVerify","_write","done","digest","sig","createHmac","EC","ec","parseKeys","curves","getKey","algo","hlen","hbits","bits2int","bits2octets","fill","obits","makeKey","kv","makeR","hashType","signType","curve","curveId","keyFromPrivate","privateKey","toDER","ecSign","params","priv_key","H","dsaSign","elliptic","checkValue","pub","pubkey","subjectPrivateKey","ecVerify","pub_key","unpacked","signature","montp","dsaVerify","padNum","dup","codes","createErrorType","NodeError","_Base","subClass","superClass","arg1","arg2","arg3","getMessage","__proto__","oneOf","expected","actual","determiner","search","pos","substr","this_len","substring","endsWith","includes","process","objectKeys","Duplex","Readable","allowHalfOpen","readable","writable","once","onend","_writableState","ended","nextTick","onEndNT","defineProperty","enumerable","highWaterMark","getBuffer","_readableState","destroyed","set","_process","PassThrough","_transform","encoding","cb","ReadableState","EventEmitter","EElistenerCount","emitter","listeners","Stream","OurUint8Array","debug","debugUtil","debuglog","StringDecoder","createReadableStreamAsyncIterator","BufferList","destroyImpl","getHighWaterMark","_require$codes","ERR_INVALID_ARG_TYPE","ERR_STREAM_PUSH_AFTER_EOF","ERR_METHOD_NOT_IMPLEMENTED","ERR_STREAM_UNSHIFT_AFTER_END_EVENT","errorOrDestroy","kProxyEvents","isDuplex","objectMode","readableObjectMode","pipes","pipesCount","flowing","endEmitted","reading","sync","needReadable","emittedReadable","readableListening","resumeScheduled","paused","emitClose","autoDestroy","defaultEncoding","awaitDrain","readingMore","read","_read","destroy","_destroy","readableAddChunk","addToFront","skipChunkCheck","er","emitReadable","emitReadable_","onEofChunk","chunkInvalid","getPrototypeOf","_uint8ArrayToBuffer","addChunk","maybeReadMore","emit","_undestroy","undestroy","isPaused","setEncoding","head","clear","MAX_HWM","howMuchToRead","computeNewHighWaterMark","flow","maybeReadMore_","updateReadableListening","listenerCount","resume","nReadingNextTick","resume_","fromList","consume","endReadable","endReadableNT","wState","finished","xs","parseInt","nOrig","doRead","pipe","pipeOpts","endFn","stdout","stderr","unpipe","onunpipe","unpipeInfo","hasUnpiped","removeListener","onclose","onfinish","ondrain","onerror","ondata","cleanedUp","needDrain","on","pipeOnDrain","pause","event","fn","prependListener","_events","dests","ev","addListener","removeAllListeners","wrap","_this","bind","asyncIterator","_fromList","iterable","events","util","ERR_MULTIPLE_CALLBACK","ERR_TRANSFORM_ALREADY_TRANSFORMING","ERR_TRANSFORM_WITH_LENGTH_0","afterTransform","ts","_transformState","transforming","writecb","writechunk","rs","needTransform","writeencoding","_flush","prefinish","err2","CorkedRequest","entry","finish","corkReq","callback","pendingcb","corkedRequestsFree","onCorkedFinish","WritableState","internalUtil","deprecate","realHasInstance","ERR_STREAM_CANNOT_PIPE","ERR_STREAM_DESTROYED","ERR_STREAM_NULL_VALUES","ERR_STREAM_WRITE_AFTER_END","ERR_UNKNOWN_ENCODING","nop","writableObjectMode","finalCalled","ending","noDecode","decodeStrings","writing","corked","bufferProcessing","onwrite","writelen","onwriteStateUpdate","finishMaybe","errorEmitted","onwriteError","needFinish","bufferedRequest","clearBuffer","afterWrite","lastBufferedRequest","prefinished","bufferedRequestCount","writev","_writev","doWrite","onwriteDrain","holder","count","allBuffers","isBuf","callFinal","need","rState","hasInstance","Function","writeAfterEnd","validChunk","newChunk","decodeChunk","writeOrBuffer","cork","uncork","setDefaultEncoding","endWritable","_Object$setPrototypeO","_defineProperty","configurable","kLastResolve","kLastReject","kError","kEnded","kLastPromise","kHandlePromise","kStream","createIterResult","readAndResolve","iter","resolve","onReadable","AsyncIteratorPrototype","ReadableStreamAsyncIteratorPrototype","setPrototypeOf","Promise","reject","promise","lastPromise","then","wrapForNext","_this2","_Object$create","iterator","ownKeys","enumerableOnly","getOwnPropertySymbols","symbols","sym","getOwnPropertyDescriptor","_defineProperties","target","props","descriptor","custom","instance","Constructor","_classCallCheck","protoProps","staticProps","hasStrings","_getString","_getBuffer","nb","source","getOwnPropertyDescriptors","defineProperties","_objectSpread","depth","customInspect","emitErrorAndCloseNT","emitErrorNT","emitCloseNT","readableDestroyed","writableDestroyed","ERR_STREAM_PREMATURE_CLOSE","noop","eos","called","onlegacyfinish","writableEnded","readableEnded","onrequest","req","setHeader","abort","isRequest","ERR_MISSING_ARGS","to","streams","pop","popCallback","destroys","closed","destroyer","reduce","ERR_INVALID_OPT_VALUE","duplexKey","hwm","highWaterMarkFrom","floor","pipeline","basex","ALPHABET","BASE_MAP","charAt","xc","BASE","LEADER","FACTOR","log","iFACTOR","decodeUnsafe","psz","zeroes","b256","it3","it4","vch","ArrayBuffer","isView","byteOffset","pbegin","pend","b58","it1","it2","repeat","ieee754","SlowBuffer","INSPECT_MAX_BYTES","K_MAX_LENGTH","createBuffer","RangeError","encodingOrOffset","isEncoding","fromString","fromArrayLike","isInstance","fromArrayBuffer","valueOf","checked","numberIsNaN","fromObject","toPrimitive","assertSize","mustMatch","loweredCase","utf8ToBytes","base64ToBytes","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","bidirectionalIndexOf","dir","arrayIndexOf","lastIndexOf","indexSize","arrLength","valLength","foundIndex","found","hexWrite","Number","remaining","strLen","parsed","utf8Write","blitBuffer","asciiWrite","byteArray","asciiToBytes","latin1Write","base64Write","ucs2Write","units","utf16leToBytes","secondByte","thirdByte","fourthByte","tempCodePoint","firstByte","codePoint","bytesPerSequence","codePoints","MAX_ARGUMENTS_LENGTH","decodeCodePointsArray","kMaxLength","TYPED_ARRAY_SUPPORT","foo","typedArraySupport","console","species","poolSize","allocUnsafeSlow","_isBuffer","compare","list","swap16","swap32","swap64","toLocaleString","trim","thisStart","thisEnd","thisCopy","targetCopy","_arr","toHex","checkOffset","ext","checkInt","checkIEEE754","writeFloat","noAssert","writeDouble","newBuf","subarray","readUIntLE","readUIntBE","readUInt16LE","readUInt32LE","readIntLE","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","readFloatBE","readDoubleLE","readDoubleBE","writeUIntLE","writeUInt16LE","writeUInt32LE","writeIntLE","limit","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32LE","writeInt32BE","writeFloatLE","writeFloatBE","writeDoubleLE","writeDoubleBE","targetStart","copyWithin","INVALID_BASE64_RE","Infinity","leadSurrogate","base64clean","dst","GetIntrinsic","callBind","$indexOf","allowMissing","intrinsic","$apply","$call","$reflectApply","$gOPD","$defineProperty","$max","originalFunction","func","applyBind","hashMode","_finalOrDigest","__final","_decoder","_encoding","inputEnc","outputEnc","outData","_toString","fin","string_decoder","PARAM_REGEXP","TEXT_REGEXP","TOKEN_REGEXP","QESC_REGEXP","QUOTE_REGEXP","TYPE_REGEXP","qstring","ContentType","parameters","format","param","parse","getHeader","headers","getcontenttype","exec","ECDH","aliases","secp256k1","secp224r1","prime256v1","prime192v1","ed25519","secp384r1","secp521r1","curveType","formatReturnValue","bn","p256","secp256r1","secp192r1","p384","p521","generateKeys","genKeyPair","getPublicKey","computeSecret","other","inenc","keyFromPublic","getPublic","getPrivate","getX","getPrivateKey","setPublicKey","_importPublic","setPrivateKey","_priv","_importPrivate","MD5","RIPEMD160","sha","Hash","alg","ripemd160","Legacy","md5","ZEROS","Hmac","blocksize","_alg","ipad","_ipad","opad","_opad","rng","pseudoRandomBytes","prng","algos","algoKeys","hashes","getHashes","pbkdf2","pbkdf2Sync","dh","DiffieHellmanGroup","createDiffieHellmanGroup","getDiffieHellman","createDiffieHellman","DiffieHellman","createECDH","publicEncrypt","privateEncrypt","publicDecrypt","privateDecrypt","rf","randomFill","randomFillSync","createCredentials","DH_CHECK_P_NOT_SAFE_PRIME","DH_CHECK_P_NOT_PRIME","DH_UNABLE_TO_CHECK_GENERATOR","DH_NOT_SUITABLE_GENERATOR","NPN_ENABLED","ALPN_ENABLED","RSA_PKCS1_PADDING","RSA_SSLV23_PADDING","RSA_NO_PADDING","RSA_PKCS1_OAEP_PADDING","RSA_X931_PADDING","RSA_PKCS1_PSS_PADDING","POINT_CONVERSION_COMPRESSED","POINT_CONVERSION_UNCOMPRESSED","POINT_CONVERSION_HYBRID","randomfill","utils","proto","CBCState","_cbcInit","_cbcState","inp","inOff","outOff","superProto","bufferOff","_updateDecrypt","_updateEncrypt","_buffer","_flushBuffer","inputOff","outputOff","_finalEncrypt","_finalDecrypt","_pad","_unpad","DESState","_desState","deriveKeys","shiftTable","kL","kR","pc1","r28shl","pc2","ip","_encrypt","lStart","rStart","keyL","keyR","expand","substitute","rip","EDEState","k1","k2","k3","_edeState","inL","inR","outL","outR","pc2table","sTable","permuteTable","padSplit","group","generatePrime","DH","ENCODINGS","binary","hex","gen","generator","genc","millerRabin","TWENTYFOUR","ELEVEN","TEN","THREE","SEVEN","_pub","primeCache","malleable","setGenerator","__prime","_primeLen","_primeCode","rem","simpleSieve","fermatTest","checkPrime","__gen","_gen","secret","getPrime","front","getGenerator","findPrime","ONE","TWO","FIVE","FOUR","_getPrimes","n2","modp1","modp2","modp5","modp14","modp15","modp16","modp17","modp18","version","eddsa","brorand","getNAF","getJSF","BaseCurve","conf","zero","pointFromJSON","gRed","_wnafT1","_wnafT2","_wnafT3","_wnafT4","_bitLength","adjustCount","redN","_maxwellTrick","BasePoint","precomputed","point","validate","_fixedNafMul","doubles","_getDoubles","naf","I","step","nafW","repr","jpoint","mixedAdd","points","toP","_wnafMul","nafPoints","_getNAFPoints","dblp","_wnafMulAdd","defW","coeffs","jacobianResult","wndWidth","comb","toJ","jsf","ja","jb","decodePoint","pointFromX","encodeCompressed","compact","getY","precompute","power","beta","_getBeta","_hasDoubles","dbl","EdwardsCurve","twisted","mOneA","dd","oneC","Point","zOne","_mulA","_mulC","rhs","lhs","y2","pointFromY","isInfinity","normalize","fromJSON","_extDbl","nx","ny","nt","nz","_projDbl","_extAdd","_projAdd","mulAdd","jmulAdd","zi","eqXToP","short","edwards","MontCurve","i4","a24","aa","bb","diffAdd","da","jumlAdd","ShortCurve","tinv","zeroA","threeA","endo","_getEndomorphism","_endoWnafT1","_endoWnafT2","isRed","inf","JPoint","lambda","betas","_getEndoRoots","lambdas","basis","vec","_getEndoBasis","ntinv","prevR","aprxSqrt","y1","len1","_endoSplit","v1","v2","p1","p2","q1","q2","ax","_endoWnafMulAdd","npoints","ncoeffs","pre","endoMul","obj2point","ys1","dyinv","_precompute","negate","zinv","zinv2","ay","pz2","z2","u1","u2","h2","h3","jx","jy","jz","jz4","jyd","jx2","jyd2","jyd4","dny","_zeroDbl","_threeDbl","_dbl","xx","yy","yyyy","yyyy8","c8","gamma","alpha","beta4","beta8","ggamma8","jy2","jxd4","jyd8","trpl","zz","mm","ee","yyu4","kbase","z3","pz3","zs","PresetCurve","defineCurve","HmacDRBG","KeyPair","Signature","nh","keyPair","fromPrivate","fromPublic","drbg","pers","persEnc","entropy","hmacStrength","entropyEnc","nonce","ns2","_truncateToN","truncOnly","bkey","ns1","kp","kpX","recoveryParam","canonical","sinv","recoverPubKey","isYOdd","isSecondKey","rInv","getKeyRecoveryParam","Q","Qprime","privEnc","pubEnc","reason","derive","_importDER","Position","place","getLength","initial","octetLen","rmPadding","constructLength","octets","LN2","slen","backHalf","parseBytes","EDDSA","pointClass","encodingLength","keyFromSecret","hashInt","messagePrefix","R","Rencoded","encodePoint","s_","pubBytes","S","makeSignature","SG","intFromLE","fromSecret","lastIx","normed","xIsOdd","encodeInt","decodeInt","isPoint","cachedProperty","_secret","_pubBytes","privBytes","getSecret","_R","_S","_Rencoded","_Sencoded","Sencoded","toBytes","minAssert","minUtils","zero2","m8","d1","d2","m14","m24","computer","description","main","files","scripts","lint","unit","repository","url","keywords","author","license","bugs","homepage","devDependencies","brfs","coveralls","eslint","grunt","istanbul","mocha","dependencies","ReflectOwnKeys","Reflect","ReflectApply","receiver","getOwnPropertyNames","NumberIsNaN","isNaN","init","errorListener","resolver","eventTargetAgnosticAddListener","handler","flags","addErrorHandlerIfEventEmitter","_eventsCount","_maxListeners","defaultMaxListeners","checkListener","listener","_getMaxListeners","that","_addListener","prepend","existing","warning","newListener","warned","warn","onceWrapper","fired","wrapFn","_onceWrap","wrapped","_listeners","unwrap","evlistener","unwrapListeners","arrayClone","addEventListener","wrapListener","removeEventListener","setMaxListeners","getMaxListeners","doError","context","prependOnceListener","originalListener","spliceOne","rawListeners","eventNames","salt","keyBits","used","keyStart","ivStart","isCallable","toStr","forEachArray","forEachString","forEachObject","thisArg","ERROR_MESSAGE","funcType","bound","boundLength","boundArgs","Empty","implementation","$SyntaxError","SyntaxError","$Function","$TypeError","getEvalledConstructor","expressionSyntax","throwTypeError","ThrowTypeError","calleeThrows","gOPDthrows","hasSymbols","getProto","needsEval","TypedArray","INTRINSICS","AggregateError","Atomics","BigInt","BigInt64Array","BigUint64Array","Boolean","DataView","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","eval","EvalError","Float32Array","Float64Array","FinalizationRegistry","Int8Array","Int16Array","Int32Array","Map","parseFloat","Proxy","ReferenceError","RegExp","Set","SharedArrayBuffer","Uint8ClampedArray","Uint16Array","Uint32Array","URIError","WeakMap","WeakRef","WeakSet","errorProto","doEval","LEGACY_ALIASES","hasOwn","$concat","$spliceApply","$replace","$strSlice","$exec","rePropName","reEscapeChar","stringToPath","quote","subString","getBaseIntrinsic","alias","intrinsicName","intrinsicBaseName","intrinsicRealName","skipFurtherCaching","isOwn","part","desc","has","origSymbol","hasSymbolSham","symObj","syms","propertyIsEnumerable","toStringTag","HashBase","_block","_blockSize","_blockOffset","_length","_finalized","prefix","throwIfNotStringOrBuffer","_digest","common","ripemd","hmac","sha1","BlockHash","pending","pendingTotal","outSize","padLength","_delta8","_delta32","join32","inner","outer","rotl32","sum32","sum32_3","sum32_4","K","Kh","E","Ah","Bh","Ch","Dh","Eh","T","rh","sh","toHex32","split32","shaCommon","sum32_5","ft_1","sha1_K","SHA1","W","SHA256","SHA224","ch32","maj32","s0_256","s1_256","g0_256","g1_256","sha256_K","T1","T2","SHA512","SHA384","rotr64_hi","rotr64_lo","shr64_hi","shr64_lo","sum64","sum64_hi","sum64_lo","sum64_4_hi","sum64_4_lo","sum64_5_hi","sum64_5_lo","sha512_K","ch64_hi","xh","xl","yh","yl","zh","ch64_lo","zl","maj64_hi","maj64_lo","s0_512_hi","s0_512_lo","s1_512_hi","s1_512_lo","g0_512_hi","g0_512_lo","g1_512_hi","g1_512_lo","_prepareBlock","c0_hi","c0_lo","c1_hi","c1_lo","c2_hi","c2_lo","c3_hi","c3_lo","ah","al","bh","ch","cl","dl","eh","el","fh","fl","gh","gl","hh","hl","c4_hi","c4_lo","T1_hi","T1_lo","T2_hi","T2_lo","rotr32","p32","isSurrogatePair","htonl","zero8","predResist","minEntropy","_reseed","reseedInterval","V","nonceEnc","seed","_hmac","kmac","reseed","addEnc","temp","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","NaN","rt","hasToStringTag","$toString","callBound","isStandardArguments","isLegacyArguments","callee","supportsStandardArguments","badArrayLike","isCallableMarker","fnToStr","reflectApply","constructorRegex","isES6ClassFn","fnStr","tryFunctionObject","isIE68","isDDA","document","all","strClass","GeneratorFunction","isFnRegex","generatorFunc","getGeneratorFunc","availableTypedArrays","gOPD","typedArrays","$slice","toStrTags","typedArray","anyTrue","getter","tryTypedArrays","gopd","root","definition","amd","undefinedType","isIE","navigator","userAgent","logMethods","bindMethod","methodName","traceForIE","trace","replaceLoggingMethods","level","loggerName","methodFactory","enableLoggingWhenConsoleArrives","defaultMethodFactory","realMethod","Logger","defaultLevel","factory","currentLevel","storageKey","getPersistedLevel","storedLevel","localStorage","ignore","cookie","location","levels","TRACE","DEBUG","INFO","WARN","ERROR","SILENT","getLevel","setLevel","persist","levelNum","levelName","persistLevelIfPossible","setDefaultLevel","resetLevel","removeItem","clearPersistedLevel","enableAll","disableAll","initialLevel","defaultLogger","_loggersByName","getLogger","logger","_log","noConflict","getLoggers","ExtensibleEvents","_NamespacedMap","_InvalidEventError","_MRoomMessage","_MMessage","_message_types","_poll_types","_MPoll","_createForOfIteratorHelper","allowArrayLike","it","minLen","_arrayLikeToArray","_unsupportedIterableToArray","F","_e","normalCompletion","didErr","_e2","arr2","NamespacedMap","LEGACY_M_ROOM_MESSAGE","parseMRoomMessage","M_MESSAGE","parseMMessage","M_EMOTE","M_NOTICE","M_POLL_START","parseMPoll","M_POLL_RESPONSE","M_POLL_END","_defaultInstance","defaultInstance","unknownInterpretOrder","wireEventType","interpreter","registerInterpreter","wireFormat","_this$_unknownInterpr","_unknownInterpretOrder","interpreters","hasNamespaced","getNamespaced","_step","_iterator","tryType","InvalidEventError","_typeof","_createSuper","Derived","hasNativeReflectConstruct","_isNativeReflectConstruct","Super","_getPrototypeOf","NewTarget","construct","_assertThisInitialized","_possibleConstructorReturn","_wrapNativeSuper","Class","Wrapper","_construct","_setPrototypeOf","Parent","sham","_Error","_inherits","_super","internalMap","altName","_createClass","UnstableValue","NamespacedValue","stable","unstable","included","_NamespacedValue","EmoteEvent","_MessageEvent2","_get","property","_superPropBase","_MessageEvent","text","html","_content","M_TEXT","M_HTML","primaryEventType","isEventTypeSame","MessageEvent","ExtensibleEvent","_ExtensibleEvent2","_types","_ExtensibleEvent","mmessage","findIn","wireContent","mtext","mhtml","isProvided","find","mimetype","renderings","isOptionalAString","matches","messageRendering","mime","_this$html","serializeMMessageOnly","msgtype","formatted_body","NoticeEvent","PollEndEvent","_relationship_types","rel","REFERENCE_RELATION","rel_type","event_id","pollEventId","closingMessage","serialize","PollResponseEvent","validateAgainst","answers","internalAnswerIds","internalSpoiled","poll","response","pa","maxSelections","spoiled","answerIds","PollStartEvent","PollAnswerSubevent","_toConsumableArray","_arrayWithoutHoles","_iterableToArray","_nonIterableSpread","_super2","question","rawKind","kind","M_POLL_KIND_DISCLOSED","M_POLL_KIND_UNDISCLOSED","max_selections","_content2","_content3","LETTERS","random","_ExtensibleEvents","_IPartialEvent","_MessageMatchers","_EmoteEvent","_NoticeEvent","_PollStartEvent","_PollResponseEvent","_PollEndEvent","wireEvent","_wireEvent$content","_wireEvent$content2","_wireEvent$content3","_objectSpread2","_objectSpread3","_objectSpread4","LegacyMsgType","isEventLike","Text","Emote","Notice","given","expectedNs","givenNs","ClientWidgetApi","_PostmessageTransport","_WidgetApiDirection","_WidgetApiAction","_Capabilities","_ApiVersion","_WidgetEventCapability","_GetOpenIDAction","_SimpleObservable","_Symbols","_regeneratorRuntime","Op","$Symbol","iteratorSymbol","asyncIteratorSymbol","toStringTagSymbol","innerFn","outerFn","tryLocsList","protoGenerator","Generator","Context","_invoke","doneResult","delegate","delegateResult","maybeInvokeDelegate","ContinueSentinel","sent","_sent","dispatchException","abrupt","record","tryCatch","GeneratorFunctionPrototype","IteratorPrototype","NativeIteratorPrototype","Gp","defineIteratorMethods","AsyncIterator","PromiseImpl","invoke","__await","unwrapped","previousPromise","callInvokeWithMethodAndArg","info","resultName","nextLoc","pushTryEntry","locs","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","resetTryEntry","completion","reset","iteratorMethod","displayName","isGeneratorFunction","genFun","mark","awrap","async","skipTempReset","stop","rootRecord","rval","exception","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","catch","thrown","delegateYield","asyncGeneratorStep","_next","_throw","_asyncToGenerator","_asyncIterator","retry","AsyncFromSyncIterator","AsyncFromSyncIteratorContinuation","return","throw","thr","_EventEmitter","_feedToDevice","_feedEvent","_handleUserDirectorySearch","_handleReadRelations","_handleUnwatchTurnServers","_handleWatchTurnServers","_pollTurnServers","_handleSendToDevice","widget","iframe","driver","contentWindow","transport","PostmessageTransport","WidgetApiDirection","ToWidget","targetOrigin","origin","handleMessage","onIframeLoad","capability","allowedCapabilities","roomId","hasCapability","Symbols","AnyRoom","eventType","allowedEvents","matchesAsRoomEvent","EventDirection","Send","stateKey","matchesAsStateEvent","matchesAsToDeviceEvent","Receive","isStopped","requestedCaps","send","WidgetApiToWidgetAction","Capabilities","caps","capabilities","validateCapabilities","allowedCaps","WidgetEventCapability","findEventCapabilities","notifyCapabilities","requested","_this3","NotifyCapabilities","approved","waitForIframeLoad","beginCapabilities","contentLoadedActionSent","action","reply","request","supported_versions","CurrentApiVersions","_request$data","_this4","newlyRequested","allowed","_request$data2","_request$data3","_this5","MatrixCapabilities","MSC2931Navigate","uri","startsWith","onErr","navigate","_this6","phase","replyState","credential","OpenIDCredentials","original_request_id","requestId","replyError","OpenIDRequestState","Blocked","observer","SimpleObservable","PendingUserConfirmation","close","Allowed","token","askOpenID","_this7","askRoomIds","room_ids","_step2","_iterator2","canUseRoomTimeline","state_key","canReceiveStateEvent","readStateEvents","canReceiveRoomEvent","readRoomEvents","evs","sendEventPromise","_this8","room_id","canSendStateEvent","sendEvent","canSendRoomEvent","sentEvent","eventId","_callee","_context","messages","encrypted","canSendToDeviceEvent","sendToDevice","_x","_callee2","turnServers","initialServer","_iteratorAbruptCompletion","_didIteratorError","_iteratorError","server","_context2","UpdateTurnServers","_x2","_x3","_callee3","_yield$turnServers$ne","_context3","MSC3846TurnServers","getTurnServers","pollTurnServers","_x4","_callee4","_context4","_x5","_callee5","_this9","_context5","readEventRelations","event_type","direction","prev_batch","prevBatch","next_batch","nextBatch","_x6","_callee6","_context6","MSC3973UserDirectorySearch","search_term","searchUserDirectory","limited","results","user_id","userId","display_name","avatar_url","avatarUrl","_x7","actionEv","CustomEvent","detail","cancelable","defaultPrevented","WidgetApiFromWidgetAction","ContentLoaded","handleContentLoadedAction","SupportedApiVersions","replyVersions","SendEvent","handleSendEvent","SendToDevice","handleSendToDevice","GetOpenIDCredentials","handleOIDC","handleNavigate","MSC2974RenegotiateCapabilities","handleCapabilitiesRenegotiate","MSC2876ReadEvents","handleReadEvents","WatchTurnServers","handleWatchTurnServers","UnwatchTurnServers","handleUnwatchTurnServers","MSC3869ReadRelations","handleReadRelations","handleUserDirectorySearch","TakeScreenshot","isVisible","UpdateVisibility","visible","WidgetConfig","ButtonClicked","CloseModalWidget","_callee7","rawEvent","currentViewedRoomId","_rawEvent$content","_context7","_x8","_x9","_callee8","_context8","canReceiveToDeviceEvent","_x10","_x11","WidgetApi","_WidgetType","_ModalWidgetActions","_awaitAsyncGenerator","_AwaitValue","_AsyncGenerator","back","wrappedAwait","settle","_searchUserDirectory","_readEventRelations","widgetId","clientOrigin","FromWidget","approvedCapabilities","requestedCapabilities","capabilitiesFinished","supportsMSC2974Renegotiate","cap","requestCapability","forStateEvent","forToDeviceEvent","forRoomEvent","forRoomMessageEvent","sendComplete","rdata","handlerFn","preventDefault","sticker","SendSticker","UpdateAlwaysOnScreen","success","buttons","MatrixWidgetType","Custom","OpenModalWidget","contentMap","roomIds","relationType","getClientVersions","UnstableApiVersion","MSC3869","buttonId","isEnabled","BuiltInModalButtonID","Close","SetModalButtonEnabled","button","enabled","setTurnServer","onUpdateTurnServers","_ref","turnServerWatchers","searchTerm","MSC3973","MSC2974","handleCapabilities","cachedClientVersions","MSC2871","WidgetDriver","_WidgetApi","_ClientWidgetApi","_ITransport","_ICustomWidgetData","_IJitsiWidgetData","_IStickerpickerWidgetData","_IWidget","_IWidgetApiErrorResponse","_IWidgetApiRequest","_IWidgetApiResponse","_CapabilitiesAction","_ContentLoadedAction","_ScreenshotAction","_StickerAction","_StickyAction","_SupportedVersionsAction","_VisibilityAction","_OpenIDCredentialsAction","_WidgetKind","_ModalButtonKind","_SetModalButtonEnabledAction","_WidgetConfigAction","_SendEventAction","_SendToDeviceAction","_ReadEventAction","_IRoomEvent","_NavigateAction","_TurnServerActions","_ReadRelationsAction","_url","_utils","_Widget","_WidgetParser","_urlTemplate","_WidgetDriver","MatrixApiVersion","Prerelease1","Prerelease2","MSC2762","MSC2931","MSC2876","MSC3819","MSC3846","VideoConferenceCapabilities","StickerpickerCapabilities","getTimelineRoomIDFromCapability","isTimelineCapability","isTimelineCapabilityFor","StickerSending","AlwaysOnScreen","isErrorResponse","responseData","ModalButtonKind","invertedDirection","WidgetKind","Widget","assertPresent","creatorUserId","rawData","title","URL","templateUrl","runTemplate","EventKind","keyStr","State","ToDevice","Event","_direction","eventSegment","_kind","expectingKeyStr","_keyStr","idx","findIndex","WidgetParser","_i","_Object$keys","_widgetId","roughWidget","sender","asStateEvent","origin_server_ts","parseRoomWidget","currentState","stateEvent","estimatedWidget","processEstimatedWidget","isValidUrl","protocol","variables","assign","matrix_room_id","widgetRoomId","matrix_user_id","currentUserId","matrix_display_name","userDisplayName","matrix_avatar_url","userHttpAvatarUrl","matrix_widget_id","clientId","clientTheme","clientLanguage","pattern","rexp","sendDirection","initialWidgetId","transportWindow","inboundWindow","AbortController","_ready","idBase","outboundRequests","postMessage","sendInternal","ready","api","nextRequestId","prResolve","prReject","cleanUp","timerId","setTimeout","timeoutSeconds","onStop","stopController","signal","clearTimeout","aborted","strictOriginCheck","handleResponse","handleRequest","_err","initialFn","ARRAY16","_a","_b","_c","_d","rotl","fnF","fnG","fnH","fnI","MillerRabin","_randbelow","min_bytes","_randrange","rone","n1","rn1","getDivisor","networkErrorMsgs","AbortError","super","originalError","pRetry","onFailedAttempt","retries","operation","attempt","attemptNumber","errorMessage","retriesLeft","decorateErrorWithCounts","mainError","default","certificate","RSAPrivateKey","seq","int","RSAPublicKey","PublicKey","AlgorithmIdentifier","bitstr","null_","PrivateKeyInfo","octstr","PrivateKey","EncryptedPrivateKeyInfo","EncryptedPrivateKey","DSAPrivateKey","DSAparam","ECPrivateKey","ECParameters","namedCurve","asn","Time","utcTime","utctime","generalTime","gentime","AttributeTypeValue","SubjectPublicKeyInfo","RelativeDistinguishedName","setof","RDNSequence","seqof","Name","rdnSequence","Validity","Extension","bool","TBSCertificate","X509Certificate","findProc","startRegex","fullRegex","evp","okey","decrypted","cipherText","cipherKey","match2","aesid","fixProc","compat","passphrase","subtype","ndata","stripped","tbsCertificate","subjectPublicKeyInfo","subjectPublicKey","kde","kdeparams","iters","keylen","ZERO_BUF","checkParameters","subtle","toBrowser","checks","getNextTick","queueMicrotask","setImmediate","browserPbkdf2","iterations","importKey","deriveBits","resolvePromise","browser","prom","checkNative","resp","MAX_ALLOC","sizes","rmd160","saltLen","shaFunc","rmd160Func","getDigest","ipad1","ipad2","run","DK","block1","destPos","hLen","U","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","currentQueue","queue","draining","queueIndex","cleanUpNextTick","drainQueue","timeout","marker","runClearTimeout","Item","env","argv","versions","binding","cwd","chdir","umask","i2ops","mgf","withPublic","zBuffer","iHash","maskedSeed","maskedDb","db","dif","oaep","status","ps","pkcs1","publicKey","paddedMsg","hLen2","dblen","cur","nonZero","MAX_BYTES","MAX_UINT32","generated","oldBrowser","safeBuffer","kBufferMaxLength","kMaxUint32","assertOffset","actualFill","ourBuf","uint","RetryOperation","timeouts","forever","unref","maxRetryTime","factor","minTimeout","maxTimeout","randomize","createTimeout","original","op","_originalTimeouts","_timeouts","_options","_maxRetryTime","_fn","_errors","_attempts","_operationTimeout","_operationTimeoutCb","_timeout","_operationStart","_timer","_cachedTimeouts","currentTime","getTime","timeoutOps","try","attempts","counts","mainErrorCount","zr","sl","sr","hr","fn1","fn2","fn3","fn4","fn5","ar","br","cr","dr","tl","tr","copyProps","SafeBuffer","safer","Safer","kStringMaxLength","MAX_LENGTH","MAX_STRING_LENGTH","grammar","reg","names","rate","address","sessionConfig","raddr","tcptype","generation","attribute","maxMessageSize","dir2","clksrcExt","mediaClockValue","rateNumerator","rateDenominator","parser","writer","parseParams","parseFmtpConfig","parsePayloads","parseRemoteCandidates","parseImageAttributes","parseSimulcastStreamList","toIntIfInt","parseReg","needsBlank","keyLocation","rawName","attachProperties","validLine","sdp","session","media","rtp","fmtp","paramReducer","expr","candidates","component","port","scid","formatRegExp","formatStr","makeLine","defaultOuterOrder","defaultInnerOrder","mLine","payloads","outerOrder","innerOrder","finalSize","_finalSize","accum","assigned","remainder","lowBits","highBits","Algorithm","Sha","_w","rotl30","ft","Sha1","rotl5","Sha256","Sha224","_f","_g","_h","maj","sigma0","sigma1","gamma0","Sha384","_ah","_bh","_ch","_dh","_eh","_fh","_gh","_hh","_al","_bl","_cl","_dl","_el","_fl","_gl","_hl","writeInt64BE","Sha512","Gamma0","Gamma0l","Gamma1","Gamma1l","getCarry","gamma0l","gamma1","gamma1l","Wi7h","Wi7l","Wi16h","Wi16l","Wil","Wih","majh","majl","sigma0h","sigma0l","sigma1h","sigma1l","Kih","Kil","chh","chl","t1l","t1h","t2l","t2h","EE","_isStdio","didOnEnd","cleanup","nenc","retried","_normalizeEncoding","normalizeEncoding","utf16Text","utf16End","fillLast","utf8FillLast","base64Text","base64End","simpleWrite","simpleEnd","lastNeed","lastTotal","lastChar","utf8CheckByte","byte","utf8CheckExtraBytes","utf8CheckIncomplete","clearImmediate","immediateIds","nextImmediateId","Timeout","clearFn","_id","_clearFn","setInterval","clearInterval","ref","enroll","msecs","_idleTimeoutId","_idleTimeout","unenroll","_unrefActive","active","_onTimeout","timers","REPLACE_RE","replace_fn","isArgumentsObject","whichTypedArray","isTypedArray","uncurryThis","BigIntSupported","SymbolSupported","ObjectToString","numberValue","stringValue","booleanValue","bigIntValue","symbolValue","checkBoxedPrimitive","prototypeValueOf","isMapToString","isSetToString","isWeakMapToString","isWeakSetToString","isArrayBufferToString","isArrayBuffer","working","isDataViewToString","isDataView","isPromise","isArrayBufferView","isUint8Array","isUint8ClampedArray","isUint16Array","isUint32Array","isInt8Array","isInt16Array","isInt32Array","isFloat32Array","isFloat64Array","isBigInt64Array","isBigUint64Array","isMap","isSet","isWeakMap","isWeakSet","SharedArrayBufferCopy","isSharedArrayBufferToString","isSharedArrayBuffer","isNumberObject","isStringObject","isBooleanObject","isBigIntObject","isSymbolObject","isAsyncFunction","isMapIterator","isSetIterator","isGeneratorObject","isWebAssemblyCompiledModule","isBoxedPrimitive","isAnyArrayBuffer","descriptors","isString","objects","isNull","isObject","noDeprecation","throwDeprecation","traceDeprecation","debugs","debugEnvRegex","NODE_DEBUG","debugEnv","seen","stylize","stylizeNoColor","colors","isBoolean","showHidden","_extend","isUndefined","stylizeWithColor","formatValue","styleType","style","styles","recurseTimes","isFunction","simple","isNumber","formatPrimitive","visibleKeys","arrayToHash","formatError","isRegExp","isDate","braces","toUTCString","formatProperty","formatArray","numLinesEst","reduceToSingleString","line","objectToString","pid","bold","italic","underline","inverse","white","grey","black","blue","cyan","green","magenta","yellow","special","boolean","null","regexp","types","isNullOrUndefined","isSymbol","isNativeError","isPrimitive","months","getHours","getMinutes","getSeconds","getDate","getMonth","kCustomPromisifiedSymbol","callbackifyOnRejected","newReason","promisify","promiseResolve","promiseReject","callbackify","callbackified","maybeCb","rej","_nil","_parse","_stringify","_v","_v2","_v3","_v4","_validate","_version","_interopRequireDefault","__esModule","getOutputLength","inputLength8","safeAdd","lsw","md5cmn","cnt","md5ff","md5gg","md5hh","md5ii","_default","unescape","length32","hexTab","md5ToHexEncodedArray","olda","oldb","oldc","oldd","wordsToMd5","length8","bytesToWords","randomUUID","uuid","rnds8","ROTL","unsafeStringify","byteToHex","_rng","_nodeId","_clockseq","_lastMSecs","_lastNSecs","clockseq","seedBytes","nsecs","dt","tmh","_md","DNS","hashfunc","generateUUID","namespace","_namespace","stringToBytes","_native","rnds","_sha","_regex","foundName","RuleId","PushRuleKind","ConditionKind","isDmMemberCountCondition","DMMemberCountCondition","ConditionOperator","TweakName","PushRuleActionName","condition","M_BEACON","M_BEACON_INFO","NamespacedValue_1","LOCAL_NOTIFICATION_SETTINGS_PREFIX","PUSHER_DEVICE_ID","PUSHER_ENABLED","EVENT_VISIBILITY_CHANGE_TYPE","UNSTABLE_ELEMENT_FUNCTIONAL_USERS","MSC3912_RELATION_BASED_REDACTIONS_PROP","UNSTABLE_MSC2716_MARKER","UNSTABLE_MSC3089_BRANCH","UNSTABLE_MSC3089_LEAF","UNSTABLE_MSC3089_TREE_SUBTYPE","UNSTABLE_MSC3088_ENABLED","UNSTABLE_MSC3088_PURPOSE","ToDeviceMessageId","RoomType","RoomCreateTypeField","MsgType","RelationType","EventType","matrix_events_sdk_1","utilities_1","M_LOCATION","M_TIMESTAMP","M_ASSET","LocationAssetType","HistoryVisibility","GuestAccess","RestrictedAllowType","JoinRule","Preset","Visibility","MAIN_ROOM_TIMELINE","ReceiptType","GroupKey","SearchOrderBy","UNREAD_THREAD_NOTIFICATIONS","ServerControlledNamespacedValue","M_TOPIC","includedIn","preferUnstable","setPreferUnstable","TypedReEmitter","ReEmitter","reEmitters","reEmit","reEmittersByEvent","eventName","forSource","stopReEmitting","delete","__awaiter","_arguments","P","fulfilled","rejected","ToDeviceMessageQueue","event_1","logger_1","client_1","scheduler_1","sync_1","utils_1","client","sending","running","retryTimeout","retryAttempts","sendQueue","headBatch","store","getOldestToDeviceBatch","sendBatch","removeToDeviceBatch","retryDelay","MatrixScheduler","RETRY_BACKOFF_RATELIMIT","httpStatus","onResumedSync","oldState","SyncState","Syncing","ClientEvent","Sync","queueBatch","batch","batches","batchWithTxnId","txnId","makeTxnId","msgmap","deviceId","payload","saveToDeviceBatches","MapWithDefault","getOrCreate","AutoDiscovery","AutoDiscoveryAction","http_api_1","AutoDiscoveryError","static","wellknown","clientConfig","FAIL_ERROR","ERROR_INVALID","base_url","PROMPT","FAIL_PROMPT","ERROR_INVALID_HS_BASE_URL","hsUrl","sanitizeWellKnownUrl","hsVersions","fetchWellKnownObject","ERROR_INVALID_HOMESERVER","SUCCESS","isUrl","failingClientConfig","ERROR_INVALID_IS","ERROR_INVALID_IS_BASE_URL","isResponse","ERROR_INVALID_IDENTITY_SERVER","notProps","domain","fromDiscoveryConfig","IGNORE","hostname","pathname","saferUrl","resource","fetchFn","fetch","Method","Get","timeoutSignal","ERROR_MISSING_WELLKNOWN","ok","json","ERROR_INVALID_JSON","Invalid","ERROR_GENERIC_FAILURE","GenericFailure","InvalidHsBaseUrl","InvalidHomeserver","InvalidIsBaseUrl","InvalidIdentityServer","InvalidIs","MissingWellknown","InvalidJson","ALL_ERRORS","__createBinding","__setModuleDefault","__importStar","__exportStar","matrixcs","__js_sdk_entrypoint","indexedDB","setCryptoStoreFactory","IndexedDBCryptoStore","__rest","fixNotificationCountOnDecryption","MatrixClient","M_AUTHENTICATION","RoomVersionStability","PendingEventOrdering","UNSTABLE_MSC3852_LAST_SEEN_UA","CRYPTO_ENABLED","stub_1","call_1","filter_1","callEventHandler_1","event_timeline_1","pushprocessor_1","autodiscovery_1","olmlib","olmlib_1","ReEmitter_1","RoomList_1","service_types_1","crypto_1","recoverykey_1","key_passphrase_1","user_1","content_repo_1","search_result_1","dehydration_1","api_1","ContentHelpers","room_1","room_member_1","event_2","partials_1","event_mapper_1","randomstring_1","backup_1","MSC3089TreeSpace_1","search_1","PushRules_1","groupCall_1","mediaHandler_1","groupCallEventHandler_1","typed_event_emitter_1","read_receipts_1","sliding_sync_sdk_1","thread_1","beacon_1","ToDeviceMessageQueue_1","invites_ignorer_1","feature_1","constants_1","isCryptoAvailable","TURN_CHECK_INTERVAL","CrossSigningKeyType","EVENT_ID_PREFIX","SSO_ACTION_PARAM","TypedEventEmitter","reEmitter","olmVersion","usingExternalCrypto","clientRunning","timelineSupport","urlPreviewCache","supportsCallTransfer","forceTURN","iceCandidatePoolSize","canSupportVoip","peekSync","isGuestAccount","ongoingScrollbacks","notifTimelineSet","fallbackICEServerAllowed","syncedLeftRooms","canSupport","pushProcessor","PushProcessor","turnServersExpiry","txnCtr","mediaHandler","MediaHandler","pendingEventEncryption","useE2eForGroupCall","startCallEventHandler","isInitialSyncComplete","callEventHandler","groupCallEventHandler","fixupRoomNotifications","unreadRooms","getRooms","room","getUnreadNotificationCount","NotificationCountType","Total","getSafeUserId","fixupNotifications","baseUrl","ensureNoTrailingSlash","idBaseUrl","identityServer","StubStore","sessionId","randomString","credentials","http","MatrixHttpApi","accessToken","ClientPrefix","R0","onlyData","extraParams","queryParams","localTimeoutMs","useAuthorizationHeader","deviceToImport","exportedOlmDeviceToImport","olmDevice","pickleKey","scheduler","setProcessFunction","eventToSend","getRoom","getRoomId","EventStatus","SENDING","updatePendingEventStatus","sendEventHttpRequest","updatePendingEvent","SENT","supportsMatrixCall","CallEventHandler","GroupCallEventHandler","cryptoStore","verificationMethods","cryptoCallbacks","isVoipWithNoMediaAllowed","roomList","RoomList","roomNameGenerator","toDeviceMessageQueue","MatrixEventEvent","Decrypted","RoomEvent","Receipt","isRoomEncrypted","getContent","eid","entries","isSupportedReceiptType","getUserId","maxHistory","getLiveTimeline","getEvents","highlightCount","hasUserReadEvent","getId","pushActions","getPushActionsForEvent","tweaks","highlight","setUnreadNotificationCount","Highlight","ignoredInvites","IgnoredInvites","startClient","initialSyncLimit","storeUser","User","checkTurnServersIntervalID","checkTurnServers","syncApi","getVersions","threads","fwdPagination","doesServerSupportThread","Thread","setServerSideSupport","setServerSideListSupport","setServerSideFwdPaginationSupport","clientOpts","slidingSync","SlidingSyncSdk","buildSyncApiOptions","SyncApi","threadSupport","experimentalThreadSupport","clientWellKnownPollPeriod","clientWellKnownIntervalID","fetchClientWellKnown","cryptoBackend","canResetEntireTimeline","canResetTimelineCallback","stopClient","stopPeeking","rehydrateDevice","getDehydrationKey","getDeviceResult","getDehydratedDevice","device_data","device_id","account","Olm","Account","deviceData","DEHYDRATION_ALGORITHM","unpickle","authedRequest","Post","pickledAccount","pickle","sessions","free","setDehydrationKey","keyInfo","deviceDisplayName","dehydrationManager","setKeyAndQueueDehydration","createDehydratedDevice","setKey","dehydrateDevice","exportDevice","export","clearStores","promises","deleteAllData","dbname","RUST_SDK_STORE_PREFIX","deleteDatabase","onsuccess","onblocked","deleteRustSdkStore","getDomain","getUserIdLocalpart","getDeviceId","getSessionId","supportsVoip","getMediaHandler","setForceTURN","force","setSupportsCallTransfer","support","getUseE2eForGroupCall","createCall","createNewMatrixCall","createGroupCall","isPtt","intent","dataChannelsEnabled","dataChannelOptions","getGroupCallForRoom","GroupCall","waitUntilRoomReadyForGroupCalls","groupCalls","getSyncState","getSyncStateData","Prepared","isGuest","setGuest","guest","getScheduler","retryImmediately","getNotifTimelineSet","setNotifTimelineSet","getCapabilities","fresh","cachedCapabilities","expiration","cacheMs","initCrypto","startup","Crypto","CryptoEvent","KeyBackupFailed","KeyBackupSessionsRemaining","RoomKeyRequest","RoomKeyRequestCancellation","Warning","DevicesUpdated","WillUpdateDevices","DeviceVerificationChanged","UserTrustStatusChanged","KeysChanged","exportedOlmDevice","getOlmVersion","registerEventHandlers","uploadDeviceKeys","initRustCrypto","RustCrypto","rustCrypto","RoomMemberEvent","Membership","onRoomMembership","getCrypto","isCryptoEnabled","getDeviceEd25519Key","getDeviceCurve25519Key","uploadKeys","downloadKeys","userIds","forceDownload","getStoredDevicesForUser","getStoredDevice","setDeviceVerified","verified","setDeviceVerification","checkKeyBackup","setDeviceBlocked","blocked","setDeviceKnown","known","requestVerificationDM","findVerificationRequestDMInProgress","getVerificationRequestsToDeviceInProgress","requestVerification","devices","beginKeyVerification","checkSecretStorageKey","setGlobalBlacklistUnverifiedDevices","globalBlacklistUnverifiedDevices","getGlobalBlacklistUnverifiedDevices","setGlobalErrorOnUnknownDevices","globalErrorOnUnknownDevices","getGlobalErrorOnUnknownDevices","getCrossSigningId","CrossSigningKey","Master","getStoredCrossSigningForUser","checkUserTrust","checkDeviceTrust","checkIfOwnDeviceCrossSigned","checkOwnCrossSigningTrust","checkCrossSigningPrivateKey","expectedPublicKey","legacyDeviceVerification","prepareToEncrypt","userHasCrossSigningKeys","isCrossSigningReady","bootstrapCrossSigning","getCryptoTrustCrossSignedDevices","setCryptoTrustCrossSignedDevices","countSessionsNeedingBackup","getEventEncryptionInfo","createRecoveryKeyFromPassphrase","isSecretStorageReady","bootstrapSecretStorage","addSecretStorageKey","keyName","hasSecretStorageKey","keyId","storeSecret","isSecretStored","requestSecret","getDefaultSecretStorageKeyId","setDefaultSecretStorageKeyId","checkSecretStoragePrivateKey","getEventSenderDeviceInfo","isEventSenderVerified","device","isVerified","getOutgoingRoomKeyRequest","getWireContent","requestBody","session_id","sender_key","cancelAndResendEventRoomKeyRequest","cancelAndResendKeyRequest","setRoomEncryption","getStateEvents","RoomEncryption","encryptAndSendToDevices","userDeviceInfoArr","forceDiscardSession","exportRoomKeys","importRoomKeys","backupManager","getKeyBackupVersion","V3","errcode","BackupManager","checkBackupVersion","isKeyBackupTrusted","getKeyBackupEnabled","enableKeyBackup","disableKeyBackup","prepareKeyBackupVersion","secureSecretStorage","auth_data","recovery_key","encodeBase64","isKeyBackupKeyStored","createKeyBackupVersion","signObject","getCrossSigningKey","crossSigningInfo","deleteKeyBackupVersion","encodeUri","$version","Delete","makeKeyBackupPath","$roomId","$sessionId","queryData","sendKeyBackup","Put","scheduleAllGroupSessionsForBackup","flagAllGroupSessionsForBackup","isValidRecoveryKey","recoveryKey","decodeRecoveryKey","keyBackupKeyFromPassword","backupInfo","keyFromAuthData","keyBackupKeyFromRecoveryKey","restoreKeyBackupWithPassword","targetRoomId","targetSessionId","privKey","restoreKeyBackup","restoreKeyBackupWithSecretStorage","storedKey","fixedKey","fixBackupKey","getSecretStorageKey","decodeBase64","restoreKeyBackupWithRecoveryKey","restoreKeyBackupWithCache","getSessionBackupPrivateKey","cacheCompleteCallback","progressCallback","totalKeyCount","makeAlgorithm","untrusted","keyMatches","MatrixError","RESTORE_BACKUP_ERROR_BAD_KEY","storeSessionBackupPrivateKey","stage","rooms","roomData","roomKeys","decryptSessions","imported","deleteKeysFromBackup","sendSharedHistoryKeys","roomEncryption","getRoomEncryption","deviceInfos","devicesByUser","getRoomDecryptor","sendSharedHistoryInboundSessions","getMediaConfig","MediaPrefix","getVisibleRooms","msc3946ProcessDynamicPredecessor","allRooms","replacedRooms","predecessor","findPredecessor","RoomTombstone","getUser","getUsers","setAccountData","$userId","$type","retryNetworkOperation","getAccountData","getAccountDataFromServer","deleteAccountData","msc3391DeleteAccountDataServerSupport","Feature","AccountDataDeletion","ServerSupport","Unsupported","Unstable","getIgnoredUsers","setIgnoredUsers","ignored_users","isUserIgnored","joinRoom","roomIdOrAlias","syncRoom","hasMembershipState","signPromise","inviteSignUrl","searchParams","requestOtherUrl","queryString","viaServers","signedInviteObj","third_party_signed","$roomid","createRoom","resendEvent","encryptAndSendEvent","cancelPendingEvent","QUEUED","NOT_SENT","ENCRYPTING","removeEventFromQueue","CANCELLED","setRoomName","sendStateEvent","RoomName","setRoomTopic","topic","htmlTopic","makeTopicContent","RoomTopic","getRoomTags","setRoomTag","tagName","metadata","$tag","deleteRoomTag","setRoomAccountData","setPowerLevel","powerLevel","users","getType","RoomPowerLevels","deepCopy","user","unstable_createLiveBeacon","beaconInfoContent","unstable_setLiveBeacon","threadIdOrEventType","eventTypeOrContent","contentOrTxnId","txnIdOrVoid","threadId","isReply","THREAD_RELATION_TYPE","is_falling_back","thread","getThread","lastReply","isRelation","sendCompleteEvent","eventObject","localEvent","MatrixEvent","setThread","Replaced","VisibilityChange","BeforeRedaction","targetId","getAssociatedId","getPendingEvents","LocalEventIdReplaced","updateAssociatedId","setTxnId","setStatus","addPendingEvent","cancelled","encryptionPromise","encryptEventIfNeeded","queueEvent","getQueueForEvent","isEncrypted","isRedaction","Reaction","encryptEvent","getEncryptedIfNeededEventType","RoomMessageEncrypted","newStatus","getTxnId","pathParams","$eventType","getWireType","$stateKey","getStateKey","$txnId","isState","pathTemplate","$redactsEventId","redacts","redactEvent","with_relations","RelationBasedRedactions","withRelations","Stable","RoomRedaction","sendMessage","RoomMessage","sendContent","sendTextMessage","makeTextMessage","sendNotice","makeNotice","sendEmoteMessage","makeEmoteMessage","sendImageMessage","Image","sendStickerMessage","Sticker","sendHtmlMessage","htmlBody","makeHtmlMessage","sendHtmlNotice","makeHtmlNotice","sendHtmlEmote","makeHtmlEmote","sendReceipt","receiptType","unthreaded","$receiptType","$eventId","isThread","threadRootId","thread_id","addLocalEchoReceipt","sendReadReceipt","Read","hasPendingEvent","setRoomReadMarkers","rmEventId","rrEvent","rpEvent","rrEventId","rpEventId","ReadPrivate","setRoomReadMarkersHttpRequest","getUrlPreview","cachedPreview","sendTyping","isTyping","timeoutMs","typing","getRoomUpgradeHistory","verifyLinks","currentRoom","findPredecessorRooms","findSuccessorRooms","predecessorRoomId","predecessorRoom","tombstone","tombstoneEvent","successorRoom","invite","membershipChange","inviteByEmail","email","inviteByThreePid","medium","identityServerUrl","getIdentityServerUrl","id_server","getAccessToken","doesServerAcceptIdentityAccessToken","identityAccessToken","leave","leaveRoomChain","includeFuture","upgradeHistory","eligibleToLeave","populationResults","doLeave","ban","forget","deleteRoom","removeRoom","DeleteRoom","unban","kick","membership","$room_id","$membership","forceRecalculate","getPushActions","setPushActions","actionsForEvent","setProfileInfo","$info","setDisplayName","displayname","UserEvent","DisplayName","presence","setAvatarUrl","AvatarUrl","mxcUrlToHttp","mxcUrl","height","resizeMethod","allowDirectLinks","getHttpUriForMxc","setPresence","getPresence","scrollback","timeToWaitMs","errorTs","timeWaitedMs","paginationToken","numAdded","sleep","createMessagesRequest","Direction","Backward","matrixEvents","getEventMapper","stateEvents","setUnknownStateEvents","timelineEvents","threadedEvents","partitionThreadedEvents","processAggregatedTimelineEvents","addEventsToTimeline","processThreadEvents","storeEvents","eventMapperFor","getEventTimeline","timelineSet","getTimelineForEvent","supportsThreads","getThreadTimeline","lazyLoadMembers","Filter","LAZY_LOADING_MESSAGES_FILTER","mapper","events_after","events_before","timeline","getState","EventTimeline","BACKWARDS","addTimeline","initialiseState","FORWARDS","findThreadForEvent","liveTimeline","canContain","hasServerSideSupport","hasServerSideFwdPaginationSupport","resOlder","fetchRelations","resNewer","Forward","processEvent","originalEvent","fetchRoomEvent","setPaginationToken","eventsNewer","getLatestTimeline","threadListType","createThreadListMessagesRequest","getFilter","messagesPath","fromToken","timelineFilter","getRoomTimelineFilterComponent","ThreadFilterType","All","include","threadFilterTypeToFilter","hasServerSideListSupport","FeatureSupport","paginateEventTimeline","eventTimeline","isNotifTimeline","getTimelineSet","backwards","getPaginationToken","pendingRequest","paginationRequests","only","next_token","notifications","noUnsafeEventProps","notification","actionListToActionsObject","actions","finally","roomState","processThreadRoots","getSender","getEventReadUpTo","newToken","getServerAggregatedRelation","atEnd","resetNotifTimelineSet","resetLiveTimeline","peekInRoom","peek","setGuestAccess","writePromise","RoomGuestAccess","guest_access","allowJoin","readPromise","allowRead","RoomHistoryVisibility","history_visibility","requestRegisterEmailToken","clientSecret","sendAttempt","nextLink","requestTokenFromEndpoint","client_secret","send_attempt","next_link","requestRegisterMsisdnToken","phoneCountry","phoneNumber","country","phone_number","requestAdd3pidEmailToken","requestAdd3pidMsisdnToken","requestPasswordEmailToken","requestPasswordMsisdnToken","endpoint","postParams","doesServerSupportSeparateAddAndBind","idServerUrl","host","id_access_token","getRoomPushRule","scope","pushRules","rule","rule_id","setRoomMutePushRule","mute","hasDontNotifyRule","roomPushRule","DontNotify","deferred","defer","deletePushRule","RoomSpecific","addPushRule","getPushRules","searchMessageText","roomEvents","query","search_categories","room_events","searchRoomEvents","term","order_by","Recent","event_context","before_limit","after_limit","include_profile","searchResults","_query","highlights","processRoomEventsSearch","backPaginateRoomEventsSearch","searchOpts","abortSignal","resultsLength","SearchResult","fromJson","getEvent","getTimeline","getMember","syncLeftRooms","syncLeftRoomsPromise","createFilter","filter_id","storeFilter","filterId","allowCached","$filterId","getOrCreateFilter","filterName","getFilterIdByName","existingId","existingFilter","oldDef","getDefinition","newDef","deepCompare","setFilterIdByName","createdFilter","getOpenIdToken","turnServer","getTurnServersExpiry","pollingTurnServers","credentialsGood","remainingTime","uris","ttl","servers","urls","username","TurnServers","TurnServersError","setFallbackICEServerAllowed","allow","isFallbackICEServerAllowed","isSynapseAdministrator","admin","whoisSynapseUser","deactivateSynapseUser","clientWellKnownPromise","getRawClientConfig","clientWellKnown","ClientWellKnown","getClientWellKnown","waitForClientWellKnown","storeClientOptions","primTypes","serializableOpts","_unstable_getSharedRooms","sharedRoomsSupport","doesServerSupportUnstableFeature","mutualRoomsSupport","joined","serverVersionsPromise","serverVersions","buildFeatureSupportMap","isVersionSupported","doesServerSupportLazyLoading","unstableFeatures","doesServerRequireIdServerParam","feature","doesServerForceEncryptionForPreset","presetName","versionsPresetName","threadUnstable","threadStable","listUnstable","listStable","fwdPaginationUnstable","fwdPaginationStable","determineFeatureSupport","None","doesServerSupportLogoutDevices","hasLazyLoadMembersEnabled","setCanResetTimelineCallback","getCanResetTimelineCallback","relations","fetchedEventType","eventResult","allEvents","decryptEventIfNeeded","Replace","getCrossSigningCacheCallbacks","getCacheCallbacks","generateClientSecret","shouldAttemptDecryption","attemptDecryption","isBeingDecrypted","getDecryptionPromise","termsUrlForService","serviceType","SERVICE_TYPES","IS","getUrl","IdentityPrefix","V2","IM","getHomeserverUrl","stripProto","setIdentityServerUrl","setIdBaseUrl","setAccessToken","isLoggedIn","isUsernameAvailable","available","register","auth","bindThreepids","guestAccessToken","inhibitLogin","refresh_token","bind_email","msisdn","bind_msisdn","guest_access_token","inhibit_login","x_show_msisdn","registerRequest","registerGuest","refreshToken","V1","inhibitLogoutEmit","loginFlows","login","loginType","loginData","access_token","loginWithPassword","loginWithSAML2","relayState","relay_state","getCasLoginUrl","redirectUrl","getSsoLoginUrl","idpId","href","loginWithToken","logout","backupPendingKeys","deactivateAccount","erase","requestLoginToken","getFallbackAuthUrl","authSessionId","$loginType","invitesNeedingToken","invite_3pid","Experimental","replaceParam","encodeParams","templatedUrl","$relationType","members","includeMembership","excludeMembership","atEventId","not_membership","at","upgradeRoom","newVersion","new_version","getStateEvent","roomInitialSync","FullyRead","getJoinedRooms","getJoinedRoomMembers","publicRooms","since","createAlias","$alias","deleteAlias","getLocalAliases","getRoomIdForAlias","resolveRoomAlias","roomAlias","getRoomDirectoryVisibility","setRoomDirectoryVisibility","visibility","setRoomDirectoryVisibilityAppService","networkId","$networkId","uploadContent","file","cancelUpload","upload","getCurrentUploads","getProfileInfo","getThreePids","addThreePid","creds","threePidCreds","addThreePidOnly","bindThreePid","unbindThreePid","deleteThreePid","setPassword","authDict","newPassword","logoutDevices","new_password","logout_devices","getDevices","getDevice","$device_id","setDeviceDetails","deleteDevice","deleteMultipleDevices","getPushers","pushers","pusher","setPusher","setLocalNotificationSettings","notificationSettings","rules","setPushRules","rewriteDefaultRules","updateCachedPushRuleKeys","ruleId","$kind","$ruleId","setPushRuleEnabled","setPushRuleActions","uploadKeysRequest","uploadKeySignatures","downloadKeysForUsers","device_keys","claimOneTimeKeys","keyAlgorithm","queries","one_time_keys","getKeyChanges","oldToken","qps","uploadDeviceSigningKeys","registerWithIdentityServer","hsOpenIdToken","requestEmailToken","idServerRequest","requestMsisdnToken","submitMsisdnToken","sid","msisdnToken","submitMsisdnTokenOtherUrl","getIdentityHashDetails","identityHashedLookup","addressPairs","localMapping","olmutil","Utility","addr","med","hashed","unhashed","foundAddresses","mxid","plainAddress","lookupThreePid","bulkLookupThreePids","v1results","mapping","originalQuery","threepids","getIdentityAccount","recursiveMapToObject","targets","deviceMessages","queueToDevice","getThirdpartyProtocols","getThirdpartyLocation","$protocol","getThirdpartyUser","getTerms","agreeToTerms","termsUrls","Authorization","user_accepts","reportEvent","score","getRoomHierarchy","maxDepth","suggestedOnly","suggested_only","max_depth","unstableCreateFileTree","preset","PrivateChat","power_level_content_override","DEFAULT_TREE_POWER_LEVELS_TEMPLATE","creation_content","Space","initial_state","MEGOLM_ALGORITHM","MSC3089TreeSpace","unstableGetFileTreeSpace","getMyMembership","createEvent","RoomCreate","purposeEvent","proxyBaseUrl","clientTimeout","supportsExperimentalThreads","supportsIntentionalMentions","intentionalMentions","getRoomSummary","via","toStartOfTimeline","processThreadedEvents","processBeaconEvents","processPollEvents","whoami","timestampToEvent","timestamp","cli","ourUserId","oldActions","isThreadEvent","isThreadRoot","currentHighlightCount","getUnreadCountForEventContext","oldHighlight","newHighlight","hasReadEvent","newCount","setThreadUnreadNotificationCount","currentTotalCount","notify","parseBeaconContent","makeBeaconContent","parseBeaconInfoContent","makeBeaconInfoContent","parseTopicContent","parseLocationEvent","makeLocationContent","getTextForLocationEvent","extensible_events_1","location_1","topic_1","assetType","toISOString","Self","defaultedText","timestampEvent","Location","geo_uri","wireEventContent","asset","geoUri","fallbackText","mtopic","isLive","live","beaconInfoEventId","mxc","serverAndMediaId","fragmentOffset","fragment","requestKeysDuringVerification","createCryptoStoreCacheCallbacks","DeviceTrustLevel","UserTrustLevel","CrossSigningLevel","CrossSigningInfo","indexeddb_crypto_store_1","aes_1","KEY_REQUEST_TIMEOUT_MS","publicKeyFromKeyInfo","callbacks","cacheCallbacks","firstUse","crossSigningVerifiedBefore","toStorage","expectedPubkey","shouldCache","validateKey","signing","PkSigning","gotPubkey","init_with_seed","privkey","getCrossSigningKeyCache","cacheresult","storeCrossSigningKeyCache","isStoredInSecretStorage","secretStorage","stored","isStored","intersect","encodedKey","isStoredInKeyCache","getCrossSigningKeysFromCache","resetKeys","saveCrossSigningKeys","MASTER","master","USER_SIGNING","SELF_SIGNING","privateKeys","masterSigning","masterPub","generate_seed","usage","sskSigning","self_signing","sskPub","pkSign","uskSigning","user_signing","uskPub","clearKeys","setKeys","signingKeys","masterKey","pkVerify","updateCrossSigningVerifiedBefore","isCrossSigningVerified","signUser","signDevice","userCrossSigning","userTrusted","userMaster","uskId","localTrust","trustCrossSignedDevices","userTrust","userSSK","deviceObj","signatures","deviceToObject","fromUserTrustLevel","crossSigningVerified","tofu","wasCrossSigningVerified","isTofu","localVerified","userTrustLevel","isLocallyVerified","_expectedPublicKey","doTxn","STORE_ACCOUNT","txn","getSecretStorePrivateKey","ciphertext","decryptAES","encryptedKey","encryptAES","storeSecretStorePrivateKey","baseApis","crossSigning","decoded","backupKeyPromise","secretReq","base64Key","decodedKey","race","DeviceList","TrackingStatus","deviceinfo_1","CrossSigning_1","index_1","keyDownloadChunkSize","userByIdentityKey","deviceTrackingStatus","syncToken","keyDownloadsInProgressByUser","dirty","savePromise","resolveSavePromise","savePromiseTime","saveTimer","hasFetched","serialiser","DeviceListUpdateSerialiser","load","STORE_DEVICE_DATA","getEndToEndDeviceData","trackingStatus","userDevices","idKey","DownloadInProgress","PendingDownload","saveIfDirty","delay","targetTime","storeEndToEndDeviceData","getSyncToken","setSyncToken","st","usersToDownload","UpToDate","downloadPromise","doKeyDownload","getDevicesFromStore","deviceMap","getKnownUserIds","devs","DeviceInfo","fromStorage","getRawStoredDevicesForUser","storeCrossSigningForUser","getUserByIdentityKey","senderKey","OLM_ALGORITHM","getDeviceByIdentityKey","storeDevicesForUser","setRawStoredDevicesForUser","startTrackingDeviceList","stopTrackingDeviceList","NotTracked","stopTrackingAllDeviceLists","invalidateUserDeviceList","refreshOutdatedDeviceLists","dev","identityKey","setRawStoredCrossSigningForUser","updateDevicesForUsers","deviceList","downloadInProgress","keyDownloadsQueuedByUser","queuedQueryDeferred","doQueuedQueries","downloadUsers","factories","userSlice","chunkPromises","responses","dk","masterKeys","master_keys","ssks","self_signing_keys","usks","user_signing_keys","processQueryResponseForUser","dkResponse","crossSigningResponse","userStore","userResult","localUserId","localDeviceId","updated","deviceResult","storeDeviceKeys","updateStoredDeviceKeysForUser","storage","UserCrossSigningUpdated","signKeyId","signKey","unsigned","verifySignature","deviceStore","getFingerprint","EncryptionSetupOperation","EncryptionSetupBuilder","accountData","delegateCryptoCallbacks","accountDataClientAdapter","AccountDataClientAdapter","crossSigningCallbacks","CrossSigningCallbacks","ssssCryptoCallbacks","SSSSCryptoCallbacks","addCrossSigningKeys","authUpload","crossSigningKeys","addSessionBackup","keyBackupInfo","addSessionBackupPrivateKeyToCache","sessionBackupPrivateKey","addKeySignature","keySignatures","userSignatures","buildOperation","storeCrossSigningKeys","existingValues","modifiedValue","existingValue","lastEvent","AccountData","addPrivateKey","cacheSecretStorageKey","WITHHELD_MESSAGES","OlmDevice","PayloadTooLargeError","MAX_PLAINTEXT_LENGTH","checkPayloadLength","payloadString","calculateWithheldMessage","withheld","deviceCurve25519Key","deviceEd25519Key","maxOneTimeKeys","outboundGroupSessionStore","inboundGroupSessionMessageIndexes","sessionsInProgress","olmPrekeyPromise","get_library_version","fromExportedDevice","e2eKeys","initialiseFromExportedDevice","initialiseAccount","identity_keys","max_number_of_one_time_keys","curve25519","exportedData","STORE_SESSIONS","storeAccount","deviceKey","sessionInfo","lastReceivedMessageTs","storeEndToEndSession","getAccount","getAllEndToEndSessions","pickledSession","getSession","getEndToEndSession","unpickleSession","Session","saveSession","describe","pickledSessionInfo","getUtility","utility","getOneTimeKeys","maxNumberOfOneTimeKeys","markKeysAsPublished","mark_keys_as_published","generateOneTimeKeys","numKeys","generate_one_time_keys","generateFallbackKey","generate_fallback_key","getFallbackKey","unpublished_fallback_key","forgetOldFallbackKey","forget_old_fallback_key","createOutboundSession","theirIdentityKey","theirOneTimeKey","newSessionId","create_outbound","withPrefix","createInboundSession","theirDeviceIdentityKey","messageType","create_inbound_from","remove_one_time_keys","getSessionIdsForDevice","sessionIds","getEndToEndSessions","getSessionIdForDevice","nowait","sessionInfos","getSessionInfoForDevice","idxOfBest","thisSessInfo","thisLastReceived","bestSessInfo","bestLastReceived","deviceIdentityKey","sessInfo","hasReceivedMessage","has_received_message","encryptMessage","sessionDesc","decryptMessage","matchesSession","matches_inbound","recordSessionProblem","fixed","storeEndToEndSessionProblem","sessionMayHaveProblems","getEndToEndSessionProblem","filterOutNotifiedErrorDevices","saveOutboundGroupSession","getOutboundGroupSession","pickled","OutboundGroupSession","createOutboundGroupSession","encryptGroupMessage","getOutboundGroupSessionKey","chain_index","message_index","session_key","unpickleInboundGroupSession","sessionData","InboundGroupSession","getInboundGroupSession","getEndToEndInboundGroupSession","addInboundGroupSession","forwardingCurve25519KeyChain","sessionKey","keysClaimed","exportFormat","extraSessionData","STORE_INBOUND_GROUP_SESSIONS","STORE_INBOUND_GROUP_SESSIONS_WITHHELD","STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS","existingSession","existingSessionData","import_session","first_known_index","export_session","storeEndToEndInboundGroupSession","sharedHistory","addSharedHistoryInboundGroupSession","addInboundGroupSessionWithheld","storeEndToEndInboundGroupSessionWithheld","decryptGroupMessage","DecryptionError","plaintext","messageIndexKey","msgInfo","hasInboundSessionKeys","getInboundGroupSessionKey","chainIndex","exportedSession","senderEd25519Key","forwardingKeyChain","forwarding_curve25519_key_chain","sender_claimed_ed25519_key","shared_history","exportInboundGroupSession","messageIndex","sender_claimed_keys","getSharedHistoryInboundGroupSessions","ed25519_verify","OutgoingRoomKeyRequestManager","RoomKeyRequestState","uuid_1","stringifyRequestBody","stringifyRecipientList","recipients","sendOutgoingRoomKeyRequestsRunning","sendQueuedRequests","startTimer","queueRoomKeyRequest","resend","CancellationPendingAndWillResend","Unsent","CancellationPending","Sent","updateOutgoingRoomKeyRequest","cancellationTxnId","updatedReq","requestTxnId","sendOutgoingRoomKeyRequestCancellation","getOrAddOutgoingRoomKeyRequest","cancelRoomKeyRequest","deleteOutgoingRoomKeyRequest","getOutgoingSentRoomKeyRequest","getOutgoingRoomKeyRequestsByTarget","cancelAndResendAllOutgoingRequests","outgoings","getAllOutgoingRoomKeyRequestsByState","sendOutgoingRoomKeyRequestsTimer","sendOutgoingRoomKeyRequests","getOutgoingRoomKeyRequestByState","sendOutgoingRoomKeyRequest","requestMessage","requesting_device_id","request_id","sendMessageToDevices","andResend","recip","v4","STORE_ROOMS","getEndToEndRooms","roomInfo","storeEndToEndRoom","SecretStorage","SECRET_STORAGE_ALGORITHM_V1_AES","accountDataAdapter","requests","getDefaultKeyId","defaultKey","setDefaultKeyId","addKey","mac","calculateKeyCheck","hasKey","checkKey","defaultKeyId","encryption","secretInfo","encInfo","decryption","requestData","toDevice","cancel","cancelData","onRequestReceived","onSecretRequested","encryptedContent","ensureOlmSessionsForDevices","encryptMessageForDevice","onSecretReceived","isOlmEncrypted","getSenderKey","requestControl","deviceInfo","checkDeviceInfoTrust","returned","zeroSalt","ivStr","aesKey","hmacKey","encodedData","TextEncoder","subtleCrypto","counter","hkdfkey","keybits","aesProm","hmacProm","TextDecoder","ZERO_STR","registerAlgorithm","UnknownDeviceError","DecryptionAlgorithm","EncryptionAlgorithm","DECRYPTION_CLASSES","ENCRYPTION_CLASSES","member","oldMembership","onRoomKeyEvent","importRoomKey","hasKeysForKeyRequest","keyRequest","shareKeysWithDevice","retryDecryptionFromSender","details","detailedString","detailedStringForDecryptionError","encryptor","decryptor","MegolmDecryption","MegolmEncryption","isRoomSharedHistory","base_1","OlmDevice_1","OutgoingRoomKeyRequestManager_1","visibilityEvent","hasCiphertext","OutboundSessionInfo","useCount","sharedWithDevices","blockedDevicesNotified","creationTime","needsRotation","rotationPeriodMsgs","rotationPeriodMs","sessionLifetime","markSharedWithDevice","markNotifiedBlockedDevice","sharedWithTooManyDevices","devicesInRoom","setupPromise","outboundSessions","prefixedLogger","sessionRotationPeriodMsgs","rotation_period_msgs","sessionRotationPeriodMs","rotation_period_ms","ensureOutboundSession","singleOlmCreationPhase","fallible","oldSession","prepareSession","shareSession","prepareNewSession","shareMap","getIdentityKey","devicesWithoutSession","olmSessions","getExistingOlmSessions","olmSessionList","sessionsByUser","flat","shareKeyWithOlmSessions","errorDevices","failedServers","shareKeyWithDevices","retryDevices","failedServerMap","failedDevices","userHS","retryDeviceList","notifyFailedOlmDevices","blockedByUser","_deviceInfo","blockedMap","blockedCount","userBlockedDevices","notifyBlockedDevices","backupGroupSession","getDevicesWithoutSessions","noOlmDevices","devicesToShareWith","sessionResults","sessionResult","splitDevices","currentSlice","mapSlices","encryptAndSendKeysToDevices","sendBlockedNotificationsToDevices","userDeviceMap","blockedInfo","reshareKeyWithDevice","obSessionInfo","sessionSharedData","otkTimeout","devicemap","userDeviceMaps","taskDetail","unnotifiedFailedDevices","encryptionPreparation","elapsedTime","startTime","isCancelled","getDevicesResult","getDevicesInRoom","removeUnknownDevices","forceDistributeToUnverified","isVerificationEvent","checkForUnknownDevices","payloadJson","KeyVerificationCancel","KeyVerificationDone","KeyVerificationMac","KeyVerificationStart","KeyVerificationKey","KeyVerificationReady","KeyVerificationAccept","KeyVerificationRequest","unknownDevices","isUnverified","isKnown","getEncryptionTargetMembers","shouldEncryptForInvitedMembers","roomMembers","isBlacklisting","isRoomBlacklisting","getBlacklistUnverifiedDevices","userDevice","immediate","deviceTrust","isBlocked","blockedDevices","pendingEvents","decryptEvent","addEventToPendingList","getTs","errorCode","requestKeysForEvent","queryKeyBackupRateLimited","problem","problemDescription","PROBLEM_DESCRIPTIONS","unknown","removeEventFromPendingList","clearEvent","senderCurve25519Key","claimedEd25519Key","getKeyRequestRecipients","requestRoomKey","senderPendingEvents","roomKeyFromEvent","getKeysClaimed","forwardedRoomKeyFromEvent","roomKey","senderKeyUser","claimedCurve25519Key","shouldAcceptForwardedKey","sendingDevice","fromUs","keyFromOurVerifiedDevice","weRequested","wasRoomKeyRequested","fromInviter","wasRoomKeyForwardedByInviter","sharedAsHistory","wasRoomKeyForwardedAsHistory","memberEvent","getUnsigned","prev_sender","getPrevContent","shouldParkForwardedKey","parkForwardedKey","parkedData","senderId","addParkedSharedHistory","addRoomKey","retryDecryption","onForwardedRoomKey","onRoomKeyWithheldEvent","onNoOlmWithheldEvent","olmSessionResult","buildKeyForwardingMessage","forceRedecryptIfUntrusted","pendingList","isRetry","_sessionId","sharedHistorySessions","no_olm","DeviceVerification","OlmEncryption","sessionPrepared","prepPromise","ensureSession","ensureOlmSessionsForUsers","payloadFields","BLOCKED","OlmDecryption","recipient","recipient_keys","intended","our_key","real_sender","reported_sender","reported_room","reallyDecryptMessage","myPromise","decryptionErrors","DefaultAlgorithm","algorithmsByName","Aes256","Curve25519","sessionLastCheckAttemptedTime","checkedForBackup","sendingBackups","KeyBackupStatus","scheduleKeyBackupSend","authData","prepare","encodeRecoveryKey","algorithmName","checkAndStart","trustInfo","usable","trusted_locally","sigs","mySigs","keyIdParts","sigInfo","crossSigningId","valid","maxDelay","numFailures","getSessionsNeedingBackup","safeSet","forwardedCount","first_message_index","forwarded_count","is_verified","session_data","encryptSession","unmarkSessionsNeedingBackup","markSessionsNeedingBackup","STORE_BACKUP","getAllEndToEndInboundGroupSessions","PkEncryption","set_recipient_key","public_key","PkDecryption","init_with_private_key","derivation","keyFromPassphrase","private_key_salt","private_key_iterations","generate_key","get_private_key","plainText","ephemeral","pubKey","UNSTABLE_MSC3270_NAME","outKey","setTextEncoder","setCrypto","webkitSubtle","webcrypto","_crypto","_TextEncoder","__importDefault","DehydrationManager","another_json_1","oneweek","inProgress","getDehydrationKeyFromCache","timeoutId","maxKeys","otks","fallbacks","fallback_key","initial_device_display_name","deviceKeys","supportedAlgorithms","deviceSignature","oneTimeKeys","fallbackKeys","fallback","Unverified","getDisplayName","device_display_name","Verified","VERIFIED","UNVERIFIED","IncomingRoomKeyRequest","DeviceList_1","EncryptionSetup_1","SecretStorage_1","QRCode_1","SAS_1","VerificationRequest_1","InRoomChannel_1","ToDeviceChannel_1","IllegalMethod_1","errors_1","room_state_1","defaultVerificationMethods","ReciprocateQRCode","NAME","SAS","SHOW_QR_CODE_METHOD","IllegalMethod","SCAN_QR_CODE_METHOD","RECIPROCATE_QR_CODE","clientStore","lastOneTimeKeyCheck","oneTimeKeyCheckInProgress","roomEncryptors","roomDecryptors","receivedRoomKeyRequests","receivedRoomKeyRequestCancellations","processingRoomKeyRequests","roomDeviceTrackingState","lastNewSessionForced","sendKeyRequestsImmediately","onDeviceListUserCrossSigningUpdated","newCrossSigning","seenPubkey","currentPubkey","storeTrustedSelfKeys","checkDeviceVerifications","onMembership","onToDeviceEvent","onRoomKeyRequestEvent","transaction_id","onKeyVerificationMessage","onToDeviceBadEncrypted","onTimelineEvent","atStart","removed","liveEvent","InRoomChannel","validateEvent","handleVerificationEvent","inRoomVerificationRequests","channel","VerificationRequest","cachedKey","getBackupKey","outgoingRoomKeyRequestManager","toDeviceVerificationRequests","ToDeviceRequests","InRoomRequests","getFromSecretStorage","myDevices","getCrossSigningKeys","encodedPrivateKey","publicKeysOnDevice","privateKeysExistSomewhere","secretStorageKeyInAccount","privateKeysInStorage","sessionBackupInStorage","authUploadDeviceSigningKeys","setupNewCrossSigning","builder","resetCrossSigning","privateKeysInCache","allowPrivateKeyRequests","crossSigningPrivateKeys","storeInSecretStorage","createSecretStorageKey","setupNewKeyBackup","setupNewSecretStorage","getKeyBackupPassphrase","newKeyId","createSSSS","ensureCanCheckPassphrase","signKeyBackupWithCrossSigning","keyBackupAuthData","oldSSSSKey","oldKeyId","oldKeyInfo","storageExists","backupKey","sessionBackupKey","fixedBackupKey","decodedBackupKey","keyID","afterCrossSigningLocalKeyChange","signedDevice","shouldEmit","failures","KeySignatureUploadFailure","KeySignatureUploadError","shouldUpgradeCb","shouldUpgradeDeviceVerifications","upgradeInfo","checkForDeviceVerificationUpgrade","usersToUpgrade","trustLevel","deviceIds","checkForValidDeviceSignature","signame","trustedLocally","trustCrossSig","masterChanged","masterExistsNotLocallyCached","oldSelfSigningId","oldUserSigningId","selfSigningChanged","userSigningChanged","selfSigningExistsNotLocallyCached","userSigningExistsNotLocallyCached","deviceSig","keysToUpload","enableLazyLoading","eventEmitter","ToDeviceEvent","Timeline","updateOneTimeKeyCount","currentCount","oneTimeKeyCount","setNeedsNewFallback","needsNewFallback","getNeedsNewFallback","maybeUploadOneTimeKeys","keyLimit","uploadLoop","keyCount","keysThisLoop","fallbackCleanup","uploadOneTimeKeys","one_time_key_counts","signed_curve25519","fallbackJson","oneTimeJson","saveDeviceList","xsk","gotKeyId","verificationStatus","knownStatus","findRequestInProgress","getRequestsInProgress","existingRequest","requestVerificationWithChannel","ToDeviceChannel","makeTransactionId","requestsMap","transactionId","setRequestByChannel","sendRequest","racingRequest","getRequestByChannel","getRequestBySenderAndTxnId","setRequestBySenderAndTxnId","verifier","waitFor","started","getOlmSessionsForUser","deviceIdKey","isKeySourceUntrusted","claimedKey","getClaimedEd25519Key","authenticated","mismatchedSender","inhibitDeviceQuery","setRoomEncryptionImpl","existingConfig","storeConfigPromise","AlgClass","membersLoaded","trackRoomDevicesImpl","onState","_state","RoomStateEvent","Update","trackRoomDevices","trackMembers","exportedSessions","sess","successes","updateProgress","mRelatesTo","elementPerfMetrics","makeEncrypted","isRedacted","redactionEvent","redacted_because","redactedBecause","handleDeviceListChanges","syncData","syncDeviceLists","oldSyncToken","evalDeviceListChanges","cancelAndResendAllOutgoingKeyRequests","onCryptoEvent","onSyncWillProcess","onSyncCompleted","nextSyncToken","catchingUp","processReceivedRoomKeyRequests","deviceLists","changed","e2eUserIds","getTrackedE2eUsers","getTrackedE2eRooms","myMembership","toDeviceBatch","preprocessToDeviceMessages","preprocessOneTimeKeyCounts","oneTimeKeysCounts","preprocessUnusedFallbackKeys","unusedFallbackKeys","getRoomDecryptors","canCreateRequest","getEventType","from_device","createRequest","isLiveEvent","isSending","eventIdListener","statusListener","Status","getRequest","isNewRequest","setRequest","setVerificationRequest","handleEvent","initiatedByMe","invalid","observeOnly","UndecryptableToDeviceEvent","lastNewSessionDevices","requestsToResend","keyReq","IncomingRoomKeyRequestCancellation","cancellations","processReceivedRoomKeyRequest","cancellation","processReceivedRoomKeyRequestCancellation","share","decryptors","deriveKey","DEFAULT_ITERATIONS","DEFAULT_BITSIZE","numBits","private_key_bits","encodeUnpaddedBase64","MEGOLM_BACKUP_ALGORITHM","_verifyKeyAndStartSession","oneTimeKey","signingUserId","signingDeviceId","signingKey","mangledObj","uint8Array","Megolm","MegolmBackup","resultsObject","ourDeviceId","recipientUserId","recipientDevice","sender_device","resolveSession","resultDevices","forWhom","resolveSessionFn","oneTimeKeyAlgorithm","otkResult","userRes","deviceRes","createdKey","keyObj","mysigs","bs58","OLM_RECOVERY_KEY_PREFIX","parity","PRIVATE_KEY_LENGTH","upgradeDatabase","VERSION","Backend","nextTxnId","onversionchange","transaction","_getOutgoingRoomKeyRequest","oncomplete","objectStore","cursorReq","openCursor","cursor","continue","wantedStates","stateIndex","wantedState","promiseifyTxn","getAll","expectedState","updates","getReq","abortWithException","accountPickle","put","countEndToEndSessions","countReq","problems","lastProblem","withheldGetReq","addEndToEndInboundGroupSession","addReq","stopPropagation","sessionStore","sessionGetReq","parked","takeParkedSharedHistory","stores","DB_MIGRATIONS","outgoingRoomKeyRequestsStore","createObjectStore","keyPath","createIndex","createDatabase","_mx_abortexception","onabort","oldVersion","migration","localStorage_crypto_store_1","memory_crypto_store_1","IndexedDBCryptoStoreBackend","IndexedDBHelpers","dbName","exists","backendPromise","open","onupgradeneeded","backend","InvalidCryptoStoreError","InvalidCryptoStoreState","TooNew","LocalStorageCryptoStore","MemoryCryptoStore","STORE_PARKED_SHARED_HISTORY","E2E_PREFIX","KEY_END_TO_END_ACCOUNT","KEY_CROSS_SIGNING_KEYS","KEY_NOTIFIED_ERROR_DEVICES","KEY_DEVICE_DATA","KEY_INBOUND_SESSION_PREFIX","KEY_INBOUND_SESSION_WITHHELD_PREFIX","KEY_ROOMS_PREFIX","KEY_SESSIONS_NEEDING_BACKUP","keyEndToEndSessions","keyEndToEndSessionProblems","keyEndToEndInboundGroupSession","keyEndToEndInboundGroupSessionWithheld","keyEndToEndRoomsPrefix","_getEndToEndSessions","getJsonItem","fixedSessions","setJsonItem","notifiedErrorDevices","sessionsNeedingBackup","getItem","setItem","outgoingRoomKeyRequests","sessionProblems","inboundGroupSessions","inboundGroupSessionsWithheld","sharedHistoryInboundGroupSessions","parkedSharedHistory","promiseTry","deviceSessions","VerificationBase","VerificationEvent","SwitchStartEventError","Error_1","timeoutException","startEvent","_done","transactionTimeoutTimer","hasBeenCancelled","resetTimer","endTimer","uncompletedContent","waitForEvent","existingEvent","getEventFromOtherParty","expectedEvent","resolveEvent","rejectEvent","canSwitchStartEvent","switchStartEvent","restartingFlow","onVerifierFinished","onVerifierCancelled","timeoutEvent","newTimeoutError","Cancel","doVerification","verifyKeys","verifiedDevices","errorFromEvent","newInvalidMessageError","newKeyMismatchError","newUnexpectedMessageError","newUnknownMethodError","newUserCancelledError","errorFactory","newVerificationError","extraData","Base_1","QRCodeData","QrCodeEvent","qrCodeData","encodedSharedSecret","reciprocateQREvent","confirm","ShowReciprocateQr","Mode","VerifyOtherUser","otherUserMasterKey","VerifySelfTrusted","targetDevice","otherDeviceKey","VerifySelfUntrusted","myMasterKey","targetKey","deviceKeyId","deviceTargetKey","sharedSecret","generateSharedSecret","determineMode","otherUserId","getOtherDeviceKey","myUserId","qrData","generateQrData","generateBuffer","secretBytes","otherDevice","firstKeyB64","secondKeyB64","secretB64","myCrossSigningInfo","appendByte","tmpBuf","appendStr","withLengthPrefix","appendInt","appendEncBase64","SasEvent","SASDecimal_1","START_TYPE","EVENTS","newMismatchedSASError","newMismatchedCommitmentError","emojiMapping","sasGenerators","decimal","generateDecimalSas","emoji","sasBytes","generateSas","sas","macMethods","calculateMAC","olmSAS","calculateKeyAgreement","ourInfo","ourSASPubKey","theirInfo","theirSASPubKey","sasInfo","generate_bytes","KEY_AGREEMENT_LIST","HASHES_LIST","MAC_LIST","SAS_LIST","KEY_AGREEMENT_SET","HASHES_SET","MAC_SET","SAS_SET","intersection","anArray","aSet","doSendVerification","doRespondVerification","waitingForAccept","sendStart","startContent","completeContent","key_agreement_protocols","message_authentication_codes","short_authentication_string","sendCompleted","verifyAndCheckMAC","keyAgreement","sasMethods","macMethod","verifySAS","sasEvent","sendMAC","mismatch","ShowSas","checkMAC","completedContentFromEvent","key_agreement_protocol","message_authentication_code","commitment","hashCommitment","get_pubkey","commitmentStr","set_their_key","hashMethod","keyList","baseInfo","crossSigningKeyId","MESSAGE_TYPE","M_REFERENCE","M_RELATES_TO","receiveStartFromOtherDevices","requestEventId","REQUEST_TYPE","ownUserId","getTimestamp","relation","getRelation","getTransactionId","getOtherPartyUserId","hasEventId","isRemoteEcho","isSentByUs","READY_TYPE","sendType","requestsByRoomId","getRequestByTxnId","requestsByTxnId","doSetRequest","removeRequest","isToDevices","cancelContent","CANCEL_TYPE","sendToDevices","wasStarted","PHASE_STARTED","PHASE_READY","isStarted","nonChosenDevices","remoteEchoEvent","requestsByUserId","VerificationRequestEvent","PHASE_DONE","PHASE_CANCELLED","PHASE_REQUESTED","PHASE_UNSENT","Phase","DONE_TYPE","EVENT_PREFIX","Requested","Ready","Started","Cancelled","Done","eventsByUs","eventsByThem","_observeOnly","timeoutTimer","_accepting","_declining","verifierHasFinished","_cancelled","_chosenMethod","_qrCodeData","requestReceivedAt","commonMethods","cancelOnTimeout","setPhase","chosenMethod","calculateEventTimeout","effectiveExpiresAt","expiresAtByReceipt","requestEvent","getEventByEither","_phase","_verifier","canAccept","accepting","declining","otherPartySupportsMethod","theirMethodEvent","myStartEvent","noEventsYet","hasMyRequest","hasTheirRequest","hasMyStart","hasTheirStart","requestingUserId","receivingUserId","isSelfVerification","cancellingUserId","myCancel","theirCancel","cancellationCode","theirFirstEvent","theirFirstContent","fromDevice","createVerifier","Change","_cancellingUserId","accept","check","handled","getEventBy","byThem","calculatePhaseTransitions","transitions","hasRequestByThem","readyEvent","theirStartEvent","ourStartEvent","fromRequestPhase","fromUnsentPhase","ourDoneEvent","cancelEvent","transitionToPhase","transition","wasSentByOwnDevice","wasSentByOwnUser","applyPhaseTransitions","existingIdx","newTransitions","isWinningStartRace","newEvent","oldEvent","oldRaceIdentifier","newRaceIdentifier","oldContent","newContent","wasObserveOnly","adjustObserveOnly","cancelOnError","oldPhase","addEvent","newEventWinsRace","lastTransition","setupTimeout","isUnexpectedRequest","isUnexpectedReady","VerifierCtor","__asyncValues","__values","verb","RoomWidgetClient","matrix_widget_api_1","event_3","widgetApi","_j","_k","widgetApiReady","syncState","onEvent","injectRoomEvents","setSyncState","ack","onToDevice","receiveEvent","receiveMessage","sendState","receiveState","requestCapabilityForRoomTimeline","requestCapabilityToSendEvent","requestCapabilityToReceiveEvent","requestCapabilityToSendMessage","msgType","requestCapabilityToReceiveMessage","requestCapabilityToSendState","requestCapabilityToReceiveState","requestCapabilityToSendToDevice","receiveToDevice","requestCapabilityToReceiveToDevice","lifecycle","storeRoom","watchTurnServers","sendRoomEvent","e_1","onClientStopped","servers_1_1","servers_1","e_1_1","InvalidStoreState","InvalidStoreError","TOGGLED_LAZY_LOADING","ToggledLazyLoading","TOO_NEW","preventReEmit","plainOldJsObject","findEventById","setUnsigned","bundledEdit","replacement","makeReplaced","featureSupportResolver","unstablePrefixes","matrixVersion","ThreadUnreadNotifications","LoginTokenRequest","supportMap","supportCondition","supportMatrixVersion","supportUnstablePrefixes","every","unstablePrefix","unstable_features","FilterComponent","filterJson","bundledRelationships","relationSenders","current_user_participated","checkFields","not_types","not_rooms","senders","not_senders","contains_url","FILTER_RELATED_BY_SENDERS","FILTER_RELATED_BY_REL_TYPES","containsUrl","relationTypes","literalKeys","actualValue","filterValue","typePrefix","matchesWildcard","matchFunc","notName","disallowedValues","allowedValues","containsUrlFilter","relationTypesFilter","arrayMatchesFilter","relationSendersFilter","filter_component_1","setProp","keyNesting","nestedKeys","currentObj","jsonObj","setDefinition","getFilterId","roomFilterJson","roomFilterFields","roomFilter","roomTimelineFilter","filterRoomTimeline","setTimelineLimit","setUnreadThreadNotifications","setLazyLoadMembers","setIncludeLeaveRooms","includeLeave","lazy_load_members","ConnectionError","HTTPError","errorJson","cause","FetchHttpApi","method_1","interface_1","abortController","checkObjectHasKeys","fullUri","requestPromise","HttpApiEvent","NoConsent","consent_uri","SessionLoggedOut","jsonBody","keepAlive","signals","anySignal","redirect","referrer","referrerPolicy","keepalive","parseErrorResponse","fetch_1","prefix_1","uploads","includeFilename","contentType","fileName","loaded","XMLHttpRequest","xhr","timeoutFn","onreadystatechange","readyState","DONE","DOMException","statusText","responseText","onprogress","progressHandler","setRequestHeader","filename","removeElement","getContentUri","content_type_1","isXhr","ms","controller","onAbort","getResponseHeader","getResponseContentType","responseURL","maxAttempts","lastConnectionError","InteractiveAuth","AuthType","EMAIL_STAGE_TYPE","MSISDN_STAGE_TYPE","NoAuthFlowFoundError","required_stages","flows","requestingEmailToken","attemptAuthDeferred","chosenFlow","currentStage","emailAttempt","submitPromise","requestTokenResult","requestEmailTokenCallback","inputs","emailAddress","emailSid","matrixClient","requestCallback","doRequest","busyChangedCallback","busyChanged","stateUpdatedCallback","stateUpdated","startAuthStage","attemptAuth","startNextAuthStage","idServerParsedUrl","threepid_creds","threepidCreds","submitAuthDict","getClientSecret","getStageParams","getChosenFlow","background","getEmailSid","setEmailSid","errorFlows","haveFlows","completed","stages","Email","nextStage","chooseStage","Dummy","chooseFlow","firstUncompletedStage","haveEmail","haveMsisdn","flowHasEmail","flowHasMsisdn","requiredStages","stageType","loglevel_1","DEFAULT_NAMESPACE","extendLogger","prefixLogger","getPrefixedLogger","logLevel","loglevel","createRoomWidgetClient","createClient","GroupCallType","GroupCallState","GroupCallIntent","GroupCallEvent","memory_1","embedded_1","cryptoStoreFactory","amendClientOpts","MemoryStore","fac","MSC3089Branch","indexEvent","directory","isActive","nextVersion","getVersionHistory","getName","setName","isLocked","setLocked","locked","getFileInfo","getFileEvent","getOriginalContent","httpUrl","getUnfilteredTimelineSet","createNewVersion","encryptedContents","additionalContent","fileEventResponse","createFile","fileHistory","childEvent","parentEvent","replacingEventId","branch","getFile","TreePermissions","p_retry_1","MSC3089Branch_1","megolm_1","redact","state_default","events_default","users_default","isTopLevel","parentEvents","SpaceParent","andSubspaces","shareHistoryKeys","retryInvite","getDirectories","simpleRetryOperation","setPermissions","role","currentPls","pls","viewLevel","editLevel","adminLevel","Viewer","Editor","Owner","getPermissions","userLevel","createDirectory","SpaceChild","trees","getDirectory","subdirectories","kickMemberships","RoomMember","getOrderedChildren","ordered","order","lexicographicCompare","roomA","roomB","createTsA","createTsB","getParentRoom","parentRoom","getOrder","setOrder","movingUp","newOrder","DEFAULT_ALPHABET","ensureBeforeIsSane","nextString","startOrder","endOrder","averageBetweenStrings","prevString","lastOrder","currentChild","content_uri","fileContent","File","fileEventId","listFiles","listAllFiles","Beacon","getBeaconInfoIdentifier","isTimestampInDuration","BeaconEvent","content_helpers_1","startTimestamp","durationMs","rootEvent","clearLatestLocation","_latestLocationEvent","LocationUpdate","latestLocationState","setBeaconInfo","_isLive","identifier","beaconInfoId","beaconInfoOwner","beaconInfoEventType","beaconInfo","_beaconInfo","latestLocationEvent","beaconInfoEvent","livenessWatchTimeout","Destroy","monitorLiveness","checkLiveness","expiryInMs","addLocations","beaconLocationEvents","sortEventsByLatestContentTimestamp","prevLiveness","LivenessChange","EventContext","ourEvent","ourEventIndex","paginateTokens","getOurEventIndex","getPaginateToken","setPaginateToken","addEvents","EventTimelineSet","DuplicateStrategy","relations_container_1","_eventIdToTimeline","displayPendingEvents","timelines","RelationsContainer","getTimelines","setFilter","setLiveTimeline","eventIdToTimeline","replaceEventId","oldEventId","newEventId","existingTimeline","backPaginationToken","forwardPaginationToken","resetAllTimelines","oldTimeline","newTimeline","forkLive","fork","TimelineReset","inverseDirection","didUpdate","lastEventWasNew","addEventToTimeline","neighbour","getNeighbouringTimeline","existingIsLive","timelineIsLive","backwardsIsLive","forwardsIsLive","setNeighbouringTimeline","addLiveEvent","duplicateStrategyOrOpts","fromCache","timelineWasEmpty","duplicateStrategy","Ignore","tlEvents","setEventMetadata","toStartOfTimelineOrOpts","eventDebugString","aggregateParentEvent","aggregateChildEvent","handleRemoteEcho","removeEvent","compareEventOrdering","eventId1","eventId2","timeline1","timeline2","idx1","idx2","evId","shouldLiveInRoom","eventShouldLiveIn","stateContext","getSentinelMember","forwardLooking","eventTimelineSet","baseIndex","startToken","endToken","prevTimeline","nextTimeline","startState","RoomState","endState","setStateEvents","forkState","getBaseIndex","insertIndex","algorithms_1","event_status_1","MESSAGE_VISIBLE","freeze","_replacingEvent","_localRedactionEvent","_isCancelled","_hasCachedExtEv","_cachedExtEv","decryptionPromise","encryptedDisabledForUnverifiedDevices","internaliseString","txn_id","localTimestamp","getAge","unstableExtensibleEvent","getEffectiveEvent","invalidateExtensibleEvent","getDetails","relatesTo","replyEventId","relationEventId","prev_content","getDirectionalContent","age","getLocalAge","cryptoType","cryptoContent","isDecryptionFailure","isEncryptedDisabledForUnverifiedDevices","alreadyDecrypted","forceRedecrypt","decryptionLoop","badEncryptedMessage","detailedError","setClearData","decryptionResult","getClearContent","getForwardingCurve25519KeyChain","unmarkLocallyRedacted","markLocallyRedacted","applyVisibilityEvent","visibilityChange","change","messageVisibility","makeRedacted","REDACT_KEEP_KEYS","keeps","REDACT_KEEP_CONTENT_MAP","asVisibilityChange","isVisibilityEvent","getRedactionEvent","oldUnsigned","oldId","replaceLocalEventId","relType","getAssociatedStatus","replaceRelation","replacingEvent","replacingEventDate","localRedactionEvent","hasAssocation","hasAssociation","flagCancelled","toSnapshot","isEquivalentTo","otherEvent","myProps","deepSortedObjectEntries","theirProps","verificationRequest","ThreadEvent","setThreadId","creator","RoomJoinRules","join_rule","PolicyScope","IGNORE_INVITES_ACCOUNT_EVENT_KEY","POLICIES_ACCOUNT_EVENT_TYPE","PolicyRecommendation","addRule","getOrCreateTargetRoom","recommendation","Ban","removeRule","addSource","sources","getOrCreateSourceRooms","withIgnoreInvitesPolicies","ignoreInvitesPolicies","getRuleForInvite","policyRooms","senderServer","roomServer","entities","Room","Server","glob","globToRegexp","ex","getIgnoreInvitesPolicies","hasChanges","sourceRooms","getPoliciesAndIgnoreInvitesPolicies","policies","hasIgnoreInvitesPolicies","Poll","PollEvent","polls_1","relations_1","filterResponseRelations","relationEvents","pollEndTimestamp","responseEvents","_isFetchingResponses","undecryptableRelationEventIds","countUndecryptableEvents","undecryptableEventIds","previousCount","undecryptableRelationsCount","UndecryptableRelations","pollEvent","pollId","endEventId","endEvent","isEnded","isFetchingResponses","getResponses","fetchResponses","onNewRelation","validateEndEvent","refilterResponsesOnEnd","End","MAX_SAFE_INTEGER","Responses","allRelations","relationsNextBatch","Relations","pollEndEvent","pollCloseTimestamp","getRelations","roomCurrentState","endEventSender","maySendRedactionForEvent","ReadReceipt","synthesizeReceipt","receipts","receiptCacheByEventId","getReadReceiptForUserId","ignoreSynthesized","realReceipt","syntheticReceipt","publicReadReceipt","privateReadReceipt","comparison","addReceiptToStructure","receipt","synthetic","receiptTypesMap","pair","existingReceipt","ordering","wrappedReceipt","preferSynthetic","cachedReceipt","previousEventId","getReceiptsForEvent","setUnread","addReceipt","getUsersReadUpTo","readUpToId","getChildEventsForEvent","getAllChildEventsForEvent","parentEventId","relationsForEvent","relationsRecord","relationsWithRelType","relationsWithEventType","setTargetEvent","onEventDecrypted","relatesToEventId","relatesToEvent","getPendingEvent","RelationsEvent","altEventTypes","relationEventIds","annotationsByKey","annotationsBySender","sortedAnnotationsByKey","targetEvent","creationEmitted","onEventStatus","onBeforeRedaction","redactedEvent","Annotation","removeAnnotationFromAggregation","lastReplacement","getLastReplacement","Redaction","targetEventType","altTargetEventTypes","matchesEventType","addAnnotationToAggregation","Add","maybeEmitCreated","Remove","eventsForKey","aEvents","eventsFromSender","getSortedAnnotationsByKey","getAnnotationsBySender","minTs","RelationsCreated","_isOutOfBand","modified","requestedProfileInfo","powerLevelNorm","disambiguate","rawDisplayName","updateModifiedTime","markOutOfBand","isOutOfBand","setMembershipEvent","selfUserId","removeHiddenChars","MXID_PATTERN","LTR_RTL_PATTERN","getUserIdsWithDisplayName","shouldDisambiguate","oldName","removeDirectionOverrideChars","calculateDisplayName","setPowerLevelEvent","powerLevelEvent","evContent","maxLevel","lvl","oldPowerLevel","oldPowerLevelNorm","isInteger","PowerLevel","setTypingEvent","oldTyping","typingList","user_ids","Typing","getLastModifiedTime","isKicked","getDMInviter","memberContent","inviteSender","is_direct","getAvatarUrl","allowDefault","rawUrl","getMxcAvatarUrl","beacon_2","OobStatus","oobMemberFlags","NotStarted","sentinels","displayNameToUserIds","userIdsToDisplayNames","tokenToInvite","joinedMemberCount","summaryJoinedMemberCount","invitedMemberCount","summaryInvitedMemberCount","beacons","_liveBeaconIds","getJoinedMemberCount","getMembers","setJoinedMemberCount","getInvitedMemberCount","setInvitedMemberCount","getMembersExcept","excludedIds","sentinel","hasLiveBeacons","liveBeaconIds","eventsByStateKey","Finished","unknownStateEvents","markerFoundOptions","setBeacon","lastStateEvent","getStateEventMatching","setStateEvent","updateDisplayNameCache","updateThirdPartyTokenCache","Events","onBeaconLivenessChange","getOrCreateMember","updateMember","Members","oldLastModified","Marker","beaconByEventIdDict","dict","beacon","processBeaconRelation","relatedToEventId","NewMember","beaconIdentifier","New","BeaconLiveness","pwrLvlEvent","needsOutOfBandMembers","outOfBandMembersReady","markOutOfBandMembersStarted","InProgress","markOutOfBandMembersFailed","clearOutOfBandMembers","setOutOfBandMembers","setOutOfBandMember","existingMember","getInviteForThreePidToken","mxEvent","canRedact","maySendEvent","hasSufficientPowerLevelFor","powerLevelsEvent","powerLevels","requiredLevel","maySendMessage","maySendEventOfType","mayClientSendStateEvent","stateEventType","maySendStateEvent","eventsLevels","stateDefault","eventsDefault","isSafeInteger","userPowerLevel","mayTriggerNotifOfType","notifLevelKey","notifLevel","getJoinRule","joinRuleEvent","Invite","getHistoryVisibility","historyVisibilityEvent","Shared","getGuestAccess","guestAccessEvent","Forbidden","predecessorEvent","RoomPredecessor","predecessor_room_id","last_known_event_id","via_servers","third_party_invite","signed","RoomThirdPartyInvite","strippedOldName","existingUserIds","filteredUserIDs","strippedDisplayname","RoomSummary","RoomNameType","KNOWN_SAFE_ROOM_VERSION","event_timeline_set_1","room_summary_1","read_receipt_1","poll_1","SAFE_ROOM_VERSIONS","txnToEvent","notificationCounts","threadNotifications","cachedThreadReadReceipts","oldestThreadedReceiptTs","unthreadedReceipts","polls","threadsTimelineSets","filteredTimelineSets","timelineNeedsRefresh","summaryHeroes","getTypeWarning","getVersionWarning","summary","visibilityEvents","threadTimelineSetsPromise","threadsReady","updateThreadRootEvents","recreateEvent","updateThreadRootEvent","hasCurrentUserParticipated","applyRedaction","redactId","currentStateEvent","redactVisibilityChangeEvent","pendingEventOrdering","Chronological","normalizedName","timelineSets","fixUpLegacyTimelineFields","Detached","pendingEventList","serializedEvent","membersPromise","createThreadsTimelineSets","createThreadTimelineSet","My","decryptCriticalEvents","readReceiptEventId","readReceiptTimelineIndex","matrixEvent","decryptionPromises","allSettled","decryptAllEvents","getCreator","getVersion","shouldUpgradeToVersion","getRecommendedVersion","versionCap","safeVer","checkVersionAgainstCapability","urgent","needsUpgrade","currentVersion","userMayUpgradeRoom","removePendingEvent","savePendingEvents","getLastActiveTimestamp","MIN_SAFE_INTEGER","selfMembership","me","getInvitedAndJoinedMemberCount","guessDMUserId","inviterId","anyMember","getAvatarFallbackMember","hasHeroes","availableMember","availableUser","updateMyMembership","prevMembership","cleanupAfterLeaving","MyMembership","loadMembersFromServer","lastSyncToken","loadMembers","fromServer","rawMembersEvents","getOutOfBandMembers","memberEvents","loadMembersIfNeeded","inMemoryUpdate","oobMembers","clearLoadedMembersIfNeeded","refreshLiveTimeline","liveTimelineBefore","backwardPaginationToken","eventsBefore","mostRecentEventInTimeline","TimelineRefresh","setTimelineNeedsRefresh","previousOldState","previousCurrentState","OldStateUpdated","CurrentStateUpdated","hasUnverifiedDevices","e2eMembers","getTimelineSets","getTimelineNeedsRefresh","getThreads","getRoomUnreadNotificationCount","threadNotification","getThreadUnreadNotificationCount","hasThreadUnreadNotification","UnreadNotifications","threadsAggregateNotificationType","resetThreadUnreadNotificationCount","notificationsToKeep","setSummary","heroes","joinedCount","invitedCount","setBlacklistUnverifiedDevices","blacklistUnverifiedDevices","roomAvatarEvent","RoomAvatar","mainUrl","getCanonicalAlias","canonicalAlias","RoomCanonicalAlias","getAltAliases","alt_aliases","getJoinedMembers","getMembersWithMembership","getDefaultRoomName","calculateRoomName","getOrCreateFilteredTimelineSet","prepopulateTimeline","useSyncEvents","unfilteredLiveTimeline","livePaginationToken","getThreadListFilter","filterType","currentUserParticipated","createThread","fetchRoomThreads","fetchRoomThreadList","allThreadsFilter","threadRoots","eventA","eventB","threadAMetadata","threadBMetadata","latest_event","latestMyThreadsRootEvent","threadRelationship","NewReply","onThreadNewReply","onThreadDelete","processPollStartEvent","processPollRelationEvent","processPollEvent","roomEvent","clearEventMetadata","removeFilteredTimelineSet","roots","shouldLiveInThread","addThreadedEvents","eventsByThread","threadEvents","relatedEvents","isNewer","lastThread","processLiveEvent","applyNewVisibilityEvent","applyPendingVisibilityEvents","tid","addLiveEventOptions","aggregateNonLiveRelation","LocalEchoUpdated","isEventEncrypted","setPendingEvents","getEventForTxnId","remoteEvent","oldStatus","ALLOWED_TRANSITIONS","removedEvent","revertRedactionLocalEcho","RedactionCancelled","addLiveEvents","findThreadRoots","memo","receiptForMainTimeline","receiptDestination","addEphemeralEvents","removeEvents","eventIds","removedAny","recalculate","membershipEvent","invite_room_state","strippedEvent","addTags","Tags","addAccountData","canInvite","isSpaceRoom","isCallRoom","UnstableCall","isElementVideoRoom","ElementVideo","Actual","memberNamesToRoomName","EmptyRoom","ignoreRoomNameEvent","mRoomName","inviteJoinCount","excludedUserIds","mFunctionalMembers","service_members","otherNames","otherMembers","thirdPartyInvites","thirdPartyNames","leftNames","visibilityEventsOnOriginalEvent","originalEventId","newVisibility","getOldestThreadedReceiptTs","getLastUnthreadedReceiptFor","unreadThreads","countWithoutMe","event_context_1","eventMapper","jsonContext","eventsAfter","rank","_currentUserParticipated","replyCount","pendingReplyCount","initialEventsFetched","replayEvents","redaction","updatePendingReplyCount","onRedaction","threadEvent","updateThreadMetadata","onEcho","onLocalEcho","processReceipts","fetchRootEvent","eventData","isNewestReply","fetchEditsWhereNeeded","getRootEventBundledRelationship","processRootEvent","bundledRelationship","lastPendingEvent","oldLive","newLive","newBackward","oldForward","replyToEvent","isCurrentUser","beforeFirstThreadedReceipt","lastReplyId","unthreadedReceipt","unthreadedReceiptTs","beforeLastUnthreadedReceipt","EventEmitterEvents","events_1","lastActiveAgo","lastPresenceTs","currentlyActive","setPresenceEvent","firstFire","eventsToFire","Presence","currently_active","CurrentlyActive","LastPresenceTs","status_msg","presenceStatusMsg","last_active_ago","eventToFire","setRawDisplayName","oldUrl","getLastActiveTs","RULEKINDS_IN_ORDER","Override","ContentSpecific","SenderSpecific","Underride","DEFAULT_OVERRIDE_RULES","conditions","EventMatch","IsUserMention","EventPropertyContains","Notify","set_tweak","IsRoomMention","EventPropertyIs","SenderNotificationPermission","RoomServerAcl","DEFAULT_UNDERRIDE_RULES","CallStarted","Sound","parsedKeys","actionList","actionObj","incomingRules","newRules","override","underride","globalOverrides","originalOverride","existingRule","globalUnderrides","toRemoveKeys","ruleset","partsForDottedKey","matchingRuleFromKindSet","kindset","rawrule","templateRuleToRaw","ruleMatchesEvent","tprule","eventFulfillsCondition","cond","eventFulfillsEventMatchCondition","eventFulfillsEventPropertyIsCondition","eventFulfillsEventPropertyContains","ContainsDisplayName","eventFulfillsDisplayNameCondition","RoomMemberCount","eventFulfillsRoomMemberCountCondition","eventFulfillsSenderNotifPermCondition","CallStartedPrefix","eventFulfillsCallStartedCondition","is","memberCount","ineq","pat","escapeRegExp","valueForDottedKey","regex","createCachedRegex","_cond","suffix","cachedGlobToRegex","firstPart","currentIndex","matchingRuleForEventWithRulesets","rulesets","pushActionsForEventAndRulesets","ContainsUserName","AtRoomNotification","getPushRuleById","getPushRuleAndKindById","randomUppercaseString","randomLowercaseString","LOWERCASE","UPPERCASE","DIGITS","randomStringFrom","chars","TIMER_CHECK_PERIOD_MS","realCallbackKey","callbackList","scheduleRealCallback","delayMs","runAt","runCallbacks","callbacksToRun","binarySearch","_http","_userId","_deviceId","waitTime","retry_after_ms","retryAlgorithm","queueAlgorithm","QUEUE_MESSAGES","queues","activeQueues","procFn","processQueue","queueName","peekNextEvent","removeNextEvent","waitTimeMs","clearQueue","disableQueue","element","startProcessingQueues","sliding_sync_1","ExtensionE2EE","when","ExtensionState","PreProcess","onRequest","isInitial","onResponse","ExtensionToDevice","extReq","cancelledKeyVerificationTxns","toDeviceEvent","ExtensionAccountData","PostProcess","processGlobalAccountData","accountDataEvents","mapEvents","globalAccountData","prevEventsMap","storeAccountDataEvents","accountDataEvent","PushRules","prevEvent","ExtensionTyping","processEphemeralEvents","ExtensionReceipts","ephEvents","ephemeralEvents","syncOpts","lastPos","failCount","notifEvents","defaultClientOpts","defaultSyncApiOpts","SlidingSyncEvent","Lifecycle","onLifecycle","RoomData","onRoomData","extensions","registerExtension","_createAndReEmitRoom","processRoomData","SlidingSyncState","Complete","purgeNotifications","updateSyncState","RequestFinished","Reconnecting","shouldAbortSync","_roomId","syncStateData","registerStateListeners","required_state","ensureNameEvent","knownEvents","oldEvents","newEvents","seenKnownEvent","recvEvent","notification_count","highlight_count","invited_count","joined_count","invite_state","inviteStateEvents","num_live","addNotifications","processRoomEvent","promiseMapSeries","stateEventList","timelineEventList","numLive","liveTimelineEvents","resolveInvites","resolveInvitesToProfiles","inviteEvent","newState","old","timelineEvent","SlidingSync","MSC3575_STATE_KEY_LAZY","MSC3575_STATE_KEY_ME","MSC3575_WILDCARD","SlidingList","roomIndexToRoomId","replaceList","setModified","isModified","updateListRange","newRanges","ranges","filters","getList","forceIncludeAllParams","isIndexInRange","lists","roomSubscriptionInfo","timeoutMS","listModifiedCount","terminated","needsResend","txnIdDefers","desiredRoomSubscriptions","confirmedRoomSubscriptions","customSubscriptions","roomIdToCustomSubscription","addCustomSubscription","useCustomSubscription","getListData","getListParams","setListRanges","setList","existingList","getRoomSubscriptions","modifyRoomSubscriptions","modifyRoomSubscriptionInfo","getExtensionRequest","extName","onPreExtensionsResponse","onPostExtensionsResponse","invokeRoomDataListeners","invokeLifecycleListeners","shiftRight","listKey","low","shiftLeft","removeEntry","addEntry","processListOps","gapIndex","listData","ops","range","startIndex","resolveTransactionDefers","txnIndex","List","resetup","currentPos","doNotUpdateList","reqLists","reqBody","newSubscriptions","difference","unsubscriptions","unsubscribe_rooms","room_subscriptions","customSubName","pendingReq","listKeysWithUpdates","setA","setB","LocalIndexedDBStoreBackend","sync_accumulator_1","autoIncrement","selectQuery","keyRange","resultMapper","txnAsPromise","reqAsEventPromise","reqAsCursorPromise","disconnected","_isNewlyCreated","pendingUserPresenceData","syncAccumulator","SyncAccumulator","connect","onClose","isNewlyCreated","loadAccountData","loadSyncData","accumulate","roomsData","account_data","roomIndex","IDBKeyRange","membershipEvents","oobWritten","oob_written","tx","markerObject","roomRange","minStateKeyProm","openKeyCursor","primaryKey","maxStateKeyProm","minStateKey","maxStateKey","writeStore","membersKeyRange","clearDatabase","getSavedSync","getJSON","getNextBatchToken","setSyncData","syncToDatabase","userTuples","syncToDatabasePromise","doSyncToDatabase","persistUserPresenceEvents","persistAccountData","persistSyncData","clobber","tuples","tuple","getUserPresenceEvents","getClientOptions","resultBatch","RemoteIndexedDBStoreBackend","workerFactory","nextSeq","inFlight","onWorkerMessage","command","ensureStarted","doCmd","startPromise","worker","onmessage","IndexedDBStore","indexeddb_local_backend_1","indexeddb_remote_backend_1","startedUp","syncTs","userModifiedMap","degradable","getSavedSyncToken","reallySave","userPresenceEvents","wantsSave","fallbackFn","serialized","pendingEventsKey","isValidFilterId","pendingToDeviceBatches","nextToDeviceBatchId","onRoomMember","getRoomSummaries","toStart","clientOptions","Category","setState","eventMap","inviteRooms","joinRooms","maxTimelineEntries","syncResponse","fromDatabase","accumulateRooms","accumulateAccountData","accumulateRoom","Join","Leave","category","accumulateInviteState","accumulateJoinState","currentData","hasAdded","_currentState","_timeline","_accountData","_unreadNotifications","_unreadThreadNotifications","_summary","_readReceipts","_threadReadReceipts","unread_notifications","HEROES_KEY","INVITED_COUNT_KEY","JOINED_COUNT_KEY","sum","transformedEvent","_localTs","forDatabase","roomJson","unread_thread_notifications","evType","receiptEvent","receiptEventContent","receiptData","threadReceipts","msgData","rollBackState","prevStateEvent","accData","MSC2716_ROOM_VERSIONS","getFilterName","SetPresence","pollTimeout","createNewUser","_peekRoom","failedSyncCount","storeIsInvalid","recoverFromSyncStartupError","savedSyncPromise","buildDefaultFilter","checkLazyLoadStatus","wasLazyLoadingToggled","onOnline","startKeepAlives","markerEvent","onMarkerStateEvent","HistoryImportedWithinTimeline","leaveRooms","mapSyncResponseToRoomArray","leaveObj","isBrandNewRoom","mapSyncEventsFormat","processEventsForNotifs","oldStateEvents","presenceEvent","peekPoll","peekRoom","keepaliveProm","lazyLoadMembersBefore","prevClientOptions","doSync","savedSyncTokenPromise","tok","savedSync","syncFromCache","currentSyncRequest","firstSyncFilter","savedSyncToken","initialFilter","doSyncRequest","keepAliveTimer","connectionReturnedDefer","syncEventData","processSyncResponse","syncOptions","onSyncError","SyncUnexpectedError","hasSyncedBefore","Stopped","getSyncParams","getGuestFilter","disablePresence","set_presence","Offline","_cacheBuster","keepAlivePromise","Catchup","to_device","toDeviceMessages","inviteObj","inviter","parkedHistory","joinObj","_l","unreadThreadNotifications","unreadNotification","hasNoNotifications","emitEvent","device_lists","device_one_time_keys_count","device_unused_fallback_key_types","pokeKeepAlive","connDidFail","unsafeProp","arrObj","TimelineIndex","TimelineWindow","eventCount","windowLimit","initialEventId","initialWindowSize","initFields","eventIndex","endIndex","getTimelineIndex","extend","retreat","advance","excess","unpaginate","canPaginate","minIndex","maxIndex","hasNeighbouringTimeline","paginate","makeRequest","requestLimit","pendingPaginate","startOfTimeline","cappedDelta","mapsEqual","recursivelyAssign","stringToBase","baseToString","alphabetPad","decodeParams","unhomoglyph_1","interns","removeHiddenCharsRegex","urlSearchParams","URLSearchParams","append","pairs","alphabet","padEnd","charIndex","replacements","_match","_resolve","_reject","fns","chunkSize","promiseFn","padN","baseA","baseB","avg","collator","Intl","Collator","getContentTimestampWithFallback","processMapToObjectValue","targetMap","fromEntries","ignoreNullish","sourceKey","sourceValue","createDefault","unhomoglyph","releaseContext","acquireContext","audioContext","refCount","AudioContext","setTracksEnabled","MatrixCall","genCallID","CallError","CallErrorCode","CallEvent","CallParty","CallDirection","CallType","CallState","sdp_transform_1","callEventTypes_1","callFeed_1","MediaType","CodecName","getCodecParamMods","mediaType","codec","enableDtx","maxAverageBitrate","getTransceiverKey","purpose","toDeviceSeq","Fledgling","candidateSendQueue","candidateSendTries","candidatesEnded","feeds","transceivers","inviteOrAnswerSent","waitForLocalAVStream","removeTrackListeners","remoteOnHold","makingOffer","ignoreOffer","remoteCandidateBuffer","gotLocalIceCandidate","candidate","callId","sdpMid","callHasEnded","queueCandidate","onIceGatheringStateChange","peerConn","iceGatheringState","getLocalOfferFailed","LocalOfferFailed","terminate","Local","getUserMediaFailed","successor","NoUserMedia","onIceConnectionStateChanged","iceConnectionState","iceDisconnectedTimeout","Connected","callLengthInterval","callStartTime","LengthChanged","restartIce","hangup","IceFailed","Connecting","feed","getRemoteFeeds","setAudioVideoMuted","onSignallingStateChanged","signalingState","onTrack","pushRemoteFeed","onRemoveTrack","getTracks","deleteFeedByStream","onDataChannel","DataChannel","onNegotiationNeeded","CreateOffer","opponentVersion","queueGotLocalOffer","onHangupReceived","partyIdMatches","Ringing","Remote","UserHangup","party_id","opponentPartyId","onRejectReceived","InviteSent","Inbound","onAnsweredElsewhere","AnsweredElsewhere","invitee","ourPartyId","opponentDeviceId","opponentSessionId","groupCallId","isOnlyDataChannelAllowed","placeVoiceCall","placeCall","placeVideoCall","createDataChannel","dataChannel","getOpponentMember","opponentMember","getOpponentDeviceId","getOpponentSessionId","opponentCanBeTransferred","opponentCaps","opponentSupportsDTMF","getRemoteAssertedIdentity","remoteAssertedIdentity","hasUserMediaVideoSender","hasRemoteUserMediaVideoTrack","Video","Voice","hasLocalUserMediaVideoTrack","localUsermediaStream","getVideoTracks","SDPStreamMetadataPurpose","Usermedia","hasLocalUserMediaAudioTrack","getAudioTracks","hasRemoteUserMediaAudioTrack","hasUserMediaAudioSender","localUsermediaFeed","getLocalFeeds","localScreensharingFeed","Screenshare","localScreensharingStream","remoteUsermediaFeed","remoteScreensharingFeed","remoteUsermediaStream","remoteScreensharingStream","getFeedByStreamId","streamId","getFeeds","isLocal","initOpponentCrypto","opponentDeviceInfo","deviceInfoMap","GroupCallUnknownDeviceError","getLocalSDPStreamMetadata","updateStreamIds","localFeed","sdpMetadataStreamId","audio_muted","isAudioMuted","video_muted","isVideoMuted","noIncomingFeeds","opponentSupportsSDPStreamMetadata","pushRemoteFeedWithoutMetadata","remoteSDPStreamMetadata","audioMuted","videoMuted","CallFeed","FeedsChanged","oldRemoteStream","pushNewLocalFeed","addToPeerConnection","pushLocalFeed","callFeed","tKey","transceiver","replaceTrack","newSender","addTrack","newTransceiver","getTransceivers","removeLocalFeed","audioTransceiverKey","videoTransceiverKey","transceiverKey","removeTrack","stopScreensharingStream","deleteFeed","deleteAllFeeds","dispose","getCurrentCallStats","callStatsAtEnd","collectCallStats","statsReport","getStats","stats","initWithInvite","sdpStreamMetadata","SDPStreamMetadataKey","updateRemoteSDPStreamMetadata","createPeerConnection","chooseOpponent","setRemoteDescription","offer","addBufferedIceCandidates","SetRemoteDescription","remoteStream","ringingTimer","hangupParty","Ended","stopAllMedia","removeStatsReportGatherer","Hangup","lifetime","initWithHangup","shouldAnswerWithMediaType","wantedValue","valueOfTheOtherSide","answer","audio","video","WaitLocalMedia","prevState","answerWithAudio","answerWithVideo","getUserMediaStream","answerWithCallFeeds","callFeeds","queueGotCallFeedsForAnswer","replacedBy","newCall","Outbound","suppressEvent","sendVoipEvent","CallHangup","CallReject","upgradeCall","getAudio","getVideo","updateLocalUsermediaStream","isScreensharing","setScreensharingEnabled","setScreensharingEnabledWithoutMetadataSupport","audioTransceiver","videoTransceiver","getScreensharingStream","forceAudio","forceVideo","audioEnabled","videoEnabled","oldSender","added","setLocalVideoMuted","muted","stopVideoTrackTimer","hasVideoDevice","isLocalVideoMuted","updateMuteStatus","sendMetadataUpdate","setMicrophoneMuted","hasAudioDevice","isMicrophoneMuted","isRemoteOnHold","setRemoteOnHold","onHold","RemoteHoldUnhold","isLocalOnHold","callOnHold","currentDirection","sendDtmfDigit","digit","getSenders","dtmf","insertDTMF","micShouldBeMuted","vidShouldBeMuted","CallSDPStreamMetadataChangedPrefix","gotCallFeedsForInvite","requestScreenshareFeed","addTransceiver","sendAnswer","answerContent","localDescription","discardCount","discardDuplicateCandidates","CallAnswer","SendAnswer","UnknownDevices","sendCandidateQueue","responsePromiseChain","gotCallFeedsForAnswer","mungeSdp","mods","payloadTypeToCodecMap","codecToPayloadTypeMap","extraConfig","createOffer","createAnswer","CreateAnswer","getRidOfRTXCodecs","setLocalDescription","SetLocalDescription","onRemoteIceCandidatesReceived","fromPartyId","addIceCandidates","bufferedCandidates","onAnswerReceived","CallSelectAnswer","selected_party_id","onSelectAnswerReceived","selectedPartyId","onNegotiateReceived","polite","offerCollision","prevLocalOnHold","CallNegotiate","newLocalOnHold","LocalHoldUnhold","HoldUnhold","onSDPStreamMetadataChangedReceived","onAssertedIdentityReceived","asserted_identity","AssertedIdentityChanged","wrappedGotLocalOffer","gotLocalOffer","CallInvite","SignallingFailed","SendInvite","inviteTimeout","InviteTimeout","RTCRtpReceiver","RTCRtpSender","recvCodecs","codecs","mimeType","rtxCodecIndex","screenshareVideoTransceiver","setCodecPreferences","realContent","call_id","conf_id","sender_session_id","dest_session_id","SendVoipEvent","newQueue","transfer","targetUserId","profileInfo","replacementId","replacement_id","target_user","create_call","CallReplaces","Transferred","transferToCall","transferTargetCall","targetProfileInfo","opponentUserId","transfereeProfileInfo","newCallId","bodyToTransferTarget","await_call","bodyToTransferee","hangupReason","calls","stopUserMediaStream","checkForErrorListener","CallCandidates","placeCallWithCallFeeds","pc","RTCPeerConnection","iceTransportPolicy","iceServers","bundlePolicy","addStatsReportGatherer","sdpMLineIndex","addIceCandidate","hasPeerConnection","initStats","peerId","tracks","RTCSessionDescription","RTCIceCandidate","mediaDevices","NODE_ENV","optionsForceTURN","CallEventHandlerEvent","nextSeqByCall","toDeviceEventBuffers","onSync","currentEventBuffer","callEventBuffer","eventBufferPromiseChain","evaluateEventBuffer","onRoomTimeline","nextEvent","candidateEventsByCall","eventBuffer","callEvents","ignoreCallIds","handleCallEvent","ReceivedVoipEvent","callRoomId","getGroupCallById","groupCall","weSentTheEvent","CallAssertedIdentity","CallAssertedIdentityPrefix","CallSDPStreamMetadataChanged","timeUntilTurnCresExpire","getGroupCallStats","GroupCallErrorCode","UnknownDevice","existingCall","thisCall","isCalling","Incoming","CallFeedEvent","SPEAKING_THRESHOLD","audioContext_1","localVolume","measuringVolumeActivity","speakingThreshold","speaking","_disposed","_connected","onAddTrack","NewStream","onCallState","connected","volumeLooper","analyser","getFloatFrequencyData","frequencyBinCount","maxVolume","volume","speakingVolumeSamples","VolumeChanged","newSpeaking","Speaking","volumeLooperTimeout","updateStream","hasAudioTrack","initVolumeMeasuring","ConnectedChanged","oldStream","newStream","measureVolumeActivity","createAnalyser","fftSize","smoothingTimeConstant","createMediaStreamSource","callRoom","isSpeaking","setNewStream","MuteStateChanged","setSpeakingThreshold","threshold","userMediaStreams","screensharingStreams","Disposed","disposed","getLocalVolume","setLocalVolume","LocalVolumeChanged","OtherUserSpeakingError","GroupCallError","GroupCallStatsReportEvent","GroupCallTerminationReason","groupCallStats_1","statsReport_1","DEVICE_TIMEOUT","getCallUserId","isCallWithoutVideoAndAudio","activeSpeakerInterval","retryCallInterval","participantTimeout","pttMaxTransmitTime","userMediaFeeds","screenshareFeeds","callHandlers","retryCallCounts","transmitTimer","participantsExpirationTimer","resendMemberStateTimer","initWithAudioMuted","initWithVideoMuted","onConnectionStats","report","ConnectionStats","onByteSentStats","ByteSentStats","LocalCallFeedUninitialized","_participants","_creationTs","_enteredViaAnotherSession","onIncomingCall","prevCall","initCall","callExpected","CallsChanged","onRetryCallLoop","needsRetry","participantMap","participants","callMap","retriesMap","participant","wantsOutgoingCall","placeOutgoingCalls","onCallFeedsChanged","opponentMemberId","currentUserMediaFeed","getUserMediaFeed","addUserMediaFeed","replaceUserMediaFeed","removeUserMediaFeed","currentScreenshareFeed","getScreenshareFeed","addScreenshareFeed","replaceScreenshareFeed","removeScreenshareFeed","onCallStateChanged","_oldState","localCallFeed","onCallHangup","disposeCall","onCallReplaced","onActiveSpeakerLoop","topAvg","nextActiveSpeaker","activeSpeaker","ActiveSpeakerChanged","onRoomState","updateParticipants","onParticipantsChanged","forEachCall","Entered","onStateChanged","updateMemberState","onLocalFeedsChanged","creationTs","GroupCallPrefix","ParticipantsChanged","GroupCallStateChanged","LocalScreenshareStateChanged","allowCallWithoutVideoAndAudio","userID","GroupCallStats","reports","StatsReport","CONNECTION_STATS","BYTE_SENT_STATS","GroupCallEventHandlerEvent","Outgoing","groupCallState","prevValue","participantStateEqual","screensharing","enteredViaAnotherSession","localScreenshareFeed","hasLocalParticipant","initLocalCallFeed","InitializingLocalCallFeed","initCallFeedPromise","initLocalCallFeedInternal","MediaStream","LocalCallFeedInitialized","enter","retryCallLoopInterval","activeSpeakerLoopInterval","localDesktopCapturerSourceId","stopAllStreams","emitStateEvent","existingStateEvent","CallEnded","sendUpdatesBefore","sendUpdates","LocalMuteStateChanged","onTrackEnded","desktopCapturerSourceId","throwOnFail","callsChanged","NewSession","PlaceCallFailed","getMemberStateEvents","GroupCallMemberPrefix","usermediaFeed","screenshareFeed","UserMediaFeedsChanged","existingFeed","replacementFeed","feedIndex","ScreenshareFeedsChanged","localMember","entered","nextExpiration","validDevices","expires_ts","updateDevices","otherCalls","newDevices","newCalls","addDeviceToMemberState","cleanMemberState","last_seen_ts","roomDeferreds","onRoomsChanged","createGroupCallForRoom","onRoomStateChanged","currentGroupCall","createGroupCallFromRoomStateEvent","getRoomDeferred","resolveFunc","sortedCallEvents","callEvent","callType","callIntent","maxPacketLifeTime","maxRetransmits","MediaHandlerEvent","restoreMediaSettings","audioInput","videoInput","setAudioInput","updateLocalUsermediaStreams","setAudioSettings","audioSettings","setVideoInput","setMediaInputs","callMediaStreamParams","localUserMediaStream","LocalStreamsChanged","enumerateDevices","reusable","getMediaStreamPromise","getUserMediaStreamInternal","shouldRequestAudio","shouldRequestVideo","canReuseStream","getSettings","constraints","getUserMediaContraints","getUserMedia","settings","mediaStream","screenshareConstraints","getScreenshareContraints","getDisplayMedia","matchingStream","isWebkit","webkitGetUserMedia","ideal","autoGainControl","echoCancellation","noiseSuppression","exact","mandatory","chromeMediaSource","chromeMediaSourceId","bandwidth","bitrate","packetLoss","ConnectionStatsReporter","availableIncomingBitrate","availableOutgoingBitrate","download","statsReportGatherer_1","statsReportEmitter_1","interval","gatherers","StatsReportEmitter","timer","processStats","stopProcessingStats","hasStatsReportGatherer","peerConnection","StatsReportGatherer","getStatsReportGatherer","MediaSsrcHandler","ssrcToMid","local","remote","findMidBySsrc","ssrc","ssrcs","getSsrcToMidMap","MediaTrackHandler","getLocalTracks","getTackById","trackId","getLocalTrackIdByMid","getRemoteTrackIdByMid","getActiveSimulcastStreams","MediaTrackStats","loss","packetsTotal","packetsLost","isDownloadStream","resolution","framerate","setLoss","loos","getLoss","setResolution","getResolution","setFramerate","getFramerate","setBitrate","getBitrate","setCodec","codecShortType","getCodec","resetBitrate","MediaTrackStatsHandler","mediaTrackStats_1","mediaSsrcHandler","mediaTrackHandler","track2stats","findTrack2Stats","trackID","trackIdentifier","trackStats","findLocalVideoTrackStats","getTrack2stats","StatsReportBuilder","totalPackets","lostPackets","bitrateDownload","bitrateUpload","resolutions","framerates","audioBitrateDownload","audioBitrateUpload","videoBitrateDownload","videoBitrateUpload","calculatePacketLoss","emitByteSendReport","byteSentStats","emitConnectionStatsReport","connectionStats_1","connectionStatsReporter_1","transportStatsReporter_1","mediaSsrcHandler_1","mediaTrackHandler_1","mediaTrackStatsHandler_1","trackStatsReporter_1","statsReportBuilder_1","statsValueFormatter_1","remoteUserId","isFocus","connectionStats","onSignalStateChange","statsPromise","currentStatsReport","processStatsReport","previousStatsReport","handleError","before","nominated","buildBandwidthReport","TransportStatsReporter","buildReport","TrackStatsReporter","buildPacketsLost","buildFramerateResolution","buildBitrateReceived","StatsValueFormatter","getNonNegativeValue","bytesSent","buildBitrateSend","buildCodec","remoteSource","calculateSimulcastFramerate","processAndEmitReport","setActive","getActive","build","currentRemoteDescription","currentLocalDescription","imput","frameHeight","frameWidth","frameRate","framesPerSecond","layer","timeMs","framesSent","codecId","calculateBitrate","bytesReceived","packetsNow","packetsBefore","packetsDiff","packetsLostNow","packetsLostBefore","packetsLostDiff","bytesNowAny","bytesBeforeAny","nowTimestamp","beforeTimestamp","bytesNow","bytesBefore","bytesProcessed","bitrateKbps","conferenceStatsTransport","localUsedCandidate","localCandidateId","remoteUsedCandidate","remoteCandidateId","localIp","localCandidateType","candidateType","remoteCandidateType","networkType","rtt","currentRoundTripTime"],"sources":["dist/browser-matrix.js"],"mappings":"CAAY,SAASA,EAAEC,EAAEC,EAAEC,GAAG,SAASC,EAAEC,EAAEC,GAAG,IAAIJ,EAAEG,GAAG,CAAC,IAAIJ,EAAEI,GAAG,CAAC,IAAIE,EAAE,mBAAmBC,SAASA,QAAQ,IAAIF,GAAGC,EAAE,OAAOA,EAAEF,GAAE,GAAI,GAAG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mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,kEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,sEAINP,IAAK,CACHngC,IAAK,EACL0gC,OAAQ,CACN,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,iEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,kEACA,oEAEF,CACE,mEACA,mEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF,CACE,mEACA,oEAEF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,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,SAAU,IACV,SAAU,IACV,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,MACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,OACN,KAAM,OACN,KAAM,OACN,KAAM,OACN,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,KACL,IAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,OACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,OACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,OACL,IAAK,OACL,IAAK,OACL,IAAK,OACL,IAAK,OACL,IAAK,OACL,IAAK,OACL,IAAK,OACL,IAAK,OACL,IAAK,OACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,OACL,IAAK,MACL,KAAM,MACN,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,OACL,IAAK,OACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,KAAM,MACN,IAAK,MACL,IAAK,MACL,KAAM,MACN,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,KAAM,MACN,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,KAAM,MACN,KAAM,MACN,KAAM,MACN,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,KAAM,MACN,IAAK,MACL,IAAK,MACL,IAAK,MACL,KAAM,MACN,IAAK,MACL,KAAM,MACN,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,KACN,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,OACL,IAAK,OACL,IAAK,MACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,MACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,KACN,IAAK,KACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,IAAK,IACL,IAAK,KACL,IAAK,MACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,OACL,IAAK,SACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,KACL,KAAM,KACN,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,KACL,KAAM,KACN,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,KAAM,OACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN8pD,EAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,OACN,IAAK,MACL,IAAK,MACL,KAAM,SACN,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,OACL,IAAK,SACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,KACL,KAAM,KACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,KACN,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,IAAK,KACL,IAAK,KACL,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,KACN,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,OACL,IAAK,OACL,IAAK,QACL,IAAK,QACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,KACL,IAAK,KACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,KACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,KACNnpC,EAAK,KACL,IAAK,KACL,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,MACN,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,KACL,IAAK,MACL,IAAK,OACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,KACN,IAAK,KACL,KAAM,KACN,IAAK,KACL,IAAK,MACL,IAAK,OACL,IAAK,KACL,IAAK,MACL,IAAK,OACL,KAAM,KACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,KACL,IAAK,KACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,MACL,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,KACL,IAAK,KACL,KAAM,KACN,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,MACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,KAAM,IACN,IAAK,IACL,IAAK,KACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,MACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,WACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,OACL,IAAK,OACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,OACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,OACL,IAAK,OACL,IAAK,OACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,OACL,IAAK,OACL,IAAK,MACL,IAAK,MACL,IAAK,OACL,IAAK,OACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,OACL,IAAK,MACL,IAAK,MACL,IAAK,qBACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,OACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,OACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,OACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,OACL,IAAK,OACL,IAAK,OACL,IAAK,OACL,IAAK,OACL,IAAK,OACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,KAAM,SACN,KAAM,SACN,KAAM,SACN,KAAM,SACN,KAAM,SACN,KAAM,SACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,OACL,IAAK,OACL,IAAK,IACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,QACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,KACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,KACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,MACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,IACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,KACL,KAAM,OACN,KAAM,OACN,KAAM,SACN,KAAM,SACN,KAAM,OACN,KAAM,OACN,KAAM,OACN,KAAM,SACN,KAAM,SACN,KAAM,OACN,KAAM,OACN,KAAM,OACN,KAAM,SACN,IAAK,KACL,IAAK,KACL,KAAM,KACN,IAAK,KACL,IAAK,KACL,KAAM,KACN,KAAM,KACN,IAAK,KACL,IAAK,KACL,IAAK,KACL,KAAM,KACN,KAAM,KACN,KAAM,KACN,KAAM,KACN,IAAK,KACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,MACL,IAAK,MACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,MACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,KACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,KACN,KAAM,KACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,KACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,KACN,KAAM,KACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,KACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,KACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,KACN,KAAM,KACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,KACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,KACL,IAAK,KACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,KACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,KACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,KACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,KACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,KAAM,IACN,KAAM,KACN,KAAM,KACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,KAAM,IACN,IAAK,IACL,IAAK,KACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,KACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,KACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,KACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,KACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,KAAM,KACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,KACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,KACN,IAAK,KACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,KACN,KAAM,IACN,IAAK,IACL,KAAM,KACN,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,KACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,KACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,KACN,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,KACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,KACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,KACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,KAAM,KACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,KACN,IAAK,IACL,KAAM,IACN,KAAM,KACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,KACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,KACL,KAAM,KACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,KACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,IACN,KAAM,KACN,IAAK,IACL,KAAM,KACN,KAAM,IACN,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,KAAM,IACN,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,KAAM,IACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL,KAAM,KACN,IAAK,IACL,IAAK,IACL,IAAK,IACL,IAAK,IACL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